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.

50441 lines
1.1 MiB

  1. /**
  2. * @license
  3. * Copyright 2010-2023 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '150';
  7. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  8. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  9. const CullFaceNone = 0;
  10. const CullFaceBack = 1;
  11. const CullFaceFront = 2;
  12. const CullFaceFrontBack = 3;
  13. const BasicShadowMap = 0;
  14. const PCFShadowMap = 1;
  15. const PCFSoftShadowMap = 2;
  16. const VSMShadowMap = 3;
  17. const FrontSide = 0;
  18. const BackSide = 1;
  19. const DoubleSide = 2;
  20. const TwoPassDoubleSide = 2; // r149
  21. const NoBlending = 0;
  22. const NormalBlending = 1;
  23. const AdditiveBlending = 2;
  24. const SubtractiveBlending = 3;
  25. const MultiplyBlending = 4;
  26. const CustomBlending = 5;
  27. const AddEquation = 100;
  28. const SubtractEquation = 101;
  29. const ReverseSubtractEquation = 102;
  30. const MinEquation = 103;
  31. const MaxEquation = 104;
  32. const ZeroFactor = 200;
  33. const OneFactor = 201;
  34. const SrcColorFactor = 202;
  35. const OneMinusSrcColorFactor = 203;
  36. const SrcAlphaFactor = 204;
  37. const OneMinusSrcAlphaFactor = 205;
  38. const DstAlphaFactor = 206;
  39. const OneMinusDstAlphaFactor = 207;
  40. const DstColorFactor = 208;
  41. const OneMinusDstColorFactor = 209;
  42. const SrcAlphaSaturateFactor = 210;
  43. const NeverDepth = 0;
  44. const AlwaysDepth = 1;
  45. const LessDepth = 2;
  46. const LessEqualDepth = 3;
  47. const EqualDepth = 4;
  48. const GreaterEqualDepth = 5;
  49. const GreaterDepth = 6;
  50. const NotEqualDepth = 7;
  51. const MultiplyOperation = 0;
  52. const MixOperation = 1;
  53. const AddOperation = 2;
  54. const NoToneMapping = 0;
  55. const LinearToneMapping = 1;
  56. const ReinhardToneMapping = 2;
  57. const CineonToneMapping = 3;
  58. const ACESFilmicToneMapping = 4;
  59. const CustomToneMapping = 5;
  60. const UVMapping = 300;
  61. const CubeReflectionMapping = 301;
  62. const CubeRefractionMapping = 302;
  63. const EquirectangularReflectionMapping = 303;
  64. const EquirectangularRefractionMapping = 304;
  65. const CubeUVReflectionMapping = 306;
  66. const RepeatWrapping = 1000;
  67. const ClampToEdgeWrapping = 1001;
  68. const MirroredRepeatWrapping = 1002;
  69. const NearestFilter = 1003;
  70. const NearestMipmapNearestFilter = 1004;
  71. const NearestMipMapNearestFilter = 1004;
  72. const NearestMipmapLinearFilter = 1005;
  73. const NearestMipMapLinearFilter = 1005;
  74. const LinearFilter = 1006;
  75. const LinearMipmapNearestFilter = 1007;
  76. const LinearMipMapNearestFilter = 1007;
  77. const LinearMipmapLinearFilter = 1008;
  78. const LinearMipMapLinearFilter = 1008;
  79. const UnsignedByteType = 1009;
  80. const ByteType = 1010;
  81. const ShortType = 1011;
  82. const UnsignedShortType = 1012;
  83. const IntType = 1013;
  84. const UnsignedIntType = 1014;
  85. const FloatType = 1015;
  86. const HalfFloatType = 1016;
  87. const UnsignedShort4444Type = 1017;
  88. const UnsignedShort5551Type = 1018;
  89. const UnsignedInt248Type = 1020;
  90. const AlphaFormat = 1021;
  91. const RGBAFormat = 1023;
  92. const LuminanceFormat = 1024;
  93. const LuminanceAlphaFormat = 1025;
  94. const DepthFormat = 1026;
  95. const DepthStencilFormat = 1027;
  96. const RedFormat = 1028;
  97. const RedIntegerFormat = 1029;
  98. const RGFormat = 1030;
  99. const RGIntegerFormat = 1031;
  100. const RGBAIntegerFormat = 1033;
  101. const RGB_S3TC_DXT1_Format = 33776;
  102. const RGBA_S3TC_DXT1_Format = 33777;
  103. const RGBA_S3TC_DXT3_Format = 33778;
  104. const RGBA_S3TC_DXT5_Format = 33779;
  105. const RGB_PVRTC_4BPPV1_Format = 35840;
  106. const RGB_PVRTC_2BPPV1_Format = 35841;
  107. const RGBA_PVRTC_4BPPV1_Format = 35842;
  108. const RGBA_PVRTC_2BPPV1_Format = 35843;
  109. const RGB_ETC1_Format = 36196;
  110. const RGB_ETC2_Format = 37492;
  111. const RGBA_ETC2_EAC_Format = 37496;
  112. const RGBA_ASTC_4x4_Format = 37808;
  113. const RGBA_ASTC_5x4_Format = 37809;
  114. const RGBA_ASTC_5x5_Format = 37810;
  115. const RGBA_ASTC_6x5_Format = 37811;
  116. const RGBA_ASTC_6x6_Format = 37812;
  117. const RGBA_ASTC_8x5_Format = 37813;
  118. const RGBA_ASTC_8x6_Format = 37814;
  119. const RGBA_ASTC_8x8_Format = 37815;
  120. const RGBA_ASTC_10x5_Format = 37816;
  121. const RGBA_ASTC_10x6_Format = 37817;
  122. const RGBA_ASTC_10x8_Format = 37818;
  123. const RGBA_ASTC_10x10_Format = 37819;
  124. const RGBA_ASTC_12x10_Format = 37820;
  125. const RGBA_ASTC_12x12_Format = 37821;
  126. const RGBA_BPTC_Format = 36492;
  127. const RED_RGTC1_Format = 36283;
  128. const SIGNED_RED_RGTC1_Format = 36284;
  129. const RED_GREEN_RGTC2_Format = 36285;
  130. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  131. const LoopOnce = 2200;
  132. const LoopRepeat = 2201;
  133. const LoopPingPong = 2202;
  134. const InterpolateDiscrete = 2300;
  135. const InterpolateLinear = 2301;
  136. const InterpolateSmooth = 2302;
  137. const ZeroCurvatureEnding = 2400;
  138. const ZeroSlopeEnding = 2401;
  139. const WrapAroundEnding = 2402;
  140. const NormalAnimationBlendMode = 2500;
  141. const AdditiveAnimationBlendMode = 2501;
  142. const TrianglesDrawMode = 0;
  143. const TriangleStripDrawMode = 1;
  144. const TriangleFanDrawMode = 2;
  145. const LinearEncoding = 3000;
  146. const sRGBEncoding = 3001;
  147. const BasicDepthPacking = 3200;
  148. const RGBADepthPacking = 3201;
  149. const TangentSpaceNormalMap = 0;
  150. const ObjectSpaceNormalMap = 1;
  151. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  152. const NoColorSpace = '';
  153. const SRGBColorSpace = 'srgb';
  154. const LinearSRGBColorSpace = 'srgb-linear';
  155. const DisplayP3ColorSpace = 'display-p3';
  156. const ZeroStencilOp = 0;
  157. const KeepStencilOp = 7680;
  158. const ReplaceStencilOp = 7681;
  159. const IncrementStencilOp = 7682;
  160. const DecrementStencilOp = 7683;
  161. const IncrementWrapStencilOp = 34055;
  162. const DecrementWrapStencilOp = 34056;
  163. const InvertStencilOp = 5386;
  164. const NeverStencilFunc = 512;
  165. const LessStencilFunc = 513;
  166. const EqualStencilFunc = 514;
  167. const LessEqualStencilFunc = 515;
  168. const GreaterStencilFunc = 516;
  169. const NotEqualStencilFunc = 517;
  170. const GreaterEqualStencilFunc = 518;
  171. const AlwaysStencilFunc = 519;
  172. const StaticDrawUsage = 35044;
  173. const DynamicDrawUsage = 35048;
  174. const StreamDrawUsage = 35040;
  175. const StaticReadUsage = 35045;
  176. const DynamicReadUsage = 35049;
  177. const StreamReadUsage = 35041;
  178. const StaticCopyUsage = 35046;
  179. const DynamicCopyUsage = 35050;
  180. const StreamCopyUsage = 35042;
  181. const GLSL1 = '100';
  182. const GLSL3 = '300 es';
  183. const _SRGBAFormat = 1035; // fallback for WebGL 1
  184. /**
  185. * https://github.com/mrdoob/eventdispatcher.js/
  186. */
  187. class EventDispatcher {
  188. addEventListener( type, listener ) {
  189. if ( this._listeners === undefined ) this._listeners = {};
  190. const listeners = this._listeners;
  191. if ( listeners[ type ] === undefined ) {
  192. listeners[ type ] = [];
  193. }
  194. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  195. listeners[ type ].push( listener );
  196. }
  197. }
  198. hasEventListener( type, listener ) {
  199. if ( this._listeners === undefined ) return false;
  200. const listeners = this._listeners;
  201. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  202. }
  203. removeEventListener( type, listener ) {
  204. if ( this._listeners === undefined ) return;
  205. const listeners = this._listeners;
  206. const listenerArray = listeners[ type ];
  207. if ( listenerArray !== undefined ) {
  208. const index = listenerArray.indexOf( listener );
  209. if ( index !== - 1 ) {
  210. listenerArray.splice( index, 1 );
  211. }
  212. }
  213. }
  214. dispatchEvent( event ) {
  215. if ( this._listeners === undefined ) return;
  216. const listeners = this._listeners;
  217. const listenerArray = listeners[ event.type ];
  218. if ( listenerArray !== undefined ) {
  219. event.target = this;
  220. // Make a copy, in case listeners are removed while iterating.
  221. const array = listenerArray.slice( 0 );
  222. for ( let i = 0, l = array.length; i < l; i ++ ) {
  223. array[ i ].call( this, event );
  224. }
  225. event.target = null;
  226. }
  227. }
  228. }
  229. 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' ];
  230. let _seed = 1234567;
  231. const DEG2RAD = Math.PI / 180;
  232. const RAD2DEG = 180 / Math.PI;
  233. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  234. function generateUUID() {
  235. const d0 = Math.random() * 0xffffffff | 0;
  236. const d1 = Math.random() * 0xffffffff | 0;
  237. const d2 = Math.random() * 0xffffffff | 0;
  238. const d3 = Math.random() * 0xffffffff | 0;
  239. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  240. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  241. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  242. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  243. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  244. return uuid.toLowerCase();
  245. }
  246. function clamp( value, min, max ) {
  247. return Math.max( min, Math.min( max, value ) );
  248. }
  249. // compute euclidean modulo of m % n
  250. // https://en.wikipedia.org/wiki/Modulo_operation
  251. function euclideanModulo( n, m ) {
  252. return ( ( n % m ) + m ) % m;
  253. }
  254. // Linear mapping from range <a1, a2> to range <b1, b2>
  255. function mapLinear( x, a1, a2, b1, b2 ) {
  256. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  257. }
  258. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  259. function inverseLerp( x, y, value ) {
  260. if ( x !== y ) {
  261. return ( value - x ) / ( y - x );
  262. } else {
  263. return 0;
  264. }
  265. }
  266. // https://en.wikipedia.org/wiki/Linear_interpolation
  267. function lerp( x, y, t ) {
  268. return ( 1 - t ) * x + t * y;
  269. }
  270. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  271. function damp( x, y, lambda, dt ) {
  272. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  273. }
  274. // https://www.desmos.com/calculator/vcsjnyz7x4
  275. function pingpong( x, length = 1 ) {
  276. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  277. }
  278. // http://en.wikipedia.org/wiki/Smoothstep
  279. function smoothstep( x, min, max ) {
  280. if ( x <= min ) return 0;
  281. if ( x >= max ) return 1;
  282. x = ( x - min ) / ( max - min );
  283. return x * x * ( 3 - 2 * x );
  284. }
  285. function smootherstep( 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 * x * ( x * ( x * 6 - 15 ) + 10 );
  290. }
  291. // Random integer from <low, high> interval
  292. function randInt( low, high ) {
  293. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  294. }
  295. // Random float from <low, high> interval
  296. function randFloat( low, high ) {
  297. return low + Math.random() * ( high - low );
  298. }
  299. // Random float from <-range/2, range/2> interval
  300. function randFloatSpread( range ) {
  301. return range * ( 0.5 - Math.random() );
  302. }
  303. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  304. function seededRandom( s ) {
  305. if ( s !== undefined ) _seed = s;
  306. // Mulberry32 generator
  307. let t = _seed += 0x6D2B79F5;
  308. t = Math.imul( t ^ t >>> 15, t | 1 );
  309. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  310. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  311. }
  312. function degToRad( degrees ) {
  313. return degrees * DEG2RAD;
  314. }
  315. function radToDeg( radians ) {
  316. return radians * RAD2DEG;
  317. }
  318. function isPowerOfTwo( value ) {
  319. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  320. }
  321. function ceilPowerOfTwo( value ) {
  322. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  323. }
  324. function floorPowerOfTwo( value ) {
  325. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  326. }
  327. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  328. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  329. // rotations are applied to the axes in the order specified by 'order'
  330. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  331. // angles are in radians
  332. const cos = Math.cos;
  333. const sin = Math.sin;
  334. const c2 = cos( b / 2 );
  335. const s2 = sin( b / 2 );
  336. const c13 = cos( ( a + c ) / 2 );
  337. const s13 = sin( ( a + c ) / 2 );
  338. const c1_3 = cos( ( a - c ) / 2 );
  339. const s1_3 = sin( ( a - c ) / 2 );
  340. const c3_1 = cos( ( c - a ) / 2 );
  341. const s3_1 = sin( ( c - a ) / 2 );
  342. switch ( order ) {
  343. case 'XYX':
  344. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  345. break;
  346. case 'YZY':
  347. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  348. break;
  349. case 'ZXZ':
  350. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  351. break;
  352. case 'XZX':
  353. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  354. break;
  355. case 'YXY':
  356. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  357. break;
  358. case 'ZYZ':
  359. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  360. break;
  361. default:
  362. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  363. }
  364. }
  365. function denormalize( value, array ) {
  366. switch ( array.constructor ) {
  367. case Float32Array:
  368. return value;
  369. case Uint16Array:
  370. return value / 65535.0;
  371. case Uint8Array:
  372. return value / 255.0;
  373. case Int16Array:
  374. return Math.max( value / 32767.0, - 1.0 );
  375. case Int8Array:
  376. return Math.max( value / 127.0, - 1.0 );
  377. default:
  378. throw new Error( 'Invalid component type.' );
  379. }
  380. }
  381. function normalize( value, array ) {
  382. switch ( array.constructor ) {
  383. case Float32Array:
  384. return value;
  385. case Uint16Array:
  386. return Math.round( value * 65535.0 );
  387. case Uint8Array:
  388. return Math.round( value * 255.0 );
  389. case Int16Array:
  390. return Math.round( value * 32767.0 );
  391. case Int8Array:
  392. return Math.round( value * 127.0 );
  393. default:
  394. throw new Error( 'Invalid component type.' );
  395. }
  396. }
  397. const MathUtils = {
  398. DEG2RAD: DEG2RAD,
  399. RAD2DEG: RAD2DEG,
  400. generateUUID: generateUUID,
  401. clamp: clamp,
  402. euclideanModulo: euclideanModulo,
  403. mapLinear: mapLinear,
  404. inverseLerp: inverseLerp,
  405. lerp: lerp,
  406. damp: damp,
  407. pingpong: pingpong,
  408. smoothstep: smoothstep,
  409. smootherstep: smootherstep,
  410. randInt: randInt,
  411. randFloat: randFloat,
  412. randFloatSpread: randFloatSpread,
  413. seededRandom: seededRandom,
  414. degToRad: degToRad,
  415. radToDeg: radToDeg,
  416. isPowerOfTwo: isPowerOfTwo,
  417. ceilPowerOfTwo: ceilPowerOfTwo,
  418. floorPowerOfTwo: floorPowerOfTwo,
  419. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  420. normalize: normalize,
  421. denormalize: denormalize
  422. };
  423. class Vector2 {
  424. constructor( x = 0, y = 0 ) {
  425. Vector2.prototype.isVector2 = true;
  426. this.x = x;
  427. this.y = y;
  428. }
  429. get width() {
  430. return this.x;
  431. }
  432. set width( value ) {
  433. this.x = value;
  434. }
  435. get height() {
  436. return this.y;
  437. }
  438. set height( value ) {
  439. this.y = value;
  440. }
  441. set( x, y ) {
  442. this.x = x;
  443. this.y = y;
  444. return this;
  445. }
  446. setScalar( scalar ) {
  447. this.x = scalar;
  448. this.y = scalar;
  449. return this;
  450. }
  451. setX( x ) {
  452. this.x = x;
  453. return this;
  454. }
  455. setY( y ) {
  456. this.y = y;
  457. return this;
  458. }
  459. setComponent( index, value ) {
  460. switch ( index ) {
  461. case 0: this.x = value; break;
  462. case 1: this.y = value; break;
  463. default: throw new Error( 'index is out of range: ' + index );
  464. }
  465. return this;
  466. }
  467. getComponent( index ) {
  468. switch ( index ) {
  469. case 0: return this.x;
  470. case 1: return this.y;
  471. default: throw new Error( 'index is out of range: ' + index );
  472. }
  473. }
  474. clone() {
  475. return new this.constructor( this.x, this.y );
  476. }
  477. copy( v ) {
  478. this.x = v.x;
  479. this.y = v.y;
  480. return this;
  481. }
  482. add( v ) {
  483. this.x += v.x;
  484. this.y += v.y;
  485. return this;
  486. }
  487. addScalar( s ) {
  488. this.x += s;
  489. this.y += s;
  490. return this;
  491. }
  492. addVectors( a, b ) {
  493. this.x = a.x + b.x;
  494. this.y = a.y + b.y;
  495. return this;
  496. }
  497. addScaledVector( v, s ) {
  498. this.x += v.x * s;
  499. this.y += v.y * s;
  500. return this;
  501. }
  502. sub( v ) {
  503. this.x -= v.x;
  504. this.y -= v.y;
  505. return this;
  506. }
  507. subScalar( s ) {
  508. this.x -= s;
  509. this.y -= s;
  510. return this;
  511. }
  512. subVectors( a, b ) {
  513. this.x = a.x - b.x;
  514. this.y = a.y - b.y;
  515. return this;
  516. }
  517. multiply( v ) {
  518. this.x *= v.x;
  519. this.y *= v.y;
  520. return this;
  521. }
  522. multiplyScalar( scalar ) {
  523. this.x *= scalar;
  524. this.y *= scalar;
  525. return this;
  526. }
  527. divide( v ) {
  528. this.x /= v.x;
  529. this.y /= v.y;
  530. return this;
  531. }
  532. divideScalar( scalar ) {
  533. return this.multiplyScalar( 1 / scalar );
  534. }
  535. applyMatrix3( m ) {
  536. const x = this.x, y = this.y;
  537. const e = m.elements;
  538. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  539. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  540. return this;
  541. }
  542. min( v ) {
  543. this.x = Math.min( this.x, v.x );
  544. this.y = Math.min( this.y, v.y );
  545. return this;
  546. }
  547. max( v ) {
  548. this.x = Math.max( this.x, v.x );
  549. this.y = Math.max( this.y, v.y );
  550. return this;
  551. }
  552. clamp( min, max ) {
  553. // assumes min < max, componentwise
  554. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  555. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  556. return this;
  557. }
  558. clampScalar( minVal, maxVal ) {
  559. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  560. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  561. return this;
  562. }
  563. clampLength( min, max ) {
  564. const length = this.length();
  565. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  566. }
  567. floor() {
  568. this.x = Math.floor( this.x );
  569. this.y = Math.floor( this.y );
  570. return this;
  571. }
  572. ceil() {
  573. this.x = Math.ceil( this.x );
  574. this.y = Math.ceil( this.y );
  575. return this;
  576. }
  577. round() {
  578. this.x = Math.round( this.x );
  579. this.y = Math.round( this.y );
  580. return this;
  581. }
  582. roundToZero() {
  583. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  584. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  585. return this;
  586. }
  587. negate() {
  588. this.x = - this.x;
  589. this.y = - this.y;
  590. return this;
  591. }
  592. dot( v ) {
  593. return this.x * v.x + this.y * v.y;
  594. }
  595. cross( v ) {
  596. return this.x * v.y - this.y * v.x;
  597. }
  598. lengthSq() {
  599. return this.x * this.x + this.y * this.y;
  600. }
  601. length() {
  602. return Math.sqrt( this.x * this.x + this.y * this.y );
  603. }
  604. manhattanLength() {
  605. return Math.abs( this.x ) + Math.abs( this.y );
  606. }
  607. normalize() {
  608. return this.divideScalar( this.length() || 1 );
  609. }
  610. angle() {
  611. // computes the angle in radians with respect to the positive x-axis
  612. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  613. return angle;
  614. }
  615. distanceTo( v ) {
  616. return Math.sqrt( this.distanceToSquared( v ) );
  617. }
  618. distanceToSquared( v ) {
  619. const dx = this.x - v.x, dy = this.y - v.y;
  620. return dx * dx + dy * dy;
  621. }
  622. manhattanDistanceTo( v ) {
  623. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  624. }
  625. setLength( length ) {
  626. return this.normalize().multiplyScalar( length );
  627. }
  628. lerp( v, alpha ) {
  629. this.x += ( v.x - this.x ) * alpha;
  630. this.y += ( v.y - this.y ) * alpha;
  631. return this;
  632. }
  633. lerpVectors( v1, v2, alpha ) {
  634. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  635. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  636. return this;
  637. }
  638. equals( v ) {
  639. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  640. }
  641. fromArray( array, offset = 0 ) {
  642. this.x = array[ offset ];
  643. this.y = array[ offset + 1 ];
  644. return this;
  645. }
  646. toArray( array = [], offset = 0 ) {
  647. array[ offset ] = this.x;
  648. array[ offset + 1 ] = this.y;
  649. return array;
  650. }
  651. fromBufferAttribute( attribute, index ) {
  652. this.x = attribute.getX( index );
  653. this.y = attribute.getY( index );
  654. return this;
  655. }
  656. rotateAround( center, angle ) {
  657. const c = Math.cos( angle ), s = Math.sin( angle );
  658. const x = this.x - center.x;
  659. const y = this.y - center.y;
  660. this.x = x * c - y * s + center.x;
  661. this.y = x * s + y * c + center.y;
  662. return this;
  663. }
  664. random() {
  665. this.x = Math.random();
  666. this.y = Math.random();
  667. return this;
  668. }
  669. *[ Symbol.iterator ]() {
  670. yield this.x;
  671. yield this.y;
  672. }
  673. }
  674. class Matrix3 {
  675. constructor() {
  676. Matrix3.prototype.isMatrix3 = true;
  677. this.elements = [
  678. 1, 0, 0,
  679. 0, 1, 0,
  680. 0, 0, 1
  681. ];
  682. }
  683. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  684. const te = this.elements;
  685. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  686. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  687. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  688. return this;
  689. }
  690. identity() {
  691. this.set(
  692. 1, 0, 0,
  693. 0, 1, 0,
  694. 0, 0, 1
  695. );
  696. return this;
  697. }
  698. copy( m ) {
  699. const te = this.elements;
  700. const me = m.elements;
  701. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  702. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  703. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  704. return this;
  705. }
  706. extractBasis( xAxis, yAxis, zAxis ) {
  707. xAxis.setFromMatrix3Column( this, 0 );
  708. yAxis.setFromMatrix3Column( this, 1 );
  709. zAxis.setFromMatrix3Column( this, 2 );
  710. return this;
  711. }
  712. setFromMatrix4( m ) {
  713. const me = m.elements;
  714. this.set(
  715. me[ 0 ], me[ 4 ], me[ 8 ],
  716. me[ 1 ], me[ 5 ], me[ 9 ],
  717. me[ 2 ], me[ 6 ], me[ 10 ]
  718. );
  719. return this;
  720. }
  721. multiply( m ) {
  722. return this.multiplyMatrices( this, m );
  723. }
  724. premultiply( m ) {
  725. return this.multiplyMatrices( m, this );
  726. }
  727. multiplyMatrices( a, b ) {
  728. const ae = a.elements;
  729. const be = b.elements;
  730. const te = this.elements;
  731. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  732. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  733. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  734. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  735. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  736. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  737. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  738. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  739. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  740. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  741. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  742. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  743. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  744. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  745. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  746. return this;
  747. }
  748. multiplyScalar( s ) {
  749. const te = this.elements;
  750. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  751. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  752. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  753. return this;
  754. }
  755. determinant() {
  756. const te = this.elements;
  757. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  758. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  759. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  760. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  761. }
  762. invert() {
  763. const te = this.elements,
  764. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  765. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  766. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  767. t11 = n33 * n22 - n32 * n23,
  768. t12 = n32 * n13 - n33 * n12,
  769. t13 = n23 * n12 - n22 * n13,
  770. det = n11 * t11 + n21 * t12 + n31 * t13;
  771. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  772. const detInv = 1 / det;
  773. te[ 0 ] = t11 * detInv;
  774. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  775. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  776. te[ 3 ] = t12 * detInv;
  777. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  778. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  779. te[ 6 ] = t13 * detInv;
  780. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  781. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  782. return this;
  783. }
  784. transpose() {
  785. let tmp;
  786. const m = this.elements;
  787. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  788. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  789. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  790. return this;
  791. }
  792. getNormalMatrix( matrix4 ) {
  793. return this.setFromMatrix4( matrix4 ).invert().transpose();
  794. }
  795. transposeIntoArray( r ) {
  796. const m = this.elements;
  797. r[ 0 ] = m[ 0 ];
  798. r[ 1 ] = m[ 3 ];
  799. r[ 2 ] = m[ 6 ];
  800. r[ 3 ] = m[ 1 ];
  801. r[ 4 ] = m[ 4 ];
  802. r[ 5 ] = m[ 7 ];
  803. r[ 6 ] = m[ 2 ];
  804. r[ 7 ] = m[ 5 ];
  805. r[ 8 ] = m[ 8 ];
  806. return this;
  807. }
  808. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  809. const c = Math.cos( rotation );
  810. const s = Math.sin( rotation );
  811. this.set(
  812. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  813. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  814. 0, 0, 1
  815. );
  816. return this;
  817. }
  818. //
  819. scale( sx, sy ) {
  820. this.premultiply( _m3.makeScale( sx, sy ) );
  821. return this;
  822. }
  823. rotate( theta ) {
  824. this.premultiply( _m3.makeRotation( - theta ) );
  825. return this;
  826. }
  827. translate( tx, ty ) {
  828. this.premultiply( _m3.makeTranslation( tx, ty ) );
  829. return this;
  830. }
  831. // for 2D Transforms
  832. makeTranslation( x, y ) {
  833. this.set(
  834. 1, 0, x,
  835. 0, 1, y,
  836. 0, 0, 1
  837. );
  838. return this;
  839. }
  840. makeRotation( theta ) {
  841. // counterclockwise
  842. const c = Math.cos( theta );
  843. const s = Math.sin( theta );
  844. this.set(
  845. c, - s, 0,
  846. s, c, 0,
  847. 0, 0, 1
  848. );
  849. return this;
  850. }
  851. makeScale( x, y ) {
  852. this.set(
  853. x, 0, 0,
  854. 0, y, 0,
  855. 0, 0, 1
  856. );
  857. return this;
  858. }
  859. //
  860. equals( matrix ) {
  861. const te = this.elements;
  862. const me = matrix.elements;
  863. for ( let i = 0; i < 9; i ++ ) {
  864. if ( te[ i ] !== me[ i ] ) return false;
  865. }
  866. return true;
  867. }
  868. fromArray( array, offset = 0 ) {
  869. for ( let i = 0; i < 9; i ++ ) {
  870. this.elements[ i ] = array[ i + offset ];
  871. }
  872. return this;
  873. }
  874. toArray( array = [], offset = 0 ) {
  875. const te = this.elements;
  876. array[ offset ] = te[ 0 ];
  877. array[ offset + 1 ] = te[ 1 ];
  878. array[ offset + 2 ] = te[ 2 ];
  879. array[ offset + 3 ] = te[ 3 ];
  880. array[ offset + 4 ] = te[ 4 ];
  881. array[ offset + 5 ] = te[ 5 ];
  882. array[ offset + 6 ] = te[ 6 ];
  883. array[ offset + 7 ] = te[ 7 ];
  884. array[ offset + 8 ] = te[ 8 ];
  885. return array;
  886. }
  887. clone() {
  888. return new this.constructor().fromArray( this.elements );
  889. }
  890. }
  891. const _m3 = /*@__PURE__*/ new Matrix3();
  892. function arrayNeedsUint32( array ) {
  893. // assumes larger values usually on last
  894. for ( let i = array.length - 1; i >= 0; -- i ) {
  895. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  896. }
  897. return false;
  898. }
  899. const TYPED_ARRAYS = {
  900. Int8Array: Int8Array,
  901. Uint8Array: Uint8Array,
  902. Uint8ClampedArray: Uint8ClampedArray,
  903. Int16Array: Int16Array,
  904. Uint16Array: Uint16Array,
  905. Int32Array: Int32Array,
  906. Uint32Array: Uint32Array,
  907. Float32Array: Float32Array,
  908. Float64Array: Float64Array
  909. };
  910. function getTypedArray( type, buffer ) {
  911. return new TYPED_ARRAYS[ type ]( buffer );
  912. }
  913. function createElementNS( name ) {
  914. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  915. }
  916. class Quaternion {
  917. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  918. this.isQuaternion = true;
  919. this._x = x;
  920. this._y = y;
  921. this._z = z;
  922. this._w = w;
  923. }
  924. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  925. // fuzz-free, array-based Quaternion SLERP operation
  926. let x0 = src0[ srcOffset0 + 0 ],
  927. y0 = src0[ srcOffset0 + 1 ],
  928. z0 = src0[ srcOffset0 + 2 ],
  929. w0 = src0[ srcOffset0 + 3 ];
  930. const x1 = src1[ srcOffset1 + 0 ],
  931. y1 = src1[ srcOffset1 + 1 ],
  932. z1 = src1[ srcOffset1 + 2 ],
  933. w1 = src1[ srcOffset1 + 3 ];
  934. if ( t === 0 ) {
  935. dst[ dstOffset + 0 ] = x0;
  936. dst[ dstOffset + 1 ] = y0;
  937. dst[ dstOffset + 2 ] = z0;
  938. dst[ dstOffset + 3 ] = w0;
  939. return;
  940. }
  941. if ( t === 1 ) {
  942. dst[ dstOffset + 0 ] = x1;
  943. dst[ dstOffset + 1 ] = y1;
  944. dst[ dstOffset + 2 ] = z1;
  945. dst[ dstOffset + 3 ] = w1;
  946. return;
  947. }
  948. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  949. let s = 1 - t;
  950. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  951. dir = ( cos >= 0 ? 1 : - 1 ),
  952. sqrSin = 1 - cos * cos;
  953. // Skip the Slerp for tiny steps to avoid numeric problems:
  954. if ( sqrSin > Number.EPSILON ) {
  955. const sin = Math.sqrt( sqrSin ),
  956. len = Math.atan2( sin, cos * dir );
  957. s = Math.sin( s * len ) / sin;
  958. t = Math.sin( t * len ) / sin;
  959. }
  960. const tDir = t * dir;
  961. x0 = x0 * s + x1 * tDir;
  962. y0 = y0 * s + y1 * tDir;
  963. z0 = z0 * s + z1 * tDir;
  964. w0 = w0 * s + w1 * tDir;
  965. // Normalize in case we just did a lerp:
  966. if ( s === 1 - t ) {
  967. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  968. x0 *= f;
  969. y0 *= f;
  970. z0 *= f;
  971. w0 *= f;
  972. }
  973. }
  974. dst[ dstOffset ] = x0;
  975. dst[ dstOffset + 1 ] = y0;
  976. dst[ dstOffset + 2 ] = z0;
  977. dst[ dstOffset + 3 ] = w0;
  978. }
  979. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  980. const x0 = src0[ srcOffset0 ];
  981. const y0 = src0[ srcOffset0 + 1 ];
  982. const z0 = src0[ srcOffset0 + 2 ];
  983. const w0 = src0[ srcOffset0 + 3 ];
  984. const x1 = src1[ srcOffset1 ];
  985. const y1 = src1[ srcOffset1 + 1 ];
  986. const z1 = src1[ srcOffset1 + 2 ];
  987. const w1 = src1[ srcOffset1 + 3 ];
  988. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  989. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  990. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  991. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  992. return dst;
  993. }
  994. get x() {
  995. return this._x;
  996. }
  997. set x( value ) {
  998. this._x = value;
  999. this._onChangeCallback();
  1000. }
  1001. get y() {
  1002. return this._y;
  1003. }
  1004. set y( value ) {
  1005. this._y = value;
  1006. this._onChangeCallback();
  1007. }
  1008. get z() {
  1009. return this._z;
  1010. }
  1011. set z( value ) {
  1012. this._z = value;
  1013. this._onChangeCallback();
  1014. }
  1015. get w() {
  1016. return this._w;
  1017. }
  1018. set w( value ) {
  1019. this._w = value;
  1020. this._onChangeCallback();
  1021. }
  1022. set( x, y, z, w ) {
  1023. this._x = x;
  1024. this._y = y;
  1025. this._z = z;
  1026. this._w = w;
  1027. this._onChangeCallback();
  1028. return this;
  1029. }
  1030. clone() {
  1031. return new this.constructor( this._x, this._y, this._z, this._w );
  1032. }
  1033. copy( quaternion ) {
  1034. this._x = quaternion.x;
  1035. this._y = quaternion.y;
  1036. this._z = quaternion.z;
  1037. this._w = quaternion.w;
  1038. this._onChangeCallback();
  1039. return this;
  1040. }
  1041. setFromEuler( euler, update ) {
  1042. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  1043. // http://www.mathworks.com/matlabcentral/fileexchange/
  1044. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1045. // content/SpinCalc.m
  1046. const cos = Math.cos;
  1047. const sin = Math.sin;
  1048. const c1 = cos( x / 2 );
  1049. const c2 = cos( y / 2 );
  1050. const c3 = cos( z / 2 );
  1051. const s1 = sin( x / 2 );
  1052. const s2 = sin( y / 2 );
  1053. const s3 = sin( z / 2 );
  1054. switch ( order ) {
  1055. case 'XYZ':
  1056. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1057. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1058. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1059. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1060. break;
  1061. case 'YXZ':
  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 'ZXY':
  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 'ZYX':
  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 'YZX':
  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 'XZY':
  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. default:
  1092. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  1093. }
  1094. if ( update !== false ) this._onChangeCallback();
  1095. return this;
  1096. }
  1097. setFromAxisAngle( axis, angle ) {
  1098. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1099. // assumes axis is normalized
  1100. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  1101. this._x = axis.x * s;
  1102. this._y = axis.y * s;
  1103. this._z = axis.z * s;
  1104. this._w = Math.cos( halfAngle );
  1105. this._onChangeCallback();
  1106. return this;
  1107. }
  1108. setFromRotationMatrix( m ) {
  1109. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1110. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1111. const te = m.elements,
  1112. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1113. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1114. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  1115. trace = m11 + m22 + m33;
  1116. if ( trace > 0 ) {
  1117. const s = 0.5 / Math.sqrt( trace + 1.0 );
  1118. this._w = 0.25 / s;
  1119. this._x = ( m32 - m23 ) * s;
  1120. this._y = ( m13 - m31 ) * s;
  1121. this._z = ( m21 - m12 ) * s;
  1122. } else if ( m11 > m22 && m11 > m33 ) {
  1123. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  1124. this._w = ( m32 - m23 ) / s;
  1125. this._x = 0.25 * s;
  1126. this._y = ( m12 + m21 ) / s;
  1127. this._z = ( m13 + m31 ) / s;
  1128. } else if ( m22 > m33 ) {
  1129. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  1130. this._w = ( m13 - m31 ) / s;
  1131. this._x = ( m12 + m21 ) / s;
  1132. this._y = 0.25 * s;
  1133. this._z = ( m23 + m32 ) / s;
  1134. } else {
  1135. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  1136. this._w = ( m21 - m12 ) / s;
  1137. this._x = ( m13 + m31 ) / s;
  1138. this._y = ( m23 + m32 ) / s;
  1139. this._z = 0.25 * s;
  1140. }
  1141. this._onChangeCallback();
  1142. return this;
  1143. }
  1144. setFromUnitVectors( vFrom, vTo ) {
  1145. // assumes direction vectors vFrom and vTo are normalized
  1146. let r = vFrom.dot( vTo ) + 1;
  1147. if ( r < Number.EPSILON ) {
  1148. // vFrom and vTo point in opposite directions
  1149. r = 0;
  1150. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  1151. this._x = - vFrom.y;
  1152. this._y = vFrom.x;
  1153. this._z = 0;
  1154. this._w = r;
  1155. } else {
  1156. this._x = 0;
  1157. this._y = - vFrom.z;
  1158. this._z = vFrom.y;
  1159. this._w = r;
  1160. }
  1161. } else {
  1162. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  1163. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  1164. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  1165. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  1166. this._w = r;
  1167. }
  1168. return this.normalize();
  1169. }
  1170. angleTo( q ) {
  1171. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  1172. }
  1173. rotateTowards( q, step ) {
  1174. const angle = this.angleTo( q );
  1175. if ( angle === 0 ) return this;
  1176. const t = Math.min( 1, step / angle );
  1177. this.slerp( q, t );
  1178. return this;
  1179. }
  1180. identity() {
  1181. return this.set( 0, 0, 0, 1 );
  1182. }
  1183. invert() {
  1184. // quaternion is assumed to have unit length
  1185. return this.conjugate();
  1186. }
  1187. conjugate() {
  1188. this._x *= - 1;
  1189. this._y *= - 1;
  1190. this._z *= - 1;
  1191. this._onChangeCallback();
  1192. return this;
  1193. }
  1194. dot( v ) {
  1195. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1196. }
  1197. lengthSq() {
  1198. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1199. }
  1200. length() {
  1201. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  1202. }
  1203. normalize() {
  1204. let l = this.length();
  1205. if ( l === 0 ) {
  1206. this._x = 0;
  1207. this._y = 0;
  1208. this._z = 0;
  1209. this._w = 1;
  1210. } else {
  1211. l = 1 / l;
  1212. this._x = this._x * l;
  1213. this._y = this._y * l;
  1214. this._z = this._z * l;
  1215. this._w = this._w * l;
  1216. }
  1217. this._onChangeCallback();
  1218. return this;
  1219. }
  1220. multiply( q ) {
  1221. return this.multiplyQuaternions( this, q );
  1222. }
  1223. premultiply( q ) {
  1224. return this.multiplyQuaternions( q, this );
  1225. }
  1226. multiplyQuaternions( a, b ) {
  1227. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  1228. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  1229. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  1230. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  1231. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  1232. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  1233. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  1234. this._onChangeCallback();
  1235. return this;
  1236. }
  1237. slerp( qb, t ) {
  1238. if ( t === 0 ) return this;
  1239. if ( t === 1 ) return this.copy( qb );
  1240. const x = this._x, y = this._y, z = this._z, w = this._w;
  1241. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  1242. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  1243. if ( cosHalfTheta < 0 ) {
  1244. this._w = - qb._w;
  1245. this._x = - qb._x;
  1246. this._y = - qb._y;
  1247. this._z = - qb._z;
  1248. cosHalfTheta = - cosHalfTheta;
  1249. } else {
  1250. this.copy( qb );
  1251. }
  1252. if ( cosHalfTheta >= 1.0 ) {
  1253. this._w = w;
  1254. this._x = x;
  1255. this._y = y;
  1256. this._z = z;
  1257. return this;
  1258. }
  1259. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  1260. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  1261. const s = 1 - t;
  1262. this._w = s * w + t * this._w;
  1263. this._x = s * x + t * this._x;
  1264. this._y = s * y + t * this._y;
  1265. this._z = s * z + t * this._z;
  1266. this.normalize();
  1267. this._onChangeCallback();
  1268. return this;
  1269. }
  1270. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  1271. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  1272. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  1273. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  1274. this._w = ( w * ratioA + this._w * ratioB );
  1275. this._x = ( x * ratioA + this._x * ratioB );
  1276. this._y = ( y * ratioA + this._y * ratioB );
  1277. this._z = ( z * ratioA + this._z * ratioB );
  1278. this._onChangeCallback();
  1279. return this;
  1280. }
  1281. slerpQuaternions( qa, qb, t ) {
  1282. return this.copy( qa ).slerp( qb, t );
  1283. }
  1284. random() {
  1285. // Derived from http://planning.cs.uiuc.edu/node198.html
  1286. // Note, this source uses w, x, y, z ordering,
  1287. // so we swap the order below.
  1288. const u1 = Math.random();
  1289. const sqrt1u1 = Math.sqrt( 1 - u1 );
  1290. const sqrtu1 = Math.sqrt( u1 );
  1291. const u2 = 2 * Math.PI * Math.random();
  1292. const u3 = 2 * Math.PI * Math.random();
  1293. return this.set(
  1294. sqrt1u1 * Math.cos( u2 ),
  1295. sqrtu1 * Math.sin( u3 ),
  1296. sqrtu1 * Math.cos( u3 ),
  1297. sqrt1u1 * Math.sin( u2 ),
  1298. );
  1299. }
  1300. equals( quaternion ) {
  1301. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  1302. }
  1303. fromArray( array, offset = 0 ) {
  1304. this._x = array[ offset ];
  1305. this._y = array[ offset + 1 ];
  1306. this._z = array[ offset + 2 ];
  1307. this._w = array[ offset + 3 ];
  1308. this._onChangeCallback();
  1309. return this;
  1310. }
  1311. toArray( array = [], offset = 0 ) {
  1312. array[ offset ] = this._x;
  1313. array[ offset + 1 ] = this._y;
  1314. array[ offset + 2 ] = this._z;
  1315. array[ offset + 3 ] = this._w;
  1316. return array;
  1317. }
  1318. fromBufferAttribute( attribute, index ) {
  1319. this._x = attribute.getX( index );
  1320. this._y = attribute.getY( index );
  1321. this._z = attribute.getZ( index );
  1322. this._w = attribute.getW( index );
  1323. return this;
  1324. }
  1325. _onChange( callback ) {
  1326. this._onChangeCallback = callback;
  1327. return this;
  1328. }
  1329. _onChangeCallback() {}
  1330. *[ Symbol.iterator ]() {
  1331. yield this._x;
  1332. yield this._y;
  1333. yield this._z;
  1334. yield this._w;
  1335. }
  1336. }
  1337. class Vector3 {
  1338. constructor( x = 0, y = 0, z = 0 ) {
  1339. Vector3.prototype.isVector3 = true;
  1340. this.x = x;
  1341. this.y = y;
  1342. this.z = z;
  1343. }
  1344. set( x, y, z ) {
  1345. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  1346. this.x = x;
  1347. this.y = y;
  1348. this.z = z;
  1349. return this;
  1350. }
  1351. setScalar( scalar ) {
  1352. this.x = scalar;
  1353. this.y = scalar;
  1354. this.z = scalar;
  1355. return this;
  1356. }
  1357. setX( x ) {
  1358. this.x = x;
  1359. return this;
  1360. }
  1361. setY( y ) {
  1362. this.y = y;
  1363. return this;
  1364. }
  1365. setZ( z ) {
  1366. this.z = z;
  1367. return this;
  1368. }
  1369. setComponent( index, value ) {
  1370. switch ( index ) {
  1371. case 0: this.x = value; break;
  1372. case 1: this.y = value; break;
  1373. case 2: this.z = value; break;
  1374. default: throw new Error( 'index is out of range: ' + index );
  1375. }
  1376. return this;
  1377. }
  1378. getComponent( index ) {
  1379. switch ( index ) {
  1380. case 0: return this.x;
  1381. case 1: return this.y;
  1382. case 2: return this.z;
  1383. default: throw new Error( 'index is out of range: ' + index );
  1384. }
  1385. }
  1386. clone() {
  1387. return new this.constructor( this.x, this.y, this.z );
  1388. }
  1389. copy( v ) {
  1390. this.x = v.x;
  1391. this.y = v.y;
  1392. this.z = v.z;
  1393. return this;
  1394. }
  1395. add( v ) {
  1396. this.x += v.x;
  1397. this.y += v.y;
  1398. this.z += v.z;
  1399. return this;
  1400. }
  1401. addScalar( s ) {
  1402. this.x += s;
  1403. this.y += s;
  1404. this.z += s;
  1405. return this;
  1406. }
  1407. addVectors( a, b ) {
  1408. this.x = a.x + b.x;
  1409. this.y = a.y + b.y;
  1410. this.z = a.z + b.z;
  1411. return this;
  1412. }
  1413. addScaledVector( v, s ) {
  1414. this.x += v.x * s;
  1415. this.y += v.y * s;
  1416. this.z += v.z * s;
  1417. return this;
  1418. }
  1419. sub( v ) {
  1420. this.x -= v.x;
  1421. this.y -= v.y;
  1422. this.z -= v.z;
  1423. return this;
  1424. }
  1425. subScalar( s ) {
  1426. this.x -= s;
  1427. this.y -= s;
  1428. this.z -= s;
  1429. return this;
  1430. }
  1431. subVectors( a, b ) {
  1432. this.x = a.x - b.x;
  1433. this.y = a.y - b.y;
  1434. this.z = a.z - b.z;
  1435. return this;
  1436. }
  1437. multiply( v ) {
  1438. this.x *= v.x;
  1439. this.y *= v.y;
  1440. this.z *= v.z;
  1441. return this;
  1442. }
  1443. multiplyScalar( scalar ) {
  1444. this.x *= scalar;
  1445. this.y *= scalar;
  1446. this.z *= scalar;
  1447. return this;
  1448. }
  1449. multiplyVectors( a, b ) {
  1450. this.x = a.x * b.x;
  1451. this.y = a.y * b.y;
  1452. this.z = a.z * b.z;
  1453. return this;
  1454. }
  1455. applyEuler( euler ) {
  1456. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  1457. }
  1458. applyAxisAngle( axis, angle ) {
  1459. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  1460. }
  1461. applyMatrix3( m ) {
  1462. const x = this.x, y = this.y, z = this.z;
  1463. const e = m.elements;
  1464. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1465. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1466. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1467. return this;
  1468. }
  1469. applyNormalMatrix( m ) {
  1470. return this.applyMatrix3( m ).normalize();
  1471. }
  1472. applyMatrix4( m ) {
  1473. const x = this.x, y = this.y, z = this.z;
  1474. const e = m.elements;
  1475. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  1476. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  1477. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  1478. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  1479. return this;
  1480. }
  1481. applyQuaternion( q ) {
  1482. const x = this.x, y = this.y, z = this.z;
  1483. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  1484. // calculate quat * vector
  1485. const ix = qw * x + qy * z - qz * y;
  1486. const iy = qw * y + qz * x - qx * z;
  1487. const iz = qw * z + qx * y - qy * x;
  1488. const iw = - qx * x - qy * y - qz * z;
  1489. // calculate result * inverse quat
  1490. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1491. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1492. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1493. return this;
  1494. }
  1495. project( camera ) {
  1496. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  1497. }
  1498. unproject( camera ) {
  1499. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  1500. }
  1501. transformDirection( m ) {
  1502. // input: THREE.Matrix4 affine matrix
  1503. // vector interpreted as a direction
  1504. const x = this.x, y = this.y, z = this.z;
  1505. const e = m.elements;
  1506. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1507. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1508. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1509. return this.normalize();
  1510. }
  1511. divide( v ) {
  1512. this.x /= v.x;
  1513. this.y /= v.y;
  1514. this.z /= v.z;
  1515. return this;
  1516. }
  1517. divideScalar( scalar ) {
  1518. return this.multiplyScalar( 1 / scalar );
  1519. }
  1520. min( v ) {
  1521. this.x = Math.min( this.x, v.x );
  1522. this.y = Math.min( this.y, v.y );
  1523. this.z = Math.min( this.z, v.z );
  1524. return this;
  1525. }
  1526. max( v ) {
  1527. this.x = Math.max( this.x, v.x );
  1528. this.y = Math.max( this.y, v.y );
  1529. this.z = Math.max( this.z, v.z );
  1530. return this;
  1531. }
  1532. clamp( min, max ) {
  1533. // assumes min < max, componentwise
  1534. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1535. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1536. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1537. return this;
  1538. }
  1539. clampScalar( minVal, maxVal ) {
  1540. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1541. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1542. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1543. return this;
  1544. }
  1545. clampLength( min, max ) {
  1546. const length = this.length();
  1547. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1548. }
  1549. floor() {
  1550. this.x = Math.floor( this.x );
  1551. this.y = Math.floor( this.y );
  1552. this.z = Math.floor( this.z );
  1553. return this;
  1554. }
  1555. ceil() {
  1556. this.x = Math.ceil( this.x );
  1557. this.y = Math.ceil( this.y );
  1558. this.z = Math.ceil( this.z );
  1559. return this;
  1560. }
  1561. round() {
  1562. this.x = Math.round( this.x );
  1563. this.y = Math.round( this.y );
  1564. this.z = Math.round( this.z );
  1565. return this;
  1566. }
  1567. roundToZero() {
  1568. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1569. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1570. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1571. return this;
  1572. }
  1573. negate() {
  1574. this.x = - this.x;
  1575. this.y = - this.y;
  1576. this.z = - this.z;
  1577. return this;
  1578. }
  1579. dot( v ) {
  1580. return this.x * v.x + this.y * v.y + this.z * v.z;
  1581. }
  1582. // TODO lengthSquared?
  1583. lengthSq() {
  1584. return this.x * this.x + this.y * this.y + this.z * this.z;
  1585. }
  1586. length() {
  1587. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1588. }
  1589. manhattanLength() {
  1590. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1591. }
  1592. normalize() {
  1593. return this.divideScalar( this.length() || 1 );
  1594. }
  1595. setLength( length ) {
  1596. return this.normalize().multiplyScalar( length );
  1597. }
  1598. lerp( v, alpha ) {
  1599. this.x += ( v.x - this.x ) * alpha;
  1600. this.y += ( v.y - this.y ) * alpha;
  1601. this.z += ( v.z - this.z ) * alpha;
  1602. return this;
  1603. }
  1604. lerpVectors( v1, v2, alpha ) {
  1605. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1606. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1607. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1608. return this;
  1609. }
  1610. cross( v ) {
  1611. return this.crossVectors( this, v );
  1612. }
  1613. crossVectors( a, b ) {
  1614. const ax = a.x, ay = a.y, az = a.z;
  1615. const bx = b.x, by = b.y, bz = b.z;
  1616. this.x = ay * bz - az * by;
  1617. this.y = az * bx - ax * bz;
  1618. this.z = ax * by - ay * bx;
  1619. return this;
  1620. }
  1621. projectOnVector( v ) {
  1622. const denominator = v.lengthSq();
  1623. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  1624. const scalar = v.dot( this ) / denominator;
  1625. return this.copy( v ).multiplyScalar( scalar );
  1626. }
  1627. projectOnPlane( planeNormal ) {
  1628. _vector$d.copy( this ).projectOnVector( planeNormal );
  1629. return this.sub( _vector$d );
  1630. }
  1631. reflect( normal ) {
  1632. // reflect incident vector off plane orthogonal to normal
  1633. // normal is assumed to have unit length
  1634. return this.sub( _vector$d.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1635. }
  1636. angleTo( v ) {
  1637. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  1638. if ( denominator === 0 ) return Math.PI / 2;
  1639. const theta = this.dot( v ) / denominator;
  1640. // clamp, to handle numerical problems
  1641. return Math.acos( clamp( theta, - 1, 1 ) );
  1642. }
  1643. distanceTo( v ) {
  1644. return Math.sqrt( this.distanceToSquared( v ) );
  1645. }
  1646. distanceToSquared( v ) {
  1647. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  1648. return dx * dx + dy * dy + dz * dz;
  1649. }
  1650. manhattanDistanceTo( v ) {
  1651. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  1652. }
  1653. setFromSpherical( s ) {
  1654. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  1655. }
  1656. setFromSphericalCoords( radius, phi, theta ) {
  1657. const sinPhiRadius = Math.sin( phi ) * radius;
  1658. this.x = sinPhiRadius * Math.sin( theta );
  1659. this.y = Math.cos( phi ) * radius;
  1660. this.z = sinPhiRadius * Math.cos( theta );
  1661. return this;
  1662. }
  1663. setFromCylindrical( c ) {
  1664. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  1665. }
  1666. setFromCylindricalCoords( radius, theta, y ) {
  1667. this.x = radius * Math.sin( theta );
  1668. this.y = y;
  1669. this.z = radius * Math.cos( theta );
  1670. return this;
  1671. }
  1672. setFromMatrixPosition( m ) {
  1673. const e = m.elements;
  1674. this.x = e[ 12 ];
  1675. this.y = e[ 13 ];
  1676. this.z = e[ 14 ];
  1677. return this;
  1678. }
  1679. setFromMatrixScale( m ) {
  1680. const sx = this.setFromMatrixColumn( m, 0 ).length();
  1681. const sy = this.setFromMatrixColumn( m, 1 ).length();
  1682. const sz = this.setFromMatrixColumn( m, 2 ).length();
  1683. this.x = sx;
  1684. this.y = sy;
  1685. this.z = sz;
  1686. return this;
  1687. }
  1688. setFromMatrixColumn( m, index ) {
  1689. return this.fromArray( m.elements, index * 4 );
  1690. }
  1691. setFromMatrix3Column( m, index ) {
  1692. return this.fromArray( m.elements, index * 3 );
  1693. }
  1694. setFromEuler( e ) {
  1695. this.x = e._x;
  1696. this.y = e._y;
  1697. this.z = e._z;
  1698. return this;
  1699. }
  1700. equals( v ) {
  1701. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1702. }
  1703. fromArray( array, offset = 0 ) {
  1704. this.x = array[ offset ];
  1705. this.y = array[ offset + 1 ];
  1706. this.z = array[ offset + 2 ];
  1707. return this;
  1708. }
  1709. toArray( array = [], offset = 0 ) {
  1710. array[ offset ] = this.x;
  1711. array[ offset + 1 ] = this.y;
  1712. array[ offset + 2 ] = this.z;
  1713. return array;
  1714. }
  1715. fromBufferAttribute( attribute, index ) {
  1716. this.x = attribute.getX( index );
  1717. this.y = attribute.getY( index );
  1718. this.z = attribute.getZ( index );
  1719. return this;
  1720. }
  1721. random() {
  1722. this.x = Math.random();
  1723. this.y = Math.random();
  1724. this.z = Math.random();
  1725. return this;
  1726. }
  1727. randomDirection() {
  1728. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  1729. const u = ( Math.random() - 0.5 ) * 2;
  1730. const t = Math.random() * Math.PI * 2;
  1731. const f = Math.sqrt( 1 - u ** 2 );
  1732. this.x = f * Math.cos( t );
  1733. this.y = f * Math.sin( t );
  1734. this.z = u;
  1735. return this;
  1736. }
  1737. *[ Symbol.iterator ]() {
  1738. yield this.x;
  1739. yield this.y;
  1740. yield this.z;
  1741. }
  1742. }
  1743. const _vector$d = /*@__PURE__*/ new Vector3();
  1744. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  1745. function SRGBToLinear( c ) {
  1746. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  1747. }
  1748. function LinearToSRGB( c ) {
  1749. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  1750. }
  1751. /**
  1752. * Matrices converting P3 <-> Rec. 709 primaries, without gamut mapping
  1753. * or clipping. Based on W3C specifications for sRGB and Display P3,
  1754. * and ICC specifications for the D50 connection space. Values in/out
  1755. * are _linear_ sRGB and _linear_ Display P3.
  1756. *
  1757. * Note that both sRGB and Display P3 use the sRGB transfer functions.
  1758. *
  1759. * Reference:
  1760. * - http://www.russellcottrell.com/photo/matrixCalculator.htm
  1761. */
  1762. const LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = new Matrix3().fromArray( [
  1763. 0.8224621, 0.0331941, 0.0170827,
  1764. 0.1775380, 0.9668058, 0.0723974,
  1765. - 0.0000001, 0.0000001, 0.9105199
  1766. ] );
  1767. const LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = new Matrix3().fromArray( [
  1768. 1.2249401, - 0.0420569, - 0.0196376,
  1769. - 0.2249404, 1.0420571, - 0.0786361,
  1770. 0.0000001, 0.0000000, 1.0982735
  1771. ] );
  1772. const _vector$c = new Vector3();
  1773. function DisplayP3ToLinearSRGB( color ) {
  1774. color.convertSRGBToLinear();
  1775. _vector$c.set( color.r, color.g, color.b ).applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB );
  1776. return color.setRGB( _vector$c.x, _vector$c.y, _vector$c.z );
  1777. }
  1778. function LinearSRGBToDisplayP3( color ) {
  1779. _vector$c.set( color.r, color.g, color.b ).applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 );
  1780. return color.setRGB( _vector$c.x, _vector$c.y, _vector$c.z ).convertLinearToSRGB();
  1781. }
  1782. // Conversions from <source> to Linear-sRGB reference space.
  1783. const TO_LINEAR = {
  1784. [ LinearSRGBColorSpace ]: ( color ) => color,
  1785. [ SRGBColorSpace ]: ( color ) => color.convertSRGBToLinear(),
  1786. [ DisplayP3ColorSpace ]: DisplayP3ToLinearSRGB,
  1787. };
  1788. // Conversions to <target> from Linear-sRGB reference space.
  1789. const FROM_LINEAR = {
  1790. [ LinearSRGBColorSpace ]: ( color ) => color,
  1791. [ SRGBColorSpace ]: ( color ) => color.convertLinearToSRGB(),
  1792. [ DisplayP3ColorSpace ]: LinearSRGBToDisplayP3,
  1793. };
  1794. const ColorManagement = {
  1795. enabled: false,
  1796. get legacyMode() {
  1797. console.warn( 'THREE.ColorManagement: .legacyMode=false renamed to .enabled=true in r150.' );
  1798. return ! this.enabled;
  1799. },
  1800. set legacyMode( legacyMode ) {
  1801. console.warn( 'THREE.ColorManagement: .legacyMode=false renamed to .enabled=true in r150.' );
  1802. this.enabled = ! legacyMode;
  1803. },
  1804. get workingColorSpace() {
  1805. return LinearSRGBColorSpace;
  1806. },
  1807. set workingColorSpace( colorSpace ) {
  1808. console.warn( 'THREE.ColorManagement: .workingColorSpace is readonly.' );
  1809. },
  1810. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  1811. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  1812. return color;
  1813. }
  1814. const sourceToLinear = TO_LINEAR[ sourceColorSpace ];
  1815. const targetFromLinear = FROM_LINEAR[ targetColorSpace ];
  1816. if ( sourceToLinear === undefined || targetFromLinear === undefined ) {
  1817. throw new Error( `Unsupported color space conversion, "${ sourceColorSpace }" to "${ targetColorSpace }".` );
  1818. }
  1819. return targetFromLinear( sourceToLinear( color ) );
  1820. },
  1821. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1822. return this.convert( color, this.workingColorSpace, targetColorSpace );
  1823. },
  1824. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1825. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  1826. },
  1827. };
  1828. let _canvas;
  1829. class ImageUtils {
  1830. static getDataURL( image ) {
  1831. if ( /^data:/i.test( image.src ) ) {
  1832. return image.src;
  1833. }
  1834. if ( typeof HTMLCanvasElement == 'undefined' ) {
  1835. return image.src;
  1836. }
  1837. let canvas;
  1838. if ( image instanceof HTMLCanvasElement ) {
  1839. canvas = image;
  1840. } else {
  1841. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1842. _canvas.width = image.width;
  1843. _canvas.height = image.height;
  1844. const context = _canvas.getContext( '2d' );
  1845. if ( image instanceof ImageData ) {
  1846. context.putImageData( image, 0, 0 );
  1847. } else {
  1848. context.drawImage( image, 0, 0, image.width, image.height );
  1849. }
  1850. canvas = _canvas;
  1851. }
  1852. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1853. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1854. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1855. } else {
  1856. return canvas.toDataURL( 'image/png' );
  1857. }
  1858. }
  1859. static sRGBToLinear( image ) {
  1860. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1861. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1862. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1863. const canvas = createElementNS( 'canvas' );
  1864. canvas.width = image.width;
  1865. canvas.height = image.height;
  1866. const context = canvas.getContext( '2d' );
  1867. context.drawImage( image, 0, 0, image.width, image.height );
  1868. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1869. const data = imageData.data;
  1870. for ( let i = 0; i < data.length; i ++ ) {
  1871. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1872. }
  1873. context.putImageData( imageData, 0, 0 );
  1874. return canvas;
  1875. } else if ( image.data ) {
  1876. const data = image.data.slice( 0 );
  1877. for ( let i = 0; i < data.length; i ++ ) {
  1878. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1879. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1880. } else {
  1881. // assuming float
  1882. data[ i ] = SRGBToLinear( data[ i ] );
  1883. }
  1884. }
  1885. return {
  1886. data: data,
  1887. width: image.width,
  1888. height: image.height
  1889. };
  1890. } else {
  1891. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1892. return image;
  1893. }
  1894. }
  1895. }
  1896. class Source {
  1897. constructor( data = null ) {
  1898. this.isSource = true;
  1899. this.uuid = generateUUID();
  1900. this.data = data;
  1901. this.version = 0;
  1902. }
  1903. set needsUpdate( value ) {
  1904. if ( value === true ) this.version ++;
  1905. }
  1906. toJSON( meta ) {
  1907. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1908. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1909. return meta.images[ this.uuid ];
  1910. }
  1911. const output = {
  1912. uuid: this.uuid,
  1913. url: ''
  1914. };
  1915. const data = this.data;
  1916. if ( data !== null ) {
  1917. let url;
  1918. if ( Array.isArray( data ) ) {
  1919. // cube texture
  1920. url = [];
  1921. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1922. if ( data[ i ].isDataTexture ) {
  1923. url.push( serializeImage( data[ i ].image ) );
  1924. } else {
  1925. url.push( serializeImage( data[ i ] ) );
  1926. }
  1927. }
  1928. } else {
  1929. // texture
  1930. url = serializeImage( data );
  1931. }
  1932. output.url = url;
  1933. }
  1934. if ( ! isRootObject ) {
  1935. meta.images[ this.uuid ] = output;
  1936. }
  1937. return output;
  1938. }
  1939. }
  1940. function serializeImage( image ) {
  1941. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1942. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1943. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1944. // default images
  1945. return ImageUtils.getDataURL( image );
  1946. } else {
  1947. if ( image.data ) {
  1948. // images of DataTexture
  1949. return {
  1950. data: Array.from( image.data ),
  1951. width: image.width,
  1952. height: image.height,
  1953. type: image.data.constructor.name
  1954. };
  1955. } else {
  1956. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1957. return {};
  1958. }
  1959. }
  1960. }
  1961. let textureId = 0;
  1962. class Texture extends EventDispatcher {
  1963. 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 ) {
  1964. super();
  1965. this.isTexture = true;
  1966. Object.defineProperty( this, 'id', { value: textureId ++ } );
  1967. this.uuid = generateUUID();
  1968. this.name = '';
  1969. this.source = new Source( image );
  1970. this.mipmaps = [];
  1971. this.mapping = mapping;
  1972. this.wrapS = wrapS;
  1973. this.wrapT = wrapT;
  1974. this.magFilter = magFilter;
  1975. this.minFilter = minFilter;
  1976. this.anisotropy = anisotropy;
  1977. this.format = format;
  1978. this.internalFormat = null;
  1979. this.type = type;
  1980. this.offset = new Vector2( 0, 0 );
  1981. this.repeat = new Vector2( 1, 1 );
  1982. this.center = new Vector2( 0, 0 );
  1983. this.rotation = 0;
  1984. this.matrixAutoUpdate = true;
  1985. this.matrix = new Matrix3();
  1986. this.generateMipmaps = true;
  1987. this.premultiplyAlpha = false;
  1988. this.flipY = true;
  1989. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1990. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1991. //
  1992. // Also changing the encoding after already used by a Material will not automatically make the Material
  1993. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1994. this.encoding = encoding;
  1995. this.userData = {};
  1996. this.version = 0;
  1997. this.onUpdate = null;
  1998. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1999. this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  2000. }
  2001. get image() {
  2002. return this.source.data;
  2003. }
  2004. set image( value = null ) {
  2005. this.source.data = value;
  2006. }
  2007. updateMatrix() {
  2008. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  2009. }
  2010. clone() {
  2011. return new this.constructor().copy( this );
  2012. }
  2013. copy( source ) {
  2014. this.name = source.name;
  2015. this.source = source.source;
  2016. this.mipmaps = source.mipmaps.slice( 0 );
  2017. this.mapping = source.mapping;
  2018. this.wrapS = source.wrapS;
  2019. this.wrapT = source.wrapT;
  2020. this.magFilter = source.magFilter;
  2021. this.minFilter = source.minFilter;
  2022. this.anisotropy = source.anisotropy;
  2023. this.format = source.format;
  2024. this.internalFormat = source.internalFormat;
  2025. this.type = source.type;
  2026. this.offset.copy( source.offset );
  2027. this.repeat.copy( source.repeat );
  2028. this.center.copy( source.center );
  2029. this.rotation = source.rotation;
  2030. this.matrixAutoUpdate = source.matrixAutoUpdate;
  2031. this.matrix.copy( source.matrix );
  2032. this.generateMipmaps = source.generateMipmaps;
  2033. this.premultiplyAlpha = source.premultiplyAlpha;
  2034. this.flipY = source.flipY;
  2035. this.unpackAlignment = source.unpackAlignment;
  2036. this.encoding = source.encoding;
  2037. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  2038. this.needsUpdate = true;
  2039. return this;
  2040. }
  2041. toJSON( meta ) {
  2042. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  2043. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  2044. return meta.textures[ this.uuid ];
  2045. }
  2046. const output = {
  2047. metadata: {
  2048. version: 4.5,
  2049. type: 'Texture',
  2050. generator: 'Texture.toJSON'
  2051. },
  2052. uuid: this.uuid,
  2053. name: this.name,
  2054. image: this.source.toJSON( meta ).uuid,
  2055. mapping: this.mapping,
  2056. repeat: [ this.repeat.x, this.repeat.y ],
  2057. offset: [ this.offset.x, this.offset.y ],
  2058. center: [ this.center.x, this.center.y ],
  2059. rotation: this.rotation,
  2060. wrap: [ this.wrapS, this.wrapT ],
  2061. format: this.format,
  2062. internalFormat: this.internalFormat,
  2063. type: this.type,
  2064. encoding: this.encoding,
  2065. minFilter: this.minFilter,
  2066. magFilter: this.magFilter,
  2067. anisotropy: this.anisotropy,
  2068. flipY: this.flipY,
  2069. generateMipmaps: this.generateMipmaps,
  2070. premultiplyAlpha: this.premultiplyAlpha,
  2071. unpackAlignment: this.unpackAlignment
  2072. };
  2073. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  2074. if ( ! isRootObject ) {
  2075. meta.textures[ this.uuid ] = output;
  2076. }
  2077. return output;
  2078. }
  2079. dispose() {
  2080. this.dispatchEvent( { type: 'dispose' } );
  2081. }
  2082. transformUv( uv ) {
  2083. if ( this.mapping !== UVMapping ) return uv;
  2084. uv.applyMatrix3( this.matrix );
  2085. if ( uv.x < 0 || uv.x > 1 ) {
  2086. switch ( this.wrapS ) {
  2087. case RepeatWrapping:
  2088. uv.x = uv.x - Math.floor( uv.x );
  2089. break;
  2090. case ClampToEdgeWrapping:
  2091. uv.x = uv.x < 0 ? 0 : 1;
  2092. break;
  2093. case MirroredRepeatWrapping:
  2094. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  2095. uv.x = Math.ceil( uv.x ) - uv.x;
  2096. } else {
  2097. uv.x = uv.x - Math.floor( uv.x );
  2098. }
  2099. break;
  2100. }
  2101. }
  2102. if ( uv.y < 0 || uv.y > 1 ) {
  2103. switch ( this.wrapT ) {
  2104. case RepeatWrapping:
  2105. uv.y = uv.y - Math.floor( uv.y );
  2106. break;
  2107. case ClampToEdgeWrapping:
  2108. uv.y = uv.y < 0 ? 0 : 1;
  2109. break;
  2110. case MirroredRepeatWrapping:
  2111. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  2112. uv.y = Math.ceil( uv.y ) - uv.y;
  2113. } else {
  2114. uv.y = uv.y - Math.floor( uv.y );
  2115. }
  2116. break;
  2117. }
  2118. }
  2119. if ( this.flipY ) {
  2120. uv.y = 1 - uv.y;
  2121. }
  2122. return uv;
  2123. }
  2124. set needsUpdate( value ) {
  2125. if ( value === true ) {
  2126. this.version ++;
  2127. this.source.needsUpdate = true;
  2128. }
  2129. }
  2130. }
  2131. Texture.DEFAULT_IMAGE = null;
  2132. Texture.DEFAULT_MAPPING = UVMapping;
  2133. Texture.DEFAULT_ANISOTROPY = 1;
  2134. class Vector4 {
  2135. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2136. Vector4.prototype.isVector4 = true;
  2137. this.x = x;
  2138. this.y = y;
  2139. this.z = z;
  2140. this.w = w;
  2141. }
  2142. get width() {
  2143. return this.z;
  2144. }
  2145. set width( value ) {
  2146. this.z = value;
  2147. }
  2148. get height() {
  2149. return this.w;
  2150. }
  2151. set height( value ) {
  2152. this.w = value;
  2153. }
  2154. set( x, y, z, w ) {
  2155. this.x = x;
  2156. this.y = y;
  2157. this.z = z;
  2158. this.w = w;
  2159. return this;
  2160. }
  2161. setScalar( scalar ) {
  2162. this.x = scalar;
  2163. this.y = scalar;
  2164. this.z = scalar;
  2165. this.w = scalar;
  2166. return this;
  2167. }
  2168. setX( x ) {
  2169. this.x = x;
  2170. return this;
  2171. }
  2172. setY( y ) {
  2173. this.y = y;
  2174. return this;
  2175. }
  2176. setZ( z ) {
  2177. this.z = z;
  2178. return this;
  2179. }
  2180. setW( w ) {
  2181. this.w = w;
  2182. return this;
  2183. }
  2184. setComponent( index, value ) {
  2185. switch ( index ) {
  2186. case 0: this.x = value; break;
  2187. case 1: this.y = value; break;
  2188. case 2: this.z = value; break;
  2189. case 3: this.w = value; break;
  2190. default: throw new Error( 'index is out of range: ' + index );
  2191. }
  2192. return this;
  2193. }
  2194. getComponent( index ) {
  2195. switch ( index ) {
  2196. case 0: return this.x;
  2197. case 1: return this.y;
  2198. case 2: return this.z;
  2199. case 3: return this.w;
  2200. default: throw new Error( 'index is out of range: ' + index );
  2201. }
  2202. }
  2203. clone() {
  2204. return new this.constructor( this.x, this.y, this.z, this.w );
  2205. }
  2206. copy( v ) {
  2207. this.x = v.x;
  2208. this.y = v.y;
  2209. this.z = v.z;
  2210. this.w = ( v.w !== undefined ) ? v.w : 1;
  2211. return this;
  2212. }
  2213. add( v ) {
  2214. this.x += v.x;
  2215. this.y += v.y;
  2216. this.z += v.z;
  2217. this.w += v.w;
  2218. return this;
  2219. }
  2220. addScalar( s ) {
  2221. this.x += s;
  2222. this.y += s;
  2223. this.z += s;
  2224. this.w += s;
  2225. return this;
  2226. }
  2227. addVectors( a, b ) {
  2228. this.x = a.x + b.x;
  2229. this.y = a.y + b.y;
  2230. this.z = a.z + b.z;
  2231. this.w = a.w + b.w;
  2232. return this;
  2233. }
  2234. addScaledVector( v, s ) {
  2235. this.x += v.x * s;
  2236. this.y += v.y * s;
  2237. this.z += v.z * s;
  2238. this.w += v.w * s;
  2239. return this;
  2240. }
  2241. sub( v ) {
  2242. this.x -= v.x;
  2243. this.y -= v.y;
  2244. this.z -= v.z;
  2245. this.w -= v.w;
  2246. return this;
  2247. }
  2248. subScalar( s ) {
  2249. this.x -= s;
  2250. this.y -= s;
  2251. this.z -= s;
  2252. this.w -= s;
  2253. return this;
  2254. }
  2255. subVectors( a, b ) {
  2256. this.x = a.x - b.x;
  2257. this.y = a.y - b.y;
  2258. this.z = a.z - b.z;
  2259. this.w = a.w - b.w;
  2260. return this;
  2261. }
  2262. multiply( v ) {
  2263. this.x *= v.x;
  2264. this.y *= v.y;
  2265. this.z *= v.z;
  2266. this.w *= v.w;
  2267. return this;
  2268. }
  2269. multiplyScalar( scalar ) {
  2270. this.x *= scalar;
  2271. this.y *= scalar;
  2272. this.z *= scalar;
  2273. this.w *= scalar;
  2274. return this;
  2275. }
  2276. applyMatrix4( m ) {
  2277. const x = this.x, y = this.y, z = this.z, w = this.w;
  2278. const e = m.elements;
  2279. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  2280. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  2281. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  2282. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  2283. return this;
  2284. }
  2285. divideScalar( scalar ) {
  2286. return this.multiplyScalar( 1 / scalar );
  2287. }
  2288. setAxisAngleFromQuaternion( q ) {
  2289. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  2290. // q is assumed to be normalized
  2291. this.w = 2 * Math.acos( q.w );
  2292. const s = Math.sqrt( 1 - q.w * q.w );
  2293. if ( s < 0.0001 ) {
  2294. this.x = 1;
  2295. this.y = 0;
  2296. this.z = 0;
  2297. } else {
  2298. this.x = q.x / s;
  2299. this.y = q.y / s;
  2300. this.z = q.z / s;
  2301. }
  2302. return this;
  2303. }
  2304. setAxisAngleFromRotationMatrix( m ) {
  2305. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  2306. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2307. let angle, x, y, z; // variables for result
  2308. const epsilon = 0.01, // margin to allow for rounding errors
  2309. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  2310. te = m.elements,
  2311. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2312. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2313. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  2314. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  2315. ( Math.abs( m13 - m31 ) < epsilon ) &&
  2316. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  2317. // singularity found
  2318. // first check for identity matrix which must have +1 for all terms
  2319. // in leading diagonal and zero in other terms
  2320. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  2321. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  2322. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  2323. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  2324. // this singularity is identity matrix so angle = 0
  2325. this.set( 1, 0, 0, 0 );
  2326. return this; // zero angle, arbitrary axis
  2327. }
  2328. // otherwise this singularity is angle = 180
  2329. angle = Math.PI;
  2330. const xx = ( m11 + 1 ) / 2;
  2331. const yy = ( m22 + 1 ) / 2;
  2332. const zz = ( m33 + 1 ) / 2;
  2333. const xy = ( m12 + m21 ) / 4;
  2334. const xz = ( m13 + m31 ) / 4;
  2335. const yz = ( m23 + m32 ) / 4;
  2336. if ( ( xx > yy ) && ( xx > zz ) ) {
  2337. // m11 is the largest diagonal term
  2338. if ( xx < epsilon ) {
  2339. x = 0;
  2340. y = 0.707106781;
  2341. z = 0.707106781;
  2342. } else {
  2343. x = Math.sqrt( xx );
  2344. y = xy / x;
  2345. z = xz / x;
  2346. }
  2347. } else if ( yy > zz ) {
  2348. // m22 is the largest diagonal term
  2349. if ( yy < epsilon ) {
  2350. x = 0.707106781;
  2351. y = 0;
  2352. z = 0.707106781;
  2353. } else {
  2354. y = Math.sqrt( yy );
  2355. x = xy / y;
  2356. z = yz / y;
  2357. }
  2358. } else {
  2359. // m33 is the largest diagonal term so base result on this
  2360. if ( zz < epsilon ) {
  2361. x = 0.707106781;
  2362. y = 0.707106781;
  2363. z = 0;
  2364. } else {
  2365. z = Math.sqrt( zz );
  2366. x = xz / z;
  2367. y = yz / z;
  2368. }
  2369. }
  2370. this.set( x, y, z, angle );
  2371. return this; // return 180 deg rotation
  2372. }
  2373. // as we have reached here there are no singularities so we can handle normally
  2374. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  2375. ( m13 - m31 ) * ( m13 - m31 ) +
  2376. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  2377. if ( Math.abs( s ) < 0.001 ) s = 1;
  2378. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  2379. // caught by singularity test above, but I've left it in just in case
  2380. this.x = ( m32 - m23 ) / s;
  2381. this.y = ( m13 - m31 ) / s;
  2382. this.z = ( m21 - m12 ) / s;
  2383. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  2384. return this;
  2385. }
  2386. min( v ) {
  2387. this.x = Math.min( this.x, v.x );
  2388. this.y = Math.min( this.y, v.y );
  2389. this.z = Math.min( this.z, v.z );
  2390. this.w = Math.min( this.w, v.w );
  2391. return this;
  2392. }
  2393. max( v ) {
  2394. this.x = Math.max( this.x, v.x );
  2395. this.y = Math.max( this.y, v.y );
  2396. this.z = Math.max( this.z, v.z );
  2397. this.w = Math.max( this.w, v.w );
  2398. return this;
  2399. }
  2400. clamp( min, max ) {
  2401. // assumes min < max, componentwise
  2402. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2403. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2404. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2405. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  2406. return this;
  2407. }
  2408. clampScalar( minVal, maxVal ) {
  2409. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2410. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2411. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2412. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  2413. return this;
  2414. }
  2415. clampLength( min, max ) {
  2416. const length = this.length();
  2417. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2418. }
  2419. floor() {
  2420. this.x = Math.floor( this.x );
  2421. this.y = Math.floor( this.y );
  2422. this.z = Math.floor( this.z );
  2423. this.w = Math.floor( this.w );
  2424. return this;
  2425. }
  2426. ceil() {
  2427. this.x = Math.ceil( this.x );
  2428. this.y = Math.ceil( this.y );
  2429. this.z = Math.ceil( this.z );
  2430. this.w = Math.ceil( this.w );
  2431. return this;
  2432. }
  2433. round() {
  2434. this.x = Math.round( this.x );
  2435. this.y = Math.round( this.y );
  2436. this.z = Math.round( this.z );
  2437. this.w = Math.round( this.w );
  2438. return this;
  2439. }
  2440. roundToZero() {
  2441. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2442. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2443. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2444. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  2445. return this;
  2446. }
  2447. negate() {
  2448. this.x = - this.x;
  2449. this.y = - this.y;
  2450. this.z = - this.z;
  2451. this.w = - this.w;
  2452. return this;
  2453. }
  2454. dot( v ) {
  2455. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  2456. }
  2457. lengthSq() {
  2458. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  2459. }
  2460. length() {
  2461. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2462. }
  2463. manhattanLength() {
  2464. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  2465. }
  2466. normalize() {
  2467. return this.divideScalar( this.length() || 1 );
  2468. }
  2469. setLength( length ) {
  2470. return this.normalize().multiplyScalar( length );
  2471. }
  2472. lerp( v, alpha ) {
  2473. this.x += ( v.x - this.x ) * alpha;
  2474. this.y += ( v.y - this.y ) * alpha;
  2475. this.z += ( v.z - this.z ) * alpha;
  2476. this.w += ( v.w - this.w ) * alpha;
  2477. return this;
  2478. }
  2479. lerpVectors( v1, v2, alpha ) {
  2480. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2481. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2482. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2483. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  2484. return this;
  2485. }
  2486. equals( v ) {
  2487. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  2488. }
  2489. fromArray( array, offset = 0 ) {
  2490. this.x = array[ offset ];
  2491. this.y = array[ offset + 1 ];
  2492. this.z = array[ offset + 2 ];
  2493. this.w = array[ offset + 3 ];
  2494. return this;
  2495. }
  2496. toArray( array = [], offset = 0 ) {
  2497. array[ offset ] = this.x;
  2498. array[ offset + 1 ] = this.y;
  2499. array[ offset + 2 ] = this.z;
  2500. array[ offset + 3 ] = this.w;
  2501. return array;
  2502. }
  2503. fromBufferAttribute( attribute, index ) {
  2504. this.x = attribute.getX( index );
  2505. this.y = attribute.getY( index );
  2506. this.z = attribute.getZ( index );
  2507. this.w = attribute.getW( index );
  2508. return this;
  2509. }
  2510. random() {
  2511. this.x = Math.random();
  2512. this.y = Math.random();
  2513. this.z = Math.random();
  2514. this.w = Math.random();
  2515. return this;
  2516. }
  2517. *[ Symbol.iterator ]() {
  2518. yield this.x;
  2519. yield this.y;
  2520. yield this.z;
  2521. yield this.w;
  2522. }
  2523. }
  2524. /*
  2525. In options, we can specify:
  2526. * Texture parameters for an auto-generated target texture
  2527. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2528. */
  2529. class WebGLRenderTarget extends EventDispatcher {
  2530. constructor( width = 1, height = 1, options = {} ) {
  2531. super();
  2532. this.isWebGLRenderTarget = true;
  2533. this.width = width;
  2534. this.height = height;
  2535. this.depth = 1;
  2536. this.scissor = new Vector4( 0, 0, width, height );
  2537. this.scissorTest = false;
  2538. this.viewport = new Vector4( 0, 0, width, height );
  2539. const image = { width: width, height: height, depth: 1 };
  2540. this.texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  2541. this.texture.isRenderTargetTexture = true;
  2542. this.texture.flipY = false;
  2543. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2544. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  2545. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2546. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2547. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  2548. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2549. this.samples = options.samples !== undefined ? options.samples : 0;
  2550. }
  2551. setSize( width, height, depth = 1 ) {
  2552. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  2553. this.width = width;
  2554. this.height = height;
  2555. this.depth = depth;
  2556. this.texture.image.width = width;
  2557. this.texture.image.height = height;
  2558. this.texture.image.depth = depth;
  2559. this.dispose();
  2560. }
  2561. this.viewport.set( 0, 0, width, height );
  2562. this.scissor.set( 0, 0, width, height );
  2563. }
  2564. clone() {
  2565. return new this.constructor().copy( this );
  2566. }
  2567. copy( source ) {
  2568. this.width = source.width;
  2569. this.height = source.height;
  2570. this.depth = source.depth;
  2571. this.viewport.copy( source.viewport );
  2572. this.texture = source.texture.clone();
  2573. this.texture.isRenderTargetTexture = true;
  2574. // ensure image object is not shared, see #20328
  2575. const image = Object.assign( {}, source.texture.image );
  2576. this.texture.source = new Source( image );
  2577. this.depthBuffer = source.depthBuffer;
  2578. this.stencilBuffer = source.stencilBuffer;
  2579. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  2580. this.samples = source.samples;
  2581. return this;
  2582. }
  2583. dispose() {
  2584. this.dispatchEvent( { type: 'dispose' } );
  2585. }
  2586. }
  2587. class DataArrayTexture extends Texture {
  2588. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  2589. super( null );
  2590. this.isDataArrayTexture = true;
  2591. this.image = { data, width, height, depth };
  2592. this.magFilter = NearestFilter;
  2593. this.minFilter = NearestFilter;
  2594. this.wrapR = ClampToEdgeWrapping;
  2595. this.generateMipmaps = false;
  2596. this.flipY = false;
  2597. this.unpackAlignment = 1;
  2598. }
  2599. }
  2600. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  2601. constructor( width = 1, height = 1, depth = 1 ) {
  2602. super( width, height );
  2603. this.isWebGLArrayRenderTarget = true;
  2604. this.depth = depth;
  2605. this.texture = new DataArrayTexture( null, width, height, depth );
  2606. this.texture.isRenderTargetTexture = true;
  2607. }
  2608. }
  2609. class Data3DTexture extends Texture {
  2610. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  2611. // We're going to add .setXXX() methods for setting properties later.
  2612. // Users can still set in DataTexture3D directly.
  2613. //
  2614. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  2615. // texture.anisotropy = 16;
  2616. //
  2617. // See #14839
  2618. super( null );
  2619. this.isData3DTexture = true;
  2620. this.image = { data, width, height, depth };
  2621. this.magFilter = NearestFilter;
  2622. this.minFilter = NearestFilter;
  2623. this.wrapR = ClampToEdgeWrapping;
  2624. this.generateMipmaps = false;
  2625. this.flipY = false;
  2626. this.unpackAlignment = 1;
  2627. }
  2628. }
  2629. class WebGL3DRenderTarget extends WebGLRenderTarget {
  2630. constructor( width = 1, height = 1, depth = 1 ) {
  2631. super( width, height );
  2632. this.isWebGL3DRenderTarget = true;
  2633. this.depth = depth;
  2634. this.texture = new Data3DTexture( null, width, height, depth );
  2635. this.texture.isRenderTargetTexture = true;
  2636. }
  2637. }
  2638. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  2639. constructor( width = 1, height = 1, count = 1, options = {} ) {
  2640. super( width, height, options );
  2641. this.isWebGLMultipleRenderTargets = true;
  2642. const texture = this.texture;
  2643. this.texture = [];
  2644. for ( let i = 0; i < count; i ++ ) {
  2645. this.texture[ i ] = texture.clone();
  2646. this.texture[ i ].isRenderTargetTexture = true;
  2647. }
  2648. }
  2649. setSize( width, height, depth = 1 ) {
  2650. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  2651. this.width = width;
  2652. this.height = height;
  2653. this.depth = depth;
  2654. for ( let i = 0, il = this.texture.length; i < il; i ++ ) {
  2655. this.texture[ i ].image.width = width;
  2656. this.texture[ i ].image.height = height;
  2657. this.texture[ i ].image.depth = depth;
  2658. }
  2659. this.dispose();
  2660. }
  2661. this.viewport.set( 0, 0, width, height );
  2662. this.scissor.set( 0, 0, width, height );
  2663. return this;
  2664. }
  2665. copy( source ) {
  2666. this.dispose();
  2667. this.width = source.width;
  2668. this.height = source.height;
  2669. this.depth = source.depth;
  2670. this.viewport.set( 0, 0, this.width, this.height );
  2671. this.scissor.set( 0, 0, this.width, this.height );
  2672. this.depthBuffer = source.depthBuffer;
  2673. this.stencilBuffer = source.stencilBuffer;
  2674. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  2675. this.texture.length = 0;
  2676. for ( let i = 0, il = source.texture.length; i < il; i ++ ) {
  2677. this.texture[ i ] = source.texture[ i ].clone();
  2678. this.texture[ i ].isRenderTargetTexture = true;
  2679. }
  2680. return this;
  2681. }
  2682. }
  2683. class Box3 {
  2684. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2685. this.isBox3 = true;
  2686. this.min = min;
  2687. this.max = max;
  2688. }
  2689. set( min, max ) {
  2690. this.min.copy( min );
  2691. this.max.copy( max );
  2692. return this;
  2693. }
  2694. setFromArray( array ) {
  2695. let minX = + Infinity;
  2696. let minY = + Infinity;
  2697. let minZ = + Infinity;
  2698. let maxX = - Infinity;
  2699. let maxY = - Infinity;
  2700. let maxZ = - Infinity;
  2701. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  2702. const x = array[ i ];
  2703. const y = array[ i + 1 ];
  2704. const z = array[ i + 2 ];
  2705. if ( x < minX ) minX = x;
  2706. if ( y < minY ) minY = y;
  2707. if ( z < minZ ) minZ = z;
  2708. if ( x > maxX ) maxX = x;
  2709. if ( y > maxY ) maxY = y;
  2710. if ( z > maxZ ) maxZ = z;
  2711. }
  2712. this.min.set( minX, minY, minZ );
  2713. this.max.set( maxX, maxY, maxZ );
  2714. return this;
  2715. }
  2716. setFromBufferAttribute( attribute ) {
  2717. let minX = + Infinity;
  2718. let minY = + Infinity;
  2719. let minZ = + Infinity;
  2720. let maxX = - Infinity;
  2721. let maxY = - Infinity;
  2722. let maxZ = - Infinity;
  2723. for ( let i = 0, l = attribute.count; i < l; i ++ ) {
  2724. const x = attribute.getX( i );
  2725. const y = attribute.getY( i );
  2726. const z = attribute.getZ( i );
  2727. if ( x < minX ) minX = x;
  2728. if ( y < minY ) minY = y;
  2729. if ( z < minZ ) minZ = z;
  2730. if ( x > maxX ) maxX = x;
  2731. if ( y > maxY ) maxY = y;
  2732. if ( z > maxZ ) maxZ = z;
  2733. }
  2734. this.min.set( minX, minY, minZ );
  2735. this.max.set( maxX, maxY, maxZ );
  2736. return this;
  2737. }
  2738. setFromPoints( points ) {
  2739. this.makeEmpty();
  2740. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2741. this.expandByPoint( points[ i ] );
  2742. }
  2743. return this;
  2744. }
  2745. setFromCenterAndSize( center, size ) {
  2746. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  2747. this.min.copy( center ).sub( halfSize );
  2748. this.max.copy( center ).add( halfSize );
  2749. return this;
  2750. }
  2751. setFromObject( object, precise = false ) {
  2752. this.makeEmpty();
  2753. return this.expandByObject( object, precise );
  2754. }
  2755. clone() {
  2756. return new this.constructor().copy( this );
  2757. }
  2758. copy( box ) {
  2759. this.min.copy( box.min );
  2760. this.max.copy( box.max );
  2761. return this;
  2762. }
  2763. makeEmpty() {
  2764. this.min.x = this.min.y = this.min.z = + Infinity;
  2765. this.max.x = this.max.y = this.max.z = - Infinity;
  2766. return this;
  2767. }
  2768. isEmpty() {
  2769. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2770. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2771. }
  2772. getCenter( target ) {
  2773. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2774. }
  2775. getSize( target ) {
  2776. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2777. }
  2778. expandByPoint( point ) {
  2779. this.min.min( point );
  2780. this.max.max( point );
  2781. return this;
  2782. }
  2783. expandByVector( vector ) {
  2784. this.min.sub( vector );
  2785. this.max.add( vector );
  2786. return this;
  2787. }
  2788. expandByScalar( scalar ) {
  2789. this.min.addScalar( - scalar );
  2790. this.max.addScalar( scalar );
  2791. return this;
  2792. }
  2793. expandByObject( object, precise = false ) {
  2794. // Computes the world-axis-aligned bounding box of an object (including its children),
  2795. // accounting for both the object's, and children's, world transforms
  2796. object.updateWorldMatrix( false, false );
  2797. const geometry = object.geometry;
  2798. if ( geometry !== undefined ) {
  2799. if ( precise && geometry.attributes != undefined && geometry.attributes.position !== undefined ) {
  2800. const position = geometry.attributes.position;
  2801. for ( let i = 0, l = position.count; i < l; i ++ ) {
  2802. _vector$b.fromBufferAttribute( position, i ).applyMatrix4( object.matrixWorld );
  2803. this.expandByPoint( _vector$b );
  2804. }
  2805. } else {
  2806. if ( geometry.boundingBox === null ) {
  2807. geometry.computeBoundingBox();
  2808. }
  2809. _box$3.copy( geometry.boundingBox );
  2810. _box$3.applyMatrix4( object.matrixWorld );
  2811. this.union( _box$3 );
  2812. }
  2813. }
  2814. const children = object.children;
  2815. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2816. this.expandByObject( children[ i ], precise );
  2817. }
  2818. return this;
  2819. }
  2820. containsPoint( point ) {
  2821. return point.x < this.min.x || point.x > this.max.x ||
  2822. point.y < this.min.y || point.y > this.max.y ||
  2823. point.z < this.min.z || point.z > this.max.z ? false : true;
  2824. }
  2825. containsBox( box ) {
  2826. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2827. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2828. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2829. }
  2830. getParameter( point, target ) {
  2831. // This can potentially have a divide by zero if the box
  2832. // has a size dimension of 0.
  2833. return target.set(
  2834. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2835. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2836. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2837. );
  2838. }
  2839. intersectsBox( box ) {
  2840. // using 6 splitting planes to rule out intersections.
  2841. return box.max.x < this.min.x || box.min.x > this.max.x ||
  2842. box.max.y < this.min.y || box.min.y > this.max.y ||
  2843. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  2844. }
  2845. intersectsSphere( sphere ) {
  2846. // Find the point on the AABB closest to the sphere center.
  2847. this.clampPoint( sphere.center, _vector$b );
  2848. // If that point is inside the sphere, the AABB and sphere intersect.
  2849. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2850. }
  2851. intersectsPlane( plane ) {
  2852. // We compute the minimum and maximum dot product values. If those values
  2853. // are on the same side (back or front) of the plane, then there is no intersection.
  2854. let min, max;
  2855. if ( plane.normal.x > 0 ) {
  2856. min = plane.normal.x * this.min.x;
  2857. max = plane.normal.x * this.max.x;
  2858. } else {
  2859. min = plane.normal.x * this.max.x;
  2860. max = plane.normal.x * this.min.x;
  2861. }
  2862. if ( plane.normal.y > 0 ) {
  2863. min += plane.normal.y * this.min.y;
  2864. max += plane.normal.y * this.max.y;
  2865. } else {
  2866. min += plane.normal.y * this.max.y;
  2867. max += plane.normal.y * this.min.y;
  2868. }
  2869. if ( plane.normal.z > 0 ) {
  2870. min += plane.normal.z * this.min.z;
  2871. max += plane.normal.z * this.max.z;
  2872. } else {
  2873. min += plane.normal.z * this.max.z;
  2874. max += plane.normal.z * this.min.z;
  2875. }
  2876. return ( min <= - plane.constant && max >= - plane.constant );
  2877. }
  2878. intersectsTriangle( triangle ) {
  2879. if ( this.isEmpty() ) {
  2880. return false;
  2881. }
  2882. // compute box center and extents
  2883. this.getCenter( _center );
  2884. _extents.subVectors( this.max, _center );
  2885. // translate triangle to aabb origin
  2886. _v0$2.subVectors( triangle.a, _center );
  2887. _v1$7.subVectors( triangle.b, _center );
  2888. _v2$4.subVectors( triangle.c, _center );
  2889. // compute edge vectors for triangle
  2890. _f0.subVectors( _v1$7, _v0$2 );
  2891. _f1.subVectors( _v2$4, _v1$7 );
  2892. _f2.subVectors( _v0$2, _v2$4 );
  2893. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2894. // 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
  2895. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2896. let axes = [
  2897. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  2898. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  2899. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  2900. ];
  2901. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2902. return false;
  2903. }
  2904. // test 3 face normals from the aabb
  2905. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  2906. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2907. return false;
  2908. }
  2909. // finally testing the face normal of the triangle
  2910. // use already existing triangle edge vectors here
  2911. _triangleNormal.crossVectors( _f0, _f1 );
  2912. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  2913. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  2914. }
  2915. clampPoint( point, target ) {
  2916. return target.copy( point ).clamp( this.min, this.max );
  2917. }
  2918. distanceToPoint( point ) {
  2919. return this.clampPoint( point, _vector$b ).distanceTo( point );
  2920. }
  2921. getBoundingSphere( target ) {
  2922. if ( this.isEmpty() ) {
  2923. target.makeEmpty();
  2924. } else {
  2925. this.getCenter( target.center );
  2926. target.radius = this.getSize( _vector$b ).length() * 0.5;
  2927. }
  2928. return target;
  2929. }
  2930. intersect( box ) {
  2931. this.min.max( box.min );
  2932. this.max.min( box.max );
  2933. // 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.
  2934. if ( this.isEmpty() ) this.makeEmpty();
  2935. return this;
  2936. }
  2937. union( box ) {
  2938. this.min.min( box.min );
  2939. this.max.max( box.max );
  2940. return this;
  2941. }
  2942. applyMatrix4( matrix ) {
  2943. // transform of empty box is an empty box.
  2944. if ( this.isEmpty() ) return this;
  2945. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2946. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2947. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2948. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2949. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2950. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2951. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2952. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2953. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2954. this.setFromPoints( _points );
  2955. return this;
  2956. }
  2957. translate( offset ) {
  2958. this.min.add( offset );
  2959. this.max.add( offset );
  2960. return this;
  2961. }
  2962. equals( box ) {
  2963. return box.min.equals( this.min ) && box.max.equals( this.max );
  2964. }
  2965. }
  2966. const _points = [
  2967. /*@__PURE__*/ new Vector3(),
  2968. /*@__PURE__*/ new Vector3(),
  2969. /*@__PURE__*/ new Vector3(),
  2970. /*@__PURE__*/ new Vector3(),
  2971. /*@__PURE__*/ new Vector3(),
  2972. /*@__PURE__*/ new Vector3(),
  2973. /*@__PURE__*/ new Vector3(),
  2974. /*@__PURE__*/ new Vector3()
  2975. ];
  2976. const _vector$b = /*@__PURE__*/ new Vector3();
  2977. const _box$3 = /*@__PURE__*/ new Box3();
  2978. // triangle centered vertices
  2979. const _v0$2 = /*@__PURE__*/ new Vector3();
  2980. const _v1$7 = /*@__PURE__*/ new Vector3();
  2981. const _v2$4 = /*@__PURE__*/ new Vector3();
  2982. // triangle edge vectors
  2983. const _f0 = /*@__PURE__*/ new Vector3();
  2984. const _f1 = /*@__PURE__*/ new Vector3();
  2985. const _f2 = /*@__PURE__*/ new Vector3();
  2986. const _center = /*@__PURE__*/ new Vector3();
  2987. const _extents = /*@__PURE__*/ new Vector3();
  2988. const _triangleNormal = /*@__PURE__*/ new Vector3();
  2989. const _testAxis = /*@__PURE__*/ new Vector3();
  2990. function satForAxes( axes, v0, v1, v2, extents ) {
  2991. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  2992. _testAxis.fromArray( axes, i );
  2993. // project the aabb onto the separating axis
  2994. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  2995. // project all 3 vertices of the triangle onto the separating axis
  2996. const p0 = v0.dot( _testAxis );
  2997. const p1 = v1.dot( _testAxis );
  2998. const p2 = v2.dot( _testAxis );
  2999. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3000. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3001. // points of the projected triangle are outside the projected half-length of the aabb
  3002. // the axis is separating and we can exit
  3003. return false;
  3004. }
  3005. }
  3006. return true;
  3007. }
  3008. const _box$2 = /*@__PURE__*/ new Box3();
  3009. const _v1$6 = /*@__PURE__*/ new Vector3();
  3010. const _v2$3 = /*@__PURE__*/ new Vector3();
  3011. class Sphere {
  3012. constructor( center = new Vector3(), radius = - 1 ) {
  3013. this.center = center;
  3014. this.radius = radius;
  3015. }
  3016. set( center, radius ) {
  3017. this.center.copy( center );
  3018. this.radius = radius;
  3019. return this;
  3020. }
  3021. setFromPoints( points, optionalCenter ) {
  3022. const center = this.center;
  3023. if ( optionalCenter !== undefined ) {
  3024. center.copy( optionalCenter );
  3025. } else {
  3026. _box$2.setFromPoints( points ).getCenter( center );
  3027. }
  3028. let maxRadiusSq = 0;
  3029. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3030. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3031. }
  3032. this.radius = Math.sqrt( maxRadiusSq );
  3033. return this;
  3034. }
  3035. copy( sphere ) {
  3036. this.center.copy( sphere.center );
  3037. this.radius = sphere.radius;
  3038. return this;
  3039. }
  3040. isEmpty() {
  3041. return ( this.radius < 0 );
  3042. }
  3043. makeEmpty() {
  3044. this.center.set( 0, 0, 0 );
  3045. this.radius = - 1;
  3046. return this;
  3047. }
  3048. containsPoint( point ) {
  3049. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3050. }
  3051. distanceToPoint( point ) {
  3052. return ( point.distanceTo( this.center ) - this.radius );
  3053. }
  3054. intersectsSphere( sphere ) {
  3055. const radiusSum = this.radius + sphere.radius;
  3056. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3057. }
  3058. intersectsBox( box ) {
  3059. return box.intersectsSphere( this );
  3060. }
  3061. intersectsPlane( plane ) {
  3062. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3063. }
  3064. clampPoint( point, target ) {
  3065. const deltaLengthSq = this.center.distanceToSquared( point );
  3066. target.copy( point );
  3067. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3068. target.sub( this.center ).normalize();
  3069. target.multiplyScalar( this.radius ).add( this.center );
  3070. }
  3071. return target;
  3072. }
  3073. getBoundingBox( target ) {
  3074. if ( this.isEmpty() ) {
  3075. // Empty sphere produces empty bounding box
  3076. target.makeEmpty();
  3077. return target;
  3078. }
  3079. target.set( this.center, this.center );
  3080. target.expandByScalar( this.radius );
  3081. return target;
  3082. }
  3083. applyMatrix4( matrix ) {
  3084. this.center.applyMatrix4( matrix );
  3085. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3086. return this;
  3087. }
  3088. translate( offset ) {
  3089. this.center.add( offset );
  3090. return this;
  3091. }
  3092. expandByPoint( point ) {
  3093. if ( this.isEmpty() ) {
  3094. this.center.copy( point );
  3095. this.radius = 0;
  3096. return this;
  3097. }
  3098. _v1$6.subVectors( point, this.center );
  3099. const lengthSq = _v1$6.lengthSq();
  3100. if ( lengthSq > ( this.radius * this.radius ) ) {
  3101. // calculate the minimal sphere
  3102. const length = Math.sqrt( lengthSq );
  3103. const delta = ( length - this.radius ) * 0.5;
  3104. this.center.addScaledVector( _v1$6, delta / length );
  3105. this.radius += delta;
  3106. }
  3107. return this;
  3108. }
  3109. union( sphere ) {
  3110. if ( sphere.isEmpty() ) {
  3111. return this;
  3112. }
  3113. if ( this.isEmpty() ) {
  3114. this.copy( sphere );
  3115. return this;
  3116. }
  3117. if ( this.center.equals( sphere.center ) === true ) {
  3118. this.radius = Math.max( this.radius, sphere.radius );
  3119. } else {
  3120. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3121. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3122. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3123. }
  3124. return this;
  3125. }
  3126. equals( sphere ) {
  3127. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3128. }
  3129. clone() {
  3130. return new this.constructor().copy( this );
  3131. }
  3132. }
  3133. const _vector$a = /*@__PURE__*/ new Vector3();
  3134. const _segCenter = /*@__PURE__*/ new Vector3();
  3135. const _segDir = /*@__PURE__*/ new Vector3();
  3136. const _diff = /*@__PURE__*/ new Vector3();
  3137. const _edge1 = /*@__PURE__*/ new Vector3();
  3138. const _edge2 = /*@__PURE__*/ new Vector3();
  3139. const _normal$1 = /*@__PURE__*/ new Vector3();
  3140. class Ray {
  3141. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3142. this.origin = origin;
  3143. this.direction = direction;
  3144. }
  3145. set( origin, direction ) {
  3146. this.origin.copy( origin );
  3147. this.direction.copy( direction );
  3148. return this;
  3149. }
  3150. copy( ray ) {
  3151. this.origin.copy( ray.origin );
  3152. this.direction.copy( ray.direction );
  3153. return this;
  3154. }
  3155. at( t, target ) {
  3156. return target.copy( this.origin ).addScaledVector( this.direction, t );
  3157. }
  3158. lookAt( v ) {
  3159. this.direction.copy( v ).sub( this.origin ).normalize();
  3160. return this;
  3161. }
  3162. recast( t ) {
  3163. this.origin.copy( this.at( t, _vector$a ) );
  3164. return this;
  3165. }
  3166. closestPointToPoint( point, target ) {
  3167. target.subVectors( point, this.origin );
  3168. const directionDistance = target.dot( this.direction );
  3169. if ( directionDistance < 0 ) {
  3170. return target.copy( this.origin );
  3171. }
  3172. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3173. }
  3174. distanceToPoint( point ) {
  3175. return Math.sqrt( this.distanceSqToPoint( point ) );
  3176. }
  3177. distanceSqToPoint( point ) {
  3178. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3179. // point behind the ray
  3180. if ( directionDistance < 0 ) {
  3181. return this.origin.distanceToSquared( point );
  3182. }
  3183. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3184. return _vector$a.distanceToSquared( point );
  3185. }
  3186. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3187. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3188. // It returns the min distance between the ray and the segment
  3189. // defined by v0 and v1
  3190. // It can also set two optional targets :
  3191. // - The closest point on the ray
  3192. // - The closest point on the segment
  3193. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3194. _segDir.copy( v1 ).sub( v0 ).normalize();
  3195. _diff.copy( this.origin ).sub( _segCenter );
  3196. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3197. const a01 = - this.direction.dot( _segDir );
  3198. const b0 = _diff.dot( this.direction );
  3199. const b1 = - _diff.dot( _segDir );
  3200. const c = _diff.lengthSq();
  3201. const det = Math.abs( 1 - a01 * a01 );
  3202. let s0, s1, sqrDist, extDet;
  3203. if ( det > 0 ) {
  3204. // The ray and segment are not parallel.
  3205. s0 = a01 * b1 - b0;
  3206. s1 = a01 * b0 - b1;
  3207. extDet = segExtent * det;
  3208. if ( s0 >= 0 ) {
  3209. if ( s1 >= - extDet ) {
  3210. if ( s1 <= extDet ) {
  3211. // region 0
  3212. // Minimum at interior points of ray and segment.
  3213. const invDet = 1 / det;
  3214. s0 *= invDet;
  3215. s1 *= invDet;
  3216. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3217. } else {
  3218. // region 1
  3219. s1 = segExtent;
  3220. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3221. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3222. }
  3223. } else {
  3224. // region 5
  3225. s1 = - segExtent;
  3226. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3227. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3228. }
  3229. } else {
  3230. if ( s1 <= - extDet ) {
  3231. // region 4
  3232. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3233. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3234. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3235. } else if ( s1 <= extDet ) {
  3236. // region 3
  3237. s0 = 0;
  3238. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3239. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3240. } else {
  3241. // region 2
  3242. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3243. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3244. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3245. }
  3246. }
  3247. } else {
  3248. // Ray and segment are parallel.
  3249. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3250. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3251. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3252. }
  3253. if ( optionalPointOnRay ) {
  3254. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  3255. }
  3256. if ( optionalPointOnSegment ) {
  3257. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  3258. }
  3259. return sqrDist;
  3260. }
  3261. intersectSphere( sphere, target ) {
  3262. _vector$a.subVectors( sphere.center, this.origin );
  3263. const tca = _vector$a.dot( this.direction );
  3264. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3265. const radius2 = sphere.radius * sphere.radius;
  3266. if ( d2 > radius2 ) return null;
  3267. const thc = Math.sqrt( radius2 - d2 );
  3268. // t0 = first intersect point - entrance on front of sphere
  3269. const t0 = tca - thc;
  3270. // t1 = second intersect point - exit point on back of sphere
  3271. const t1 = tca + thc;
  3272. // test to see if t1 is behind the ray - if so, return null
  3273. if ( t1 < 0 ) return null;
  3274. // test to see if t0 is behind the ray:
  3275. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3276. // in order to always return an intersect point that is in front of the ray.
  3277. if ( t0 < 0 ) return this.at( t1, target );
  3278. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3279. return this.at( t0, target );
  3280. }
  3281. intersectsSphere( sphere ) {
  3282. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3283. }
  3284. distanceToPlane( plane ) {
  3285. const denominator = plane.normal.dot( this.direction );
  3286. if ( denominator === 0 ) {
  3287. // line is coplanar, return origin
  3288. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3289. return 0;
  3290. }
  3291. // Null is preferable to undefined since undefined means.... it is undefined
  3292. return null;
  3293. }
  3294. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3295. // Return if the ray never intersects the plane
  3296. return t >= 0 ? t : null;
  3297. }
  3298. intersectPlane( plane, target ) {
  3299. const t = this.distanceToPlane( plane );
  3300. if ( t === null ) {
  3301. return null;
  3302. }
  3303. return this.at( t, target );
  3304. }
  3305. intersectsPlane( plane ) {
  3306. // check if the ray lies on the plane first
  3307. const distToPoint = plane.distanceToPoint( this.origin );
  3308. if ( distToPoint === 0 ) {
  3309. return true;
  3310. }
  3311. const denominator = plane.normal.dot( this.direction );
  3312. if ( denominator * distToPoint < 0 ) {
  3313. return true;
  3314. }
  3315. // ray origin is behind the plane (and is pointing behind it)
  3316. return false;
  3317. }
  3318. intersectBox( box, target ) {
  3319. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3320. const invdirx = 1 / this.direction.x,
  3321. invdiry = 1 / this.direction.y,
  3322. invdirz = 1 / this.direction.z;
  3323. const origin = this.origin;
  3324. if ( invdirx >= 0 ) {
  3325. tmin = ( box.min.x - origin.x ) * invdirx;
  3326. tmax = ( box.max.x - origin.x ) * invdirx;
  3327. } else {
  3328. tmin = ( box.max.x - origin.x ) * invdirx;
  3329. tmax = ( box.min.x - origin.x ) * invdirx;
  3330. }
  3331. if ( invdiry >= 0 ) {
  3332. tymin = ( box.min.y - origin.y ) * invdiry;
  3333. tymax = ( box.max.y - origin.y ) * invdiry;
  3334. } else {
  3335. tymin = ( box.max.y - origin.y ) * invdiry;
  3336. tymax = ( box.min.y - origin.y ) * invdiry;
  3337. }
  3338. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3339. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3340. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3341. if ( invdirz >= 0 ) {
  3342. tzmin = ( box.min.z - origin.z ) * invdirz;
  3343. tzmax = ( box.max.z - origin.z ) * invdirz;
  3344. } else {
  3345. tzmin = ( box.max.z - origin.z ) * invdirz;
  3346. tzmax = ( box.min.z - origin.z ) * invdirz;
  3347. }
  3348. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3349. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3350. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3351. //return point closest to the ray (positive side)
  3352. if ( tmax < 0 ) return null;
  3353. return this.at( tmin >= 0 ? tmin : tmax, target );
  3354. }
  3355. intersectsBox( box ) {
  3356. return this.intersectBox( box, _vector$a ) !== null;
  3357. }
  3358. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3359. // Compute the offset origin, edges, and normal.
  3360. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3361. _edge1.subVectors( b, a );
  3362. _edge2.subVectors( c, a );
  3363. _normal$1.crossVectors( _edge1, _edge2 );
  3364. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3365. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3366. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3367. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3368. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3369. let DdN = this.direction.dot( _normal$1 );
  3370. let sign;
  3371. if ( DdN > 0 ) {
  3372. if ( backfaceCulling ) return null;
  3373. sign = 1;
  3374. } else if ( DdN < 0 ) {
  3375. sign = - 1;
  3376. DdN = - DdN;
  3377. } else {
  3378. return null;
  3379. }
  3380. _diff.subVectors( this.origin, a );
  3381. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3382. // b1 < 0, no intersection
  3383. if ( DdQxE2 < 0 ) {
  3384. return null;
  3385. }
  3386. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3387. // b2 < 0, no intersection
  3388. if ( DdE1xQ < 0 ) {
  3389. return null;
  3390. }
  3391. // b1+b2 > 1, no intersection
  3392. if ( DdQxE2 + DdE1xQ > DdN ) {
  3393. return null;
  3394. }
  3395. // Line intersects triangle, check if ray does.
  3396. const QdN = - sign * _diff.dot( _normal$1 );
  3397. // t < 0, no intersection
  3398. if ( QdN < 0 ) {
  3399. return null;
  3400. }
  3401. // Ray intersects triangle.
  3402. return this.at( QdN / DdN, target );
  3403. }
  3404. applyMatrix4( matrix4 ) {
  3405. this.origin.applyMatrix4( matrix4 );
  3406. this.direction.transformDirection( matrix4 );
  3407. return this;
  3408. }
  3409. equals( ray ) {
  3410. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3411. }
  3412. clone() {
  3413. return new this.constructor().copy( this );
  3414. }
  3415. }
  3416. class Matrix4 {
  3417. constructor() {
  3418. Matrix4.prototype.isMatrix4 = true;
  3419. this.elements = [
  3420. 1, 0, 0, 0,
  3421. 0, 1, 0, 0,
  3422. 0, 0, 1, 0,
  3423. 0, 0, 0, 1
  3424. ];
  3425. }
  3426. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3427. const te = this.elements;
  3428. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3429. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3430. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3431. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3432. return this;
  3433. }
  3434. identity() {
  3435. this.set(
  3436. 1, 0, 0, 0,
  3437. 0, 1, 0, 0,
  3438. 0, 0, 1, 0,
  3439. 0, 0, 0, 1
  3440. );
  3441. return this;
  3442. }
  3443. clone() {
  3444. return new Matrix4().fromArray( this.elements );
  3445. }
  3446. copy( m ) {
  3447. const te = this.elements;
  3448. const me = m.elements;
  3449. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3450. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3451. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3452. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3453. return this;
  3454. }
  3455. copyPosition( m ) {
  3456. const te = this.elements, me = m.elements;
  3457. te[ 12 ] = me[ 12 ];
  3458. te[ 13 ] = me[ 13 ];
  3459. te[ 14 ] = me[ 14 ];
  3460. return this;
  3461. }
  3462. setFromMatrix3( m ) {
  3463. const me = m.elements;
  3464. this.set(
  3465. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3466. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3467. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3468. 0, 0, 0, 1
  3469. );
  3470. return this;
  3471. }
  3472. extractBasis( xAxis, yAxis, zAxis ) {
  3473. xAxis.setFromMatrixColumn( this, 0 );
  3474. yAxis.setFromMatrixColumn( this, 1 );
  3475. zAxis.setFromMatrixColumn( this, 2 );
  3476. return this;
  3477. }
  3478. makeBasis( xAxis, yAxis, zAxis ) {
  3479. this.set(
  3480. xAxis.x, yAxis.x, zAxis.x, 0,
  3481. xAxis.y, yAxis.y, zAxis.y, 0,
  3482. xAxis.z, yAxis.z, zAxis.z, 0,
  3483. 0, 0, 0, 1
  3484. );
  3485. return this;
  3486. }
  3487. extractRotation( m ) {
  3488. // this method does not support reflection matrices
  3489. const te = this.elements;
  3490. const me = m.elements;
  3491. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3492. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3493. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3494. te[ 0 ] = me[ 0 ] * scaleX;
  3495. te[ 1 ] = me[ 1 ] * scaleX;
  3496. te[ 2 ] = me[ 2 ] * scaleX;
  3497. te[ 3 ] = 0;
  3498. te[ 4 ] = me[ 4 ] * scaleY;
  3499. te[ 5 ] = me[ 5 ] * scaleY;
  3500. te[ 6 ] = me[ 6 ] * scaleY;
  3501. te[ 7 ] = 0;
  3502. te[ 8 ] = me[ 8 ] * scaleZ;
  3503. te[ 9 ] = me[ 9 ] * scaleZ;
  3504. te[ 10 ] = me[ 10 ] * scaleZ;
  3505. te[ 11 ] = 0;
  3506. te[ 12 ] = 0;
  3507. te[ 13 ] = 0;
  3508. te[ 14 ] = 0;
  3509. te[ 15 ] = 1;
  3510. return this;
  3511. }
  3512. makeRotationFromEuler( euler ) {
  3513. const te = this.elements;
  3514. const x = euler.x, y = euler.y, z = euler.z;
  3515. const a = Math.cos( x ), b = Math.sin( x );
  3516. const c = Math.cos( y ), d = Math.sin( y );
  3517. const e = Math.cos( z ), f = Math.sin( z );
  3518. if ( euler.order === 'XYZ' ) {
  3519. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3520. te[ 0 ] = c * e;
  3521. te[ 4 ] = - c * f;
  3522. te[ 8 ] = d;
  3523. te[ 1 ] = af + be * d;
  3524. te[ 5 ] = ae - bf * d;
  3525. te[ 9 ] = - b * c;
  3526. te[ 2 ] = bf - ae * d;
  3527. te[ 6 ] = be + af * d;
  3528. te[ 10 ] = a * c;
  3529. } else if ( euler.order === 'YXZ' ) {
  3530. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3531. te[ 0 ] = ce + df * b;
  3532. te[ 4 ] = de * b - cf;
  3533. te[ 8 ] = a * d;
  3534. te[ 1 ] = a * f;
  3535. te[ 5 ] = a * e;
  3536. te[ 9 ] = - b;
  3537. te[ 2 ] = cf * b - de;
  3538. te[ 6 ] = df + ce * b;
  3539. te[ 10 ] = a * c;
  3540. } else if ( euler.order === 'ZXY' ) {
  3541. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3542. te[ 0 ] = ce - df * b;
  3543. te[ 4 ] = - a * f;
  3544. te[ 8 ] = de + cf * b;
  3545. te[ 1 ] = cf + de * b;
  3546. te[ 5 ] = a * e;
  3547. te[ 9 ] = df - ce * b;
  3548. te[ 2 ] = - a * d;
  3549. te[ 6 ] = b;
  3550. te[ 10 ] = a * c;
  3551. } else if ( euler.order === 'ZYX' ) {
  3552. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3553. te[ 0 ] = c * e;
  3554. te[ 4 ] = be * d - af;
  3555. te[ 8 ] = ae * d + bf;
  3556. te[ 1 ] = c * f;
  3557. te[ 5 ] = bf * d + ae;
  3558. te[ 9 ] = af * d - be;
  3559. te[ 2 ] = - d;
  3560. te[ 6 ] = b * c;
  3561. te[ 10 ] = a * c;
  3562. } else if ( euler.order === 'YZX' ) {
  3563. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3564. te[ 0 ] = c * e;
  3565. te[ 4 ] = bd - ac * f;
  3566. te[ 8 ] = bc * f + ad;
  3567. te[ 1 ] = f;
  3568. te[ 5 ] = a * e;
  3569. te[ 9 ] = - b * e;
  3570. te[ 2 ] = - d * e;
  3571. te[ 6 ] = ad * f + bc;
  3572. te[ 10 ] = ac - bd * f;
  3573. } else if ( euler.order === 'XZY' ) {
  3574. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3575. te[ 0 ] = c * e;
  3576. te[ 4 ] = - f;
  3577. te[ 8 ] = d * e;
  3578. te[ 1 ] = ac * f + bd;
  3579. te[ 5 ] = a * e;
  3580. te[ 9 ] = ad * f - bc;
  3581. te[ 2 ] = bc * f - ad;
  3582. te[ 6 ] = b * e;
  3583. te[ 10 ] = bd * f + ac;
  3584. }
  3585. // bottom row
  3586. te[ 3 ] = 0;
  3587. te[ 7 ] = 0;
  3588. te[ 11 ] = 0;
  3589. // last column
  3590. te[ 12 ] = 0;
  3591. te[ 13 ] = 0;
  3592. te[ 14 ] = 0;
  3593. te[ 15 ] = 1;
  3594. return this;
  3595. }
  3596. makeRotationFromQuaternion( q ) {
  3597. return this.compose( _zero, q, _one );
  3598. }
  3599. lookAt( eye, target, up ) {
  3600. const te = this.elements;
  3601. _z.subVectors( eye, target );
  3602. if ( _z.lengthSq() === 0 ) {
  3603. // eye and target are in the same position
  3604. _z.z = 1;
  3605. }
  3606. _z.normalize();
  3607. _x.crossVectors( up, _z );
  3608. if ( _x.lengthSq() === 0 ) {
  3609. // up and z are parallel
  3610. if ( Math.abs( up.z ) === 1 ) {
  3611. _z.x += 0.0001;
  3612. } else {
  3613. _z.z += 0.0001;
  3614. }
  3615. _z.normalize();
  3616. _x.crossVectors( up, _z );
  3617. }
  3618. _x.normalize();
  3619. _y.crossVectors( _z, _x );
  3620. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3621. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3622. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3623. return this;
  3624. }
  3625. multiply( m ) {
  3626. return this.multiplyMatrices( this, m );
  3627. }
  3628. premultiply( m ) {
  3629. return this.multiplyMatrices( m, this );
  3630. }
  3631. multiplyMatrices( a, b ) {
  3632. const ae = a.elements;
  3633. const be = b.elements;
  3634. const te = this.elements;
  3635. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3636. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3637. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3638. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3639. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3640. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3641. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3642. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3643. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3644. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3645. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3646. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3647. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3648. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3649. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3650. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3651. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3652. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3653. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3654. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3655. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3656. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3657. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3658. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3659. return this;
  3660. }
  3661. multiplyScalar( s ) {
  3662. const te = this.elements;
  3663. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3664. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3665. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3666. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3667. return this;
  3668. }
  3669. determinant() {
  3670. const te = this.elements;
  3671. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3672. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3673. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3674. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3675. //TODO: make this more efficient
  3676. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3677. return (
  3678. n41 * (
  3679. + n14 * n23 * n32
  3680. - n13 * n24 * n32
  3681. - n14 * n22 * n33
  3682. + n12 * n24 * n33
  3683. + n13 * n22 * n34
  3684. - n12 * n23 * n34
  3685. ) +
  3686. n42 * (
  3687. + n11 * n23 * n34
  3688. - n11 * n24 * n33
  3689. + n14 * n21 * n33
  3690. - n13 * n21 * n34
  3691. + n13 * n24 * n31
  3692. - n14 * n23 * n31
  3693. ) +
  3694. n43 * (
  3695. + n11 * n24 * n32
  3696. - n11 * n22 * n34
  3697. - n14 * n21 * n32
  3698. + n12 * n21 * n34
  3699. + n14 * n22 * n31
  3700. - n12 * n24 * n31
  3701. ) +
  3702. n44 * (
  3703. - n13 * n22 * n31
  3704. - n11 * n23 * n32
  3705. + n11 * n22 * n33
  3706. + n13 * n21 * n32
  3707. - n12 * n21 * n33
  3708. + n12 * n23 * n31
  3709. )
  3710. );
  3711. }
  3712. transpose() {
  3713. const te = this.elements;
  3714. let tmp;
  3715. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3716. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3717. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3718. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3719. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3720. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3721. return this;
  3722. }
  3723. setPosition( x, y, z ) {
  3724. const te = this.elements;
  3725. if ( x.isVector3 ) {
  3726. te[ 12 ] = x.x;
  3727. te[ 13 ] = x.y;
  3728. te[ 14 ] = x.z;
  3729. } else {
  3730. te[ 12 ] = x;
  3731. te[ 13 ] = y;
  3732. te[ 14 ] = z;
  3733. }
  3734. return this;
  3735. }
  3736. invert() {
  3737. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3738. const te = this.elements,
  3739. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3740. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3741. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3742. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3743. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3744. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3745. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3746. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3747. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3748. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3749. const detInv = 1 / det;
  3750. te[ 0 ] = t11 * detInv;
  3751. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3752. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3753. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3754. te[ 4 ] = t12 * detInv;
  3755. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3756. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3757. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3758. te[ 8 ] = t13 * detInv;
  3759. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3760. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3761. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3762. te[ 12 ] = t14 * detInv;
  3763. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3764. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3765. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3766. return this;
  3767. }
  3768. scale( v ) {
  3769. const te = this.elements;
  3770. const x = v.x, y = v.y, z = v.z;
  3771. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3772. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3773. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3774. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3775. return this;
  3776. }
  3777. getMaxScaleOnAxis() {
  3778. const te = this.elements;
  3779. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3780. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3781. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3782. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3783. }
  3784. makeTranslation( x, y, z ) {
  3785. this.set(
  3786. 1, 0, 0, x,
  3787. 0, 1, 0, y,
  3788. 0, 0, 1, z,
  3789. 0, 0, 0, 1
  3790. );
  3791. return this;
  3792. }
  3793. makeRotationX( theta ) {
  3794. const c = Math.cos( theta ), s = Math.sin( theta );
  3795. this.set(
  3796. 1, 0, 0, 0,
  3797. 0, c, - s, 0,
  3798. 0, s, c, 0,
  3799. 0, 0, 0, 1
  3800. );
  3801. return this;
  3802. }
  3803. makeRotationY( theta ) {
  3804. const c = Math.cos( theta ), s = Math.sin( theta );
  3805. this.set(
  3806. c, 0, s, 0,
  3807. 0, 1, 0, 0,
  3808. - s, 0, c, 0,
  3809. 0, 0, 0, 1
  3810. );
  3811. return this;
  3812. }
  3813. makeRotationZ( theta ) {
  3814. const c = Math.cos( theta ), s = Math.sin( theta );
  3815. this.set(
  3816. c, - s, 0, 0,
  3817. s, c, 0, 0,
  3818. 0, 0, 1, 0,
  3819. 0, 0, 0, 1
  3820. );
  3821. return this;
  3822. }
  3823. makeRotationAxis( axis, angle ) {
  3824. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3825. const c = Math.cos( angle );
  3826. const s = Math.sin( angle );
  3827. const t = 1 - c;
  3828. const x = axis.x, y = axis.y, z = axis.z;
  3829. const tx = t * x, ty = t * y;
  3830. this.set(
  3831. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3832. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3833. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3834. 0, 0, 0, 1
  3835. );
  3836. return this;
  3837. }
  3838. makeScale( x, y, z ) {
  3839. this.set(
  3840. x, 0, 0, 0,
  3841. 0, y, 0, 0,
  3842. 0, 0, z, 0,
  3843. 0, 0, 0, 1
  3844. );
  3845. return this;
  3846. }
  3847. makeShear( xy, xz, yx, yz, zx, zy ) {
  3848. this.set(
  3849. 1, yx, zx, 0,
  3850. xy, 1, zy, 0,
  3851. xz, yz, 1, 0,
  3852. 0, 0, 0, 1
  3853. );
  3854. return this;
  3855. }
  3856. compose( position, quaternion, scale ) {
  3857. const te = this.elements;
  3858. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3859. const x2 = x + x, y2 = y + y, z2 = z + z;
  3860. const xx = x * x2, xy = x * y2, xz = x * z2;
  3861. const yy = y * y2, yz = y * z2, zz = z * z2;
  3862. const wx = w * x2, wy = w * y2, wz = w * z2;
  3863. const sx = scale.x, sy = scale.y, sz = scale.z;
  3864. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3865. te[ 1 ] = ( xy + wz ) * sx;
  3866. te[ 2 ] = ( xz - wy ) * sx;
  3867. te[ 3 ] = 0;
  3868. te[ 4 ] = ( xy - wz ) * sy;
  3869. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3870. te[ 6 ] = ( yz + wx ) * sy;
  3871. te[ 7 ] = 0;
  3872. te[ 8 ] = ( xz + wy ) * sz;
  3873. te[ 9 ] = ( yz - wx ) * sz;
  3874. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3875. te[ 11 ] = 0;
  3876. te[ 12 ] = position.x;
  3877. te[ 13 ] = position.y;
  3878. te[ 14 ] = position.z;
  3879. te[ 15 ] = 1;
  3880. return this;
  3881. }
  3882. decompose( position, quaternion, scale ) {
  3883. const te = this.elements;
  3884. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3885. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3886. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3887. // if determine is negative, we need to invert one scale
  3888. const det = this.determinant();
  3889. if ( det < 0 ) sx = - sx;
  3890. position.x = te[ 12 ];
  3891. position.y = te[ 13 ];
  3892. position.z = te[ 14 ];
  3893. // scale the rotation part
  3894. _m1$2.copy( this );
  3895. const invSX = 1 / sx;
  3896. const invSY = 1 / sy;
  3897. const invSZ = 1 / sz;
  3898. _m1$2.elements[ 0 ] *= invSX;
  3899. _m1$2.elements[ 1 ] *= invSX;
  3900. _m1$2.elements[ 2 ] *= invSX;
  3901. _m1$2.elements[ 4 ] *= invSY;
  3902. _m1$2.elements[ 5 ] *= invSY;
  3903. _m1$2.elements[ 6 ] *= invSY;
  3904. _m1$2.elements[ 8 ] *= invSZ;
  3905. _m1$2.elements[ 9 ] *= invSZ;
  3906. _m1$2.elements[ 10 ] *= invSZ;
  3907. quaternion.setFromRotationMatrix( _m1$2 );
  3908. scale.x = sx;
  3909. scale.y = sy;
  3910. scale.z = sz;
  3911. return this;
  3912. }
  3913. makePerspective( left, right, top, bottom, near, far ) {
  3914. const te = this.elements;
  3915. const x = 2 * near / ( right - left );
  3916. const y = 2 * near / ( top - bottom );
  3917. const a = ( right + left ) / ( right - left );
  3918. const b = ( top + bottom ) / ( top - bottom );
  3919. const c = - ( far + near ) / ( far - near );
  3920. const d = - 2 * far * near / ( far - near );
  3921. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3922. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3923. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  3924. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  3925. return this;
  3926. }
  3927. makeOrthographic( left, right, top, bottom, near, far ) {
  3928. const te = this.elements;
  3929. const w = 1.0 / ( right - left );
  3930. const h = 1.0 / ( top - bottom );
  3931. const p = 1.0 / ( far - near );
  3932. const x = ( right + left ) * w;
  3933. const y = ( top + bottom ) * h;
  3934. const z = ( far + near ) * p;
  3935. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  3936. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  3937. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  3938. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  3939. return this;
  3940. }
  3941. equals( matrix ) {
  3942. const te = this.elements;
  3943. const me = matrix.elements;
  3944. for ( let i = 0; i < 16; i ++ ) {
  3945. if ( te[ i ] !== me[ i ] ) return false;
  3946. }
  3947. return true;
  3948. }
  3949. fromArray( array, offset = 0 ) {
  3950. for ( let i = 0; i < 16; i ++ ) {
  3951. this.elements[ i ] = array[ i + offset ];
  3952. }
  3953. return this;
  3954. }
  3955. toArray( array = [], offset = 0 ) {
  3956. const te = this.elements;
  3957. array[ offset ] = te[ 0 ];
  3958. array[ offset + 1 ] = te[ 1 ];
  3959. array[ offset + 2 ] = te[ 2 ];
  3960. array[ offset + 3 ] = te[ 3 ];
  3961. array[ offset + 4 ] = te[ 4 ];
  3962. array[ offset + 5 ] = te[ 5 ];
  3963. array[ offset + 6 ] = te[ 6 ];
  3964. array[ offset + 7 ] = te[ 7 ];
  3965. array[ offset + 8 ] = te[ 8 ];
  3966. array[ offset + 9 ] = te[ 9 ];
  3967. array[ offset + 10 ] = te[ 10 ];
  3968. array[ offset + 11 ] = te[ 11 ];
  3969. array[ offset + 12 ] = te[ 12 ];
  3970. array[ offset + 13 ] = te[ 13 ];
  3971. array[ offset + 14 ] = te[ 14 ];
  3972. array[ offset + 15 ] = te[ 15 ];
  3973. return array;
  3974. }
  3975. }
  3976. const _v1$5 = /*@__PURE__*/ new Vector3();
  3977. const _m1$2 = /*@__PURE__*/ new Matrix4();
  3978. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  3979. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  3980. const _x = /*@__PURE__*/ new Vector3();
  3981. const _y = /*@__PURE__*/ new Vector3();
  3982. const _z = /*@__PURE__*/ new Vector3();
  3983. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  3984. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  3985. class Euler {
  3986. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  3987. this.isEuler = true;
  3988. this._x = x;
  3989. this._y = y;
  3990. this._z = z;
  3991. this._order = order;
  3992. }
  3993. get x() {
  3994. return this._x;
  3995. }
  3996. set x( value ) {
  3997. this._x = value;
  3998. this._onChangeCallback();
  3999. }
  4000. get y() {
  4001. return this._y;
  4002. }
  4003. set y( value ) {
  4004. this._y = value;
  4005. this._onChangeCallback();
  4006. }
  4007. get z() {
  4008. return this._z;
  4009. }
  4010. set z( value ) {
  4011. this._z = value;
  4012. this._onChangeCallback();
  4013. }
  4014. get order() {
  4015. return this._order;
  4016. }
  4017. set order( value ) {
  4018. this._order = value;
  4019. this._onChangeCallback();
  4020. }
  4021. set( x, y, z, order = this._order ) {
  4022. this._x = x;
  4023. this._y = y;
  4024. this._z = z;
  4025. this._order = order;
  4026. this._onChangeCallback();
  4027. return this;
  4028. }
  4029. clone() {
  4030. return new this.constructor( this._x, this._y, this._z, this._order );
  4031. }
  4032. copy( euler ) {
  4033. this._x = euler._x;
  4034. this._y = euler._y;
  4035. this._z = euler._z;
  4036. this._order = euler._order;
  4037. this._onChangeCallback();
  4038. return this;
  4039. }
  4040. setFromRotationMatrix( m, order = this._order, update = true ) {
  4041. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4042. const te = m.elements;
  4043. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4044. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4045. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4046. switch ( order ) {
  4047. case 'XYZ':
  4048. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  4049. if ( Math.abs( m13 ) < 0.9999999 ) {
  4050. this._x = Math.atan2( - m23, m33 );
  4051. this._z = Math.atan2( - m12, m11 );
  4052. } else {
  4053. this._x = Math.atan2( m32, m22 );
  4054. this._z = 0;
  4055. }
  4056. break;
  4057. case 'YXZ':
  4058. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  4059. if ( Math.abs( m23 ) < 0.9999999 ) {
  4060. this._y = Math.atan2( m13, m33 );
  4061. this._z = Math.atan2( m21, m22 );
  4062. } else {
  4063. this._y = Math.atan2( - m31, m11 );
  4064. this._z = 0;
  4065. }
  4066. break;
  4067. case 'ZXY':
  4068. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  4069. if ( Math.abs( m32 ) < 0.9999999 ) {
  4070. this._y = Math.atan2( - m31, m33 );
  4071. this._z = Math.atan2( - m12, m22 );
  4072. } else {
  4073. this._y = 0;
  4074. this._z = Math.atan2( m21, m11 );
  4075. }
  4076. break;
  4077. case 'ZYX':
  4078. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  4079. if ( Math.abs( m31 ) < 0.9999999 ) {
  4080. this._x = Math.atan2( m32, m33 );
  4081. this._z = Math.atan2( m21, m11 );
  4082. } else {
  4083. this._x = 0;
  4084. this._z = Math.atan2( - m12, m22 );
  4085. }
  4086. break;
  4087. case 'YZX':
  4088. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  4089. if ( Math.abs( m21 ) < 0.9999999 ) {
  4090. this._x = Math.atan2( - m23, m22 );
  4091. this._y = Math.atan2( - m31, m11 );
  4092. } else {
  4093. this._x = 0;
  4094. this._y = Math.atan2( m13, m33 );
  4095. }
  4096. break;
  4097. case 'XZY':
  4098. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  4099. if ( Math.abs( m12 ) < 0.9999999 ) {
  4100. this._x = Math.atan2( m32, m22 );
  4101. this._y = Math.atan2( m13, m11 );
  4102. } else {
  4103. this._x = Math.atan2( - m23, m33 );
  4104. this._y = 0;
  4105. }
  4106. break;
  4107. default:
  4108. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4109. }
  4110. this._order = order;
  4111. if ( update === true ) this._onChangeCallback();
  4112. return this;
  4113. }
  4114. setFromQuaternion( q, order, update ) {
  4115. _matrix$1.makeRotationFromQuaternion( q );
  4116. return this.setFromRotationMatrix( _matrix$1, order, update );
  4117. }
  4118. setFromVector3( v, order = this._order ) {
  4119. return this.set( v.x, v.y, v.z, order );
  4120. }
  4121. reorder( newOrder ) {
  4122. // WARNING: this discards revolution information -bhouston
  4123. _quaternion$3.setFromEuler( this );
  4124. return this.setFromQuaternion( _quaternion$3, newOrder );
  4125. }
  4126. equals( euler ) {
  4127. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4128. }
  4129. fromArray( array ) {
  4130. this._x = array[ 0 ];
  4131. this._y = array[ 1 ];
  4132. this._z = array[ 2 ];
  4133. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4134. this._onChangeCallback();
  4135. return this;
  4136. }
  4137. toArray( array = [], offset = 0 ) {
  4138. array[ offset ] = this._x;
  4139. array[ offset + 1 ] = this._y;
  4140. array[ offset + 2 ] = this._z;
  4141. array[ offset + 3 ] = this._order;
  4142. return array;
  4143. }
  4144. _onChange( callback ) {
  4145. this._onChangeCallback = callback;
  4146. return this;
  4147. }
  4148. _onChangeCallback() {}
  4149. *[ Symbol.iterator ]() {
  4150. yield this._x;
  4151. yield this._y;
  4152. yield this._z;
  4153. yield this._order;
  4154. }
  4155. }
  4156. Euler.DEFAULT_ORDER = 'XYZ';
  4157. class Layers {
  4158. constructor() {
  4159. this.mask = 1 | 0;
  4160. }
  4161. set( channel ) {
  4162. this.mask = ( 1 << channel | 0 ) >>> 0;
  4163. }
  4164. enable( channel ) {
  4165. this.mask |= 1 << channel | 0;
  4166. }
  4167. enableAll() {
  4168. this.mask = 0xffffffff | 0;
  4169. }
  4170. toggle( channel ) {
  4171. this.mask ^= 1 << channel | 0;
  4172. }
  4173. disable( channel ) {
  4174. this.mask &= ~ ( 1 << channel | 0 );
  4175. }
  4176. disableAll() {
  4177. this.mask = 0;
  4178. }
  4179. test( layers ) {
  4180. return ( this.mask & layers.mask ) !== 0;
  4181. }
  4182. isEnabled( channel ) {
  4183. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4184. }
  4185. }
  4186. let _object3DId = 0;
  4187. const _v1$4 = /*@__PURE__*/ new Vector3();
  4188. const _q1 = /*@__PURE__*/ new Quaternion();
  4189. const _m1$1 = /*@__PURE__*/ new Matrix4();
  4190. const _target = /*@__PURE__*/ new Vector3();
  4191. const _position$3 = /*@__PURE__*/ new Vector3();
  4192. const _scale$2 = /*@__PURE__*/ new Vector3();
  4193. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4194. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4195. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4196. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4197. const _addedEvent = { type: 'added' };
  4198. const _removedEvent = { type: 'removed' };
  4199. class Object3D extends EventDispatcher {
  4200. constructor() {
  4201. super();
  4202. this.isObject3D = true;
  4203. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4204. this.uuid = generateUUID();
  4205. this.name = '';
  4206. this.type = 'Object3D';
  4207. this.parent = null;
  4208. this.children = [];
  4209. this.up = Object3D.DEFAULT_UP.clone();
  4210. const position = new Vector3();
  4211. const rotation = new Euler();
  4212. const quaternion = new Quaternion();
  4213. const scale = new Vector3( 1, 1, 1 );
  4214. function onRotationChange() {
  4215. quaternion.setFromEuler( rotation, false );
  4216. }
  4217. function onQuaternionChange() {
  4218. rotation.setFromQuaternion( quaternion, undefined, false );
  4219. }
  4220. rotation._onChange( onRotationChange );
  4221. quaternion._onChange( onQuaternionChange );
  4222. Object.defineProperties( this, {
  4223. position: {
  4224. configurable: true,
  4225. enumerable: true,
  4226. value: position
  4227. },
  4228. rotation: {
  4229. configurable: true,
  4230. enumerable: true,
  4231. value: rotation
  4232. },
  4233. quaternion: {
  4234. configurable: true,
  4235. enumerable: true,
  4236. value: quaternion
  4237. },
  4238. scale: {
  4239. configurable: true,
  4240. enumerable: true,
  4241. value: scale
  4242. },
  4243. modelViewMatrix: {
  4244. value: new Matrix4()
  4245. },
  4246. normalMatrix: {
  4247. value: new Matrix3()
  4248. }
  4249. } );
  4250. this.matrix = new Matrix4();
  4251. this.matrixWorld = new Matrix4();
  4252. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4253. this.matrixWorldNeedsUpdate = false;
  4254. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4255. this.layers = new Layers();
  4256. this.visible = true;
  4257. this.castShadow = false;
  4258. this.receiveShadow = false;
  4259. this.frustumCulled = true;
  4260. this.renderOrder = 0;
  4261. this.animations = [];
  4262. this.userData = {};
  4263. }
  4264. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4265. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4266. applyMatrix4( matrix ) {
  4267. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4268. this.matrix.premultiply( matrix );
  4269. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4270. }
  4271. applyQuaternion( q ) {
  4272. this.quaternion.premultiply( q );
  4273. return this;
  4274. }
  4275. setRotationFromAxisAngle( axis, angle ) {
  4276. // assumes axis is normalized
  4277. this.quaternion.setFromAxisAngle( axis, angle );
  4278. }
  4279. setRotationFromEuler( euler ) {
  4280. this.quaternion.setFromEuler( euler, true );
  4281. }
  4282. setRotationFromMatrix( m ) {
  4283. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4284. this.quaternion.setFromRotationMatrix( m );
  4285. }
  4286. setRotationFromQuaternion( q ) {
  4287. // assumes q is normalized
  4288. this.quaternion.copy( q );
  4289. }
  4290. rotateOnAxis( axis, angle ) {
  4291. // rotate object on axis in object space
  4292. // axis is assumed to be normalized
  4293. _q1.setFromAxisAngle( axis, angle );
  4294. this.quaternion.multiply( _q1 );
  4295. return this;
  4296. }
  4297. rotateOnWorldAxis( axis, angle ) {
  4298. // rotate object on axis in world space
  4299. // axis is assumed to be normalized
  4300. // method assumes no rotated parent
  4301. _q1.setFromAxisAngle( axis, angle );
  4302. this.quaternion.premultiply( _q1 );
  4303. return this;
  4304. }
  4305. rotateX( angle ) {
  4306. return this.rotateOnAxis( _xAxis, angle );
  4307. }
  4308. rotateY( angle ) {
  4309. return this.rotateOnAxis( _yAxis, angle );
  4310. }
  4311. rotateZ( angle ) {
  4312. return this.rotateOnAxis( _zAxis, angle );
  4313. }
  4314. translateOnAxis( axis, distance ) {
  4315. // translate object by distance along axis in object space
  4316. // axis is assumed to be normalized
  4317. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4318. this.position.add( _v1$4.multiplyScalar( distance ) );
  4319. return this;
  4320. }
  4321. translateX( distance ) {
  4322. return this.translateOnAxis( _xAxis, distance );
  4323. }
  4324. translateY( distance ) {
  4325. return this.translateOnAxis( _yAxis, distance );
  4326. }
  4327. translateZ( distance ) {
  4328. return this.translateOnAxis( _zAxis, distance );
  4329. }
  4330. localToWorld( vector ) {
  4331. this.updateWorldMatrix( true, false );
  4332. return vector.applyMatrix4( this.matrixWorld );
  4333. }
  4334. worldToLocal( vector ) {
  4335. this.updateWorldMatrix( true, false );
  4336. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4337. }
  4338. lookAt( x, y, z ) {
  4339. // This method does not support objects having non-uniformly-scaled parent(s)
  4340. if ( x.isVector3 ) {
  4341. _target.copy( x );
  4342. } else {
  4343. _target.set( x, y, z );
  4344. }
  4345. const parent = this.parent;
  4346. this.updateWorldMatrix( true, false );
  4347. _position$3.setFromMatrixPosition( this.matrixWorld );
  4348. if ( this.isCamera || this.isLight ) {
  4349. _m1$1.lookAt( _position$3, _target, this.up );
  4350. } else {
  4351. _m1$1.lookAt( _target, _position$3, this.up );
  4352. }
  4353. this.quaternion.setFromRotationMatrix( _m1$1 );
  4354. if ( parent ) {
  4355. _m1$1.extractRotation( parent.matrixWorld );
  4356. _q1.setFromRotationMatrix( _m1$1 );
  4357. this.quaternion.premultiply( _q1.invert() );
  4358. }
  4359. }
  4360. add( object ) {
  4361. if ( arguments.length > 1 ) {
  4362. for ( let i = 0; i < arguments.length; i ++ ) {
  4363. this.add( arguments[ i ] );
  4364. }
  4365. return this;
  4366. }
  4367. if ( object === this ) {
  4368. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4369. return this;
  4370. }
  4371. if ( object && object.isObject3D ) {
  4372. if ( object.parent !== null ) {
  4373. object.parent.remove( object );
  4374. }
  4375. object.parent = this;
  4376. this.children.push( object );
  4377. object.dispatchEvent( _addedEvent );
  4378. } else {
  4379. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4380. }
  4381. return this;
  4382. }
  4383. remove( object ) {
  4384. if ( arguments.length > 1 ) {
  4385. for ( let i = 0; i < arguments.length; i ++ ) {
  4386. this.remove( arguments[ i ] );
  4387. }
  4388. return this;
  4389. }
  4390. const index = this.children.indexOf( object );
  4391. if ( index !== - 1 ) {
  4392. object.parent = null;
  4393. this.children.splice( index, 1 );
  4394. object.dispatchEvent( _removedEvent );
  4395. }
  4396. return this;
  4397. }
  4398. removeFromParent() {
  4399. const parent = this.parent;
  4400. if ( parent !== null ) {
  4401. parent.remove( this );
  4402. }
  4403. return this;
  4404. }
  4405. clear() {
  4406. for ( let i = 0; i < this.children.length; i ++ ) {
  4407. const object = this.children[ i ];
  4408. object.parent = null;
  4409. object.dispatchEvent( _removedEvent );
  4410. }
  4411. this.children.length = 0;
  4412. return this;
  4413. }
  4414. attach( object ) {
  4415. // adds object as a child of this, while maintaining the object's world transform
  4416. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4417. this.updateWorldMatrix( true, false );
  4418. _m1$1.copy( this.matrixWorld ).invert();
  4419. if ( object.parent !== null ) {
  4420. object.parent.updateWorldMatrix( true, false );
  4421. _m1$1.multiply( object.parent.matrixWorld );
  4422. }
  4423. object.applyMatrix4( _m1$1 );
  4424. this.add( object );
  4425. object.updateWorldMatrix( false, true );
  4426. return this;
  4427. }
  4428. getObjectById( id ) {
  4429. return this.getObjectByProperty( 'id', id );
  4430. }
  4431. getObjectByName( name ) {
  4432. return this.getObjectByProperty( 'name', name );
  4433. }
  4434. getObjectByProperty( name, value ) {
  4435. if ( this[ name ] === value ) return this;
  4436. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4437. const child = this.children[ i ];
  4438. const object = child.getObjectByProperty( name, value );
  4439. if ( object !== undefined ) {
  4440. return object;
  4441. }
  4442. }
  4443. return undefined;
  4444. }
  4445. getObjectsByProperty( name, value ) {
  4446. let result = [];
  4447. if ( this[ name ] === value ) result.push( this );
  4448. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4449. const childResult = this.children[ i ].getObjectsByProperty( name, value );
  4450. if ( childResult.length > 0 ) {
  4451. result = result.concat( childResult );
  4452. }
  4453. }
  4454. return result;
  4455. }
  4456. getWorldPosition( target ) {
  4457. this.updateWorldMatrix( true, false );
  4458. return target.setFromMatrixPosition( this.matrixWorld );
  4459. }
  4460. getWorldQuaternion( target ) {
  4461. this.updateWorldMatrix( true, false );
  4462. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4463. return target;
  4464. }
  4465. getWorldScale( target ) {
  4466. this.updateWorldMatrix( true, false );
  4467. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4468. return target;
  4469. }
  4470. getWorldDirection( target ) {
  4471. this.updateWorldMatrix( true, false );
  4472. const e = this.matrixWorld.elements;
  4473. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4474. }
  4475. raycast( /* raycaster, intersects */ ) {}
  4476. traverse( callback ) {
  4477. callback( this );
  4478. const children = this.children;
  4479. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4480. children[ i ].traverse( callback );
  4481. }
  4482. }
  4483. traverseVisible( callback ) {
  4484. if ( this.visible === false ) return;
  4485. callback( this );
  4486. const children = this.children;
  4487. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4488. children[ i ].traverseVisible( callback );
  4489. }
  4490. }
  4491. traverseAncestors( callback ) {
  4492. const parent = this.parent;
  4493. if ( parent !== null ) {
  4494. callback( parent );
  4495. parent.traverseAncestors( callback );
  4496. }
  4497. }
  4498. updateMatrix() {
  4499. this.matrix.compose( this.position, this.quaternion, this.scale );
  4500. this.matrixWorldNeedsUpdate = true;
  4501. }
  4502. updateMatrixWorld( force ) {
  4503. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4504. if ( this.matrixWorldNeedsUpdate || force ) {
  4505. if ( this.parent === null ) {
  4506. this.matrixWorld.copy( this.matrix );
  4507. } else {
  4508. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4509. }
  4510. this.matrixWorldNeedsUpdate = false;
  4511. force = true;
  4512. }
  4513. // update children
  4514. const children = this.children;
  4515. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4516. const child = children[ i ];
  4517. if ( child.matrixWorldAutoUpdate === true || force === true ) {
  4518. child.updateMatrixWorld( force );
  4519. }
  4520. }
  4521. }
  4522. updateWorldMatrix( updateParents, updateChildren ) {
  4523. const parent = this.parent;
  4524. if ( updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true ) {
  4525. parent.updateWorldMatrix( true, false );
  4526. }
  4527. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4528. if ( this.parent === null ) {
  4529. this.matrixWorld.copy( this.matrix );
  4530. } else {
  4531. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4532. }
  4533. // update children
  4534. if ( updateChildren === true ) {
  4535. const children = this.children;
  4536. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4537. const child = children[ i ];
  4538. if ( child.matrixWorldAutoUpdate === true ) {
  4539. child.updateWorldMatrix( false, true );
  4540. }
  4541. }
  4542. }
  4543. }
  4544. toJSON( meta ) {
  4545. // meta is a string when called from JSON.stringify
  4546. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4547. const output = {};
  4548. // meta is a hash used to collect geometries, materials.
  4549. // not providing it implies that this is the root object
  4550. // being serialized.
  4551. if ( isRootObject ) {
  4552. // initialize meta obj
  4553. meta = {
  4554. geometries: {},
  4555. materials: {},
  4556. textures: {},
  4557. images: {},
  4558. shapes: {},
  4559. skeletons: {},
  4560. animations: {},
  4561. nodes: {}
  4562. };
  4563. output.metadata = {
  4564. version: 4.5,
  4565. type: 'Object',
  4566. generator: 'Object3D.toJSON'
  4567. };
  4568. }
  4569. // standard Object3D serialization
  4570. const object = {};
  4571. object.uuid = this.uuid;
  4572. object.type = this.type;
  4573. if ( this.name !== '' ) object.name = this.name;
  4574. if ( this.castShadow === true ) object.castShadow = true;
  4575. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4576. if ( this.visible === false ) object.visible = false;
  4577. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4578. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4579. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  4580. object.layers = this.layers.mask;
  4581. object.matrix = this.matrix.toArray();
  4582. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4583. // object specific properties
  4584. if ( this.isInstancedMesh ) {
  4585. object.type = 'InstancedMesh';
  4586. object.count = this.count;
  4587. object.instanceMatrix = this.instanceMatrix.toJSON();
  4588. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4589. }
  4590. //
  4591. function serialize( library, element ) {
  4592. if ( library[ element.uuid ] === undefined ) {
  4593. library[ element.uuid ] = element.toJSON( meta );
  4594. }
  4595. return element.uuid;
  4596. }
  4597. if ( this.isScene ) {
  4598. if ( this.background ) {
  4599. if ( this.background.isColor ) {
  4600. object.background = this.background.toJSON();
  4601. } else if ( this.background.isTexture ) {
  4602. object.background = this.background.toJSON( meta ).uuid;
  4603. }
  4604. }
  4605. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4606. object.environment = this.environment.toJSON( meta ).uuid;
  4607. }
  4608. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4609. object.geometry = serialize( meta.geometries, this.geometry );
  4610. const parameters = this.geometry.parameters;
  4611. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4612. const shapes = parameters.shapes;
  4613. if ( Array.isArray( shapes ) ) {
  4614. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4615. const shape = shapes[ i ];
  4616. serialize( meta.shapes, shape );
  4617. }
  4618. } else {
  4619. serialize( meta.shapes, shapes );
  4620. }
  4621. }
  4622. }
  4623. if ( this.isSkinnedMesh ) {
  4624. object.bindMode = this.bindMode;
  4625. object.bindMatrix = this.bindMatrix.toArray();
  4626. if ( this.skeleton !== undefined ) {
  4627. serialize( meta.skeletons, this.skeleton );
  4628. object.skeleton = this.skeleton.uuid;
  4629. }
  4630. }
  4631. if ( this.material !== undefined ) {
  4632. if ( Array.isArray( this.material ) ) {
  4633. const uuids = [];
  4634. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4635. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4636. }
  4637. object.material = uuids;
  4638. } else {
  4639. object.material = serialize( meta.materials, this.material );
  4640. }
  4641. }
  4642. //
  4643. if ( this.children.length > 0 ) {
  4644. object.children = [];
  4645. for ( let i = 0; i < this.children.length; i ++ ) {
  4646. object.children.push( this.children[ i ].toJSON( meta ).object );
  4647. }
  4648. }
  4649. //
  4650. if ( this.animations.length > 0 ) {
  4651. object.animations = [];
  4652. for ( let i = 0; i < this.animations.length; i ++ ) {
  4653. const animation = this.animations[ i ];
  4654. object.animations.push( serialize( meta.animations, animation ) );
  4655. }
  4656. }
  4657. if ( isRootObject ) {
  4658. const geometries = extractFromCache( meta.geometries );
  4659. const materials = extractFromCache( meta.materials );
  4660. const textures = extractFromCache( meta.textures );
  4661. const images = extractFromCache( meta.images );
  4662. const shapes = extractFromCache( meta.shapes );
  4663. const skeletons = extractFromCache( meta.skeletons );
  4664. const animations = extractFromCache( meta.animations );
  4665. const nodes = extractFromCache( meta.nodes );
  4666. if ( geometries.length > 0 ) output.geometries = geometries;
  4667. if ( materials.length > 0 ) output.materials = materials;
  4668. if ( textures.length > 0 ) output.textures = textures;
  4669. if ( images.length > 0 ) output.images = images;
  4670. if ( shapes.length > 0 ) output.shapes = shapes;
  4671. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4672. if ( animations.length > 0 ) output.animations = animations;
  4673. if ( nodes.length > 0 ) output.nodes = nodes;
  4674. }
  4675. output.object = object;
  4676. return output;
  4677. // extract data from the cache hash
  4678. // remove metadata on each item
  4679. // and return as array
  4680. function extractFromCache( cache ) {
  4681. const values = [];
  4682. for ( const key in cache ) {
  4683. const data = cache[ key ];
  4684. delete data.metadata;
  4685. values.push( data );
  4686. }
  4687. return values;
  4688. }
  4689. }
  4690. clone( recursive ) {
  4691. return new this.constructor().copy( this, recursive );
  4692. }
  4693. copy( source, recursive = true ) {
  4694. this.name = source.name;
  4695. this.up.copy( source.up );
  4696. this.position.copy( source.position );
  4697. this.rotation.order = source.rotation.order;
  4698. this.quaternion.copy( source.quaternion );
  4699. this.scale.copy( source.scale );
  4700. this.matrix.copy( source.matrix );
  4701. this.matrixWorld.copy( source.matrixWorld );
  4702. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4703. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4704. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  4705. this.layers.mask = source.layers.mask;
  4706. this.visible = source.visible;
  4707. this.castShadow = source.castShadow;
  4708. this.receiveShadow = source.receiveShadow;
  4709. this.frustumCulled = source.frustumCulled;
  4710. this.renderOrder = source.renderOrder;
  4711. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4712. if ( recursive === true ) {
  4713. for ( let i = 0; i < source.children.length; i ++ ) {
  4714. const child = source.children[ i ];
  4715. this.add( child.clone() );
  4716. }
  4717. }
  4718. return this;
  4719. }
  4720. }
  4721. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4722. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  4723. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  4724. const _v0$1 = /*@__PURE__*/ new Vector3();
  4725. const _v1$3 = /*@__PURE__*/ new Vector3();
  4726. const _v2$2 = /*@__PURE__*/ new Vector3();
  4727. const _v3$1 = /*@__PURE__*/ new Vector3();
  4728. const _vab = /*@__PURE__*/ new Vector3();
  4729. const _vac = /*@__PURE__*/ new Vector3();
  4730. const _vbc = /*@__PURE__*/ new Vector3();
  4731. const _vap = /*@__PURE__*/ new Vector3();
  4732. const _vbp = /*@__PURE__*/ new Vector3();
  4733. const _vcp = /*@__PURE__*/ new Vector3();
  4734. class Triangle {
  4735. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4736. this.a = a;
  4737. this.b = b;
  4738. this.c = c;
  4739. }
  4740. static getNormal( a, b, c, target ) {
  4741. target.subVectors( c, b );
  4742. _v0$1.subVectors( a, b );
  4743. target.cross( _v0$1 );
  4744. const targetLengthSq = target.lengthSq();
  4745. if ( targetLengthSq > 0 ) {
  4746. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4747. }
  4748. return target.set( 0, 0, 0 );
  4749. }
  4750. // static/instance method to calculate barycentric coordinates
  4751. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4752. static getBarycoord( point, a, b, c, target ) {
  4753. _v0$1.subVectors( c, a );
  4754. _v1$3.subVectors( b, a );
  4755. _v2$2.subVectors( point, a );
  4756. const dot00 = _v0$1.dot( _v0$1 );
  4757. const dot01 = _v0$1.dot( _v1$3 );
  4758. const dot02 = _v0$1.dot( _v2$2 );
  4759. const dot11 = _v1$3.dot( _v1$3 );
  4760. const dot12 = _v1$3.dot( _v2$2 );
  4761. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4762. // collinear or singular triangle
  4763. if ( denom === 0 ) {
  4764. // arbitrary location outside of triangle?
  4765. // not sure if this is the best idea, maybe should be returning undefined
  4766. return target.set( - 2, - 1, - 1 );
  4767. }
  4768. const invDenom = 1 / denom;
  4769. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4770. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4771. // barycentric coordinates must always sum to 1
  4772. return target.set( 1 - u - v, v, u );
  4773. }
  4774. static containsPoint( point, a, b, c ) {
  4775. this.getBarycoord( point, a, b, c, _v3$1 );
  4776. return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 );
  4777. }
  4778. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  4779. this.getBarycoord( point, p1, p2, p3, _v3$1 );
  4780. target.set( 0, 0 );
  4781. target.addScaledVector( uv1, _v3$1.x );
  4782. target.addScaledVector( uv2, _v3$1.y );
  4783. target.addScaledVector( uv3, _v3$1.z );
  4784. return target;
  4785. }
  4786. static isFrontFacing( a, b, c, direction ) {
  4787. _v0$1.subVectors( c, b );
  4788. _v1$3.subVectors( a, b );
  4789. // strictly front facing
  4790. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4791. }
  4792. set( a, b, c ) {
  4793. this.a.copy( a );
  4794. this.b.copy( b );
  4795. this.c.copy( c );
  4796. return this;
  4797. }
  4798. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4799. this.a.copy( points[ i0 ] );
  4800. this.b.copy( points[ i1 ] );
  4801. this.c.copy( points[ i2 ] );
  4802. return this;
  4803. }
  4804. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  4805. this.a.fromBufferAttribute( attribute, i0 );
  4806. this.b.fromBufferAttribute( attribute, i1 );
  4807. this.c.fromBufferAttribute( attribute, i2 );
  4808. return this;
  4809. }
  4810. clone() {
  4811. return new this.constructor().copy( this );
  4812. }
  4813. copy( triangle ) {
  4814. this.a.copy( triangle.a );
  4815. this.b.copy( triangle.b );
  4816. this.c.copy( triangle.c );
  4817. return this;
  4818. }
  4819. getArea() {
  4820. _v0$1.subVectors( this.c, this.b );
  4821. _v1$3.subVectors( this.a, this.b );
  4822. return _v0$1.cross( _v1$3 ).length() * 0.5;
  4823. }
  4824. getMidpoint( target ) {
  4825. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4826. }
  4827. getNormal( target ) {
  4828. return Triangle.getNormal( this.a, this.b, this.c, target );
  4829. }
  4830. getPlane( target ) {
  4831. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  4832. }
  4833. getBarycoord( point, target ) {
  4834. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  4835. }
  4836. getUV( point, uv1, uv2, uv3, target ) {
  4837. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  4838. }
  4839. containsPoint( point ) {
  4840. return Triangle.containsPoint( point, this.a, this.b, this.c );
  4841. }
  4842. isFrontFacing( direction ) {
  4843. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  4844. }
  4845. intersectsBox( box ) {
  4846. return box.intersectsTriangle( this );
  4847. }
  4848. closestPointToPoint( p, target ) {
  4849. const a = this.a, b = this.b, c = this.c;
  4850. let v, w;
  4851. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4852. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4853. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4854. // basically, we're distinguishing which of the voronoi regions of the triangle
  4855. // the point lies in with the minimum amount of redundant computation.
  4856. _vab.subVectors( b, a );
  4857. _vac.subVectors( c, a );
  4858. _vap.subVectors( p, a );
  4859. const d1 = _vab.dot( _vap );
  4860. const d2 = _vac.dot( _vap );
  4861. if ( d1 <= 0 && d2 <= 0 ) {
  4862. // vertex region of A; barycentric coords (1, 0, 0)
  4863. return target.copy( a );
  4864. }
  4865. _vbp.subVectors( p, b );
  4866. const d3 = _vab.dot( _vbp );
  4867. const d4 = _vac.dot( _vbp );
  4868. if ( d3 >= 0 && d4 <= d3 ) {
  4869. // vertex region of B; barycentric coords (0, 1, 0)
  4870. return target.copy( b );
  4871. }
  4872. const vc = d1 * d4 - d3 * d2;
  4873. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  4874. v = d1 / ( d1 - d3 );
  4875. // edge region of AB; barycentric coords (1-v, v, 0)
  4876. return target.copy( a ).addScaledVector( _vab, v );
  4877. }
  4878. _vcp.subVectors( p, c );
  4879. const d5 = _vab.dot( _vcp );
  4880. const d6 = _vac.dot( _vcp );
  4881. if ( d6 >= 0 && d5 <= d6 ) {
  4882. // vertex region of C; barycentric coords (0, 0, 1)
  4883. return target.copy( c );
  4884. }
  4885. const vb = d5 * d2 - d1 * d6;
  4886. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  4887. w = d2 / ( d2 - d6 );
  4888. // edge region of AC; barycentric coords (1-w, 0, w)
  4889. return target.copy( a ).addScaledVector( _vac, w );
  4890. }
  4891. const va = d3 * d6 - d5 * d4;
  4892. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  4893. _vbc.subVectors( c, b );
  4894. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  4895. // edge region of BC; barycentric coords (0, 1-w, w)
  4896. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  4897. }
  4898. // face region
  4899. const denom = 1 / ( va + vb + vc );
  4900. // u = va * denom
  4901. v = vb * denom;
  4902. w = vc * denom;
  4903. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  4904. }
  4905. equals( triangle ) {
  4906. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4907. }
  4908. }
  4909. let materialId = 0;
  4910. class Material extends EventDispatcher {
  4911. constructor() {
  4912. super();
  4913. this.isMaterial = true;
  4914. Object.defineProperty( this, 'id', { value: materialId ++ } );
  4915. this.uuid = generateUUID();
  4916. this.name = '';
  4917. this.type = 'Material';
  4918. this.blending = NormalBlending;
  4919. this.side = FrontSide;
  4920. this.vertexColors = false;
  4921. this.opacity = 1;
  4922. this.transparent = false;
  4923. this.blendSrc = SrcAlphaFactor;
  4924. this.blendDst = OneMinusSrcAlphaFactor;
  4925. this.blendEquation = AddEquation;
  4926. this.blendSrcAlpha = null;
  4927. this.blendDstAlpha = null;
  4928. this.blendEquationAlpha = null;
  4929. this.depthFunc = LessEqualDepth;
  4930. this.depthTest = true;
  4931. this.depthWrite = true;
  4932. this.stencilWriteMask = 0xff;
  4933. this.stencilFunc = AlwaysStencilFunc;
  4934. this.stencilRef = 0;
  4935. this.stencilFuncMask = 0xff;
  4936. this.stencilFail = KeepStencilOp;
  4937. this.stencilZFail = KeepStencilOp;
  4938. this.stencilZPass = KeepStencilOp;
  4939. this.stencilWrite = false;
  4940. this.clippingPlanes = null;
  4941. this.clipIntersection = false;
  4942. this.clipShadows = false;
  4943. this.shadowSide = null;
  4944. this.colorWrite = true;
  4945. this.precision = null; // override the renderer's default precision for this material
  4946. this.polygonOffset = false;
  4947. this.polygonOffsetFactor = 0;
  4948. this.polygonOffsetUnits = 0;
  4949. this.dithering = false;
  4950. this.alphaToCoverage = false;
  4951. this.premultipliedAlpha = false;
  4952. this.forceSinglePass = false;
  4953. this.visible = true;
  4954. this.toneMapped = true;
  4955. this.userData = {};
  4956. this.version = 0;
  4957. this._alphaTest = 0;
  4958. }
  4959. get alphaTest() {
  4960. return this._alphaTest;
  4961. }
  4962. set alphaTest( value ) {
  4963. if ( this._alphaTest > 0 !== value > 0 ) {
  4964. this.version ++;
  4965. }
  4966. this._alphaTest = value;
  4967. }
  4968. onBuild( /* shaderobject, renderer */ ) {}
  4969. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  4970. onBeforeCompile( /* shaderobject, renderer */ ) {}
  4971. customProgramCacheKey() {
  4972. return this.onBeforeCompile.toString();
  4973. }
  4974. setValues( values ) {
  4975. if ( values === undefined ) return;
  4976. for ( const key in values ) {
  4977. const newValue = values[ key ];
  4978. if ( newValue === undefined ) {
  4979. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  4980. continue;
  4981. }
  4982. const currentValue = this[ key ];
  4983. if ( currentValue === undefined ) {
  4984. console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' );
  4985. continue;
  4986. }
  4987. if ( currentValue && currentValue.isColor ) {
  4988. currentValue.set( newValue );
  4989. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  4990. currentValue.copy( newValue );
  4991. } else {
  4992. this[ key ] = newValue;
  4993. }
  4994. }
  4995. }
  4996. toJSON( meta ) {
  4997. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4998. if ( isRootObject ) {
  4999. meta = {
  5000. textures: {},
  5001. images: {}
  5002. };
  5003. }
  5004. const data = {
  5005. metadata: {
  5006. version: 4.5,
  5007. type: 'Material',
  5008. generator: 'Material.toJSON'
  5009. }
  5010. };
  5011. // standard Material serialization
  5012. data.uuid = this.uuid;
  5013. data.type = this.type;
  5014. if ( this.name !== '' ) data.name = this.name;
  5015. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5016. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5017. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5018. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5019. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5020. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5021. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5022. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5023. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5024. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5025. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5026. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5027. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5028. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5029. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5030. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5031. }
  5032. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5033. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5034. }
  5035. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5036. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5037. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5038. }
  5039. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5040. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5041. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5042. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5043. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5044. }
  5045. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5046. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5047. }
  5048. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5049. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5050. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5051. if ( this.lightMap && this.lightMap.isTexture ) {
  5052. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5053. data.lightMapIntensity = this.lightMapIntensity;
  5054. }
  5055. if ( this.aoMap && this.aoMap.isTexture ) {
  5056. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5057. data.aoMapIntensity = this.aoMapIntensity;
  5058. }
  5059. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5060. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5061. data.bumpScale = this.bumpScale;
  5062. }
  5063. if ( this.normalMap && this.normalMap.isTexture ) {
  5064. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5065. data.normalMapType = this.normalMapType;
  5066. data.normalScale = this.normalScale.toArray();
  5067. }
  5068. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5069. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5070. data.displacementScale = this.displacementScale;
  5071. data.displacementBias = this.displacementBias;
  5072. }
  5073. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5074. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5075. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5076. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5077. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5078. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5079. if ( this.envMap && this.envMap.isTexture ) {
  5080. data.envMap = this.envMap.toJSON( meta ).uuid;
  5081. if ( this.combine !== undefined ) data.combine = this.combine;
  5082. }
  5083. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5084. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5085. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5086. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5087. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5088. }
  5089. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5090. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5091. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5092. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5093. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5094. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5095. if ( this.size !== undefined ) data.size = this.size;
  5096. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5097. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5098. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5099. if ( this.side !== FrontSide ) data.side = this.side;
  5100. if ( this.vertexColors ) data.vertexColors = true;
  5101. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5102. if ( this.transparent === true ) data.transparent = this.transparent;
  5103. data.depthFunc = this.depthFunc;
  5104. data.depthTest = this.depthTest;
  5105. data.depthWrite = this.depthWrite;
  5106. data.colorWrite = this.colorWrite;
  5107. data.stencilWrite = this.stencilWrite;
  5108. data.stencilWriteMask = this.stencilWriteMask;
  5109. data.stencilFunc = this.stencilFunc;
  5110. data.stencilRef = this.stencilRef;
  5111. data.stencilFuncMask = this.stencilFuncMask;
  5112. data.stencilFail = this.stencilFail;
  5113. data.stencilZFail = this.stencilZFail;
  5114. data.stencilZPass = this.stencilZPass;
  5115. // rotation (SpriteMaterial)
  5116. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5117. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5118. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5119. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5120. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5121. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5122. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5123. if ( this.scale !== undefined ) data.scale = this.scale;
  5124. if ( this.dithering === true ) data.dithering = true;
  5125. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5126. if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage;
  5127. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  5128. if ( this.forceSinglePass === true ) data.forceSinglePass = this.forceSinglePass;
  5129. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  5130. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5131. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5132. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5133. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  5134. if ( this.visible === false ) data.visible = false;
  5135. if ( this.toneMapped === false ) data.toneMapped = false;
  5136. if ( this.fog === false ) data.fog = false;
  5137. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5138. // TODO: Copied from Object3D.toJSON
  5139. function extractFromCache( cache ) {
  5140. const values = [];
  5141. for ( const key in cache ) {
  5142. const data = cache[ key ];
  5143. delete data.metadata;
  5144. values.push( data );
  5145. }
  5146. return values;
  5147. }
  5148. if ( isRootObject ) {
  5149. const textures = extractFromCache( meta.textures );
  5150. const images = extractFromCache( meta.images );
  5151. if ( textures.length > 0 ) data.textures = textures;
  5152. if ( images.length > 0 ) data.images = images;
  5153. }
  5154. return data;
  5155. }
  5156. clone() {
  5157. return new this.constructor().copy( this );
  5158. }
  5159. copy( source ) {
  5160. this.name = source.name;
  5161. this.blending = source.blending;
  5162. this.side = source.side;
  5163. this.vertexColors = source.vertexColors;
  5164. this.opacity = source.opacity;
  5165. this.transparent = source.transparent;
  5166. this.blendSrc = source.blendSrc;
  5167. this.blendDst = source.blendDst;
  5168. this.blendEquation = source.blendEquation;
  5169. this.blendSrcAlpha = source.blendSrcAlpha;
  5170. this.blendDstAlpha = source.blendDstAlpha;
  5171. this.blendEquationAlpha = source.blendEquationAlpha;
  5172. this.depthFunc = source.depthFunc;
  5173. this.depthTest = source.depthTest;
  5174. this.depthWrite = source.depthWrite;
  5175. this.stencilWriteMask = source.stencilWriteMask;
  5176. this.stencilFunc = source.stencilFunc;
  5177. this.stencilRef = source.stencilRef;
  5178. this.stencilFuncMask = source.stencilFuncMask;
  5179. this.stencilFail = source.stencilFail;
  5180. this.stencilZFail = source.stencilZFail;
  5181. this.stencilZPass = source.stencilZPass;
  5182. this.stencilWrite = source.stencilWrite;
  5183. const srcPlanes = source.clippingPlanes;
  5184. let dstPlanes = null;
  5185. if ( srcPlanes !== null ) {
  5186. const n = srcPlanes.length;
  5187. dstPlanes = new Array( n );
  5188. for ( let i = 0; i !== n; ++ i ) {
  5189. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5190. }
  5191. }
  5192. this.clippingPlanes = dstPlanes;
  5193. this.clipIntersection = source.clipIntersection;
  5194. this.clipShadows = source.clipShadows;
  5195. this.shadowSide = source.shadowSide;
  5196. this.colorWrite = source.colorWrite;
  5197. this.precision = source.precision;
  5198. this.polygonOffset = source.polygonOffset;
  5199. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5200. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5201. this.dithering = source.dithering;
  5202. this.alphaTest = source.alphaTest;
  5203. this.alphaToCoverage = source.alphaToCoverage;
  5204. this.premultipliedAlpha = source.premultipliedAlpha;
  5205. this.forceSinglePass = source.forceSinglePass;
  5206. this.visible = source.visible;
  5207. this.toneMapped = source.toneMapped;
  5208. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5209. return this;
  5210. }
  5211. dispose() {
  5212. this.dispatchEvent( { type: 'dispose' } );
  5213. }
  5214. set needsUpdate( value ) {
  5215. if ( value === true ) this.version ++;
  5216. }
  5217. }
  5218. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5219. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5220. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5221. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5222. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5223. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5224. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5225. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5226. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5227. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5228. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5229. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5230. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5231. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5232. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5233. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5234. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5235. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5236. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5237. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5238. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5239. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5240. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5241. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5242. const _hslA = { h: 0, s: 0, l: 0 };
  5243. const _hslB = { h: 0, s: 0, l: 0 };
  5244. function hue2rgb( p, q, t ) {
  5245. if ( t < 0 ) t += 1;
  5246. if ( t > 1 ) t -= 1;
  5247. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5248. if ( t < 1 / 2 ) return q;
  5249. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5250. return p;
  5251. }
  5252. class Color {
  5253. constructor( r, g, b ) {
  5254. this.isColor = true;
  5255. this.r = 1;
  5256. this.g = 1;
  5257. this.b = 1;
  5258. if ( g === undefined && b === undefined ) {
  5259. // r is THREE.Color, hex or string
  5260. return this.set( r );
  5261. }
  5262. return this.setRGB( r, g, b );
  5263. }
  5264. set( value ) {
  5265. if ( value && value.isColor ) {
  5266. this.copy( value );
  5267. } else if ( typeof value === 'number' ) {
  5268. this.setHex( value );
  5269. } else if ( typeof value === 'string' ) {
  5270. this.setStyle( value );
  5271. }
  5272. return this;
  5273. }
  5274. setScalar( scalar ) {
  5275. this.r = scalar;
  5276. this.g = scalar;
  5277. this.b = scalar;
  5278. return this;
  5279. }
  5280. setHex( hex, colorSpace = SRGBColorSpace ) {
  5281. hex = Math.floor( hex );
  5282. this.r = ( hex >> 16 & 255 ) / 255;
  5283. this.g = ( hex >> 8 & 255 ) / 255;
  5284. this.b = ( hex & 255 ) / 255;
  5285. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5286. return this;
  5287. }
  5288. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  5289. this.r = r;
  5290. this.g = g;
  5291. this.b = b;
  5292. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5293. return this;
  5294. }
  5295. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  5296. // h,s,l ranges are in 0.0 - 1.0
  5297. h = euclideanModulo( h, 1 );
  5298. s = clamp( s, 0, 1 );
  5299. l = clamp( l, 0, 1 );
  5300. if ( s === 0 ) {
  5301. this.r = this.g = this.b = l;
  5302. } else {
  5303. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5304. const q = ( 2 * l ) - p;
  5305. this.r = hue2rgb( q, p, h + 1 / 3 );
  5306. this.g = hue2rgb( q, p, h );
  5307. this.b = hue2rgb( q, p, h - 1 / 3 );
  5308. }
  5309. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5310. return this;
  5311. }
  5312. setStyle( style, colorSpace = SRGBColorSpace ) {
  5313. function handleAlpha( string ) {
  5314. if ( string === undefined ) return;
  5315. if ( parseFloat( string ) < 1 ) {
  5316. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5317. }
  5318. }
  5319. let m;
  5320. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  5321. // rgb / hsl
  5322. let color;
  5323. const name = m[ 1 ];
  5324. const components = m[ 2 ];
  5325. switch ( name ) {
  5326. case 'rgb':
  5327. case 'rgba':
  5328. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5329. // rgb(255,0,0) rgba(255,0,0,0.5)
  5330. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  5331. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  5332. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  5333. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5334. handleAlpha( color[ 4 ] );
  5335. return this;
  5336. }
  5337. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5338. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5339. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  5340. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  5341. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  5342. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5343. handleAlpha( color[ 4 ] );
  5344. return this;
  5345. }
  5346. break;
  5347. case 'hsl':
  5348. case 'hsla':
  5349. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5350. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5351. const h = parseFloat( color[ 1 ] ) / 360;
  5352. const s = parseFloat( color[ 2 ] ) / 100;
  5353. const l = parseFloat( color[ 3 ] ) / 100;
  5354. handleAlpha( color[ 4 ] );
  5355. return this.setHSL( h, s, l, colorSpace );
  5356. }
  5357. break;
  5358. default:
  5359. console.warn( 'THREE.Color: Unknown color model ' + style );
  5360. }
  5361. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5362. // hex color
  5363. const hex = m[ 1 ];
  5364. const size = hex.length;
  5365. if ( size === 3 ) {
  5366. // #ff0
  5367. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  5368. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  5369. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  5370. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5371. return this;
  5372. } else if ( size === 6 ) {
  5373. // #ff0000
  5374. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  5375. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  5376. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  5377. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5378. return this;
  5379. } else {
  5380. console.warn( 'THREE.Color: Invalid hex color ' + style );
  5381. }
  5382. } else if ( style && style.length > 0 ) {
  5383. return this.setColorName( style, colorSpace );
  5384. }
  5385. return this;
  5386. }
  5387. setColorName( style, colorSpace = SRGBColorSpace ) {
  5388. // color keywords
  5389. const hex = _colorKeywords[ style.toLowerCase() ];
  5390. if ( hex !== undefined ) {
  5391. // red
  5392. this.setHex( hex, colorSpace );
  5393. } else {
  5394. // unknown color
  5395. console.warn( 'THREE.Color: Unknown color ' + style );
  5396. }
  5397. return this;
  5398. }
  5399. clone() {
  5400. return new this.constructor( this.r, this.g, this.b );
  5401. }
  5402. copy( color ) {
  5403. this.r = color.r;
  5404. this.g = color.g;
  5405. this.b = color.b;
  5406. return this;
  5407. }
  5408. copySRGBToLinear( color ) {
  5409. this.r = SRGBToLinear( color.r );
  5410. this.g = SRGBToLinear( color.g );
  5411. this.b = SRGBToLinear( color.b );
  5412. return this;
  5413. }
  5414. copyLinearToSRGB( color ) {
  5415. this.r = LinearToSRGB( color.r );
  5416. this.g = LinearToSRGB( color.g );
  5417. this.b = LinearToSRGB( color.b );
  5418. return this;
  5419. }
  5420. convertSRGBToLinear() {
  5421. this.copySRGBToLinear( this );
  5422. return this;
  5423. }
  5424. convertLinearToSRGB() {
  5425. this.copyLinearToSRGB( this );
  5426. return this;
  5427. }
  5428. getHex( colorSpace = SRGBColorSpace ) {
  5429. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5430. return clamp( _color.r * 255, 0, 255 ) << 16 ^ clamp( _color.g * 255, 0, 255 ) << 8 ^ clamp( _color.b * 255, 0, 255 ) << 0;
  5431. }
  5432. getHexString( colorSpace = SRGBColorSpace ) {
  5433. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  5434. }
  5435. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  5436. // h,s,l ranges are in 0.0 - 1.0
  5437. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5438. const r = _color.r, g = _color.g, b = _color.b;
  5439. const max = Math.max( r, g, b );
  5440. const min = Math.min( r, g, b );
  5441. let hue, saturation;
  5442. const lightness = ( min + max ) / 2.0;
  5443. if ( min === max ) {
  5444. hue = 0;
  5445. saturation = 0;
  5446. } else {
  5447. const delta = max - min;
  5448. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5449. switch ( max ) {
  5450. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5451. case g: hue = ( b - r ) / delta + 2; break;
  5452. case b: hue = ( r - g ) / delta + 4; break;
  5453. }
  5454. hue /= 6;
  5455. }
  5456. target.h = hue;
  5457. target.s = saturation;
  5458. target.l = lightness;
  5459. return target;
  5460. }
  5461. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  5462. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5463. target.r = _color.r;
  5464. target.g = _color.g;
  5465. target.b = _color.b;
  5466. return target;
  5467. }
  5468. getStyle( colorSpace = SRGBColorSpace ) {
  5469. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5470. const r = _color.r, g = _color.g, b = _color.b;
  5471. if ( colorSpace !== SRGBColorSpace ) {
  5472. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  5473. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  5474. }
  5475. return `rgb(${( r * 255 ) | 0},${( g * 255 ) | 0},${( b * 255 ) | 0})`;
  5476. }
  5477. offsetHSL( h, s, l ) {
  5478. this.getHSL( _hslA );
  5479. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  5480. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  5481. return this;
  5482. }
  5483. add( color ) {
  5484. this.r += color.r;
  5485. this.g += color.g;
  5486. this.b += color.b;
  5487. return this;
  5488. }
  5489. addColors( color1, color2 ) {
  5490. this.r = color1.r + color2.r;
  5491. this.g = color1.g + color2.g;
  5492. this.b = color1.b + color2.b;
  5493. return this;
  5494. }
  5495. addScalar( s ) {
  5496. this.r += s;
  5497. this.g += s;
  5498. this.b += s;
  5499. return this;
  5500. }
  5501. sub( color ) {
  5502. this.r = Math.max( 0, this.r - color.r );
  5503. this.g = Math.max( 0, this.g - color.g );
  5504. this.b = Math.max( 0, this.b - color.b );
  5505. return this;
  5506. }
  5507. multiply( color ) {
  5508. this.r *= color.r;
  5509. this.g *= color.g;
  5510. this.b *= color.b;
  5511. return this;
  5512. }
  5513. multiplyScalar( s ) {
  5514. this.r *= s;
  5515. this.g *= s;
  5516. this.b *= s;
  5517. return this;
  5518. }
  5519. lerp( color, alpha ) {
  5520. this.r += ( color.r - this.r ) * alpha;
  5521. this.g += ( color.g - this.g ) * alpha;
  5522. this.b += ( color.b - this.b ) * alpha;
  5523. return this;
  5524. }
  5525. lerpColors( color1, color2, alpha ) {
  5526. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5527. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5528. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5529. return this;
  5530. }
  5531. lerpHSL( color, alpha ) {
  5532. this.getHSL( _hslA );
  5533. color.getHSL( _hslB );
  5534. const h = lerp( _hslA.h, _hslB.h, alpha );
  5535. const s = lerp( _hslA.s, _hslB.s, alpha );
  5536. const l = lerp( _hslA.l, _hslB.l, alpha );
  5537. this.setHSL( h, s, l );
  5538. return this;
  5539. }
  5540. equals( c ) {
  5541. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5542. }
  5543. fromArray( array, offset = 0 ) {
  5544. this.r = array[ offset ];
  5545. this.g = array[ offset + 1 ];
  5546. this.b = array[ offset + 2 ];
  5547. return this;
  5548. }
  5549. toArray( array = [], offset = 0 ) {
  5550. array[ offset ] = this.r;
  5551. array[ offset + 1 ] = this.g;
  5552. array[ offset + 2 ] = this.b;
  5553. return array;
  5554. }
  5555. fromBufferAttribute( attribute, index ) {
  5556. this.r = attribute.getX( index );
  5557. this.g = attribute.getY( index );
  5558. this.b = attribute.getZ( index );
  5559. return this;
  5560. }
  5561. toJSON() {
  5562. return this.getHex();
  5563. }
  5564. *[ Symbol.iterator ]() {
  5565. yield this.r;
  5566. yield this.g;
  5567. yield this.b;
  5568. }
  5569. }
  5570. const _color = new Color();
  5571. Color.NAMES = _colorKeywords;
  5572. class MeshBasicMaterial extends Material {
  5573. constructor( parameters ) {
  5574. super();
  5575. this.isMeshBasicMaterial = true;
  5576. this.type = 'MeshBasicMaterial';
  5577. this.color = new Color( 0xffffff ); // emissive
  5578. this.map = null;
  5579. this.lightMap = null;
  5580. this.lightMapIntensity = 1.0;
  5581. this.aoMap = null;
  5582. this.aoMapIntensity = 1.0;
  5583. this.specularMap = null;
  5584. this.alphaMap = null;
  5585. this.envMap = null;
  5586. this.combine = MultiplyOperation;
  5587. this.reflectivity = 1;
  5588. this.refractionRatio = 0.98;
  5589. this.wireframe = false;
  5590. this.wireframeLinewidth = 1;
  5591. this.wireframeLinecap = 'round';
  5592. this.wireframeLinejoin = 'round';
  5593. this.fog = true;
  5594. this.setValues( parameters );
  5595. }
  5596. copy( source ) {
  5597. super.copy( source );
  5598. this.color.copy( source.color );
  5599. this.map = source.map;
  5600. this.lightMap = source.lightMap;
  5601. this.lightMapIntensity = source.lightMapIntensity;
  5602. this.aoMap = source.aoMap;
  5603. this.aoMapIntensity = source.aoMapIntensity;
  5604. this.specularMap = source.specularMap;
  5605. this.alphaMap = source.alphaMap;
  5606. this.envMap = source.envMap;
  5607. this.combine = source.combine;
  5608. this.reflectivity = source.reflectivity;
  5609. this.refractionRatio = source.refractionRatio;
  5610. this.wireframe = source.wireframe;
  5611. this.wireframeLinewidth = source.wireframeLinewidth;
  5612. this.wireframeLinecap = source.wireframeLinecap;
  5613. this.wireframeLinejoin = source.wireframeLinejoin;
  5614. this.fog = source.fog;
  5615. return this;
  5616. }
  5617. }
  5618. const _vector$9 = /*@__PURE__*/ new Vector3();
  5619. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5620. class BufferAttribute {
  5621. constructor( array, itemSize, normalized = false ) {
  5622. if ( Array.isArray( array ) ) {
  5623. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5624. }
  5625. this.isBufferAttribute = true;
  5626. this.name = '';
  5627. this.array = array;
  5628. this.itemSize = itemSize;
  5629. this.count = array !== undefined ? array.length / itemSize : 0;
  5630. this.normalized = normalized;
  5631. this.usage = StaticDrawUsage;
  5632. this.updateRange = { offset: 0, count: - 1 };
  5633. this.version = 0;
  5634. }
  5635. onUploadCallback() {}
  5636. set needsUpdate( value ) {
  5637. if ( value === true ) this.version ++;
  5638. }
  5639. setUsage( value ) {
  5640. this.usage = value;
  5641. return this;
  5642. }
  5643. copy( source ) {
  5644. this.name = source.name;
  5645. this.array = new source.array.constructor( source.array );
  5646. this.itemSize = source.itemSize;
  5647. this.count = source.count;
  5648. this.normalized = source.normalized;
  5649. this.usage = source.usage;
  5650. return this;
  5651. }
  5652. copyAt( index1, attribute, index2 ) {
  5653. index1 *= this.itemSize;
  5654. index2 *= attribute.itemSize;
  5655. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5656. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5657. }
  5658. return this;
  5659. }
  5660. copyArray( array ) {
  5661. this.array.set( array );
  5662. return this;
  5663. }
  5664. applyMatrix3( m ) {
  5665. if ( this.itemSize === 2 ) {
  5666. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5667. _vector2$1.fromBufferAttribute( this, i );
  5668. _vector2$1.applyMatrix3( m );
  5669. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5670. }
  5671. } else if ( this.itemSize === 3 ) {
  5672. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5673. _vector$9.fromBufferAttribute( this, i );
  5674. _vector$9.applyMatrix3( m );
  5675. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5676. }
  5677. }
  5678. return this;
  5679. }
  5680. applyMatrix4( m ) {
  5681. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5682. _vector$9.fromBufferAttribute( this, i );
  5683. _vector$9.applyMatrix4( m );
  5684. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5685. }
  5686. return this;
  5687. }
  5688. applyNormalMatrix( m ) {
  5689. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5690. _vector$9.fromBufferAttribute( this, i );
  5691. _vector$9.applyNormalMatrix( m );
  5692. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5693. }
  5694. return this;
  5695. }
  5696. transformDirection( m ) {
  5697. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5698. _vector$9.fromBufferAttribute( this, i );
  5699. _vector$9.transformDirection( m );
  5700. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5701. }
  5702. return this;
  5703. }
  5704. set( value, offset = 0 ) {
  5705. // Matching BufferAttribute constructor, do not normalize the array.
  5706. this.array.set( value, offset );
  5707. return this;
  5708. }
  5709. getX( index ) {
  5710. let x = this.array[ index * this.itemSize ];
  5711. if ( this.normalized ) x = denormalize( x, this.array );
  5712. return x;
  5713. }
  5714. setX( index, x ) {
  5715. if ( this.normalized ) x = normalize( x, this.array );
  5716. this.array[ index * this.itemSize ] = x;
  5717. return this;
  5718. }
  5719. getY( index ) {
  5720. let y = this.array[ index * this.itemSize + 1 ];
  5721. if ( this.normalized ) y = denormalize( y, this.array );
  5722. return y;
  5723. }
  5724. setY( index, y ) {
  5725. if ( this.normalized ) y = normalize( y, this.array );
  5726. this.array[ index * this.itemSize + 1 ] = y;
  5727. return this;
  5728. }
  5729. getZ( index ) {
  5730. let z = this.array[ index * this.itemSize + 2 ];
  5731. if ( this.normalized ) z = denormalize( z, this.array );
  5732. return z;
  5733. }
  5734. setZ( index, z ) {
  5735. if ( this.normalized ) z = normalize( z, this.array );
  5736. this.array[ index * this.itemSize + 2 ] = z;
  5737. return this;
  5738. }
  5739. getW( index ) {
  5740. let w = this.array[ index * this.itemSize + 3 ];
  5741. if ( this.normalized ) w = denormalize( w, this.array );
  5742. return w;
  5743. }
  5744. setW( index, w ) {
  5745. if ( this.normalized ) w = normalize( w, this.array );
  5746. this.array[ index * this.itemSize + 3 ] = w;
  5747. return this;
  5748. }
  5749. setXY( index, x, y ) {
  5750. index *= this.itemSize;
  5751. if ( this.normalized ) {
  5752. x = normalize( x, this.array );
  5753. y = normalize( y, this.array );
  5754. }
  5755. this.array[ index + 0 ] = x;
  5756. this.array[ index + 1 ] = y;
  5757. return this;
  5758. }
  5759. setXYZ( index, x, y, z ) {
  5760. index *= this.itemSize;
  5761. if ( this.normalized ) {
  5762. x = normalize( x, this.array );
  5763. y = normalize( y, this.array );
  5764. z = normalize( z, this.array );
  5765. }
  5766. this.array[ index + 0 ] = x;
  5767. this.array[ index + 1 ] = y;
  5768. this.array[ index + 2 ] = z;
  5769. return this;
  5770. }
  5771. setXYZW( index, x, y, z, w ) {
  5772. index *= this.itemSize;
  5773. if ( this.normalized ) {
  5774. x = normalize( x, this.array );
  5775. y = normalize( y, this.array );
  5776. z = normalize( z, this.array );
  5777. w = normalize( w, this.array );
  5778. }
  5779. this.array[ index + 0 ] = x;
  5780. this.array[ index + 1 ] = y;
  5781. this.array[ index + 2 ] = z;
  5782. this.array[ index + 3 ] = w;
  5783. return this;
  5784. }
  5785. onUpload( callback ) {
  5786. this.onUploadCallback = callback;
  5787. return this;
  5788. }
  5789. clone() {
  5790. return new this.constructor( this.array, this.itemSize ).copy( this );
  5791. }
  5792. toJSON() {
  5793. const data = {
  5794. itemSize: this.itemSize,
  5795. type: this.array.constructor.name,
  5796. array: Array.from( this.array ),
  5797. normalized: this.normalized
  5798. };
  5799. if ( this.name !== '' ) data.name = this.name;
  5800. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  5801. if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange;
  5802. return data;
  5803. }
  5804. // @deprecated
  5805. copyColorsArray() {
  5806. console.error( 'THREE.BufferAttribute: copyColorsArray() was removed in r144.' );
  5807. }
  5808. copyVector2sArray() {
  5809. console.error( 'THREE.BufferAttribute: copyVector2sArray() was removed in r144.' );
  5810. }
  5811. copyVector3sArray() {
  5812. console.error( 'THREE.BufferAttribute: copyVector3sArray() was removed in r144.' );
  5813. }
  5814. copyVector4sArray() {
  5815. console.error( 'THREE.BufferAttribute: copyVector4sArray() was removed in r144.' );
  5816. }
  5817. }
  5818. //
  5819. class Int8BufferAttribute extends BufferAttribute {
  5820. constructor( array, itemSize, normalized ) {
  5821. super( new Int8Array( array ), itemSize, normalized );
  5822. }
  5823. }
  5824. class Uint8BufferAttribute extends BufferAttribute {
  5825. constructor( array, itemSize, normalized ) {
  5826. super( new Uint8Array( array ), itemSize, normalized );
  5827. }
  5828. }
  5829. class Uint8ClampedBufferAttribute extends BufferAttribute {
  5830. constructor( array, itemSize, normalized ) {
  5831. super( new Uint8ClampedArray( array ), itemSize, normalized );
  5832. }
  5833. }
  5834. class Int16BufferAttribute extends BufferAttribute {
  5835. constructor( array, itemSize, normalized ) {
  5836. super( new Int16Array( array ), itemSize, normalized );
  5837. }
  5838. }
  5839. class Uint16BufferAttribute extends BufferAttribute {
  5840. constructor( array, itemSize, normalized ) {
  5841. super( new Uint16Array( array ), itemSize, normalized );
  5842. }
  5843. }
  5844. class Int32BufferAttribute extends BufferAttribute {
  5845. constructor( array, itemSize, normalized ) {
  5846. super( new Int32Array( array ), itemSize, normalized );
  5847. }
  5848. }
  5849. class Uint32BufferAttribute extends BufferAttribute {
  5850. constructor( array, itemSize, normalized ) {
  5851. super( new Uint32Array( array ), itemSize, normalized );
  5852. }
  5853. }
  5854. class Float16BufferAttribute extends BufferAttribute {
  5855. constructor( array, itemSize, normalized ) {
  5856. super( new Uint16Array( array ), itemSize, normalized );
  5857. this.isFloat16BufferAttribute = true;
  5858. }
  5859. }
  5860. class Float32BufferAttribute extends BufferAttribute {
  5861. constructor( array, itemSize, normalized ) {
  5862. super( new Float32Array( array ), itemSize, normalized );
  5863. }
  5864. }
  5865. class Float64BufferAttribute extends BufferAttribute {
  5866. constructor( array, itemSize, normalized ) {
  5867. super( new Float64Array( array ), itemSize, normalized );
  5868. }
  5869. }
  5870. let _id$1 = 0;
  5871. const _m1 = /*@__PURE__*/ new Matrix4();
  5872. const _obj = /*@__PURE__*/ new Object3D();
  5873. const _offset = /*@__PURE__*/ new Vector3();
  5874. const _box$1 = /*@__PURE__*/ new Box3();
  5875. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  5876. const _vector$8 = /*@__PURE__*/ new Vector3();
  5877. class BufferGeometry extends EventDispatcher {
  5878. constructor() {
  5879. super();
  5880. this.isBufferGeometry = true;
  5881. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  5882. this.uuid = generateUUID();
  5883. this.name = '';
  5884. this.type = 'BufferGeometry';
  5885. this.index = null;
  5886. this.attributes = {};
  5887. this.morphAttributes = {};
  5888. this.morphTargetsRelative = false;
  5889. this.groups = [];
  5890. this.boundingBox = null;
  5891. this.boundingSphere = null;
  5892. this.drawRange = { start: 0, count: Infinity };
  5893. this.userData = {};
  5894. }
  5895. getIndex() {
  5896. return this.index;
  5897. }
  5898. setIndex( index ) {
  5899. if ( Array.isArray( index ) ) {
  5900. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  5901. } else {
  5902. this.index = index;
  5903. }
  5904. return this;
  5905. }
  5906. getAttribute( name ) {
  5907. return this.attributes[ name ];
  5908. }
  5909. setAttribute( name, attribute ) {
  5910. this.attributes[ name ] = attribute;
  5911. return this;
  5912. }
  5913. deleteAttribute( name ) {
  5914. delete this.attributes[ name ];
  5915. return this;
  5916. }
  5917. hasAttribute( name ) {
  5918. return this.attributes[ name ] !== undefined;
  5919. }
  5920. addGroup( start, count, materialIndex = 0 ) {
  5921. this.groups.push( {
  5922. start: start,
  5923. count: count,
  5924. materialIndex: materialIndex
  5925. } );
  5926. }
  5927. clearGroups() {
  5928. this.groups = [];
  5929. }
  5930. setDrawRange( start, count ) {
  5931. this.drawRange.start = start;
  5932. this.drawRange.count = count;
  5933. }
  5934. applyMatrix4( matrix ) {
  5935. const position = this.attributes.position;
  5936. if ( position !== undefined ) {
  5937. position.applyMatrix4( matrix );
  5938. position.needsUpdate = true;
  5939. }
  5940. const normal = this.attributes.normal;
  5941. if ( normal !== undefined ) {
  5942. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  5943. normal.applyNormalMatrix( normalMatrix );
  5944. normal.needsUpdate = true;
  5945. }
  5946. const tangent = this.attributes.tangent;
  5947. if ( tangent !== undefined ) {
  5948. tangent.transformDirection( matrix );
  5949. tangent.needsUpdate = true;
  5950. }
  5951. if ( this.boundingBox !== null ) {
  5952. this.computeBoundingBox();
  5953. }
  5954. if ( this.boundingSphere !== null ) {
  5955. this.computeBoundingSphere();
  5956. }
  5957. return this;
  5958. }
  5959. applyQuaternion( q ) {
  5960. _m1.makeRotationFromQuaternion( q );
  5961. this.applyMatrix4( _m1 );
  5962. return this;
  5963. }
  5964. rotateX( angle ) {
  5965. // rotate geometry around world x-axis
  5966. _m1.makeRotationX( angle );
  5967. this.applyMatrix4( _m1 );
  5968. return this;
  5969. }
  5970. rotateY( angle ) {
  5971. // rotate geometry around world y-axis
  5972. _m1.makeRotationY( angle );
  5973. this.applyMatrix4( _m1 );
  5974. return this;
  5975. }
  5976. rotateZ( angle ) {
  5977. // rotate geometry around world z-axis
  5978. _m1.makeRotationZ( angle );
  5979. this.applyMatrix4( _m1 );
  5980. return this;
  5981. }
  5982. translate( x, y, z ) {
  5983. // translate geometry
  5984. _m1.makeTranslation( x, y, z );
  5985. this.applyMatrix4( _m1 );
  5986. return this;
  5987. }
  5988. scale( x, y, z ) {
  5989. // scale geometry
  5990. _m1.makeScale( x, y, z );
  5991. this.applyMatrix4( _m1 );
  5992. return this;
  5993. }
  5994. lookAt( vector ) {
  5995. _obj.lookAt( vector );
  5996. _obj.updateMatrix();
  5997. this.applyMatrix4( _obj.matrix );
  5998. return this;
  5999. }
  6000. center() {
  6001. this.computeBoundingBox();
  6002. this.boundingBox.getCenter( _offset ).negate();
  6003. this.translate( _offset.x, _offset.y, _offset.z );
  6004. return this;
  6005. }
  6006. setFromPoints( points ) {
  6007. const position = [];
  6008. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6009. const point = points[ i ];
  6010. position.push( point.x, point.y, point.z || 0 );
  6011. }
  6012. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6013. return this;
  6014. }
  6015. computeBoundingBox() {
  6016. if ( this.boundingBox === null ) {
  6017. this.boundingBox = new Box3();
  6018. }
  6019. const position = this.attributes.position;
  6020. const morphAttributesPosition = this.morphAttributes.position;
  6021. if ( position && position.isGLBufferAttribute ) {
  6022. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  6023. this.boundingBox.set(
  6024. new Vector3( - Infinity, - Infinity, - Infinity ),
  6025. new Vector3( + Infinity, + Infinity, + Infinity )
  6026. );
  6027. return;
  6028. }
  6029. if ( position !== undefined ) {
  6030. this.boundingBox.setFromBufferAttribute( position );
  6031. // process morph attributes if present
  6032. if ( morphAttributesPosition ) {
  6033. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6034. const morphAttribute = morphAttributesPosition[ i ];
  6035. _box$1.setFromBufferAttribute( morphAttribute );
  6036. if ( this.morphTargetsRelative ) {
  6037. _vector$8.addVectors( this.boundingBox.min, _box$1.min );
  6038. this.boundingBox.expandByPoint( _vector$8 );
  6039. _vector$8.addVectors( this.boundingBox.max, _box$1.max );
  6040. this.boundingBox.expandByPoint( _vector$8 );
  6041. } else {
  6042. this.boundingBox.expandByPoint( _box$1.min );
  6043. this.boundingBox.expandByPoint( _box$1.max );
  6044. }
  6045. }
  6046. }
  6047. } else {
  6048. this.boundingBox.makeEmpty();
  6049. }
  6050. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6051. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6052. }
  6053. }
  6054. computeBoundingSphere() {
  6055. if ( this.boundingSphere === null ) {
  6056. this.boundingSphere = new Sphere();
  6057. }
  6058. const position = this.attributes.position;
  6059. const morphAttributesPosition = this.morphAttributes.position;
  6060. if ( position && position.isGLBufferAttribute ) {
  6061. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  6062. this.boundingSphere.set( new Vector3(), Infinity );
  6063. return;
  6064. }
  6065. if ( position ) {
  6066. // first, find the center of the bounding sphere
  6067. const center = this.boundingSphere.center;
  6068. _box$1.setFromBufferAttribute( position );
  6069. // process morph attributes if present
  6070. if ( morphAttributesPosition ) {
  6071. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6072. const morphAttribute = morphAttributesPosition[ i ];
  6073. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6074. if ( this.morphTargetsRelative ) {
  6075. _vector$8.addVectors( _box$1.min, _boxMorphTargets.min );
  6076. _box$1.expandByPoint( _vector$8 );
  6077. _vector$8.addVectors( _box$1.max, _boxMorphTargets.max );
  6078. _box$1.expandByPoint( _vector$8 );
  6079. } else {
  6080. _box$1.expandByPoint( _boxMorphTargets.min );
  6081. _box$1.expandByPoint( _boxMorphTargets.max );
  6082. }
  6083. }
  6084. }
  6085. _box$1.getCenter( center );
  6086. // second, try to find a boundingSphere with a radius smaller than the
  6087. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6088. let maxRadiusSq = 0;
  6089. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6090. _vector$8.fromBufferAttribute( position, i );
  6091. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6092. }
  6093. // process morph attributes if present
  6094. if ( morphAttributesPosition ) {
  6095. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6096. const morphAttribute = morphAttributesPosition[ i ];
  6097. const morphTargetsRelative = this.morphTargetsRelative;
  6098. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6099. _vector$8.fromBufferAttribute( morphAttribute, j );
  6100. if ( morphTargetsRelative ) {
  6101. _offset.fromBufferAttribute( position, j );
  6102. _vector$8.add( _offset );
  6103. }
  6104. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6105. }
  6106. }
  6107. }
  6108. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6109. if ( isNaN( this.boundingSphere.radius ) ) {
  6110. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6111. }
  6112. }
  6113. }
  6114. computeTangents() {
  6115. const index = this.index;
  6116. const attributes = this.attributes;
  6117. // based on http://www.terathon.com/code/tangent.html
  6118. // (per vertex tangents)
  6119. if ( index === null ||
  6120. attributes.position === undefined ||
  6121. attributes.normal === undefined ||
  6122. attributes.uv === undefined ) {
  6123. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6124. return;
  6125. }
  6126. const indices = index.array;
  6127. const positions = attributes.position.array;
  6128. const normals = attributes.normal.array;
  6129. const uvs = attributes.uv.array;
  6130. const nVertices = positions.length / 3;
  6131. if ( this.hasAttribute( 'tangent' ) === false ) {
  6132. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  6133. }
  6134. const tangents = this.getAttribute( 'tangent' ).array;
  6135. const tan1 = [], tan2 = [];
  6136. for ( let i = 0; i < nVertices; i ++ ) {
  6137. tan1[ i ] = new Vector3();
  6138. tan2[ i ] = new Vector3();
  6139. }
  6140. const vA = new Vector3(),
  6141. vB = new Vector3(),
  6142. vC = new Vector3(),
  6143. uvA = new Vector2(),
  6144. uvB = new Vector2(),
  6145. uvC = new Vector2(),
  6146. sdir = new Vector3(),
  6147. tdir = new Vector3();
  6148. function handleTriangle( a, b, c ) {
  6149. vA.fromArray( positions, a * 3 );
  6150. vB.fromArray( positions, b * 3 );
  6151. vC.fromArray( positions, c * 3 );
  6152. uvA.fromArray( uvs, a * 2 );
  6153. uvB.fromArray( uvs, b * 2 );
  6154. uvC.fromArray( uvs, c * 2 );
  6155. vB.sub( vA );
  6156. vC.sub( vA );
  6157. uvB.sub( uvA );
  6158. uvC.sub( uvA );
  6159. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6160. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6161. if ( ! isFinite( r ) ) return;
  6162. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6163. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6164. tan1[ a ].add( sdir );
  6165. tan1[ b ].add( sdir );
  6166. tan1[ c ].add( sdir );
  6167. tan2[ a ].add( tdir );
  6168. tan2[ b ].add( tdir );
  6169. tan2[ c ].add( tdir );
  6170. }
  6171. let groups = this.groups;
  6172. if ( groups.length === 0 ) {
  6173. groups = [ {
  6174. start: 0,
  6175. count: indices.length
  6176. } ];
  6177. }
  6178. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6179. const group = groups[ i ];
  6180. const start = group.start;
  6181. const count = group.count;
  6182. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6183. handleTriangle(
  6184. indices[ j + 0 ],
  6185. indices[ j + 1 ],
  6186. indices[ j + 2 ]
  6187. );
  6188. }
  6189. }
  6190. const tmp = new Vector3(), tmp2 = new Vector3();
  6191. const n = new Vector3(), n2 = new Vector3();
  6192. function handleVertex( v ) {
  6193. n.fromArray( normals, v * 3 );
  6194. n2.copy( n );
  6195. const t = tan1[ v ];
  6196. // Gram-Schmidt orthogonalize
  6197. tmp.copy( t );
  6198. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6199. // Calculate handedness
  6200. tmp2.crossVectors( n2, t );
  6201. const test = tmp2.dot( tan2[ v ] );
  6202. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6203. tangents[ v * 4 ] = tmp.x;
  6204. tangents[ v * 4 + 1 ] = tmp.y;
  6205. tangents[ v * 4 + 2 ] = tmp.z;
  6206. tangents[ v * 4 + 3 ] = w;
  6207. }
  6208. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6209. const group = groups[ i ];
  6210. const start = group.start;
  6211. const count = group.count;
  6212. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6213. handleVertex( indices[ j + 0 ] );
  6214. handleVertex( indices[ j + 1 ] );
  6215. handleVertex( indices[ j + 2 ] );
  6216. }
  6217. }
  6218. }
  6219. computeVertexNormals() {
  6220. const index = this.index;
  6221. const positionAttribute = this.getAttribute( 'position' );
  6222. if ( positionAttribute !== undefined ) {
  6223. let normalAttribute = this.getAttribute( 'normal' );
  6224. if ( normalAttribute === undefined ) {
  6225. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6226. this.setAttribute( 'normal', normalAttribute );
  6227. } else {
  6228. // reset existing normals to zero
  6229. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6230. normalAttribute.setXYZ( i, 0, 0, 0 );
  6231. }
  6232. }
  6233. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6234. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6235. const cb = new Vector3(), ab = new Vector3();
  6236. // indexed elements
  6237. if ( index ) {
  6238. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6239. const vA = index.getX( i + 0 );
  6240. const vB = index.getX( i + 1 );
  6241. const vC = index.getX( i + 2 );
  6242. pA.fromBufferAttribute( positionAttribute, vA );
  6243. pB.fromBufferAttribute( positionAttribute, vB );
  6244. pC.fromBufferAttribute( positionAttribute, vC );
  6245. cb.subVectors( pC, pB );
  6246. ab.subVectors( pA, pB );
  6247. cb.cross( ab );
  6248. nA.fromBufferAttribute( normalAttribute, vA );
  6249. nB.fromBufferAttribute( normalAttribute, vB );
  6250. nC.fromBufferAttribute( normalAttribute, vC );
  6251. nA.add( cb );
  6252. nB.add( cb );
  6253. nC.add( cb );
  6254. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6255. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6256. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6257. }
  6258. } else {
  6259. // non-indexed elements (unconnected triangle soup)
  6260. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6261. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6262. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6263. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6264. cb.subVectors( pC, pB );
  6265. ab.subVectors( pA, pB );
  6266. cb.cross( ab );
  6267. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6268. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6269. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6270. }
  6271. }
  6272. this.normalizeNormals();
  6273. normalAttribute.needsUpdate = true;
  6274. }
  6275. }
  6276. // @deprecated since r144
  6277. merge() {
  6278. console.error( 'THREE.BufferGeometry.merge() has been removed. Use THREE.BufferGeometryUtils.mergeBufferGeometries() instead.' );
  6279. return this;
  6280. }
  6281. normalizeNormals() {
  6282. const normals = this.attributes.normal;
  6283. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6284. _vector$8.fromBufferAttribute( normals, i );
  6285. _vector$8.normalize();
  6286. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6287. }
  6288. }
  6289. toNonIndexed() {
  6290. function convertBufferAttribute( attribute, indices ) {
  6291. const array = attribute.array;
  6292. const itemSize = attribute.itemSize;
  6293. const normalized = attribute.normalized;
  6294. const array2 = new array.constructor( indices.length * itemSize );
  6295. let index = 0, index2 = 0;
  6296. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6297. if ( attribute.isInterleavedBufferAttribute ) {
  6298. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6299. } else {
  6300. index = indices[ i ] * itemSize;
  6301. }
  6302. for ( let j = 0; j < itemSize; j ++ ) {
  6303. array2[ index2 ++ ] = array[ index ++ ];
  6304. }
  6305. }
  6306. return new BufferAttribute( array2, itemSize, normalized );
  6307. }
  6308. //
  6309. if ( this.index === null ) {
  6310. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6311. return this;
  6312. }
  6313. const geometry2 = new BufferGeometry();
  6314. const indices = this.index.array;
  6315. const attributes = this.attributes;
  6316. // attributes
  6317. for ( const name in attributes ) {
  6318. const attribute = attributes[ name ];
  6319. const newAttribute = convertBufferAttribute( attribute, indices );
  6320. geometry2.setAttribute( name, newAttribute );
  6321. }
  6322. // morph attributes
  6323. const morphAttributes = this.morphAttributes;
  6324. for ( const name in morphAttributes ) {
  6325. const morphArray = [];
  6326. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6327. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6328. const attribute = morphAttribute[ i ];
  6329. const newAttribute = convertBufferAttribute( attribute, indices );
  6330. morphArray.push( newAttribute );
  6331. }
  6332. geometry2.morphAttributes[ name ] = morphArray;
  6333. }
  6334. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6335. // groups
  6336. const groups = this.groups;
  6337. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6338. const group = groups[ i ];
  6339. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6340. }
  6341. return geometry2;
  6342. }
  6343. toJSON() {
  6344. const data = {
  6345. metadata: {
  6346. version: 4.5,
  6347. type: 'BufferGeometry',
  6348. generator: 'BufferGeometry.toJSON'
  6349. }
  6350. };
  6351. // standard BufferGeometry serialization
  6352. data.uuid = this.uuid;
  6353. data.type = this.type;
  6354. if ( this.name !== '' ) data.name = this.name;
  6355. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6356. if ( this.parameters !== undefined ) {
  6357. const parameters = this.parameters;
  6358. for ( const key in parameters ) {
  6359. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6360. }
  6361. return data;
  6362. }
  6363. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6364. data.data = { attributes: {} };
  6365. const index = this.index;
  6366. if ( index !== null ) {
  6367. data.data.index = {
  6368. type: index.array.constructor.name,
  6369. array: Array.prototype.slice.call( index.array )
  6370. };
  6371. }
  6372. const attributes = this.attributes;
  6373. for ( const key in attributes ) {
  6374. const attribute = attributes[ key ];
  6375. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6376. }
  6377. const morphAttributes = {};
  6378. let hasMorphAttributes = false;
  6379. for ( const key in this.morphAttributes ) {
  6380. const attributeArray = this.morphAttributes[ key ];
  6381. const array = [];
  6382. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6383. const attribute = attributeArray[ i ];
  6384. array.push( attribute.toJSON( data.data ) );
  6385. }
  6386. if ( array.length > 0 ) {
  6387. morphAttributes[ key ] = array;
  6388. hasMorphAttributes = true;
  6389. }
  6390. }
  6391. if ( hasMorphAttributes ) {
  6392. data.data.morphAttributes = morphAttributes;
  6393. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6394. }
  6395. const groups = this.groups;
  6396. if ( groups.length > 0 ) {
  6397. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6398. }
  6399. const boundingSphere = this.boundingSphere;
  6400. if ( boundingSphere !== null ) {
  6401. data.data.boundingSphere = {
  6402. center: boundingSphere.center.toArray(),
  6403. radius: boundingSphere.radius
  6404. };
  6405. }
  6406. return data;
  6407. }
  6408. clone() {
  6409. return new this.constructor().copy( this );
  6410. }
  6411. copy( source ) {
  6412. // reset
  6413. this.index = null;
  6414. this.attributes = {};
  6415. this.morphAttributes = {};
  6416. this.groups = [];
  6417. this.boundingBox = null;
  6418. this.boundingSphere = null;
  6419. // used for storing cloned, shared data
  6420. const data = {};
  6421. // name
  6422. this.name = source.name;
  6423. // index
  6424. const index = source.index;
  6425. if ( index !== null ) {
  6426. this.setIndex( index.clone( data ) );
  6427. }
  6428. // attributes
  6429. const attributes = source.attributes;
  6430. for ( const name in attributes ) {
  6431. const attribute = attributes[ name ];
  6432. this.setAttribute( name, attribute.clone( data ) );
  6433. }
  6434. // morph attributes
  6435. const morphAttributes = source.morphAttributes;
  6436. for ( const name in morphAttributes ) {
  6437. const array = [];
  6438. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6439. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6440. array.push( morphAttribute[ i ].clone( data ) );
  6441. }
  6442. this.morphAttributes[ name ] = array;
  6443. }
  6444. this.morphTargetsRelative = source.morphTargetsRelative;
  6445. // groups
  6446. const groups = source.groups;
  6447. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6448. const group = groups[ i ];
  6449. this.addGroup( group.start, group.count, group.materialIndex );
  6450. }
  6451. // bounding box
  6452. const boundingBox = source.boundingBox;
  6453. if ( boundingBox !== null ) {
  6454. this.boundingBox = boundingBox.clone();
  6455. }
  6456. // bounding sphere
  6457. const boundingSphere = source.boundingSphere;
  6458. if ( boundingSphere !== null ) {
  6459. this.boundingSphere = boundingSphere.clone();
  6460. }
  6461. // draw range
  6462. this.drawRange.start = source.drawRange.start;
  6463. this.drawRange.count = source.drawRange.count;
  6464. // user data
  6465. this.userData = source.userData;
  6466. return this;
  6467. }
  6468. dispose() {
  6469. this.dispatchEvent( { type: 'dispose' } );
  6470. }
  6471. }
  6472. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  6473. const _ray$2 = /*@__PURE__*/ new Ray();
  6474. const _sphere$3 = /*@__PURE__*/ new Sphere();
  6475. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  6476. const _vA$1 = /*@__PURE__*/ new Vector3();
  6477. const _vB$1 = /*@__PURE__*/ new Vector3();
  6478. const _vC$1 = /*@__PURE__*/ new Vector3();
  6479. const _tempA = /*@__PURE__*/ new Vector3();
  6480. const _morphA = /*@__PURE__*/ new Vector3();
  6481. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6482. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6483. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6484. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6485. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6486. class Mesh extends Object3D {
  6487. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6488. super();
  6489. this.isMesh = true;
  6490. this.type = 'Mesh';
  6491. this.geometry = geometry;
  6492. this.material = material;
  6493. this.updateMorphTargets();
  6494. }
  6495. copy( source, recursive ) {
  6496. super.copy( source, recursive );
  6497. if ( source.morphTargetInfluences !== undefined ) {
  6498. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6499. }
  6500. if ( source.morphTargetDictionary !== undefined ) {
  6501. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6502. }
  6503. this.material = source.material;
  6504. this.geometry = source.geometry;
  6505. return this;
  6506. }
  6507. updateMorphTargets() {
  6508. const geometry = this.geometry;
  6509. const morphAttributes = geometry.morphAttributes;
  6510. const keys = Object.keys( morphAttributes );
  6511. if ( keys.length > 0 ) {
  6512. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6513. if ( morphAttribute !== undefined ) {
  6514. this.morphTargetInfluences = [];
  6515. this.morphTargetDictionary = {};
  6516. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6517. const name = morphAttribute[ m ].name || String( m );
  6518. this.morphTargetInfluences.push( 0 );
  6519. this.morphTargetDictionary[ name ] = m;
  6520. }
  6521. }
  6522. }
  6523. }
  6524. getVertexPosition( index, target ) {
  6525. const geometry = this.geometry;
  6526. const position = geometry.attributes.position;
  6527. const morphPosition = geometry.morphAttributes.position;
  6528. const morphTargetsRelative = geometry.morphTargetsRelative;
  6529. target.fromBufferAttribute( position, index );
  6530. const morphInfluences = this.morphTargetInfluences;
  6531. if ( morphPosition && morphInfluences ) {
  6532. _morphA.set( 0, 0, 0 );
  6533. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6534. const influence = morphInfluences[ i ];
  6535. const morphAttribute = morphPosition[ i ];
  6536. if ( influence === 0 ) continue;
  6537. _tempA.fromBufferAttribute( morphAttribute, index );
  6538. if ( morphTargetsRelative ) {
  6539. _morphA.addScaledVector( _tempA, influence );
  6540. } else {
  6541. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6542. }
  6543. }
  6544. target.add( _morphA );
  6545. }
  6546. if ( this.isSkinnedMesh ) {
  6547. this.boneTransform( index, target );
  6548. }
  6549. return target;
  6550. }
  6551. raycast( raycaster, intersects ) {
  6552. const geometry = this.geometry;
  6553. const material = this.material;
  6554. const matrixWorld = this.matrixWorld;
  6555. if ( material === undefined ) return;
  6556. // Checking boundingSphere distance to ray
  6557. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6558. _sphere$3.copy( geometry.boundingSphere );
  6559. _sphere$3.applyMatrix4( matrixWorld );
  6560. _ray$2.copy( raycaster.ray ).recast( raycaster.near );
  6561. if ( _sphere$3.containsPoint( _ray$2.origin ) === false ) {
  6562. if ( _ray$2.intersectSphere( _sphere$3, _sphereHitAt ) === null ) return;
  6563. if ( _ray$2.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  6564. }
  6565. //
  6566. _inverseMatrix$2.copy( matrixWorld ).invert();
  6567. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  6568. // Check boundingBox before continuing
  6569. if ( geometry.boundingBox !== null ) {
  6570. if ( _ray$2.intersectsBox( geometry.boundingBox ) === false ) return;
  6571. }
  6572. let intersection;
  6573. const index = geometry.index;
  6574. const position = geometry.attributes.position;
  6575. const uv = geometry.attributes.uv;
  6576. const uv2 = geometry.attributes.uv2;
  6577. const groups = geometry.groups;
  6578. const drawRange = geometry.drawRange;
  6579. if ( index !== null ) {
  6580. // indexed buffer geometry
  6581. if ( Array.isArray( material ) ) {
  6582. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6583. const group = groups[ i ];
  6584. const groupMaterial = material[ group.materialIndex ];
  6585. const start = Math.max( group.start, drawRange.start );
  6586. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6587. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6588. const a = index.getX( j );
  6589. const b = index.getX( j + 1 );
  6590. const c = index.getX( j + 2 );
  6591. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, uv, uv2, a, b, c );
  6592. if ( intersection ) {
  6593. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6594. intersection.face.materialIndex = group.materialIndex;
  6595. intersects.push( intersection );
  6596. }
  6597. }
  6598. }
  6599. } else {
  6600. const start = Math.max( 0, drawRange.start );
  6601. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6602. for ( let i = start, il = end; i < il; i += 3 ) {
  6603. const a = index.getX( i );
  6604. const b = index.getX( i + 1 );
  6605. const c = index.getX( i + 2 );
  6606. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, uv, uv2, a, b, c );
  6607. if ( intersection ) {
  6608. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6609. intersects.push( intersection );
  6610. }
  6611. }
  6612. }
  6613. } else if ( position !== undefined ) {
  6614. // non-indexed buffer geometry
  6615. if ( Array.isArray( material ) ) {
  6616. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6617. const group = groups[ i ];
  6618. const groupMaterial = material[ group.materialIndex ];
  6619. const start = Math.max( group.start, drawRange.start );
  6620. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6621. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6622. const a = j;
  6623. const b = j + 1;
  6624. const c = j + 2;
  6625. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, uv, uv2, a, b, c );
  6626. if ( intersection ) {
  6627. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  6628. intersection.face.materialIndex = group.materialIndex;
  6629. intersects.push( intersection );
  6630. }
  6631. }
  6632. }
  6633. } else {
  6634. const start = Math.max( 0, drawRange.start );
  6635. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  6636. for ( let i = start, il = end; i < il; i += 3 ) {
  6637. const a = i;
  6638. const b = i + 1;
  6639. const c = i + 2;
  6640. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, uv, uv2, a, b, c );
  6641. if ( intersection ) {
  6642. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  6643. intersects.push( intersection );
  6644. }
  6645. }
  6646. }
  6647. }
  6648. }
  6649. }
  6650. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  6651. let intersect;
  6652. if ( material.side === BackSide ) {
  6653. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  6654. } else {
  6655. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  6656. }
  6657. if ( intersect === null ) return null;
  6658. _intersectionPointWorld.copy( point );
  6659. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  6660. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  6661. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  6662. return {
  6663. distance: distance,
  6664. point: _intersectionPointWorld.clone(),
  6665. object: object
  6666. };
  6667. }
  6668. function checkBufferGeometryIntersection( object, material, raycaster, ray, uv, uv2, a, b, c ) {
  6669. object.getVertexPosition( a, _vA$1 );
  6670. object.getVertexPosition( b, _vB$1 );
  6671. object.getVertexPosition( c, _vC$1 );
  6672. const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  6673. if ( intersection ) {
  6674. if ( uv ) {
  6675. _uvA$1.fromBufferAttribute( uv, a );
  6676. _uvB$1.fromBufferAttribute( uv, b );
  6677. _uvC$1.fromBufferAttribute( uv, c );
  6678. intersection.uv = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6679. }
  6680. if ( uv2 ) {
  6681. _uvA$1.fromBufferAttribute( uv2, a );
  6682. _uvB$1.fromBufferAttribute( uv2, b );
  6683. _uvC$1.fromBufferAttribute( uv2, c );
  6684. intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6685. }
  6686. const face = {
  6687. a: a,
  6688. b: b,
  6689. c: c,
  6690. normal: new Vector3(),
  6691. materialIndex: 0
  6692. };
  6693. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  6694. intersection.face = face;
  6695. }
  6696. return intersection;
  6697. }
  6698. class BoxGeometry extends BufferGeometry {
  6699. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  6700. super();
  6701. this.type = 'BoxGeometry';
  6702. this.parameters = {
  6703. width: width,
  6704. height: height,
  6705. depth: depth,
  6706. widthSegments: widthSegments,
  6707. heightSegments: heightSegments,
  6708. depthSegments: depthSegments
  6709. };
  6710. const scope = this;
  6711. // segments
  6712. widthSegments = Math.floor( widthSegments );
  6713. heightSegments = Math.floor( heightSegments );
  6714. depthSegments = Math.floor( depthSegments );
  6715. // buffers
  6716. const indices = [];
  6717. const vertices = [];
  6718. const normals = [];
  6719. const uvs = [];
  6720. // helper variables
  6721. let numberOfVertices = 0;
  6722. let groupStart = 0;
  6723. // build each side of the box geometry
  6724. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  6725. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  6726. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  6727. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  6728. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  6729. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  6730. // build geometry
  6731. this.setIndex( indices );
  6732. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  6733. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  6734. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  6735. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  6736. const segmentWidth = width / gridX;
  6737. const segmentHeight = height / gridY;
  6738. const widthHalf = width / 2;
  6739. const heightHalf = height / 2;
  6740. const depthHalf = depth / 2;
  6741. const gridX1 = gridX + 1;
  6742. const gridY1 = gridY + 1;
  6743. let vertexCounter = 0;
  6744. let groupCount = 0;
  6745. const vector = new Vector3();
  6746. // generate vertices, normals and uvs
  6747. for ( let iy = 0; iy < gridY1; iy ++ ) {
  6748. const y = iy * segmentHeight - heightHalf;
  6749. for ( let ix = 0; ix < gridX1; ix ++ ) {
  6750. const x = ix * segmentWidth - widthHalf;
  6751. // set values to correct vector component
  6752. vector[ u ] = x * udir;
  6753. vector[ v ] = y * vdir;
  6754. vector[ w ] = depthHalf;
  6755. // now apply vector to vertex buffer
  6756. vertices.push( vector.x, vector.y, vector.z );
  6757. // set values to correct vector component
  6758. vector[ u ] = 0;
  6759. vector[ v ] = 0;
  6760. vector[ w ] = depth > 0 ? 1 : - 1;
  6761. // now apply vector to normal buffer
  6762. normals.push( vector.x, vector.y, vector.z );
  6763. // uvs
  6764. uvs.push( ix / gridX );
  6765. uvs.push( 1 - ( iy / gridY ) );
  6766. // counters
  6767. vertexCounter += 1;
  6768. }
  6769. }
  6770. // indices
  6771. // 1. you need three indices to draw a single face
  6772. // 2. a single segment consists of two faces
  6773. // 3. so we need to generate six (2*3) indices per segment
  6774. for ( let iy = 0; iy < gridY; iy ++ ) {
  6775. for ( let ix = 0; ix < gridX; ix ++ ) {
  6776. const a = numberOfVertices + ix + gridX1 * iy;
  6777. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  6778. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  6779. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  6780. // faces
  6781. indices.push( a, b, d );
  6782. indices.push( b, c, d );
  6783. // increase counter
  6784. groupCount += 6;
  6785. }
  6786. }
  6787. // add a group to the geometry. this will ensure multi material support
  6788. scope.addGroup( groupStart, groupCount, materialIndex );
  6789. // calculate new start value for groups
  6790. groupStart += groupCount;
  6791. // update total number of vertices
  6792. numberOfVertices += vertexCounter;
  6793. }
  6794. }
  6795. copy( source ) {
  6796. super.copy( source );
  6797. this.parameters = Object.assign( {}, source.parameters );
  6798. return this;
  6799. }
  6800. static fromJSON( data ) {
  6801. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  6802. }
  6803. }
  6804. /**
  6805. * Uniform Utilities
  6806. */
  6807. function cloneUniforms( src ) {
  6808. const dst = {};
  6809. for ( const u in src ) {
  6810. dst[ u ] = {};
  6811. for ( const p in src[ u ] ) {
  6812. const property = src[ u ][ p ];
  6813. if ( property && ( property.isColor ||
  6814. property.isMatrix3 || property.isMatrix4 ||
  6815. property.isVector2 || property.isVector3 || property.isVector4 ||
  6816. property.isTexture || property.isQuaternion ) ) {
  6817. dst[ u ][ p ] = property.clone();
  6818. } else if ( Array.isArray( property ) ) {
  6819. dst[ u ][ p ] = property.slice();
  6820. } else {
  6821. dst[ u ][ p ] = property;
  6822. }
  6823. }
  6824. }
  6825. return dst;
  6826. }
  6827. function mergeUniforms( uniforms ) {
  6828. const merged = {};
  6829. for ( let u = 0; u < uniforms.length; u ++ ) {
  6830. const tmp = cloneUniforms( uniforms[ u ] );
  6831. for ( const p in tmp ) {
  6832. merged[ p ] = tmp[ p ];
  6833. }
  6834. }
  6835. return merged;
  6836. }
  6837. function cloneUniformsGroups( src ) {
  6838. const dst = [];
  6839. for ( let u = 0; u < src.length; u ++ ) {
  6840. dst.push( src[ u ].clone() );
  6841. }
  6842. return dst;
  6843. }
  6844. function getUnlitUniformColorSpace( renderer ) {
  6845. if ( renderer.getRenderTarget() === null ) {
  6846. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  6847. return renderer.outputEncoding === sRGBEncoding ? SRGBColorSpace : LinearSRGBColorSpace;
  6848. }
  6849. return LinearSRGBColorSpace;
  6850. }
  6851. // Legacy
  6852. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  6853. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  6854. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  6855. class ShaderMaterial extends Material {
  6856. constructor( parameters ) {
  6857. super();
  6858. this.isShaderMaterial = true;
  6859. this.type = 'ShaderMaterial';
  6860. this.defines = {};
  6861. this.uniforms = {};
  6862. this.uniformsGroups = [];
  6863. this.vertexShader = default_vertex;
  6864. this.fragmentShader = default_fragment;
  6865. this.linewidth = 1;
  6866. this.wireframe = false;
  6867. this.wireframeLinewidth = 1;
  6868. this.fog = false; // set to use scene fog
  6869. this.lights = false; // set to use scene lights
  6870. this.clipping = false; // set to use user-defined clipping planes
  6871. this.extensions = {
  6872. derivatives: false, // set to use derivatives
  6873. fragDepth: false, // set to use fragment depth values
  6874. drawBuffers: false, // set to use draw buffers
  6875. shaderTextureLOD: false // set to use shader texture LOD
  6876. };
  6877. // When rendered geometry doesn't include these attributes but the material does,
  6878. // use these default values in WebGL. This avoids errors when buffer data is missing.
  6879. this.defaultAttributeValues = {
  6880. 'color': [ 1, 1, 1 ],
  6881. 'uv': [ 0, 0 ],
  6882. 'uv2': [ 0, 0 ]
  6883. };
  6884. this.index0AttributeName = undefined;
  6885. this.uniformsNeedUpdate = false;
  6886. this.glslVersion = null;
  6887. if ( parameters !== undefined ) {
  6888. this.setValues( parameters );
  6889. }
  6890. }
  6891. copy( source ) {
  6892. super.copy( source );
  6893. this.fragmentShader = source.fragmentShader;
  6894. this.vertexShader = source.vertexShader;
  6895. this.uniforms = cloneUniforms( source.uniforms );
  6896. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  6897. this.defines = Object.assign( {}, source.defines );
  6898. this.wireframe = source.wireframe;
  6899. this.wireframeLinewidth = source.wireframeLinewidth;
  6900. this.fog = source.fog;
  6901. this.lights = source.lights;
  6902. this.clipping = source.clipping;
  6903. this.extensions = Object.assign( {}, source.extensions );
  6904. this.glslVersion = source.glslVersion;
  6905. return this;
  6906. }
  6907. toJSON( meta ) {
  6908. const data = super.toJSON( meta );
  6909. data.glslVersion = this.glslVersion;
  6910. data.uniforms = {};
  6911. for ( const name in this.uniforms ) {
  6912. const uniform = this.uniforms[ name ];
  6913. const value = uniform.value;
  6914. if ( value && value.isTexture ) {
  6915. data.uniforms[ name ] = {
  6916. type: 't',
  6917. value: value.toJSON( meta ).uuid
  6918. };
  6919. } else if ( value && value.isColor ) {
  6920. data.uniforms[ name ] = {
  6921. type: 'c',
  6922. value: value.getHex()
  6923. };
  6924. } else if ( value && value.isVector2 ) {
  6925. data.uniforms[ name ] = {
  6926. type: 'v2',
  6927. value: value.toArray()
  6928. };
  6929. } else if ( value && value.isVector3 ) {
  6930. data.uniforms[ name ] = {
  6931. type: 'v3',
  6932. value: value.toArray()
  6933. };
  6934. } else if ( value && value.isVector4 ) {
  6935. data.uniforms[ name ] = {
  6936. type: 'v4',
  6937. value: value.toArray()
  6938. };
  6939. } else if ( value && value.isMatrix3 ) {
  6940. data.uniforms[ name ] = {
  6941. type: 'm3',
  6942. value: value.toArray()
  6943. };
  6944. } else if ( value && value.isMatrix4 ) {
  6945. data.uniforms[ name ] = {
  6946. type: 'm4',
  6947. value: value.toArray()
  6948. };
  6949. } else {
  6950. data.uniforms[ name ] = {
  6951. value: value
  6952. };
  6953. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  6954. }
  6955. }
  6956. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  6957. data.vertexShader = this.vertexShader;
  6958. data.fragmentShader = this.fragmentShader;
  6959. const extensions = {};
  6960. for ( const key in this.extensions ) {
  6961. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  6962. }
  6963. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  6964. return data;
  6965. }
  6966. }
  6967. class Camera extends Object3D {
  6968. constructor() {
  6969. super();
  6970. this.isCamera = true;
  6971. this.type = 'Camera';
  6972. this.matrixWorldInverse = new Matrix4();
  6973. this.projectionMatrix = new Matrix4();
  6974. this.projectionMatrixInverse = new Matrix4();
  6975. }
  6976. copy( source, recursive ) {
  6977. super.copy( source, recursive );
  6978. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  6979. this.projectionMatrix.copy( source.projectionMatrix );
  6980. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  6981. return this;
  6982. }
  6983. getWorldDirection( target ) {
  6984. this.updateWorldMatrix( true, false );
  6985. const e = this.matrixWorld.elements;
  6986. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  6987. }
  6988. updateMatrixWorld( force ) {
  6989. super.updateMatrixWorld( force );
  6990. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  6991. }
  6992. updateWorldMatrix( updateParents, updateChildren ) {
  6993. super.updateWorldMatrix( updateParents, updateChildren );
  6994. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  6995. }
  6996. clone() {
  6997. return new this.constructor().copy( this );
  6998. }
  6999. }
  7000. class PerspectiveCamera extends Camera {
  7001. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7002. super();
  7003. this.isPerspectiveCamera = true;
  7004. this.type = 'PerspectiveCamera';
  7005. this.fov = fov;
  7006. this.zoom = 1;
  7007. this.near = near;
  7008. this.far = far;
  7009. this.focus = 10;
  7010. this.aspect = aspect;
  7011. this.view = null;
  7012. this.filmGauge = 35; // width of the film (default in millimeters)
  7013. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7014. this.updateProjectionMatrix();
  7015. }
  7016. copy( source, recursive ) {
  7017. super.copy( source, recursive );
  7018. this.fov = source.fov;
  7019. this.zoom = source.zoom;
  7020. this.near = source.near;
  7021. this.far = source.far;
  7022. this.focus = source.focus;
  7023. this.aspect = source.aspect;
  7024. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7025. this.filmGauge = source.filmGauge;
  7026. this.filmOffset = source.filmOffset;
  7027. return this;
  7028. }
  7029. /**
  7030. * Sets the FOV by focal length in respect to the current .filmGauge.
  7031. *
  7032. * The default film gauge is 35, so that the focal length can be specified for
  7033. * a 35mm (full frame) camera.
  7034. *
  7035. * Values for focal length and film gauge must have the same unit.
  7036. */
  7037. setFocalLength( focalLength ) {
  7038. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7039. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7040. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7041. this.updateProjectionMatrix();
  7042. }
  7043. /**
  7044. * Calculates the focal length from the current .fov and .filmGauge.
  7045. */
  7046. getFocalLength() {
  7047. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7048. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7049. }
  7050. getEffectiveFOV() {
  7051. return RAD2DEG * 2 * Math.atan(
  7052. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7053. }
  7054. getFilmWidth() {
  7055. // film not completely covered in portrait format (aspect < 1)
  7056. return this.filmGauge * Math.min( this.aspect, 1 );
  7057. }
  7058. getFilmHeight() {
  7059. // film not completely covered in landscape format (aspect > 1)
  7060. return this.filmGauge / Math.max( this.aspect, 1 );
  7061. }
  7062. /**
  7063. * Sets an offset in a larger frustum. This is useful for multi-window or
  7064. * multi-monitor/multi-machine setups.
  7065. *
  7066. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7067. * the monitors are in grid like this
  7068. *
  7069. * +---+---+---+
  7070. * | A | B | C |
  7071. * +---+---+---+
  7072. * | D | E | F |
  7073. * +---+---+---+
  7074. *
  7075. * then for each monitor you would call it like this
  7076. *
  7077. * const w = 1920;
  7078. * const h = 1080;
  7079. * const fullWidth = w * 3;
  7080. * const fullHeight = h * 2;
  7081. *
  7082. * --A--
  7083. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7084. * --B--
  7085. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7086. * --C--
  7087. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7088. * --D--
  7089. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7090. * --E--
  7091. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7092. * --F--
  7093. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7094. *
  7095. * Note there is no reason monitors have to be the same size or in a grid.
  7096. */
  7097. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7098. this.aspect = fullWidth / fullHeight;
  7099. if ( this.view === null ) {
  7100. this.view = {
  7101. enabled: true,
  7102. fullWidth: 1,
  7103. fullHeight: 1,
  7104. offsetX: 0,
  7105. offsetY: 0,
  7106. width: 1,
  7107. height: 1
  7108. };
  7109. }
  7110. this.view.enabled = true;
  7111. this.view.fullWidth = fullWidth;
  7112. this.view.fullHeight = fullHeight;
  7113. this.view.offsetX = x;
  7114. this.view.offsetY = y;
  7115. this.view.width = width;
  7116. this.view.height = height;
  7117. this.updateProjectionMatrix();
  7118. }
  7119. clearViewOffset() {
  7120. if ( this.view !== null ) {
  7121. this.view.enabled = false;
  7122. }
  7123. this.updateProjectionMatrix();
  7124. }
  7125. updateProjectionMatrix() {
  7126. const near = this.near;
  7127. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7128. let height = 2 * top;
  7129. let width = this.aspect * height;
  7130. let left = - 0.5 * width;
  7131. const view = this.view;
  7132. if ( this.view !== null && this.view.enabled ) {
  7133. const fullWidth = view.fullWidth,
  7134. fullHeight = view.fullHeight;
  7135. left += view.offsetX * width / fullWidth;
  7136. top -= view.offsetY * height / fullHeight;
  7137. width *= view.width / fullWidth;
  7138. height *= view.height / fullHeight;
  7139. }
  7140. const skew = this.filmOffset;
  7141. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7142. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  7143. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7144. }
  7145. toJSON( meta ) {
  7146. const data = super.toJSON( meta );
  7147. data.object.fov = this.fov;
  7148. data.object.zoom = this.zoom;
  7149. data.object.near = this.near;
  7150. data.object.far = this.far;
  7151. data.object.focus = this.focus;
  7152. data.object.aspect = this.aspect;
  7153. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7154. data.object.filmGauge = this.filmGauge;
  7155. data.object.filmOffset = this.filmOffset;
  7156. return data;
  7157. }
  7158. }
  7159. const fov = - 90; // negative fov is not an error
  7160. const aspect = 1;
  7161. class CubeCamera extends Object3D {
  7162. constructor( near, far, renderTarget ) {
  7163. super();
  7164. this.type = 'CubeCamera';
  7165. this.renderTarget = renderTarget;
  7166. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7167. cameraPX.layers = this.layers;
  7168. cameraPX.up.set( 0, 1, 0 );
  7169. cameraPX.lookAt( 1, 0, 0 );
  7170. this.add( cameraPX );
  7171. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7172. cameraNX.layers = this.layers;
  7173. cameraNX.up.set( 0, 1, 0 );
  7174. cameraNX.lookAt( - 1, 0, 0 );
  7175. this.add( cameraNX );
  7176. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7177. cameraPY.layers = this.layers;
  7178. cameraPY.up.set( 0, 0, - 1 );
  7179. cameraPY.lookAt( 0, 1, 0 );
  7180. this.add( cameraPY );
  7181. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7182. cameraNY.layers = this.layers;
  7183. cameraNY.up.set( 0, 0, 1 );
  7184. cameraNY.lookAt( 0, - 1, 0 );
  7185. this.add( cameraNY );
  7186. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7187. cameraPZ.layers = this.layers;
  7188. cameraPZ.up.set( 0, 1, 0 );
  7189. cameraPZ.lookAt( 0, 0, 1 );
  7190. this.add( cameraPZ );
  7191. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7192. cameraNZ.layers = this.layers;
  7193. cameraNZ.up.set( 0, 1, 0 );
  7194. cameraNZ.lookAt( 0, 0, - 1 );
  7195. this.add( cameraNZ );
  7196. }
  7197. update( renderer, scene ) {
  7198. if ( this.parent === null ) this.updateMatrixWorld();
  7199. const renderTarget = this.renderTarget;
  7200. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7201. const currentRenderTarget = renderer.getRenderTarget();
  7202. const currentToneMapping = renderer.toneMapping;
  7203. const currentXrEnabled = renderer.xr.enabled;
  7204. renderer.toneMapping = NoToneMapping;
  7205. renderer.xr.enabled = false;
  7206. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7207. renderTarget.texture.generateMipmaps = false;
  7208. renderer.setRenderTarget( renderTarget, 0 );
  7209. renderer.render( scene, cameraPX );
  7210. renderer.setRenderTarget( renderTarget, 1 );
  7211. renderer.render( scene, cameraNX );
  7212. renderer.setRenderTarget( renderTarget, 2 );
  7213. renderer.render( scene, cameraPY );
  7214. renderer.setRenderTarget( renderTarget, 3 );
  7215. renderer.render( scene, cameraNY );
  7216. renderer.setRenderTarget( renderTarget, 4 );
  7217. renderer.render( scene, cameraPZ );
  7218. renderTarget.texture.generateMipmaps = generateMipmaps;
  7219. renderer.setRenderTarget( renderTarget, 5 );
  7220. renderer.render( scene, cameraNZ );
  7221. renderer.setRenderTarget( currentRenderTarget );
  7222. renderer.toneMapping = currentToneMapping;
  7223. renderer.xr.enabled = currentXrEnabled;
  7224. renderTarget.texture.needsPMREMUpdate = true;
  7225. }
  7226. }
  7227. class CubeTexture extends Texture {
  7228. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  7229. images = images !== undefined ? images : [];
  7230. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7231. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7232. this.isCubeTexture = true;
  7233. this.flipY = false;
  7234. }
  7235. get images() {
  7236. return this.image;
  7237. }
  7238. set images( value ) {
  7239. this.image = value;
  7240. }
  7241. }
  7242. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7243. constructor( size = 1, options = {} ) {
  7244. super( size, size, options );
  7245. this.isWebGLCubeRenderTarget = true;
  7246. const image = { width: size, height: size, depth: 1 };
  7247. const images = [ image, image, image, image, image, image ];
  7248. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  7249. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7250. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7251. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7252. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7253. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7254. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7255. this.texture.isRenderTargetTexture = true;
  7256. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7257. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7258. }
  7259. fromEquirectangularTexture( renderer, texture ) {
  7260. this.texture.type = texture.type;
  7261. this.texture.encoding = texture.encoding;
  7262. this.texture.generateMipmaps = texture.generateMipmaps;
  7263. this.texture.minFilter = texture.minFilter;
  7264. this.texture.magFilter = texture.magFilter;
  7265. const shader = {
  7266. uniforms: {
  7267. tEquirect: { value: null },
  7268. },
  7269. vertexShader: /* glsl */`
  7270. varying vec3 vWorldDirection;
  7271. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7272. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7273. }
  7274. void main() {
  7275. vWorldDirection = transformDirection( position, modelMatrix );
  7276. #include <begin_vertex>
  7277. #include <project_vertex>
  7278. }
  7279. `,
  7280. fragmentShader: /* glsl */`
  7281. uniform sampler2D tEquirect;
  7282. varying vec3 vWorldDirection;
  7283. #include <common>
  7284. void main() {
  7285. vec3 direction = normalize( vWorldDirection );
  7286. vec2 sampleUV = equirectUv( direction );
  7287. gl_FragColor = texture2D( tEquirect, sampleUV );
  7288. }
  7289. `
  7290. };
  7291. const geometry = new BoxGeometry( 5, 5, 5 );
  7292. const material = new ShaderMaterial( {
  7293. name: 'CubemapFromEquirect',
  7294. uniforms: cloneUniforms( shader.uniforms ),
  7295. vertexShader: shader.vertexShader,
  7296. fragmentShader: shader.fragmentShader,
  7297. side: BackSide,
  7298. blending: NoBlending
  7299. } );
  7300. material.uniforms.tEquirect.value = texture;
  7301. const mesh = new Mesh( geometry, material );
  7302. const currentMinFilter = texture.minFilter;
  7303. // Avoid blurred poles
  7304. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7305. const camera = new CubeCamera( 1, 10, this );
  7306. camera.update( renderer, mesh );
  7307. texture.minFilter = currentMinFilter;
  7308. mesh.geometry.dispose();
  7309. mesh.material.dispose();
  7310. return this;
  7311. }
  7312. clear( renderer, color, depth, stencil ) {
  7313. const currentRenderTarget = renderer.getRenderTarget();
  7314. for ( let i = 0; i < 6; i ++ ) {
  7315. renderer.setRenderTarget( this, i );
  7316. renderer.clear( color, depth, stencil );
  7317. }
  7318. renderer.setRenderTarget( currentRenderTarget );
  7319. }
  7320. }
  7321. const _vector1 = /*@__PURE__*/ new Vector3();
  7322. const _vector2 = /*@__PURE__*/ new Vector3();
  7323. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  7324. class Plane {
  7325. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  7326. this.isPlane = true;
  7327. // normal is assumed to be normalized
  7328. this.normal = normal;
  7329. this.constant = constant;
  7330. }
  7331. set( normal, constant ) {
  7332. this.normal.copy( normal );
  7333. this.constant = constant;
  7334. return this;
  7335. }
  7336. setComponents( x, y, z, w ) {
  7337. this.normal.set( x, y, z );
  7338. this.constant = w;
  7339. return this;
  7340. }
  7341. setFromNormalAndCoplanarPoint( normal, point ) {
  7342. this.normal.copy( normal );
  7343. this.constant = - point.dot( this.normal );
  7344. return this;
  7345. }
  7346. setFromCoplanarPoints( a, b, c ) {
  7347. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  7348. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7349. this.setFromNormalAndCoplanarPoint( normal, a );
  7350. return this;
  7351. }
  7352. copy( plane ) {
  7353. this.normal.copy( plane.normal );
  7354. this.constant = plane.constant;
  7355. return this;
  7356. }
  7357. normalize() {
  7358. // Note: will lead to a divide by zero if the plane is invalid.
  7359. const inverseNormalLength = 1.0 / this.normal.length();
  7360. this.normal.multiplyScalar( inverseNormalLength );
  7361. this.constant *= inverseNormalLength;
  7362. return this;
  7363. }
  7364. negate() {
  7365. this.constant *= - 1;
  7366. this.normal.negate();
  7367. return this;
  7368. }
  7369. distanceToPoint( point ) {
  7370. return this.normal.dot( point ) + this.constant;
  7371. }
  7372. distanceToSphere( sphere ) {
  7373. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7374. }
  7375. projectPoint( point, target ) {
  7376. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  7377. }
  7378. intersectLine( line, target ) {
  7379. const direction = line.delta( _vector1 );
  7380. const denominator = this.normal.dot( direction );
  7381. if ( denominator === 0 ) {
  7382. // line is coplanar, return origin
  7383. if ( this.distanceToPoint( line.start ) === 0 ) {
  7384. return target.copy( line.start );
  7385. }
  7386. // Unsure if this is the correct method to handle this case.
  7387. return null;
  7388. }
  7389. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7390. if ( t < 0 || t > 1 ) {
  7391. return null;
  7392. }
  7393. return target.copy( line.start ).addScaledVector( direction, t );
  7394. }
  7395. intersectsLine( line ) {
  7396. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7397. const startSign = this.distanceToPoint( line.start );
  7398. const endSign = this.distanceToPoint( line.end );
  7399. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7400. }
  7401. intersectsBox( box ) {
  7402. return box.intersectsPlane( this );
  7403. }
  7404. intersectsSphere( sphere ) {
  7405. return sphere.intersectsPlane( this );
  7406. }
  7407. coplanarPoint( target ) {
  7408. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7409. }
  7410. applyMatrix4( matrix, optionalNormalMatrix ) {
  7411. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  7412. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  7413. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7414. this.constant = - referencePoint.dot( normal );
  7415. return this;
  7416. }
  7417. translate( offset ) {
  7418. this.constant -= offset.dot( this.normal );
  7419. return this;
  7420. }
  7421. equals( plane ) {
  7422. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7423. }
  7424. clone() {
  7425. return new this.constructor().copy( this );
  7426. }
  7427. }
  7428. const _sphere$2 = /*@__PURE__*/ new Sphere();
  7429. const _vector$7 = /*@__PURE__*/ new Vector3();
  7430. class Frustum {
  7431. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7432. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7433. }
  7434. set( p0, p1, p2, p3, p4, p5 ) {
  7435. const planes = this.planes;
  7436. planes[ 0 ].copy( p0 );
  7437. planes[ 1 ].copy( p1 );
  7438. planes[ 2 ].copy( p2 );
  7439. planes[ 3 ].copy( p3 );
  7440. planes[ 4 ].copy( p4 );
  7441. planes[ 5 ].copy( p5 );
  7442. return this;
  7443. }
  7444. copy( frustum ) {
  7445. const planes = this.planes;
  7446. for ( let i = 0; i < 6; i ++ ) {
  7447. planes[ i ].copy( frustum.planes[ i ] );
  7448. }
  7449. return this;
  7450. }
  7451. setFromProjectionMatrix( m ) {
  7452. const planes = this.planes;
  7453. const me = m.elements;
  7454. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7455. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7456. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7457. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7458. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7459. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7460. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7461. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7462. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7463. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7464. return this;
  7465. }
  7466. intersectsObject( object ) {
  7467. const geometry = object.geometry;
  7468. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7469. _sphere$2.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7470. return this.intersectsSphere( _sphere$2 );
  7471. }
  7472. intersectsSprite( sprite ) {
  7473. _sphere$2.center.set( 0, 0, 0 );
  7474. _sphere$2.radius = 0.7071067811865476;
  7475. _sphere$2.applyMatrix4( sprite.matrixWorld );
  7476. return this.intersectsSphere( _sphere$2 );
  7477. }
  7478. intersectsSphere( sphere ) {
  7479. const planes = this.planes;
  7480. const center = sphere.center;
  7481. const negRadius = - sphere.radius;
  7482. for ( let i = 0; i < 6; i ++ ) {
  7483. const distance = planes[ i ].distanceToPoint( center );
  7484. if ( distance < negRadius ) {
  7485. return false;
  7486. }
  7487. }
  7488. return true;
  7489. }
  7490. intersectsBox( box ) {
  7491. const planes = this.planes;
  7492. for ( let i = 0; i < 6; i ++ ) {
  7493. const plane = planes[ i ];
  7494. // corner at max distance
  7495. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7496. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7497. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7498. if ( plane.distanceToPoint( _vector$7 ) < 0 ) {
  7499. return false;
  7500. }
  7501. }
  7502. return true;
  7503. }
  7504. containsPoint( point ) {
  7505. const planes = this.planes;
  7506. for ( let i = 0; i < 6; i ++ ) {
  7507. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7508. return false;
  7509. }
  7510. }
  7511. return true;
  7512. }
  7513. clone() {
  7514. return new this.constructor().copy( this );
  7515. }
  7516. }
  7517. function WebGLAnimation() {
  7518. let context = null;
  7519. let isAnimating = false;
  7520. let animationLoop = null;
  7521. let requestId = null;
  7522. function onAnimationFrame( time, frame ) {
  7523. animationLoop( time, frame );
  7524. requestId = context.requestAnimationFrame( onAnimationFrame );
  7525. }
  7526. return {
  7527. start: function () {
  7528. if ( isAnimating === true ) return;
  7529. if ( animationLoop === null ) return;
  7530. requestId = context.requestAnimationFrame( onAnimationFrame );
  7531. isAnimating = true;
  7532. },
  7533. stop: function () {
  7534. context.cancelAnimationFrame( requestId );
  7535. isAnimating = false;
  7536. },
  7537. setAnimationLoop: function ( callback ) {
  7538. animationLoop = callback;
  7539. },
  7540. setContext: function ( value ) {
  7541. context = value;
  7542. }
  7543. };
  7544. }
  7545. function WebGLAttributes( gl, capabilities ) {
  7546. const isWebGL2 = capabilities.isWebGL2;
  7547. const buffers = new WeakMap();
  7548. function createBuffer( attribute, bufferType ) {
  7549. const array = attribute.array;
  7550. const usage = attribute.usage;
  7551. const buffer = gl.createBuffer();
  7552. gl.bindBuffer( bufferType, buffer );
  7553. gl.bufferData( bufferType, array, usage );
  7554. attribute.onUploadCallback();
  7555. let type;
  7556. if ( array instanceof Float32Array ) {
  7557. type = 5126;
  7558. } else if ( array instanceof Uint16Array ) {
  7559. if ( attribute.isFloat16BufferAttribute ) {
  7560. if ( isWebGL2 ) {
  7561. type = 5131;
  7562. } else {
  7563. throw new Error( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  7564. }
  7565. } else {
  7566. type = 5123;
  7567. }
  7568. } else if ( array instanceof Int16Array ) {
  7569. type = 5122;
  7570. } else if ( array instanceof Uint32Array ) {
  7571. type = 5125;
  7572. } else if ( array instanceof Int32Array ) {
  7573. type = 5124;
  7574. } else if ( array instanceof Int8Array ) {
  7575. type = 5120;
  7576. } else if ( array instanceof Uint8Array ) {
  7577. type = 5121;
  7578. } else if ( array instanceof Uint8ClampedArray ) {
  7579. type = 5121;
  7580. } else {
  7581. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  7582. }
  7583. return {
  7584. buffer: buffer,
  7585. type: type,
  7586. bytesPerElement: array.BYTES_PER_ELEMENT,
  7587. version: attribute.version
  7588. };
  7589. }
  7590. function updateBuffer( buffer, attribute, bufferType ) {
  7591. const array = attribute.array;
  7592. const updateRange = attribute.updateRange;
  7593. gl.bindBuffer( bufferType, buffer );
  7594. if ( updateRange.count === - 1 ) {
  7595. // Not using update ranges
  7596. gl.bufferSubData( bufferType, 0, array );
  7597. } else {
  7598. if ( isWebGL2 ) {
  7599. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7600. array, updateRange.offset, updateRange.count );
  7601. } else {
  7602. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7603. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  7604. }
  7605. updateRange.count = - 1; // reset range
  7606. }
  7607. attribute.onUploadCallback();
  7608. }
  7609. //
  7610. function get( attribute ) {
  7611. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7612. return buffers.get( attribute );
  7613. }
  7614. function remove( attribute ) {
  7615. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7616. const data = buffers.get( attribute );
  7617. if ( data ) {
  7618. gl.deleteBuffer( data.buffer );
  7619. buffers.delete( attribute );
  7620. }
  7621. }
  7622. function update( attribute, bufferType ) {
  7623. if ( attribute.isGLBufferAttribute ) {
  7624. const cached = buffers.get( attribute );
  7625. if ( ! cached || cached.version < attribute.version ) {
  7626. buffers.set( attribute, {
  7627. buffer: attribute.buffer,
  7628. type: attribute.type,
  7629. bytesPerElement: attribute.elementSize,
  7630. version: attribute.version
  7631. } );
  7632. }
  7633. return;
  7634. }
  7635. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7636. const data = buffers.get( attribute );
  7637. if ( data === undefined ) {
  7638. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  7639. } else if ( data.version < attribute.version ) {
  7640. updateBuffer( data.buffer, attribute, bufferType );
  7641. data.version = attribute.version;
  7642. }
  7643. }
  7644. return {
  7645. get: get,
  7646. remove: remove,
  7647. update: update
  7648. };
  7649. }
  7650. class PlaneGeometry extends BufferGeometry {
  7651. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  7652. super();
  7653. this.type = 'PlaneGeometry';
  7654. this.parameters = {
  7655. width: width,
  7656. height: height,
  7657. widthSegments: widthSegments,
  7658. heightSegments: heightSegments
  7659. };
  7660. const width_half = width / 2;
  7661. const height_half = height / 2;
  7662. const gridX = Math.floor( widthSegments );
  7663. const gridY = Math.floor( heightSegments );
  7664. const gridX1 = gridX + 1;
  7665. const gridY1 = gridY + 1;
  7666. const segment_width = width / gridX;
  7667. const segment_height = height / gridY;
  7668. //
  7669. const indices = [];
  7670. const vertices = [];
  7671. const normals = [];
  7672. const uvs = [];
  7673. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7674. const y = iy * segment_height - height_half;
  7675. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7676. const x = ix * segment_width - width_half;
  7677. vertices.push( x, - y, 0 );
  7678. normals.push( 0, 0, 1 );
  7679. uvs.push( ix / gridX );
  7680. uvs.push( 1 - ( iy / gridY ) );
  7681. }
  7682. }
  7683. for ( let iy = 0; iy < gridY; iy ++ ) {
  7684. for ( let ix = 0; ix < gridX; ix ++ ) {
  7685. const a = ix + gridX1 * iy;
  7686. const b = ix + gridX1 * ( iy + 1 );
  7687. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  7688. const d = ( ix + 1 ) + gridX1 * iy;
  7689. indices.push( a, b, d );
  7690. indices.push( b, c, d );
  7691. }
  7692. }
  7693. this.setIndex( indices );
  7694. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7695. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7696. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7697. }
  7698. copy( source ) {
  7699. super.copy( source );
  7700. this.parameters = Object.assign( {}, source.parameters );
  7701. return this;
  7702. }
  7703. static fromJSON( data ) {
  7704. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  7705. }
  7706. }
  7707. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7708. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7709. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  7710. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  7711. 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";
  7712. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7713. var begin_vertex = "vec3 transformed = vec3( position );";
  7714. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7715. 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[
  7716. 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";
  7717. 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";
  7718. 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";
  7719. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7720. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7721. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7722. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7723. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7724. 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";
  7725. 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";
  7726. 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}";
  7727. 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";
  7728. 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";
  7729. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7730. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7731. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7732. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7733. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7734. 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}";
  7735. 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";
  7736. 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";
  7737. 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";
  7738. 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";
  7739. 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";
  7740. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  7741. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  7742. 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";
  7743. 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";
  7744. 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}";
  7745. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  7746. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7747. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  7748. 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";
  7749. 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 NUM
  7750. 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";
  7751. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7752. 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";
  7753. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7754. 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";
  7755. 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";
  7756. 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\tvec3
  7757. 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.visi
  7758. 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";
  7759. 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";
  7760. 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";
  7761. 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";
  7762. 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";
  7763. 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";
  7764. 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";
  7765. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7766. 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";
  7767. 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";
  7768. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7769. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7770. 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";
  7771. 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";
  7772. 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";
  7773. 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";
  7774. 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;";
  7775. 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";
  7776. 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";
  7777. 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";
  7778. 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";
  7779. 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";
  7780. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7781. 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";
  7782. 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";
  7783. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  7784. 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 );";
  7785. 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 linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}";
  7786. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7787. 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;";
  7788. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7789. 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";
  7790. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7791. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7792. 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 + vec
  7793. 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";
  7794. 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";
  7795. 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}";
  7796. 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";
  7797. 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";
  7798. 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";
  7799. 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";
  7800. 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";
  7801. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7802. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7803. 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; }";
  7804. 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";
  7805. 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( co
  7806. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7807. 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";
  7808. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7809. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7810. 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";
  7811. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7812. 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";
  7813. 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}";
  7814. 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}";
  7815. 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}";
  7816. 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}";
  7817. 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}";
  7818. 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}";
  7819. 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}";
  7820. 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}";
  7821. 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}";
  7822. 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}";
  7823. 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}";
  7824. 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}";
  7825. 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}";
  7826. 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}";
  7827. 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}";
  7828. 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}";
  7829. 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}";
  7830. 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}";
  7831. 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}";
  7832. 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}";
  7833. 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}";
  7834. 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}";
  7835. 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}";
  7836. 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}";
  7837. 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}";
  7838. 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}";
  7839. 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}";
  7840. 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}";
  7841. 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}";
  7842. 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}";
  7843. 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}";
  7844. 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}";
  7845. 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}";
  7846. 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}";
  7847. const ShaderChunk = {
  7848. alphamap_fragment: alphamap_fragment,
  7849. alphamap_pars_fragment: alphamap_pars_fragment,
  7850. alphatest_fragment: alphatest_fragment,
  7851. alphatest_pars_fragment: alphatest_pars_fragment,
  7852. aomap_fragment: aomap_fragment,
  7853. aomap_pars_fragment: aomap_pars_fragment,
  7854. begin_vertex: begin_vertex,
  7855. beginnormal_vertex: beginnormal_vertex,
  7856. bsdfs: bsdfs,
  7857. iridescence_fragment: iridescence_fragment,
  7858. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7859. clipping_planes_fragment: clipping_planes_fragment,
  7860. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7861. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7862. clipping_planes_vertex: clipping_planes_vertex,
  7863. color_fragment: color_fragment,
  7864. color_pars_fragment: color_pars_fragment,
  7865. color_pars_vertex: color_pars_vertex,
  7866. color_vertex: color_vertex,
  7867. common: common,
  7868. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  7869. defaultnormal_vertex: defaultnormal_vertex,
  7870. displacementmap_pars_vertex: displacementmap_pars_vertex,
  7871. displacementmap_vertex: displacementmap_vertex,
  7872. emissivemap_fragment: emissivemap_fragment,
  7873. emissivemap_pars_fragment: emissivemap_pars_fragment,
  7874. encodings_fragment: encodings_fragment,
  7875. encodings_pars_fragment: encodings_pars_fragment,
  7876. envmap_fragment: envmap_fragment,
  7877. envmap_common_pars_fragment: envmap_common_pars_fragment,
  7878. envmap_pars_fragment: envmap_pars_fragment,
  7879. envmap_pars_vertex: envmap_pars_vertex,
  7880. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  7881. envmap_vertex: envmap_vertex,
  7882. fog_vertex: fog_vertex,
  7883. fog_pars_vertex: fog_pars_vertex,
  7884. fog_fragment: fog_fragment,
  7885. fog_pars_fragment: fog_pars_fragment,
  7886. gradientmap_pars_fragment: gradientmap_pars_fragment,
  7887. lightmap_fragment: lightmap_fragment,
  7888. lightmap_pars_fragment: lightmap_pars_fragment,
  7889. lights_lambert_fragment: lights_lambert_fragment,
  7890. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  7891. lights_pars_begin: lights_pars_begin,
  7892. lights_toon_fragment: lights_toon_fragment,
  7893. lights_toon_pars_fragment: lights_toon_pars_fragment,
  7894. lights_phong_fragment: lights_phong_fragment,
  7895. lights_phong_pars_fragment: lights_phong_pars_fragment,
  7896. lights_physical_fragment: lights_physical_fragment,
  7897. lights_physical_pars_fragment: lights_physical_pars_fragment,
  7898. lights_fragment_begin: lights_fragment_begin,
  7899. lights_fragment_maps: lights_fragment_maps,
  7900. lights_fragment_end: lights_fragment_end,
  7901. logdepthbuf_fragment: logdepthbuf_fragment,
  7902. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  7903. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  7904. logdepthbuf_vertex: logdepthbuf_vertex,
  7905. map_fragment: map_fragment,
  7906. map_pars_fragment: map_pars_fragment,
  7907. map_particle_fragment: map_particle_fragment,
  7908. map_particle_pars_fragment: map_particle_pars_fragment,
  7909. metalnessmap_fragment: metalnessmap_fragment,
  7910. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  7911. morphcolor_vertex: morphcolor_vertex,
  7912. morphnormal_vertex: morphnormal_vertex,
  7913. morphtarget_pars_vertex: morphtarget_pars_vertex,
  7914. morphtarget_vertex: morphtarget_vertex,
  7915. normal_fragment_begin: normal_fragment_begin,
  7916. normal_fragment_maps: normal_fragment_maps,
  7917. normal_pars_fragment: normal_pars_fragment,
  7918. normal_pars_vertex: normal_pars_vertex,
  7919. normal_vertex: normal_vertex,
  7920. normalmap_pars_fragment: normalmap_pars_fragment,
  7921. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  7922. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  7923. clearcoat_pars_fragment: clearcoat_pars_fragment,
  7924. iridescence_pars_fragment: iridescence_pars_fragment,
  7925. output_fragment: output_fragment,
  7926. packing: packing,
  7927. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  7928. project_vertex: project_vertex,
  7929. dithering_fragment: dithering_fragment,
  7930. dithering_pars_fragment: dithering_pars_fragment,
  7931. roughnessmap_fragment: roughnessmap_fragment,
  7932. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  7933. shadowmap_pars_fragment: shadowmap_pars_fragment,
  7934. shadowmap_pars_vertex: shadowmap_pars_vertex,
  7935. shadowmap_vertex: shadowmap_vertex,
  7936. shadowmask_pars_fragment: shadowmask_pars_fragment,
  7937. skinbase_vertex: skinbase_vertex,
  7938. skinning_pars_vertex: skinning_pars_vertex,
  7939. skinning_vertex: skinning_vertex,
  7940. skinnormal_vertex: skinnormal_vertex,
  7941. specularmap_fragment: specularmap_fragment,
  7942. specularmap_pars_fragment: specularmap_pars_fragment,
  7943. tonemapping_fragment: tonemapping_fragment,
  7944. tonemapping_pars_fragment: tonemapping_pars_fragment,
  7945. transmission_fragment: transmission_fragment,
  7946. transmission_pars_fragment: transmission_pars_fragment,
  7947. uv_pars_fragment: uv_pars_fragment,
  7948. uv_pars_vertex: uv_pars_vertex,
  7949. uv_vertex: uv_vertex,
  7950. uv2_pars_fragment: uv2_pars_fragment,
  7951. uv2_pars_vertex: uv2_pars_vertex,
  7952. uv2_vertex: uv2_vertex,
  7953. worldpos_vertex: worldpos_vertex,
  7954. background_vert: vertex$h,
  7955. background_frag: fragment$h,
  7956. backgroundCube_vert: vertex$g,
  7957. backgroundCube_frag: fragment$g,
  7958. cube_vert: vertex$f,
  7959. cube_frag: fragment$f,
  7960. depth_vert: vertex$e,
  7961. depth_frag: fragment$e,
  7962. distanceRGBA_vert: vertex$d,
  7963. distanceRGBA_frag: fragment$d,
  7964. equirect_vert: vertex$c,
  7965. equirect_frag: fragment$c,
  7966. linedashed_vert: vertex$b,
  7967. linedashed_frag: fragment$b,
  7968. meshbasic_vert: vertex$a,
  7969. meshbasic_frag: fragment$a,
  7970. meshlambert_vert: vertex$9,
  7971. meshlambert_frag: fragment$9,
  7972. meshmatcap_vert: vertex$8,
  7973. meshmatcap_frag: fragment$8,
  7974. meshnormal_vert: vertex$7,
  7975. meshnormal_frag: fragment$7,
  7976. meshphong_vert: vertex$6,
  7977. meshphong_frag: fragment$6,
  7978. meshphysical_vert: vertex$5,
  7979. meshphysical_frag: fragment$5,
  7980. meshtoon_vert: vertex$4,
  7981. meshtoon_frag: fragment$4,
  7982. points_vert: vertex$3,
  7983. points_frag: fragment$3,
  7984. shadow_vert: vertex$2,
  7985. shadow_frag: fragment$2,
  7986. sprite_vert: vertex$1,
  7987. sprite_frag: fragment$1
  7988. };
  7989. /**
  7990. * Uniforms library for shared webgl shaders
  7991. */
  7992. const UniformsLib = {
  7993. common: {
  7994. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  7995. opacity: { value: 1.0 },
  7996. map: { value: null },
  7997. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  7998. uv2Transform: { value: /*@__PURE__*/ new Matrix3() },
  7999. alphaMap: { value: null },
  8000. alphaTest: { value: 0 }
  8001. },
  8002. specularmap: {
  8003. specularMap: { value: null },
  8004. },
  8005. envmap: {
  8006. envMap: { value: null },
  8007. flipEnvMap: { value: - 1 },
  8008. reflectivity: { value: 1.0 }, // basic, lambert, phong
  8009. ior: { value: 1.5 }, // physical
  8010. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  8011. },
  8012. aomap: {
  8013. aoMap: { value: null },
  8014. aoMapIntensity: { value: 1 }
  8015. },
  8016. lightmap: {
  8017. lightMap: { value: null },
  8018. lightMapIntensity: { value: 1 }
  8019. },
  8020. emissivemap: {
  8021. emissiveMap: { value: null }
  8022. },
  8023. bumpmap: {
  8024. bumpMap: { value: null },
  8025. bumpScale: { value: 1 }
  8026. },
  8027. normalmap: {
  8028. normalMap: { value: null },
  8029. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  8030. },
  8031. displacementmap: {
  8032. displacementMap: { value: null },
  8033. displacementScale: { value: 1 },
  8034. displacementBias: { value: 0 }
  8035. },
  8036. roughnessmap: {
  8037. roughnessMap: { value: null }
  8038. },
  8039. metalnessmap: {
  8040. metalnessMap: { value: null }
  8041. },
  8042. gradientmap: {
  8043. gradientMap: { value: null }
  8044. },
  8045. fog: {
  8046. fogDensity: { value: 0.00025 },
  8047. fogNear: { value: 1 },
  8048. fogFar: { value: 2000 },
  8049. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  8050. },
  8051. lights: {
  8052. ambientLightColor: { value: [] },
  8053. lightProbe: { value: [] },
  8054. directionalLights: { value: [], properties: {
  8055. direction: {},
  8056. color: {}
  8057. } },
  8058. directionalLightShadows: { value: [], properties: {
  8059. shadowBias: {},
  8060. shadowNormalBias: {},
  8061. shadowRadius: {},
  8062. shadowMapSize: {}
  8063. } },
  8064. directionalShadowMap: { value: [] },
  8065. directionalShadowMatrix: { value: [] },
  8066. spotLights: { value: [], properties: {
  8067. color: {},
  8068. position: {},
  8069. direction: {},
  8070. distance: {},
  8071. coneCos: {},
  8072. penumbraCos: {},
  8073. decay: {}
  8074. } },
  8075. spotLightShadows: { value: [], properties: {
  8076. shadowBias: {},
  8077. shadowNormalBias: {},
  8078. shadowRadius: {},
  8079. shadowMapSize: {}
  8080. } },
  8081. spotLightMap: { value: [] },
  8082. spotShadowMap: { value: [] },
  8083. spotLightMatrix: { value: [] },
  8084. pointLights: { value: [], properties: {
  8085. color: {},
  8086. position: {},
  8087. decay: {},
  8088. distance: {}
  8089. } },
  8090. pointLightShadows: { value: [], properties: {
  8091. shadowBias: {},
  8092. shadowNormalBias: {},
  8093. shadowRadius: {},
  8094. shadowMapSize: {},
  8095. shadowCameraNear: {},
  8096. shadowCameraFar: {}
  8097. } },
  8098. pointShadowMap: { value: [] },
  8099. pointShadowMatrix: { value: [] },
  8100. hemisphereLights: { value: [], properties: {
  8101. direction: {},
  8102. skyColor: {},
  8103. groundColor: {}
  8104. } },
  8105. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8106. rectAreaLights: { value: [], properties: {
  8107. color: {},
  8108. position: {},
  8109. width: {},
  8110. height: {}
  8111. } },
  8112. ltc_1: { value: null },
  8113. ltc_2: { value: null }
  8114. },
  8115. points: {
  8116. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8117. opacity: { value: 1.0 },
  8118. size: { value: 1.0 },
  8119. scale: { value: 1.0 },
  8120. map: { value: null },
  8121. alphaMap: { value: null },
  8122. alphaTest: { value: 0 },
  8123. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8124. },
  8125. sprite: {
  8126. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8127. opacity: { value: 1.0 },
  8128. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  8129. rotation: { value: 0.0 },
  8130. map: { value: null },
  8131. alphaMap: { value: null },
  8132. alphaTest: { value: 0 },
  8133. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8134. }
  8135. };
  8136. const ShaderLib = {
  8137. basic: {
  8138. uniforms: /*@__PURE__*/ mergeUniforms( [
  8139. UniformsLib.common,
  8140. UniformsLib.specularmap,
  8141. UniformsLib.envmap,
  8142. UniformsLib.aomap,
  8143. UniformsLib.lightmap,
  8144. UniformsLib.fog
  8145. ] ),
  8146. vertexShader: ShaderChunk.meshbasic_vert,
  8147. fragmentShader: ShaderChunk.meshbasic_frag
  8148. },
  8149. lambert: {
  8150. uniforms: /*@__PURE__*/ mergeUniforms( [
  8151. UniformsLib.common,
  8152. UniformsLib.specularmap,
  8153. UniformsLib.envmap,
  8154. UniformsLib.aomap,
  8155. UniformsLib.lightmap,
  8156. UniformsLib.emissivemap,
  8157. UniformsLib.bumpmap,
  8158. UniformsLib.normalmap,
  8159. UniformsLib.displacementmap,
  8160. UniformsLib.fog,
  8161. UniformsLib.lights,
  8162. {
  8163. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8164. }
  8165. ] ),
  8166. vertexShader: ShaderChunk.meshlambert_vert,
  8167. fragmentShader: ShaderChunk.meshlambert_frag
  8168. },
  8169. phong: {
  8170. uniforms: /*@__PURE__*/ mergeUniforms( [
  8171. UniformsLib.common,
  8172. UniformsLib.specularmap,
  8173. UniformsLib.envmap,
  8174. UniformsLib.aomap,
  8175. UniformsLib.lightmap,
  8176. UniformsLib.emissivemap,
  8177. UniformsLib.bumpmap,
  8178. UniformsLib.normalmap,
  8179. UniformsLib.displacementmap,
  8180. UniformsLib.fog,
  8181. UniformsLib.lights,
  8182. {
  8183. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8184. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  8185. shininess: { value: 30 }
  8186. }
  8187. ] ),
  8188. vertexShader: ShaderChunk.meshphong_vert,
  8189. fragmentShader: ShaderChunk.meshphong_frag
  8190. },
  8191. standard: {
  8192. uniforms: /*@__PURE__*/ mergeUniforms( [
  8193. UniformsLib.common,
  8194. UniformsLib.envmap,
  8195. UniformsLib.aomap,
  8196. UniformsLib.lightmap,
  8197. UniformsLib.emissivemap,
  8198. UniformsLib.bumpmap,
  8199. UniformsLib.normalmap,
  8200. UniformsLib.displacementmap,
  8201. UniformsLib.roughnessmap,
  8202. UniformsLib.metalnessmap,
  8203. UniformsLib.fog,
  8204. UniformsLib.lights,
  8205. {
  8206. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8207. roughness: { value: 1.0 },
  8208. metalness: { value: 0.0 },
  8209. envMapIntensity: { value: 1 } // temporary
  8210. }
  8211. ] ),
  8212. vertexShader: ShaderChunk.meshphysical_vert,
  8213. fragmentShader: ShaderChunk.meshphysical_frag
  8214. },
  8215. toon: {
  8216. uniforms: /*@__PURE__*/ mergeUniforms( [
  8217. UniformsLib.common,
  8218. UniformsLib.aomap,
  8219. UniformsLib.lightmap,
  8220. UniformsLib.emissivemap,
  8221. UniformsLib.bumpmap,
  8222. UniformsLib.normalmap,
  8223. UniformsLib.displacementmap,
  8224. UniformsLib.gradientmap,
  8225. UniformsLib.fog,
  8226. UniformsLib.lights,
  8227. {
  8228. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8229. }
  8230. ] ),
  8231. vertexShader: ShaderChunk.meshtoon_vert,
  8232. fragmentShader: ShaderChunk.meshtoon_frag
  8233. },
  8234. matcap: {
  8235. uniforms: /*@__PURE__*/ mergeUniforms( [
  8236. UniformsLib.common,
  8237. UniformsLib.bumpmap,
  8238. UniformsLib.normalmap,
  8239. UniformsLib.displacementmap,
  8240. UniformsLib.fog,
  8241. {
  8242. matcap: { value: null }
  8243. }
  8244. ] ),
  8245. vertexShader: ShaderChunk.meshmatcap_vert,
  8246. fragmentShader: ShaderChunk.meshmatcap_frag
  8247. },
  8248. points: {
  8249. uniforms: /*@__PURE__*/ mergeUniforms( [
  8250. UniformsLib.points,
  8251. UniformsLib.fog
  8252. ] ),
  8253. vertexShader: ShaderChunk.points_vert,
  8254. fragmentShader: ShaderChunk.points_frag
  8255. },
  8256. dashed: {
  8257. uniforms: /*@__PURE__*/ mergeUniforms( [
  8258. UniformsLib.common,
  8259. UniformsLib.fog,
  8260. {
  8261. scale: { value: 1 },
  8262. dashSize: { value: 1 },
  8263. totalSize: { value: 2 }
  8264. }
  8265. ] ),
  8266. vertexShader: ShaderChunk.linedashed_vert,
  8267. fragmentShader: ShaderChunk.linedashed_frag
  8268. },
  8269. depth: {
  8270. uniforms: /*@__PURE__*/ mergeUniforms( [
  8271. UniformsLib.common,
  8272. UniformsLib.displacementmap
  8273. ] ),
  8274. vertexShader: ShaderChunk.depth_vert,
  8275. fragmentShader: ShaderChunk.depth_frag
  8276. },
  8277. normal: {
  8278. uniforms: /*@__PURE__*/ mergeUniforms( [
  8279. UniformsLib.common,
  8280. UniformsLib.bumpmap,
  8281. UniformsLib.normalmap,
  8282. UniformsLib.displacementmap,
  8283. {
  8284. opacity: { value: 1.0 }
  8285. }
  8286. ] ),
  8287. vertexShader: ShaderChunk.meshnormal_vert,
  8288. fragmentShader: ShaderChunk.meshnormal_frag
  8289. },
  8290. sprite: {
  8291. uniforms: /*@__PURE__*/ mergeUniforms( [
  8292. UniformsLib.sprite,
  8293. UniformsLib.fog
  8294. ] ),
  8295. vertexShader: ShaderChunk.sprite_vert,
  8296. fragmentShader: ShaderChunk.sprite_frag
  8297. },
  8298. background: {
  8299. uniforms: {
  8300. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  8301. t2D: { value: null },
  8302. backgroundIntensity: { value: 1 }
  8303. },
  8304. vertexShader: ShaderChunk.background_vert,
  8305. fragmentShader: ShaderChunk.background_frag
  8306. },
  8307. backgroundCube: {
  8308. uniforms: {
  8309. envMap: { value: null },
  8310. flipEnvMap: { value: - 1 },
  8311. backgroundBlurriness: { value: 0 },
  8312. backgroundIntensity: { value: 1 }
  8313. },
  8314. vertexShader: ShaderChunk.backgroundCube_vert,
  8315. fragmentShader: ShaderChunk.backgroundCube_frag
  8316. },
  8317. cube: {
  8318. uniforms: {
  8319. tCube: { value: null },
  8320. tFlip: { value: - 1 },
  8321. opacity: { value: 1.0 }
  8322. },
  8323. vertexShader: ShaderChunk.cube_vert,
  8324. fragmentShader: ShaderChunk.cube_frag
  8325. },
  8326. equirect: {
  8327. uniforms: {
  8328. tEquirect: { value: null },
  8329. },
  8330. vertexShader: ShaderChunk.equirect_vert,
  8331. fragmentShader: ShaderChunk.equirect_frag
  8332. },
  8333. distanceRGBA: {
  8334. uniforms: /*@__PURE__*/ mergeUniforms( [
  8335. UniformsLib.common,
  8336. UniformsLib.displacementmap,
  8337. {
  8338. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  8339. nearDistance: { value: 1 },
  8340. farDistance: { value: 1000 }
  8341. }
  8342. ] ),
  8343. vertexShader: ShaderChunk.distanceRGBA_vert,
  8344. fragmentShader: ShaderChunk.distanceRGBA_frag
  8345. },
  8346. shadow: {
  8347. uniforms: /*@__PURE__*/ mergeUniforms( [
  8348. UniformsLib.lights,
  8349. UniformsLib.fog,
  8350. {
  8351. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  8352. opacity: { value: 1.0 }
  8353. },
  8354. ] ),
  8355. vertexShader: ShaderChunk.shadow_vert,
  8356. fragmentShader: ShaderChunk.shadow_frag
  8357. }
  8358. };
  8359. ShaderLib.physical = {
  8360. uniforms: /*@__PURE__*/ mergeUniforms( [
  8361. ShaderLib.standard.uniforms,
  8362. {
  8363. clearcoat: { value: 0 },
  8364. clearcoatMap: { value: null },
  8365. clearcoatRoughness: { value: 0 },
  8366. clearcoatRoughnessMap: { value: null },
  8367. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  8368. clearcoatNormalMap: { value: null },
  8369. iridescence: { value: 0 },
  8370. iridescenceMap: { value: null },
  8371. iridescenceIOR: { value: 1.3 },
  8372. iridescenceThicknessMinimum: { value: 100 },
  8373. iridescenceThicknessMaximum: { value: 400 },
  8374. iridescenceThicknessMap: { value: null },
  8375. sheen: { value: 0 },
  8376. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8377. sheenColorMap: { value: null },
  8378. sheenRoughness: { value: 1 },
  8379. sheenRoughnessMap: { value: null },
  8380. transmission: { value: 0 },
  8381. transmissionMap: { value: null },
  8382. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  8383. transmissionSamplerMap: { value: null },
  8384. thickness: { value: 0 },
  8385. thicknessMap: { value: null },
  8386. attenuationDistance: { value: 0 },
  8387. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8388. specularIntensity: { value: 1 },
  8389. specularIntensityMap: { value: null },
  8390. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  8391. specularColorMap: { value: null },
  8392. }
  8393. ] ),
  8394. vertexShader: ShaderChunk.meshphysical_vert,
  8395. fragmentShader: ShaderChunk.meshphysical_frag
  8396. };
  8397. const _rgb = { r: 0, b: 0, g: 0 };
  8398. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  8399. const clearColor = new Color( 0x000000 );
  8400. let clearAlpha = alpha === true ? 0 : 1;
  8401. let planeMesh;
  8402. let boxMesh;
  8403. let currentBackground = null;
  8404. let currentBackgroundVersion = 0;
  8405. let currentTonemapping = null;
  8406. function render( renderList, scene ) {
  8407. let forceClear = false;
  8408. let background = scene.isScene === true ? scene.background : null;
  8409. if ( background && background.isTexture ) {
  8410. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  8411. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  8412. }
  8413. // Ignore background in AR
  8414. // TODO: Reconsider this.
  8415. const xr = renderer.xr;
  8416. const session = xr.getSession && xr.getSession();
  8417. if ( session && session.environmentBlendMode === 'additive' ) {
  8418. background = null;
  8419. }
  8420. if ( background === null ) {
  8421. setClear( clearColor, clearAlpha );
  8422. } else if ( background && background.isColor ) {
  8423. setClear( background, 1 );
  8424. forceClear = true;
  8425. }
  8426. if ( renderer.autoClear || forceClear ) {
  8427. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8428. }
  8429. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  8430. if ( boxMesh === undefined ) {
  8431. boxMesh = new Mesh(
  8432. new BoxGeometry( 1, 1, 1 ),
  8433. new ShaderMaterial( {
  8434. name: 'BackgroundCubeMaterial',
  8435. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  8436. vertexShader: ShaderLib.backgroundCube.vertexShader,
  8437. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  8438. side: BackSide,
  8439. depthTest: false,
  8440. depthWrite: false,
  8441. fog: false
  8442. } )
  8443. );
  8444. boxMesh.geometry.deleteAttribute( 'normal' );
  8445. boxMesh.geometry.deleteAttribute( 'uv' );
  8446. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8447. this.matrixWorld.copyPosition( camera.matrixWorld );
  8448. };
  8449. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  8450. Object.defineProperty( boxMesh.material, 'envMap', {
  8451. get: function () {
  8452. return this.uniforms.envMap.value;
  8453. }
  8454. } );
  8455. objects.update( boxMesh );
  8456. }
  8457. boxMesh.material.uniforms.envMap.value = background;
  8458. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  8459. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  8460. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8461. boxMesh.material.toneMapped = ( background.encoding === sRGBEncoding ) ? false : true;
  8462. if ( currentBackground !== background ||
  8463. currentBackgroundVersion !== background.version ||
  8464. currentTonemapping !== renderer.toneMapping ) {
  8465. boxMesh.material.needsUpdate = true;
  8466. currentBackground = background;
  8467. currentBackgroundVersion = background.version;
  8468. currentTonemapping = renderer.toneMapping;
  8469. }
  8470. boxMesh.layers.enableAll();
  8471. // push to the pre-sorted opaque render list
  8472. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  8473. } else if ( background && background.isTexture ) {
  8474. if ( planeMesh === undefined ) {
  8475. planeMesh = new Mesh(
  8476. new PlaneGeometry( 2, 2 ),
  8477. new ShaderMaterial( {
  8478. name: 'BackgroundMaterial',
  8479. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  8480. vertexShader: ShaderLib.background.vertexShader,
  8481. fragmentShader: ShaderLib.background.fragmentShader,
  8482. side: FrontSide,
  8483. depthTest: false,
  8484. depthWrite: false,
  8485. fog: false
  8486. } )
  8487. );
  8488. planeMesh.geometry.deleteAttribute( 'normal' );
  8489. // add "map" material property so the renderer can evaluate it like for built-in materials
  8490. Object.defineProperty( planeMesh.material, 'map', {
  8491. get: function () {
  8492. return this.uniforms.t2D.value;
  8493. }
  8494. } );
  8495. objects.update( planeMesh );
  8496. }
  8497. planeMesh.material.uniforms.t2D.value = background;
  8498. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8499. planeMesh.material.toneMapped = ( background.encoding === sRGBEncoding ) ? false : true;
  8500. if ( background.matrixAutoUpdate === true ) {
  8501. background.updateMatrix();
  8502. }
  8503. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  8504. if ( currentBackground !== background ||
  8505. currentBackgroundVersion !== background.version ||
  8506. currentTonemapping !== renderer.toneMapping ) {
  8507. planeMesh.material.needsUpdate = true;
  8508. currentBackground = background;
  8509. currentBackgroundVersion = background.version;
  8510. currentTonemapping = renderer.toneMapping;
  8511. }
  8512. planeMesh.layers.enableAll();
  8513. // push to the pre-sorted opaque render list
  8514. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  8515. }
  8516. }
  8517. function setClear( color, alpha ) {
  8518. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  8519. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  8520. }
  8521. return {
  8522. getClearColor: function () {
  8523. return clearColor;
  8524. },
  8525. setClearColor: function ( color, alpha = 1 ) {
  8526. clearColor.set( color );
  8527. clearAlpha = alpha;
  8528. setClear( clearColor, clearAlpha );
  8529. },
  8530. getClearAlpha: function () {
  8531. return clearAlpha;
  8532. },
  8533. setClearAlpha: function ( alpha ) {
  8534. clearAlpha = alpha;
  8535. setClear( clearColor, clearAlpha );
  8536. },
  8537. render: render
  8538. };
  8539. }
  8540. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  8541. const maxVertexAttributes = gl.getParameter( 34921 );
  8542. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  8543. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8544. const bindingStates = {};
  8545. const defaultState = createBindingState( null );
  8546. let currentState = defaultState;
  8547. let forceUpdate = false;
  8548. function setup( object, material, program, geometry, index ) {
  8549. let updateBuffers = false;
  8550. if ( vaoAvailable ) {
  8551. const state = getBindingState( geometry, program, material );
  8552. if ( currentState !== state ) {
  8553. currentState = state;
  8554. bindVertexArrayObject( currentState.object );
  8555. }
  8556. updateBuffers = needsUpdate( object, geometry, program, index );
  8557. if ( updateBuffers ) saveCache( object, geometry, program, index );
  8558. } else {
  8559. const wireframe = ( material.wireframe === true );
  8560. if ( currentState.geometry !== geometry.id ||
  8561. currentState.program !== program.id ||
  8562. currentState.wireframe !== wireframe ) {
  8563. currentState.geometry = geometry.id;
  8564. currentState.program = program.id;
  8565. currentState.wireframe = wireframe;
  8566. updateBuffers = true;
  8567. }
  8568. }
  8569. if ( index !== null ) {
  8570. attributes.update( index, 34963 );
  8571. }
  8572. if ( updateBuffers || forceUpdate ) {
  8573. forceUpdate = false;
  8574. setupVertexAttributes( object, material, program, geometry );
  8575. if ( index !== null ) {
  8576. gl.bindBuffer( 34963, attributes.get( index ).buffer );
  8577. }
  8578. }
  8579. }
  8580. function createVertexArrayObject() {
  8581. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  8582. return extension.createVertexArrayOES();
  8583. }
  8584. function bindVertexArrayObject( vao ) {
  8585. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  8586. return extension.bindVertexArrayOES( vao );
  8587. }
  8588. function deleteVertexArrayObject( vao ) {
  8589. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  8590. return extension.deleteVertexArrayOES( vao );
  8591. }
  8592. function getBindingState( geometry, program, material ) {
  8593. const wireframe = ( material.wireframe === true );
  8594. let programMap = bindingStates[ geometry.id ];
  8595. if ( programMap === undefined ) {
  8596. programMap = {};
  8597. bindingStates[ geometry.id ] = programMap;
  8598. }
  8599. let stateMap = programMap[ program.id ];
  8600. if ( stateMap === undefined ) {
  8601. stateMap = {};
  8602. programMap[ program.id ] = stateMap;
  8603. }
  8604. let state = stateMap[ wireframe ];
  8605. if ( state === undefined ) {
  8606. state = createBindingState( createVertexArrayObject() );
  8607. stateMap[ wireframe ] = state;
  8608. }
  8609. return state;
  8610. }
  8611. function createBindingState( vao ) {
  8612. const newAttributes = [];
  8613. const enabledAttributes = [];
  8614. const attributeDivisors = [];
  8615. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  8616. newAttributes[ i ] = 0;
  8617. enabledAttributes[ i ] = 0;
  8618. attributeDivisors[ i ] = 0;
  8619. }
  8620. return {
  8621. // for backward compatibility on non-VAO support browser
  8622. geometry: null,
  8623. program: null,
  8624. wireframe: false,
  8625. newAttributes: newAttributes,
  8626. enabledAttributes: enabledAttributes,
  8627. attributeDivisors: attributeDivisors,
  8628. object: vao,
  8629. attributes: {},
  8630. index: null
  8631. };
  8632. }
  8633. function needsUpdate( object, geometry, program, index ) {
  8634. const cachedAttributes = currentState.attributes;
  8635. const geometryAttributes = geometry.attributes;
  8636. let attributesNum = 0;
  8637. const programAttributes = program.getAttributes();
  8638. for ( const name in programAttributes ) {
  8639. const programAttribute = programAttributes[ name ];
  8640. if ( programAttribute.location >= 0 ) {
  8641. const cachedAttribute = cachedAttributes[ name ];
  8642. let geometryAttribute = geometryAttributes[ name ];
  8643. if ( geometryAttribute === undefined ) {
  8644. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8645. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8646. }
  8647. if ( cachedAttribute === undefined ) return true;
  8648. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  8649. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  8650. attributesNum ++;
  8651. }
  8652. }
  8653. if ( currentState.attributesNum !== attributesNum ) return true;
  8654. if ( currentState.index !== index ) return true;
  8655. return false;
  8656. }
  8657. function saveCache( object, geometry, program, index ) {
  8658. const cache = {};
  8659. const attributes = geometry.attributes;
  8660. let attributesNum = 0;
  8661. const programAttributes = program.getAttributes();
  8662. for ( const name in programAttributes ) {
  8663. const programAttribute = programAttributes[ name ];
  8664. if ( programAttribute.location >= 0 ) {
  8665. let attribute = attributes[ name ];
  8666. if ( attribute === undefined ) {
  8667. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  8668. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  8669. }
  8670. const data = {};
  8671. data.attribute = attribute;
  8672. if ( attribute && attribute.data ) {
  8673. data.data = attribute.data;
  8674. }
  8675. cache[ name ] = data;
  8676. attributesNum ++;
  8677. }
  8678. }
  8679. currentState.attributes = cache;
  8680. currentState.attributesNum = attributesNum;
  8681. currentState.index = index;
  8682. }
  8683. function initAttributes() {
  8684. const newAttributes = currentState.newAttributes;
  8685. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  8686. newAttributes[ i ] = 0;
  8687. }
  8688. }
  8689. function enableAttribute( attribute ) {
  8690. enableAttributeAndDivisor( attribute, 0 );
  8691. }
  8692. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  8693. const newAttributes = currentState.newAttributes;
  8694. const enabledAttributes = currentState.enabledAttributes;
  8695. const attributeDivisors = currentState.attributeDivisors;
  8696. newAttributes[ attribute ] = 1;
  8697. if ( enabledAttributes[ attribute ] === 0 ) {
  8698. gl.enableVertexAttribArray( attribute );
  8699. enabledAttributes[ attribute ] = 1;
  8700. }
  8701. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  8702. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  8703. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  8704. attributeDivisors[ attribute ] = meshPerAttribute;
  8705. }
  8706. }
  8707. function disableUnusedAttributes() {
  8708. const newAttributes = currentState.newAttributes;
  8709. const enabledAttributes = currentState.enabledAttributes;
  8710. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  8711. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  8712. gl.disableVertexAttribArray( i );
  8713. enabledAttributes[ i ] = 0;
  8714. }
  8715. }
  8716. }
  8717. function vertexAttribPointer( index, size, type, normalized, stride, offset ) {
  8718. if ( capabilities.isWebGL2 === true && ( type === 5124 || type === 5125 ) ) {
  8719. gl.vertexAttribIPointer( index, size, type, stride, offset );
  8720. } else {
  8721. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  8722. }
  8723. }
  8724. function setupVertexAttributes( object, material, program, geometry ) {
  8725. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  8726. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  8727. }
  8728. initAttributes();
  8729. const geometryAttributes = geometry.attributes;
  8730. const programAttributes = program.getAttributes();
  8731. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8732. for ( const name in programAttributes ) {
  8733. const programAttribute = programAttributes[ name ];
  8734. if ( programAttribute.location >= 0 ) {
  8735. let geometryAttribute = geometryAttributes[ name ];
  8736. if ( geometryAttribute === undefined ) {
  8737. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8738. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8739. }
  8740. if ( geometryAttribute !== undefined ) {
  8741. const normalized = geometryAttribute.normalized;
  8742. const size = geometryAttribute.itemSize;
  8743. const attribute = attributes.get( geometryAttribute );
  8744. // TODO Attribute may not be available on context restore
  8745. if ( attribute === undefined ) continue;
  8746. const buffer = attribute.buffer;
  8747. const type = attribute.type;
  8748. const bytesPerElement = attribute.bytesPerElement;
  8749. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  8750. const data = geometryAttribute.data;
  8751. const stride = data.stride;
  8752. const offset = geometryAttribute.offset;
  8753. if ( data.isInstancedInterleavedBuffer ) {
  8754. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8755. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  8756. }
  8757. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8758. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8759. }
  8760. } else {
  8761. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8762. enableAttribute( programAttribute.location + i );
  8763. }
  8764. }
  8765. gl.bindBuffer( 34962, buffer );
  8766. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8767. vertexAttribPointer(
  8768. programAttribute.location + i,
  8769. size / programAttribute.locationSize,
  8770. type,
  8771. normalized,
  8772. stride * bytesPerElement,
  8773. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement
  8774. );
  8775. }
  8776. } else {
  8777. if ( geometryAttribute.isInstancedBufferAttribute ) {
  8778. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8779. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  8780. }
  8781. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8782. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8783. }
  8784. } else {
  8785. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8786. enableAttribute( programAttribute.location + i );
  8787. }
  8788. }
  8789. gl.bindBuffer( 34962, buffer );
  8790. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8791. vertexAttribPointer(
  8792. programAttribute.location + i,
  8793. size / programAttribute.locationSize,
  8794. type,
  8795. normalized,
  8796. size * bytesPerElement,
  8797. ( size / programAttribute.locationSize ) * i * bytesPerElement
  8798. );
  8799. }
  8800. }
  8801. } else if ( materialDefaultAttributeValues !== undefined ) {
  8802. const value = materialDefaultAttributeValues[ name ];
  8803. if ( value !== undefined ) {
  8804. switch ( value.length ) {
  8805. case 2:
  8806. gl.vertexAttrib2fv( programAttribute.location, value );
  8807. break;
  8808. case 3:
  8809. gl.vertexAttrib3fv( programAttribute.location, value );
  8810. break;
  8811. case 4:
  8812. gl.vertexAttrib4fv( programAttribute.location, value );
  8813. break;
  8814. default:
  8815. gl.vertexAttrib1fv( programAttribute.location, value );
  8816. }
  8817. }
  8818. }
  8819. }
  8820. }
  8821. disableUnusedAttributes();
  8822. }
  8823. function dispose() {
  8824. reset();
  8825. for ( const geometryId in bindingStates ) {
  8826. const programMap = bindingStates[ geometryId ];
  8827. for ( const programId in programMap ) {
  8828. const stateMap = programMap[ programId ];
  8829. for ( const wireframe in stateMap ) {
  8830. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8831. delete stateMap[ wireframe ];
  8832. }
  8833. delete programMap[ programId ];
  8834. }
  8835. delete bindingStates[ geometryId ];
  8836. }
  8837. }
  8838. function releaseStatesOfGeometry( geometry ) {
  8839. if ( bindingStates[ geometry.id ] === undefined ) return;
  8840. const programMap = bindingStates[ geometry.id ];
  8841. for ( const programId in programMap ) {
  8842. const stateMap = programMap[ programId ];
  8843. for ( const wireframe in stateMap ) {
  8844. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8845. delete stateMap[ wireframe ];
  8846. }
  8847. delete programMap[ programId ];
  8848. }
  8849. delete bindingStates[ geometry.id ];
  8850. }
  8851. function releaseStatesOfProgram( program ) {
  8852. for ( const geometryId in bindingStates ) {
  8853. const programMap = bindingStates[ geometryId ];
  8854. if ( programMap[ program.id ] === undefined ) continue;
  8855. const stateMap = programMap[ program.id ];
  8856. for ( const wireframe in stateMap ) {
  8857. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8858. delete stateMap[ wireframe ];
  8859. }
  8860. delete programMap[ program.id ];
  8861. }
  8862. }
  8863. function reset() {
  8864. resetDefaultState();
  8865. forceUpdate = true;
  8866. if ( currentState === defaultState ) return;
  8867. currentState = defaultState;
  8868. bindVertexArrayObject( currentState.object );
  8869. }
  8870. // for backward-compatibility
  8871. function resetDefaultState() {
  8872. defaultState.geometry = null;
  8873. defaultState.program = null;
  8874. defaultState.wireframe = false;
  8875. }
  8876. return {
  8877. setup: setup,
  8878. reset: reset,
  8879. resetDefaultState: resetDefaultState,
  8880. dispose: dispose,
  8881. releaseStatesOfGeometry: releaseStatesOfGeometry,
  8882. releaseStatesOfProgram: releaseStatesOfProgram,
  8883. initAttributes: initAttributes,
  8884. enableAttribute: enableAttribute,
  8885. disableUnusedAttributes: disableUnusedAttributes
  8886. };
  8887. }
  8888. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  8889. const isWebGL2 = capabilities.isWebGL2;
  8890. let mode;
  8891. function setMode( value ) {
  8892. mode = value;
  8893. }
  8894. function render( start, count ) {
  8895. gl.drawArrays( mode, start, count );
  8896. info.update( count, mode, 1 );
  8897. }
  8898. function renderInstances( start, count, primcount ) {
  8899. if ( primcount === 0 ) return;
  8900. let extension, methodName;
  8901. if ( isWebGL2 ) {
  8902. extension = gl;
  8903. methodName = 'drawArraysInstanced';
  8904. } else {
  8905. extension = extensions.get( 'ANGLE_instanced_arrays' );
  8906. methodName = 'drawArraysInstancedANGLE';
  8907. if ( extension === null ) {
  8908. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  8909. return;
  8910. }
  8911. }
  8912. extension[ methodName ]( mode, start, count, primcount );
  8913. info.update( count, mode, primcount );
  8914. }
  8915. //
  8916. this.setMode = setMode;
  8917. this.render = render;
  8918. this.renderInstances = renderInstances;
  8919. }
  8920. function WebGLCapabilities( gl, extensions, parameters ) {
  8921. let maxAnisotropy;
  8922. function getMaxAnisotropy() {
  8923. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  8924. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  8925. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  8926. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  8927. } else {
  8928. maxAnisotropy = 0;
  8929. }
  8930. return maxAnisotropy;
  8931. }
  8932. function getMaxPrecision( precision ) {
  8933. if ( precision === 'highp' ) {
  8934. if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
  8935. gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {
  8936. return 'highp';
  8937. }
  8938. precision = 'mediump';
  8939. }
  8940. if ( precision === 'mediump' ) {
  8941. if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
  8942. gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {
  8943. return 'mediump';
  8944. }
  8945. }
  8946. return 'lowp';
  8947. }
  8948. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext;
  8949. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  8950. const maxPrecision = getMaxPrecision( precision );
  8951. if ( maxPrecision !== precision ) {
  8952. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  8953. precision = maxPrecision;
  8954. }
  8955. const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' );
  8956. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  8957. const maxTextures = gl.getParameter( 34930 );
  8958. const maxVertexTextures = gl.getParameter( 35660 );
  8959. const maxTextureSize = gl.getParameter( 3379 );
  8960. const maxCubemapSize = gl.getParameter( 34076 );
  8961. const maxAttributes = gl.getParameter( 34921 );
  8962. const maxVertexUniforms = gl.getParameter( 36347 );
  8963. const maxVaryings = gl.getParameter( 36348 );
  8964. const maxFragmentUniforms = gl.getParameter( 36349 );
  8965. const vertexTextures = maxVertexTextures > 0;
  8966. const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' );
  8967. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  8968. const maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;
  8969. return {
  8970. isWebGL2: isWebGL2,
  8971. drawBuffers: drawBuffers,
  8972. getMaxAnisotropy: getMaxAnisotropy,
  8973. getMaxPrecision: getMaxPrecision,
  8974. precision: precision,
  8975. logarithmicDepthBuffer: logarithmicDepthBuffer,
  8976. maxTextures: maxTextures,
  8977. maxVertexTextures: maxVertexTextures,
  8978. maxTextureSize: maxTextureSize,
  8979. maxCubemapSize: maxCubemapSize,
  8980. maxAttributes: maxAttributes,
  8981. maxVertexUniforms: maxVertexUniforms,
  8982. maxVaryings: maxVaryings,
  8983. maxFragmentUniforms: maxFragmentUniforms,
  8984. vertexTextures: vertexTextures,
  8985. floatFragmentTextures: floatFragmentTextures,
  8986. floatVertexTextures: floatVertexTextures,
  8987. maxSamples: maxSamples
  8988. };
  8989. }
  8990. function WebGLClipping( properties ) {
  8991. const scope = this;
  8992. let globalState = null,
  8993. numGlobalPlanes = 0,
  8994. localClippingEnabled = false,
  8995. renderingShadows = false;
  8996. const plane = new Plane(),
  8997. viewNormalMatrix = new Matrix3(),
  8998. uniform = { value: null, needsUpdate: false };
  8999. this.uniform = uniform;
  9000. this.numPlanes = 0;
  9001. this.numIntersection = 0;
  9002. this.init = function ( planes, enableLocalClipping ) {
  9003. const enabled =
  9004. planes.length !== 0 ||
  9005. enableLocalClipping ||
  9006. // enable state of previous frame - the clipping code has to
  9007. // run another frame in order to reset the state:
  9008. numGlobalPlanes !== 0 ||
  9009. localClippingEnabled;
  9010. localClippingEnabled = enableLocalClipping;
  9011. numGlobalPlanes = planes.length;
  9012. return enabled;
  9013. };
  9014. this.beginShadows = function () {
  9015. renderingShadows = true;
  9016. projectPlanes( null );
  9017. };
  9018. this.endShadows = function () {
  9019. renderingShadows = false;
  9020. };
  9021. this.setGlobalState = function ( planes, camera ) {
  9022. globalState = projectPlanes( planes, camera, 0 );
  9023. };
  9024. this.setState = function ( material, camera, useCache ) {
  9025. const planes = material.clippingPlanes,
  9026. clipIntersection = material.clipIntersection,
  9027. clipShadows = material.clipShadows;
  9028. const materialProperties = properties.get( material );
  9029. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  9030. // there's no local clipping
  9031. if ( renderingShadows ) {
  9032. // there's no global clipping
  9033. projectPlanes( null );
  9034. } else {
  9035. resetGlobalState();
  9036. }
  9037. } else {
  9038. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9039. lGlobal = nGlobal * 4;
  9040. let dstArray = materialProperties.clippingState || null;
  9041. uniform.value = dstArray; // ensure unique state
  9042. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  9043. for ( let i = 0; i !== lGlobal; ++ i ) {
  9044. dstArray[ i ] = globalState[ i ];
  9045. }
  9046. materialProperties.clippingState = dstArray;
  9047. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9048. this.numPlanes += nGlobal;
  9049. }
  9050. };
  9051. function resetGlobalState() {
  9052. if ( uniform.value !== globalState ) {
  9053. uniform.value = globalState;
  9054. uniform.needsUpdate = numGlobalPlanes > 0;
  9055. }
  9056. scope.numPlanes = numGlobalPlanes;
  9057. scope.numIntersection = 0;
  9058. }
  9059. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  9060. const nPlanes = planes !== null ? planes.length : 0;
  9061. let dstArray = null;
  9062. if ( nPlanes !== 0 ) {
  9063. dstArray = uniform.value;
  9064. if ( skipTransform !== true || dstArray === null ) {
  9065. const flatSize = dstOffset + nPlanes * 4,
  9066. viewMatrix = camera.matrixWorldInverse;
  9067. viewNormalMatrix.getNormalMatrix( viewMatrix );
  9068. if ( dstArray === null || dstArray.length < flatSize ) {
  9069. dstArray = new Float32Array( flatSize );
  9070. }
  9071. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  9072. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  9073. plane.normal.toArray( dstArray, i4 );
  9074. dstArray[ i4 + 3 ] = plane.constant;
  9075. }
  9076. }
  9077. uniform.value = dstArray;
  9078. uniform.needsUpdate = true;
  9079. }
  9080. scope.numPlanes = nPlanes;
  9081. scope.numIntersection = 0;
  9082. return dstArray;
  9083. }
  9084. }
  9085. function WebGLCubeMaps( renderer ) {
  9086. let cubemaps = new WeakMap();
  9087. function mapTextureMapping( texture, mapping ) {
  9088. if ( mapping === EquirectangularReflectionMapping ) {
  9089. texture.mapping = CubeReflectionMapping;
  9090. } else if ( mapping === EquirectangularRefractionMapping ) {
  9091. texture.mapping = CubeRefractionMapping;
  9092. }
  9093. return texture;
  9094. }
  9095. function get( texture ) {
  9096. if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
  9097. const mapping = texture.mapping;
  9098. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  9099. if ( cubemaps.has( texture ) ) {
  9100. const cubemap = cubemaps.get( texture ).texture;
  9101. return mapTextureMapping( cubemap, texture.mapping );
  9102. } else {
  9103. const image = texture.image;
  9104. if ( image && image.height > 0 ) {
  9105. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  9106. renderTarget.fromEquirectangularTexture( renderer, texture );
  9107. cubemaps.set( texture, renderTarget );
  9108. texture.addEventListener( 'dispose', onTextureDispose );
  9109. return mapTextureMapping( renderTarget.texture, texture.mapping );
  9110. } else {
  9111. // image not yet ready. try the conversion next frame
  9112. return null;
  9113. }
  9114. }
  9115. }
  9116. }
  9117. return texture;
  9118. }
  9119. function onTextureDispose( event ) {
  9120. const texture = event.target;
  9121. texture.removeEventListener( 'dispose', onTextureDispose );
  9122. const cubemap = cubemaps.get( texture );
  9123. if ( cubemap !== undefined ) {
  9124. cubemaps.delete( texture );
  9125. cubemap.dispose();
  9126. }
  9127. }
  9128. function dispose() {
  9129. cubemaps = new WeakMap();
  9130. }
  9131. return {
  9132. get: get,
  9133. dispose: dispose
  9134. };
  9135. }
  9136. class OrthographicCamera extends Camera {
  9137. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  9138. super();
  9139. this.isOrthographicCamera = true;
  9140. this.type = 'OrthographicCamera';
  9141. this.zoom = 1;
  9142. this.view = null;
  9143. this.left = left;
  9144. this.right = right;
  9145. this.top = top;
  9146. this.bottom = bottom;
  9147. this.near = near;
  9148. this.far = far;
  9149. this.updateProjectionMatrix();
  9150. }
  9151. copy( source, recursive ) {
  9152. super.copy( source, recursive );
  9153. this.left = source.left;
  9154. this.right = source.right;
  9155. this.top = source.top;
  9156. this.bottom = source.bottom;
  9157. this.near = source.near;
  9158. this.far = source.far;
  9159. this.zoom = source.zoom;
  9160. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9161. return this;
  9162. }
  9163. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  9164. if ( this.view === null ) {
  9165. this.view = {
  9166. enabled: true,
  9167. fullWidth: 1,
  9168. fullHeight: 1,
  9169. offsetX: 0,
  9170. offsetY: 0,
  9171. width: 1,
  9172. height: 1
  9173. };
  9174. }
  9175. this.view.enabled = true;
  9176. this.view.fullWidth = fullWidth;
  9177. this.view.fullHeight = fullHeight;
  9178. this.view.offsetX = x;
  9179. this.view.offsetY = y;
  9180. this.view.width = width;
  9181. this.view.height = height;
  9182. this.updateProjectionMatrix();
  9183. }
  9184. clearViewOffset() {
  9185. if ( this.view !== null ) {
  9186. this.view.enabled = false;
  9187. }
  9188. this.updateProjectionMatrix();
  9189. }
  9190. updateProjectionMatrix() {
  9191. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9192. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9193. const cx = ( this.right + this.left ) / 2;
  9194. const cy = ( this.top + this.bottom ) / 2;
  9195. let left = cx - dx;
  9196. let right = cx + dx;
  9197. let top = cy + dy;
  9198. let bottom = cy - dy;
  9199. if ( this.view !== null && this.view.enabled ) {
  9200. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  9201. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  9202. left += scaleW * this.view.offsetX;
  9203. right = left + scaleW * this.view.width;
  9204. top -= scaleH * this.view.offsetY;
  9205. bottom = top - scaleH * this.view.height;
  9206. }
  9207. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  9208. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  9209. }
  9210. toJSON( meta ) {
  9211. const data = super.toJSON( meta );
  9212. data.object.zoom = this.zoom;
  9213. data.object.left = this.left;
  9214. data.object.right = this.right;
  9215. data.object.top = this.top;
  9216. data.object.bottom = this.bottom;
  9217. data.object.near = this.near;
  9218. data.object.far = this.far;
  9219. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9220. return data;
  9221. }
  9222. }
  9223. const LOD_MIN = 4;
  9224. // The standard deviations (radians) associated with the extra mips. These are
  9225. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9226. // geometric shadowing function. These sigma values squared must match the
  9227. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9228. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  9229. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9230. // samples and exit early, but not recompile the shader.
  9231. const MAX_SAMPLES = 20;
  9232. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  9233. const _clearColor = /*@__PURE__*/ new Color();
  9234. let _oldTarget = null;
  9235. // Golden Ratio
  9236. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  9237. const INV_PHI = 1 / PHI;
  9238. // Vertices of a dodecahedron (except the opposites, which represent the
  9239. // same axis), used as axis directions evenly spread on a sphere.
  9240. const _axisDirections = [
  9241. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  9242. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  9243. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  9244. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  9245. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  9246. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  9247. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  9248. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  9249. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  9250. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  9251. /**
  9252. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9253. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9254. * blur to be quickly accessed based on material roughness. It is packed into a
  9255. * special CubeUV format that allows us to perform custom interpolation so that
  9256. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9257. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9258. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9259. * higher roughness levels. In this way we maintain resolution to smoothly
  9260. * interpolate diffuse lighting while limiting sampling computation.
  9261. *
  9262. * Paper: Fast, Accurate Image-Based Lighting
  9263. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9264. */
  9265. class PMREMGenerator {
  9266. constructor( renderer ) {
  9267. this._renderer = renderer;
  9268. this._pingPongRenderTarget = null;
  9269. this._lodMax = 0;
  9270. this._cubeSize = 0;
  9271. this._lodPlanes = [];
  9272. this._sizeLods = [];
  9273. this._sigmas = [];
  9274. this._blurMaterial = null;
  9275. this._cubemapMaterial = null;
  9276. this._equirectMaterial = null;
  9277. this._compileMaterial( this._blurMaterial );
  9278. }
  9279. /**
  9280. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9281. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9282. * in radians to be applied to the scene before PMREM generation. Optional near
  9283. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9284. * is placed at the origin).
  9285. */
  9286. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  9287. _oldTarget = this._renderer.getRenderTarget();
  9288. this._setSize( 256 );
  9289. const cubeUVRenderTarget = this._allocateTargets();
  9290. cubeUVRenderTarget.depthBuffer = true;
  9291. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  9292. if ( sigma > 0 ) {
  9293. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  9294. }
  9295. this._applyPMREM( cubeUVRenderTarget );
  9296. this._cleanup( cubeUVRenderTarget );
  9297. return cubeUVRenderTarget;
  9298. }
  9299. /**
  9300. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9301. * or HDR. The ideal input image size is 1k (1024 x 512),
  9302. * as this matches best with the 256 x 256 cubemap output.
  9303. */
  9304. fromEquirectangular( equirectangular, renderTarget = null ) {
  9305. return this._fromTexture( equirectangular, renderTarget );
  9306. }
  9307. /**
  9308. * Generates a PMREM from an cubemap texture, which can be either LDR
  9309. * or HDR. The ideal input cube size is 256 x 256,
  9310. * as this matches best with the 256 x 256 cubemap output.
  9311. */
  9312. fromCubemap( cubemap, renderTarget = null ) {
  9313. return this._fromTexture( cubemap, renderTarget );
  9314. }
  9315. /**
  9316. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9317. * your texture's network fetch for increased concurrency.
  9318. */
  9319. compileCubemapShader() {
  9320. if ( this._cubemapMaterial === null ) {
  9321. this._cubemapMaterial = _getCubemapMaterial();
  9322. this._compileMaterial( this._cubemapMaterial );
  9323. }
  9324. }
  9325. /**
  9326. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9327. * your texture's network fetch for increased concurrency.
  9328. */
  9329. compileEquirectangularShader() {
  9330. if ( this._equirectMaterial === null ) {
  9331. this._equirectMaterial = _getEquirectMaterial();
  9332. this._compileMaterial( this._equirectMaterial );
  9333. }
  9334. }
  9335. /**
  9336. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9337. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9338. * one of them will cause any others to also become unusable.
  9339. */
  9340. dispose() {
  9341. this._dispose();
  9342. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  9343. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  9344. }
  9345. // private interface
  9346. _setSize( cubeSize ) {
  9347. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  9348. this._cubeSize = Math.pow( 2, this._lodMax );
  9349. }
  9350. _dispose() {
  9351. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  9352. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  9353. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  9354. this._lodPlanes[ i ].dispose();
  9355. }
  9356. }
  9357. _cleanup( outputTarget ) {
  9358. this._renderer.setRenderTarget( _oldTarget );
  9359. outputTarget.scissorTest = false;
  9360. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  9361. }
  9362. _fromTexture( texture, renderTarget ) {
  9363. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  9364. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  9365. } else { // Equirectangular
  9366. this._setSize( texture.image.width / 4 );
  9367. }
  9368. _oldTarget = this._renderer.getRenderTarget();
  9369. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9370. this._textureToCubeUV( texture, cubeUVRenderTarget );
  9371. this._applyPMREM( cubeUVRenderTarget );
  9372. this._cleanup( cubeUVRenderTarget );
  9373. return cubeUVRenderTarget;
  9374. }
  9375. _allocateTargets() {
  9376. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  9377. const height = 4 * this._cubeSize;
  9378. const params = {
  9379. magFilter: LinearFilter,
  9380. minFilter: LinearFilter,
  9381. generateMipmaps: false,
  9382. type: HalfFloatType,
  9383. format: RGBAFormat,
  9384. encoding: LinearEncoding,
  9385. depthBuffer: false
  9386. };
  9387. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  9388. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  9389. if ( this._pingPongRenderTarget !== null ) {
  9390. this._dispose();
  9391. }
  9392. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  9393. const { _lodMax } = this;
  9394. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  9395. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  9396. }
  9397. return cubeUVRenderTarget;
  9398. }
  9399. _compileMaterial( material ) {
  9400. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  9401. this._renderer.compile( tmpMesh, _flatCamera );
  9402. }
  9403. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  9404. const fov = 90;
  9405. const aspect = 1;
  9406. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  9407. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  9408. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  9409. const renderer = this._renderer;
  9410. const originalAutoClear = renderer.autoClear;
  9411. const toneMapping = renderer.toneMapping;
  9412. renderer.getClearColor( _clearColor );
  9413. renderer.toneMapping = NoToneMapping;
  9414. renderer.autoClear = false;
  9415. const backgroundMaterial = new MeshBasicMaterial( {
  9416. name: 'PMREM.Background',
  9417. side: BackSide,
  9418. depthWrite: false,
  9419. depthTest: false,
  9420. } );
  9421. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  9422. let useSolidColor = false;
  9423. const background = scene.background;
  9424. if ( background ) {
  9425. if ( background.isColor ) {
  9426. backgroundMaterial.color.copy( background );
  9427. scene.background = null;
  9428. useSolidColor = true;
  9429. }
  9430. } else {
  9431. backgroundMaterial.color.copy( _clearColor );
  9432. useSolidColor = true;
  9433. }
  9434. for ( let i = 0; i < 6; i ++ ) {
  9435. const col = i % 3;
  9436. if ( col === 0 ) {
  9437. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9438. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  9439. } else if ( col === 1 ) {
  9440. cubeCamera.up.set( 0, 0, upSign[ i ] );
  9441. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  9442. } else {
  9443. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9444. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  9445. }
  9446. const size = this._cubeSize;
  9447. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  9448. renderer.setRenderTarget( cubeUVRenderTarget );
  9449. if ( useSolidColor ) {
  9450. renderer.render( backgroundBox, cubeCamera );
  9451. }
  9452. renderer.render( scene, cubeCamera );
  9453. }
  9454. backgroundBox.geometry.dispose();
  9455. backgroundBox.material.dispose();
  9456. renderer.toneMapping = toneMapping;
  9457. renderer.autoClear = originalAutoClear;
  9458. scene.background = background;
  9459. }
  9460. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  9461. const renderer = this._renderer;
  9462. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  9463. if ( isCubeTexture ) {
  9464. if ( this._cubemapMaterial === null ) {
  9465. this._cubemapMaterial = _getCubemapMaterial();
  9466. }
  9467. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1;
  9468. } else {
  9469. if ( this._equirectMaterial === null ) {
  9470. this._equirectMaterial = _getEquirectMaterial();
  9471. }
  9472. }
  9473. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  9474. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  9475. const uniforms = material.uniforms;
  9476. uniforms[ 'envMap' ].value = texture;
  9477. const size = this._cubeSize;
  9478. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  9479. renderer.setRenderTarget( cubeUVRenderTarget );
  9480. renderer.render( mesh, _flatCamera );
  9481. }
  9482. _applyPMREM( cubeUVRenderTarget ) {
  9483. const renderer = this._renderer;
  9484. const autoClear = renderer.autoClear;
  9485. renderer.autoClear = false;
  9486. for ( let i = 1; i < this._lodPlanes.length; i ++ ) {
  9487. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  9488. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  9489. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  9490. }
  9491. renderer.autoClear = autoClear;
  9492. }
  9493. /**
  9494. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9495. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9496. * the blur latitudinally (around the poles), and then longitudinally (towards
  9497. * the poles) to approximate the orthogonally-separable blur. It is least
  9498. * accurate at the poles, but still does a decent job.
  9499. */
  9500. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  9501. const pingPongRenderTarget = this._pingPongRenderTarget;
  9502. this._halfBlur(
  9503. cubeUVRenderTarget,
  9504. pingPongRenderTarget,
  9505. lodIn,
  9506. lodOut,
  9507. sigma,
  9508. 'latitudinal',
  9509. poleAxis );
  9510. this._halfBlur(
  9511. pingPongRenderTarget,
  9512. cubeUVRenderTarget,
  9513. lodOut,
  9514. lodOut,
  9515. sigma,
  9516. 'longitudinal',
  9517. poleAxis );
  9518. }
  9519. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  9520. const renderer = this._renderer;
  9521. const blurMaterial = this._blurMaterial;
  9522. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  9523. console.error(
  9524. 'blur direction must be either latitudinal or longitudinal!' );
  9525. }
  9526. // Number of standard deviations at which to cut off the discrete approximation.
  9527. const STANDARD_DEVIATIONS = 3;
  9528. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  9529. const blurUniforms = blurMaterial.uniforms;
  9530. const pixels = this._sizeLods[ lodIn ] - 1;
  9531. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  9532. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9533. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  9534. if ( samples > MAX_SAMPLES ) {
  9535. console.warn( `sigmaRadians, ${
  9536. sigmaRadians}, is too large and will clip, as it requested ${
  9537. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  9538. }
  9539. const weights = [];
  9540. let sum = 0;
  9541. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  9542. const x = i / sigmaPixels;
  9543. const weight = Math.exp( - x * x / 2 );
  9544. weights.push( weight );
  9545. if ( i === 0 ) {
  9546. sum += weight;
  9547. } else if ( i < samples ) {
  9548. sum += 2 * weight;
  9549. }
  9550. }
  9551. for ( let i = 0; i < weights.length; i ++ ) {
  9552. weights[ i ] = weights[ i ] / sum;
  9553. }
  9554. blurUniforms[ 'envMap' ].value = targetIn.texture;
  9555. blurUniforms[ 'samples' ].value = samples;
  9556. blurUniforms[ 'weights' ].value = weights;
  9557. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  9558. if ( poleAxis ) {
  9559. blurUniforms[ 'poleAxis' ].value = poleAxis;
  9560. }
  9561. const { _lodMax } = this;
  9562. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  9563. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  9564. const outputSize = this._sizeLods[ lodOut ];
  9565. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  9566. const y = 4 * ( this._cubeSize - outputSize );
  9567. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  9568. renderer.setRenderTarget( targetOut );
  9569. renderer.render( blurMesh, _flatCamera );
  9570. }
  9571. }
  9572. function _createPlanes( lodMax ) {
  9573. const lodPlanes = [];
  9574. const sizeLods = [];
  9575. const sigmas = [];
  9576. let lod = lodMax;
  9577. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  9578. for ( let i = 0; i < totalLods; i ++ ) {
  9579. const sizeLod = Math.pow( 2, lod );
  9580. sizeLods.push( sizeLod );
  9581. let sigma = 1.0 / sizeLod;
  9582. if ( i > lodMax - LOD_MIN ) {
  9583. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  9584. } else if ( i === 0 ) {
  9585. sigma = 0;
  9586. }
  9587. sigmas.push( sigma );
  9588. const texelSize = 1.0 / ( sizeLod - 2 );
  9589. const min = - texelSize;
  9590. const max = 1 + texelSize;
  9591. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  9592. const cubeFaces = 6;
  9593. const vertices = 6;
  9594. const positionSize = 3;
  9595. const uvSize = 2;
  9596. const faceIndexSize = 1;
  9597. const position = new Float32Array( positionSize * vertices * cubeFaces );
  9598. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  9599. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  9600. for ( let face = 0; face < cubeFaces; face ++ ) {
  9601. const x = ( face % 3 ) * 2 / 3 - 1;
  9602. const y = face > 2 ? 0 : - 1;
  9603. const coordinates = [
  9604. x, y, 0,
  9605. x + 2 / 3, y, 0,
  9606. x + 2 / 3, y + 1, 0,
  9607. x, y, 0,
  9608. x + 2 / 3, y + 1, 0,
  9609. x, y + 1, 0
  9610. ];
  9611. position.set( coordinates, positionSize * vertices * face );
  9612. uv.set( uv1, uvSize * vertices * face );
  9613. const fill = [ face, face, face, face, face, face ];
  9614. faceIndex.set( fill, faceIndexSize * vertices * face );
  9615. }
  9616. const planes = new BufferGeometry();
  9617. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  9618. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  9619. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  9620. lodPlanes.push( planes );
  9621. if ( lod > LOD_MIN ) {
  9622. lod --;
  9623. }
  9624. }
  9625. return { lodPlanes, sizeLods, sigmas };
  9626. }
  9627. function _createRenderTarget( width, height, params ) {
  9628. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  9629. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9630. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9631. cubeUVRenderTarget.scissorTest = true;
  9632. return cubeUVRenderTarget;
  9633. }
  9634. function _setViewport( target, x, y, width, height ) {
  9635. target.viewport.set( x, y, width, height );
  9636. target.scissor.set( x, y, width, height );
  9637. }
  9638. function _getBlurShader( lodMax, width, height ) {
  9639. const weights = new Float32Array( MAX_SAMPLES );
  9640. const poleAxis = new Vector3( 0, 1, 0 );
  9641. const shaderMaterial = new ShaderMaterial( {
  9642. name: 'SphericalGaussianBlur',
  9643. defines: {
  9644. 'n': MAX_SAMPLES,
  9645. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  9646. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  9647. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  9648. },
  9649. uniforms: {
  9650. 'envMap': { value: null },
  9651. 'samples': { value: 1 },
  9652. 'weights': { value: weights },
  9653. 'latitudinal': { value: false },
  9654. 'dTheta': { value: 0 },
  9655. 'mipInt': { value: 0 },
  9656. 'poleAxis': { value: poleAxis }
  9657. },
  9658. vertexShader: _getCommonVertexShader(),
  9659. fragmentShader: /* glsl */`
  9660. precision mediump float;
  9661. precision mediump int;
  9662. varying vec3 vOutputDirection;
  9663. uniform sampler2D envMap;
  9664. uniform int samples;
  9665. uniform float weights[ n ];
  9666. uniform bool latitudinal;
  9667. uniform float dTheta;
  9668. uniform float mipInt;
  9669. uniform vec3 poleAxis;
  9670. #define ENVMAP_TYPE_CUBE_UV
  9671. #include <cube_uv_reflection_fragment>
  9672. vec3 getSample( float theta, vec3 axis ) {
  9673. float cosTheta = cos( theta );
  9674. // Rodrigues' axis-angle rotation
  9675. vec3 sampleDirection = vOutputDirection * cosTheta
  9676. + cross( axis, vOutputDirection ) * sin( theta )
  9677. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  9678. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  9679. }
  9680. void main() {
  9681. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  9682. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  9683. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  9684. }
  9685. axis = normalize( axis );
  9686. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9687. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  9688. for ( int i = 1; i < n; i++ ) {
  9689. if ( i >= samples ) {
  9690. break;
  9691. }
  9692. float theta = dTheta * float( i );
  9693. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  9694. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  9695. }
  9696. }
  9697. `,
  9698. blending: NoBlending,
  9699. depthTest: false,
  9700. depthWrite: false
  9701. } );
  9702. return shaderMaterial;
  9703. }
  9704. function _getEquirectMaterial() {
  9705. return new ShaderMaterial( {
  9706. name: 'EquirectangularToCubeUV',
  9707. uniforms: {
  9708. 'envMap': { value: null }
  9709. },
  9710. vertexShader: _getCommonVertexShader(),
  9711. fragmentShader: /* glsl */`
  9712. precision mediump float;
  9713. precision mediump int;
  9714. varying vec3 vOutputDirection;
  9715. uniform sampler2D envMap;
  9716. #include <common>
  9717. void main() {
  9718. vec3 outputDirection = normalize( vOutputDirection );
  9719. vec2 uv = equirectUv( outputDirection );
  9720. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  9721. }
  9722. `,
  9723. blending: NoBlending,
  9724. depthTest: false,
  9725. depthWrite: false
  9726. } );
  9727. }
  9728. function _getCubemapMaterial() {
  9729. return new ShaderMaterial( {
  9730. name: 'CubemapToCubeUV',
  9731. uniforms: {
  9732. 'envMap': { value: null },
  9733. 'flipEnvMap': { value: - 1 }
  9734. },
  9735. vertexShader: _getCommonVertexShader(),
  9736. fragmentShader: /* glsl */`
  9737. precision mediump float;
  9738. precision mediump int;
  9739. uniform float flipEnvMap;
  9740. varying vec3 vOutputDirection;
  9741. uniform samplerCube envMap;
  9742. void main() {
  9743. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  9744. }
  9745. `,
  9746. blending: NoBlending,
  9747. depthTest: false,
  9748. depthWrite: false
  9749. } );
  9750. }
  9751. function _getCommonVertexShader() {
  9752. return /* glsl */`
  9753. precision mediump float;
  9754. precision mediump int;
  9755. attribute float faceIndex;
  9756. varying vec3 vOutputDirection;
  9757. // RH coordinate system; PMREM face-indexing convention
  9758. vec3 getDirection( vec2 uv, float face ) {
  9759. uv = 2.0 * uv - 1.0;
  9760. vec3 direction = vec3( uv, 1.0 );
  9761. if ( face == 0.0 ) {
  9762. direction = direction.zyx; // ( 1, v, u ) pos x
  9763. } else if ( face == 1.0 ) {
  9764. direction = direction.xzy;
  9765. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  9766. } else if ( face == 2.0 ) {
  9767. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  9768. } else if ( face == 3.0 ) {
  9769. direction = direction.zyx;
  9770. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  9771. } else if ( face == 4.0 ) {
  9772. direction = direction.xzy;
  9773. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  9774. } else if ( face == 5.0 ) {
  9775. direction.z *= -1.0; // ( u, v, -1 ) neg z
  9776. }
  9777. return direction;
  9778. }
  9779. void main() {
  9780. vOutputDirection = getDirection( uv, faceIndex );
  9781. gl_Position = vec4( position, 1.0 );
  9782. }
  9783. `;
  9784. }
  9785. function WebGLCubeUVMaps( renderer ) {
  9786. let cubeUVmaps = new WeakMap();
  9787. let pmremGenerator = null;
  9788. function get( texture ) {
  9789. if ( texture && texture.isTexture ) {
  9790. const mapping = texture.mapping;
  9791. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  9792. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  9793. // equirect/cube map to cubeUV conversion
  9794. if ( isEquirectMap || isCubeMap ) {
  9795. if ( texture.isRenderTargetTexture && texture.needsPMREMUpdate === true ) {
  9796. texture.needsPMREMUpdate = false;
  9797. let renderTarget = cubeUVmaps.get( texture );
  9798. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  9799. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  9800. cubeUVmaps.set( texture, renderTarget );
  9801. return renderTarget.texture;
  9802. } else {
  9803. if ( cubeUVmaps.has( texture ) ) {
  9804. return cubeUVmaps.get( texture ).texture;
  9805. } else {
  9806. const image = texture.image;
  9807. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  9808. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  9809. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  9810. cubeUVmaps.set( texture, renderTarget );
  9811. texture.addEventListener( 'dispose', onTextureDispose );
  9812. return renderTarget.texture;
  9813. } else {
  9814. // image not yet ready. try the conversion next frame
  9815. return null;
  9816. }
  9817. }
  9818. }
  9819. }
  9820. }
  9821. return texture;
  9822. }
  9823. function isCubeTextureComplete( image ) {
  9824. let count = 0;
  9825. const length = 6;
  9826. for ( let i = 0; i < length; i ++ ) {
  9827. if ( image[ i ] !== undefined ) count ++;
  9828. }
  9829. return count === length;
  9830. }
  9831. function onTextureDispose( event ) {
  9832. const texture = event.target;
  9833. texture.removeEventListener( 'dispose', onTextureDispose );
  9834. const cubemapUV = cubeUVmaps.get( texture );
  9835. if ( cubemapUV !== undefined ) {
  9836. cubeUVmaps.delete( texture );
  9837. cubemapUV.dispose();
  9838. }
  9839. }
  9840. function dispose() {
  9841. cubeUVmaps = new WeakMap();
  9842. if ( pmremGenerator !== null ) {
  9843. pmremGenerator.dispose();
  9844. pmremGenerator = null;
  9845. }
  9846. }
  9847. return {
  9848. get: get,
  9849. dispose: dispose
  9850. };
  9851. }
  9852. function WebGLExtensions( gl ) {
  9853. const extensions = {};
  9854. function getExtension( name ) {
  9855. if ( extensions[ name ] !== undefined ) {
  9856. return extensions[ name ];
  9857. }
  9858. let extension;
  9859. switch ( name ) {
  9860. case 'WEBGL_depth_texture':
  9861. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  9862. break;
  9863. case 'EXT_texture_filter_anisotropic':
  9864. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  9865. break;
  9866. case 'WEBGL_compressed_texture_s3tc':
  9867. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  9868. break;
  9869. case 'WEBGL_compressed_texture_pvrtc':
  9870. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  9871. break;
  9872. default:
  9873. extension = gl.getExtension( name );
  9874. }
  9875. extensions[ name ] = extension;
  9876. return extension;
  9877. }
  9878. return {
  9879. has: function ( name ) {
  9880. return getExtension( name ) !== null;
  9881. },
  9882. init: function ( capabilities ) {
  9883. if ( capabilities.isWebGL2 ) {
  9884. getExtension( 'EXT_color_buffer_float' );
  9885. } else {
  9886. getExtension( 'WEBGL_depth_texture' );
  9887. getExtension( 'OES_texture_float' );
  9888. getExtension( 'OES_texture_half_float' );
  9889. getExtension( 'OES_texture_half_float_linear' );
  9890. getExtension( 'OES_standard_derivatives' );
  9891. getExtension( 'OES_element_index_uint' );
  9892. getExtension( 'OES_vertex_array_object' );
  9893. getExtension( 'ANGLE_instanced_arrays' );
  9894. }
  9895. getExtension( 'OES_texture_float_linear' );
  9896. getExtension( 'EXT_color_buffer_half_float' );
  9897. getExtension( 'WEBGL_multisampled_render_to_texture' );
  9898. },
  9899. get: function ( name ) {
  9900. const extension = getExtension( name );
  9901. if ( extension === null ) {
  9902. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  9903. }
  9904. return extension;
  9905. }
  9906. };
  9907. }
  9908. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  9909. const geometries = {};
  9910. const wireframeAttributes = new WeakMap();
  9911. function onGeometryDispose( event ) {
  9912. const geometry = event.target;
  9913. if ( geometry.index !== null ) {
  9914. attributes.remove( geometry.index );
  9915. }
  9916. for ( const name in geometry.attributes ) {
  9917. attributes.remove( geometry.attributes[ name ] );
  9918. }
  9919. geometry.removeEventListener( 'dispose', onGeometryDispose );
  9920. delete geometries[ geometry.id ];
  9921. const attribute = wireframeAttributes.get( geometry );
  9922. if ( attribute ) {
  9923. attributes.remove( attribute );
  9924. wireframeAttributes.delete( geometry );
  9925. }
  9926. bindingStates.releaseStatesOfGeometry( geometry );
  9927. if ( geometry.isInstancedBufferGeometry === true ) {
  9928. delete geometry._maxInstanceCount;
  9929. }
  9930. //
  9931. info.memory.geometries --;
  9932. }
  9933. function get( object, geometry ) {
  9934. if ( geometries[ geometry.id ] === true ) return geometry;
  9935. geometry.addEventListener( 'dispose', onGeometryDispose );
  9936. geometries[ geometry.id ] = true;
  9937. info.memory.geometries ++;
  9938. return geometry;
  9939. }
  9940. function update( geometry ) {
  9941. const geometryAttributes = geometry.attributes;
  9942. // Updating index buffer in VAO now. See WebGLBindingStates.
  9943. for ( const name in geometryAttributes ) {
  9944. attributes.update( geometryAttributes[ name ], 34962 );
  9945. }
  9946. // morph targets
  9947. const morphAttributes = geometry.morphAttributes;
  9948. for ( const name in morphAttributes ) {
  9949. const array = morphAttributes[ name ];
  9950. for ( let i = 0, l = array.length; i < l; i ++ ) {
  9951. attributes.update( array[ i ], 34962 );
  9952. }
  9953. }
  9954. }
  9955. function updateWireframeAttribute( geometry ) {
  9956. const indices = [];
  9957. const geometryIndex = geometry.index;
  9958. const geometryPosition = geometry.attributes.position;
  9959. let version = 0;
  9960. if ( geometryIndex !== null ) {
  9961. const array = geometryIndex.array;
  9962. version = geometryIndex.version;
  9963. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  9964. const a = array[ i + 0 ];
  9965. const b = array[ i + 1 ];
  9966. const c = array[ i + 2 ];
  9967. indices.push( a, b, b, c, c, a );
  9968. }
  9969. } else {
  9970. const array = geometryPosition.array;
  9971. version = geometryPosition.version;
  9972. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  9973. const a = i + 0;
  9974. const b = i + 1;
  9975. const c = i + 2;
  9976. indices.push( a, b, b, c, c, a );
  9977. }
  9978. }
  9979. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  9980. attribute.version = version;
  9981. // Updating index buffer in VAO now. See WebGLBindingStates
  9982. //
  9983. const previousAttribute = wireframeAttributes.get( geometry );
  9984. if ( previousAttribute ) attributes.remove( previousAttribute );
  9985. //
  9986. wireframeAttributes.set( geometry, attribute );
  9987. }
  9988. function getWireframeAttribute( geometry ) {
  9989. const currentAttribute = wireframeAttributes.get( geometry );
  9990. if ( currentAttribute ) {
  9991. const geometryIndex = geometry.index;
  9992. if ( geometryIndex !== null ) {
  9993. // if the attribute is obsolete, create a new one
  9994. if ( currentAttribute.version < geometryIndex.version ) {
  9995. updateWireframeAttribute( geometry );
  9996. }
  9997. }
  9998. } else {
  9999. updateWireframeAttribute( geometry );
  10000. }
  10001. return wireframeAttributes.get( geometry );
  10002. }
  10003. return {
  10004. get: get,
  10005. update: update,
  10006. getWireframeAttribute: getWireframeAttribute
  10007. };
  10008. }
  10009. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  10010. const isWebGL2 = capabilities.isWebGL2;
  10011. let mode;
  10012. function setMode( value ) {
  10013. mode = value;
  10014. }
  10015. let type, bytesPerElement;
  10016. function setIndex( value ) {
  10017. type = value.type;
  10018. bytesPerElement = value.bytesPerElement;
  10019. }
  10020. function render( start, count ) {
  10021. gl.drawElements( mode, count, type, start * bytesPerElement );
  10022. info.update( count, mode, 1 );
  10023. }
  10024. function renderInstances( start, count, primcount ) {
  10025. if ( primcount === 0 ) return;
  10026. let extension, methodName;
  10027. if ( isWebGL2 ) {
  10028. extension = gl;
  10029. methodName = 'drawElementsInstanced';
  10030. } else {
  10031. extension = extensions.get( 'ANGLE_instanced_arrays' );
  10032. methodName = 'drawElementsInstancedANGLE';
  10033. if ( extension === null ) {
  10034. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  10035. return;
  10036. }
  10037. }
  10038. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  10039. info.update( count, mode, primcount );
  10040. }
  10041. //
  10042. this.setMode = setMode;
  10043. this.setIndex = setIndex;
  10044. this.render = render;
  10045. this.renderInstances = renderInstances;
  10046. }
  10047. function WebGLInfo( gl ) {
  10048. const memory = {
  10049. geometries: 0,
  10050. textures: 0
  10051. };
  10052. const render = {
  10053. frame: 0,
  10054. calls: 0,
  10055. triangles: 0,
  10056. points: 0,
  10057. lines: 0
  10058. };
  10059. function update( count, mode, instanceCount ) {
  10060. render.calls ++;
  10061. switch ( mode ) {
  10062. case 4:
  10063. render.triangles += instanceCount * ( count / 3 );
  10064. break;
  10065. case 1:
  10066. render.lines += instanceCount * ( count / 2 );
  10067. break;
  10068. case 3:
  10069. render.lines += instanceCount * ( count - 1 );
  10070. break;
  10071. case 2:
  10072. render.lines += instanceCount * count;
  10073. break;
  10074. case 0:
  10075. render.points += instanceCount * count;
  10076. break;
  10077. default:
  10078. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  10079. break;
  10080. }
  10081. }
  10082. function reset() {
  10083. render.frame ++;
  10084. render.calls = 0;
  10085. render.triangles = 0;
  10086. render.points = 0;
  10087. render.lines = 0;
  10088. }
  10089. return {
  10090. memory: memory,
  10091. render: render,
  10092. programs: null,
  10093. autoReset: true,
  10094. reset: reset,
  10095. update: update
  10096. };
  10097. }
  10098. function numericalSort( a, b ) {
  10099. return a[ 0 ] - b[ 0 ];
  10100. }
  10101. function absNumericalSort( a, b ) {
  10102. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  10103. }
  10104. function WebGLMorphtargets( gl, capabilities, textures ) {
  10105. const influencesList = {};
  10106. const morphInfluences = new Float32Array( 8 );
  10107. const morphTextures = new WeakMap();
  10108. const morph = new Vector4();
  10109. const workInfluences = [];
  10110. for ( let i = 0; i < 8; i ++ ) {
  10111. workInfluences[ i ] = [ i, 0 ];
  10112. }
  10113. function update( object, geometry, program ) {
  10114. const objectInfluences = object.morphTargetInfluences;
  10115. if ( capabilities.isWebGL2 === true ) {
  10116. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10117. // into an array of data textures. Each layer represents a single morph target.
  10118. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10119. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10120. let entry = morphTextures.get( geometry );
  10121. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10122. if ( entry !== undefined ) entry.texture.dispose();
  10123. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10124. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10125. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10126. const morphTargets = geometry.morphAttributes.position || [];
  10127. const morphNormals = geometry.morphAttributes.normal || [];
  10128. const morphColors = geometry.morphAttributes.color || [];
  10129. let vertexDataCount = 0;
  10130. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10131. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10132. if ( hasMorphColors === true ) vertexDataCount = 3;
  10133. let width = geometry.attributes.position.count * vertexDataCount;
  10134. let height = 1;
  10135. if ( width > capabilities.maxTextureSize ) {
  10136. height = Math.ceil( width / capabilities.maxTextureSize );
  10137. width = capabilities.maxTextureSize;
  10138. }
  10139. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10140. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10141. texture.type = FloatType;
  10142. texture.needsUpdate = true;
  10143. // fill buffer
  10144. const vertexDataStride = vertexDataCount * 4;
  10145. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10146. const morphTarget = morphTargets[ i ];
  10147. const morphNormal = morphNormals[ i ];
  10148. const morphColor = morphColors[ i ];
  10149. const offset = width * height * 4 * i;
  10150. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10151. const stride = j * vertexDataStride;
  10152. if ( hasMorphPosition === true ) {
  10153. morph.fromBufferAttribute( morphTarget, j );
  10154. buffer[ offset + stride + 0 ] = morph.x;
  10155. buffer[ offset + stride + 1 ] = morph.y;
  10156. buffer[ offset + stride + 2 ] = morph.z;
  10157. buffer[ offset + stride + 3 ] = 0;
  10158. }
  10159. if ( hasMorphNormals === true ) {
  10160. morph.fromBufferAttribute( morphNormal, j );
  10161. buffer[ offset + stride + 4 ] = morph.x;
  10162. buffer[ offset + stride + 5 ] = morph.y;
  10163. buffer[ offset + stride + 6 ] = morph.z;
  10164. buffer[ offset + stride + 7 ] = 0;
  10165. }
  10166. if ( hasMorphColors === true ) {
  10167. morph.fromBufferAttribute( morphColor, j );
  10168. buffer[ offset + stride + 8 ] = morph.x;
  10169. buffer[ offset + stride + 9 ] = morph.y;
  10170. buffer[ offset + stride + 10 ] = morph.z;
  10171. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  10172. }
  10173. }
  10174. }
  10175. entry = {
  10176. count: morphTargetsCount,
  10177. texture: texture,
  10178. size: new Vector2( width, height )
  10179. };
  10180. morphTextures.set( geometry, entry );
  10181. function disposeTexture() {
  10182. texture.dispose();
  10183. morphTextures.delete( geometry );
  10184. geometry.removeEventListener( 'dispose', disposeTexture );
  10185. }
  10186. geometry.addEventListener( 'dispose', disposeTexture );
  10187. }
  10188. //
  10189. let morphInfluencesSum = 0;
  10190. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10191. morphInfluencesSum += objectInfluences[ i ];
  10192. }
  10193. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10194. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10195. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  10196. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  10197. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  10198. } else {
  10199. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10200. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10201. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10202. let influences = influencesList[ geometry.id ];
  10203. if ( influences === undefined || influences.length !== length ) {
  10204. // initialise list
  10205. influences = [];
  10206. for ( let i = 0; i < length; i ++ ) {
  10207. influences[ i ] = [ i, 0 ];
  10208. }
  10209. influencesList[ geometry.id ] = influences;
  10210. }
  10211. // Collect influences
  10212. for ( let i = 0; i < length; i ++ ) {
  10213. const influence = influences[ i ];
  10214. influence[ 0 ] = i;
  10215. influence[ 1 ] = objectInfluences[ i ];
  10216. }
  10217. influences.sort( absNumericalSort );
  10218. for ( let i = 0; i < 8; i ++ ) {
  10219. if ( i < length && influences[ i ][ 1 ] ) {
  10220. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  10221. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  10222. } else {
  10223. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  10224. workInfluences[ i ][ 1 ] = 0;
  10225. }
  10226. }
  10227. workInfluences.sort( numericalSort );
  10228. const morphTargets = geometry.morphAttributes.position;
  10229. const morphNormals = geometry.morphAttributes.normal;
  10230. let morphInfluencesSum = 0;
  10231. for ( let i = 0; i < 8; i ++ ) {
  10232. const influence = workInfluences[ i ];
  10233. const index = influence[ 0 ];
  10234. const value = influence[ 1 ];
  10235. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  10236. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  10237. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  10238. }
  10239. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  10240. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  10241. }
  10242. morphInfluences[ i ] = value;
  10243. morphInfluencesSum += value;
  10244. } else {
  10245. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  10246. geometry.deleteAttribute( 'morphTarget' + i );
  10247. }
  10248. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  10249. geometry.deleteAttribute( 'morphNormal' + i );
  10250. }
  10251. morphInfluences[ i ] = 0;
  10252. }
  10253. }
  10254. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10255. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10256. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10257. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10258. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10259. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  10260. }
  10261. }
  10262. return {
  10263. update: update
  10264. };
  10265. }
  10266. function WebGLObjects( gl, geometries, attributes, info ) {
  10267. let updateMap = new WeakMap();
  10268. function update( object ) {
  10269. const frame = info.render.frame;
  10270. const geometry = object.geometry;
  10271. const buffergeometry = geometries.get( object, geometry );
  10272. // Update once per frame
  10273. if ( updateMap.get( buffergeometry ) !== frame ) {
  10274. geometries.update( buffergeometry );
  10275. updateMap.set( buffergeometry, frame );
  10276. }
  10277. if ( object.isInstancedMesh ) {
  10278. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10279. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10280. }
  10281. attributes.update( object.instanceMatrix, 34962 );
  10282. if ( object.instanceColor !== null ) {
  10283. attributes.update( object.instanceColor, 34962 );
  10284. }
  10285. }
  10286. return buffergeometry;
  10287. }
  10288. function dispose() {
  10289. updateMap = new WeakMap();
  10290. }
  10291. function onInstancedMeshDispose( event ) {
  10292. const instancedMesh = event.target;
  10293. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10294. attributes.remove( instancedMesh.instanceMatrix );
  10295. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10296. }
  10297. return {
  10298. update: update,
  10299. dispose: dispose
  10300. };
  10301. }
  10302. /**
  10303. * Uniforms of a program.
  10304. * Those form a tree structure with a special top-level container for the root,
  10305. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10306. *
  10307. *
  10308. * Properties of inner nodes including the top-level container:
  10309. *
  10310. * .seq - array of nested uniforms
  10311. * .map - nested uniforms by name
  10312. *
  10313. *
  10314. * Methods of all nodes except the top-level container:
  10315. *
  10316. * .setValue( gl, value, [textures] )
  10317. *
  10318. * uploads a uniform value(s)
  10319. * the 'textures' parameter is needed for sampler uniforms
  10320. *
  10321. *
  10322. * Static methods of the top-level container (textures factorizations):
  10323. *
  10324. * .upload( gl, seq, values, textures )
  10325. *
  10326. * sets uniforms in 'seq' to 'values[id].value'
  10327. *
  10328. * .seqWithValue( seq, values ) : filteredSeq
  10329. *
  10330. * filters 'seq' entries with corresponding entry in values
  10331. *
  10332. *
  10333. * Methods of the top-level container (textures factorizations):
  10334. *
  10335. * .setValue( gl, name, value, textures )
  10336. *
  10337. * sets uniform with name 'name' to 'value'
  10338. *
  10339. * .setOptional( gl, obj, prop )
  10340. *
  10341. * like .set for an optional property of the object
  10342. *
  10343. */
  10344. const emptyTexture = /*@__PURE__*/ new Texture();
  10345. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  10346. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  10347. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  10348. // --- Utilities ---
  10349. // Array Caches (provide typed arrays for temporary by size)
  10350. const arrayCacheF32 = [];
  10351. const arrayCacheI32 = [];
  10352. // Float32Array caches used for uploading Matrix uniforms
  10353. const mat4array = new Float32Array( 16 );
  10354. const mat3array = new Float32Array( 9 );
  10355. const mat2array = new Float32Array( 4 );
  10356. // Flattening for arrays of vectors and matrices
  10357. function flatten( array, nBlocks, blockSize ) {
  10358. const firstElem = array[ 0 ];
  10359. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10360. // unoptimized: ! isNaN( firstElem )
  10361. // see http://jacksondunstan.com/articles/983
  10362. const n = nBlocks * blockSize;
  10363. let r = arrayCacheF32[ n ];
  10364. if ( r === undefined ) {
  10365. r = new Float32Array( n );
  10366. arrayCacheF32[ n ] = r;
  10367. }
  10368. if ( nBlocks !== 0 ) {
  10369. firstElem.toArray( r, 0 );
  10370. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10371. offset += blockSize;
  10372. array[ i ].toArray( r, offset );
  10373. }
  10374. }
  10375. return r;
  10376. }
  10377. function arraysEqual( a, b ) {
  10378. if ( a.length !== b.length ) return false;
  10379. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10380. if ( a[ i ] !== b[ i ] ) return false;
  10381. }
  10382. return true;
  10383. }
  10384. function copyArray( a, b ) {
  10385. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10386. a[ i ] = b[ i ];
  10387. }
  10388. }
  10389. // Texture unit allocation
  10390. function allocTexUnits( textures, n ) {
  10391. let r = arrayCacheI32[ n ];
  10392. if ( r === undefined ) {
  10393. r = new Int32Array( n );
  10394. arrayCacheI32[ n ] = r;
  10395. }
  10396. for ( let i = 0; i !== n; ++ i ) {
  10397. r[ i ] = textures.allocateTextureUnit();
  10398. }
  10399. return r;
  10400. }
  10401. // --- Setters ---
  10402. // Note: Defining these methods externally, because they come in a bunch
  10403. // and this way their names minify.
  10404. // Single scalar
  10405. function setValueV1f( gl, v ) {
  10406. const cache = this.cache;
  10407. if ( cache[ 0 ] === v ) return;
  10408. gl.uniform1f( this.addr, v );
  10409. cache[ 0 ] = v;
  10410. }
  10411. // Single float vector (from flat array or THREE.VectorN)
  10412. function setValueV2f( gl, v ) {
  10413. const cache = this.cache;
  10414. if ( v.x !== undefined ) {
  10415. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10416. gl.uniform2f( this.addr, v.x, v.y );
  10417. cache[ 0 ] = v.x;
  10418. cache[ 1 ] = v.y;
  10419. }
  10420. } else {
  10421. if ( arraysEqual( cache, v ) ) return;
  10422. gl.uniform2fv( this.addr, v );
  10423. copyArray( cache, v );
  10424. }
  10425. }
  10426. function setValueV3f( gl, v ) {
  10427. const cache = this.cache;
  10428. if ( v.x !== undefined ) {
  10429. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10430. gl.uniform3f( this.addr, v.x, v.y, v.z );
  10431. cache[ 0 ] = v.x;
  10432. cache[ 1 ] = v.y;
  10433. cache[ 2 ] = v.z;
  10434. }
  10435. } else if ( v.r !== undefined ) {
  10436. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  10437. gl.uniform3f( this.addr, v.r, v.g, v.b );
  10438. cache[ 0 ] = v.r;
  10439. cache[ 1 ] = v.g;
  10440. cache[ 2 ] = v.b;
  10441. }
  10442. } else {
  10443. if ( arraysEqual( cache, v ) ) return;
  10444. gl.uniform3fv( this.addr, v );
  10445. copyArray( cache, v );
  10446. }
  10447. }
  10448. function setValueV4f( gl, v ) {
  10449. const cache = this.cache;
  10450. if ( v.x !== undefined ) {
  10451. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10452. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  10453. cache[ 0 ] = v.x;
  10454. cache[ 1 ] = v.y;
  10455. cache[ 2 ] = v.z;
  10456. cache[ 3 ] = v.w;
  10457. }
  10458. } else {
  10459. if ( arraysEqual( cache, v ) ) return;
  10460. gl.uniform4fv( this.addr, v );
  10461. copyArray( cache, v );
  10462. }
  10463. }
  10464. // Single matrix (from flat array or THREE.MatrixN)
  10465. function setValueM2( gl, v ) {
  10466. const cache = this.cache;
  10467. const elements = v.elements;
  10468. if ( elements === undefined ) {
  10469. if ( arraysEqual( cache, v ) ) return;
  10470. gl.uniformMatrix2fv( this.addr, false, v );
  10471. copyArray( cache, v );
  10472. } else {
  10473. if ( arraysEqual( cache, elements ) ) return;
  10474. mat2array.set( elements );
  10475. gl.uniformMatrix2fv( this.addr, false, mat2array );
  10476. copyArray( cache, elements );
  10477. }
  10478. }
  10479. function setValueM3( gl, v ) {
  10480. const cache = this.cache;
  10481. const elements = v.elements;
  10482. if ( elements === undefined ) {
  10483. if ( arraysEqual( cache, v ) ) return;
  10484. gl.uniformMatrix3fv( this.addr, false, v );
  10485. copyArray( cache, v );
  10486. } else {
  10487. if ( arraysEqual( cache, elements ) ) return;
  10488. mat3array.set( elements );
  10489. gl.uniformMatrix3fv( this.addr, false, mat3array );
  10490. copyArray( cache, elements );
  10491. }
  10492. }
  10493. function setValueM4( gl, v ) {
  10494. const cache = this.cache;
  10495. const elements = v.elements;
  10496. if ( elements === undefined ) {
  10497. if ( arraysEqual( cache, v ) ) return;
  10498. gl.uniformMatrix4fv( this.addr, false, v );
  10499. copyArray( cache, v );
  10500. } else {
  10501. if ( arraysEqual( cache, elements ) ) return;
  10502. mat4array.set( elements );
  10503. gl.uniformMatrix4fv( this.addr, false, mat4array );
  10504. copyArray( cache, elements );
  10505. }
  10506. }
  10507. // Single integer / boolean
  10508. function setValueV1i( gl, v ) {
  10509. const cache = this.cache;
  10510. if ( cache[ 0 ] === v ) return;
  10511. gl.uniform1i( this.addr, v );
  10512. cache[ 0 ] = v;
  10513. }
  10514. // Single integer / boolean vector (from flat array or THREE.VectorN)
  10515. function setValueV2i( gl, v ) {
  10516. const cache = this.cache;
  10517. if ( v.x !== undefined ) {
  10518. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10519. gl.uniform2i( this.addr, v.x, v.y );
  10520. cache[ 0 ] = v.x;
  10521. cache[ 1 ] = v.y;
  10522. }
  10523. } else {
  10524. if ( arraysEqual( cache, v ) ) return;
  10525. gl.uniform2iv( this.addr, v );
  10526. copyArray( cache, v );
  10527. }
  10528. }
  10529. function setValueV3i( gl, v ) {
  10530. const cache = this.cache;
  10531. if ( v.x !== undefined ) {
  10532. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10533. gl.uniform3i( this.addr, v.x, v.y, v.z );
  10534. cache[ 0 ] = v.x;
  10535. cache[ 1 ] = v.y;
  10536. cache[ 2 ] = v.z;
  10537. }
  10538. } else {
  10539. if ( arraysEqual( cache, v ) ) return;
  10540. gl.uniform3iv( this.addr, v );
  10541. copyArray( cache, v );
  10542. }
  10543. }
  10544. function setValueV4i( gl, v ) {
  10545. const cache = this.cache;
  10546. if ( v.x !== undefined ) {
  10547. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10548. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  10549. cache[ 0 ] = v.x;
  10550. cache[ 1 ] = v.y;
  10551. cache[ 2 ] = v.z;
  10552. cache[ 3 ] = v.w;
  10553. }
  10554. } else {
  10555. if ( arraysEqual( cache, v ) ) return;
  10556. gl.uniform4iv( this.addr, v );
  10557. copyArray( cache, v );
  10558. }
  10559. }
  10560. // Single unsigned integer
  10561. function setValueV1ui( gl, v ) {
  10562. const cache = this.cache;
  10563. if ( cache[ 0 ] === v ) return;
  10564. gl.uniform1ui( this.addr, v );
  10565. cache[ 0 ] = v;
  10566. }
  10567. // Single unsigned integer vector (from flat array or THREE.VectorN)
  10568. function setValueV2ui( gl, v ) {
  10569. const cache = this.cache;
  10570. if ( v.x !== undefined ) {
  10571. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10572. gl.uniform2ui( this.addr, v.x, v.y );
  10573. cache[ 0 ] = v.x;
  10574. cache[ 1 ] = v.y;
  10575. }
  10576. } else {
  10577. if ( arraysEqual( cache, v ) ) return;
  10578. gl.uniform2uiv( this.addr, v );
  10579. copyArray( cache, v );
  10580. }
  10581. }
  10582. function setValueV3ui( gl, v ) {
  10583. const cache = this.cache;
  10584. if ( v.x !== undefined ) {
  10585. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10586. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  10587. cache[ 0 ] = v.x;
  10588. cache[ 1 ] = v.y;
  10589. cache[ 2 ] = v.z;
  10590. }
  10591. } else {
  10592. if ( arraysEqual( cache, v ) ) return;
  10593. gl.uniform3uiv( this.addr, v );
  10594. copyArray( cache, v );
  10595. }
  10596. }
  10597. function setValueV4ui( gl, v ) {
  10598. const cache = this.cache;
  10599. if ( v.x !== undefined ) {
  10600. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10601. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  10602. cache[ 0 ] = v.x;
  10603. cache[ 1 ] = v.y;
  10604. cache[ 2 ] = v.z;
  10605. cache[ 3 ] = v.w;
  10606. }
  10607. } else {
  10608. if ( arraysEqual( cache, v ) ) return;
  10609. gl.uniform4uiv( this.addr, v );
  10610. copyArray( cache, v );
  10611. }
  10612. }
  10613. // Single texture (2D / Cube)
  10614. function setValueT1( gl, v, textures ) {
  10615. const cache = this.cache;
  10616. const unit = textures.allocateTextureUnit();
  10617. if ( cache[ 0 ] !== unit ) {
  10618. gl.uniform1i( this.addr, unit );
  10619. cache[ 0 ] = unit;
  10620. }
  10621. textures.setTexture2D( v || emptyTexture, unit );
  10622. }
  10623. function setValueT3D1( gl, v, textures ) {
  10624. const cache = this.cache;
  10625. const unit = textures.allocateTextureUnit();
  10626. if ( cache[ 0 ] !== unit ) {
  10627. gl.uniform1i( this.addr, unit );
  10628. cache[ 0 ] = unit;
  10629. }
  10630. textures.setTexture3D( v || empty3dTexture, unit );
  10631. }
  10632. function setValueT6( gl, v, textures ) {
  10633. const cache = this.cache;
  10634. const unit = textures.allocateTextureUnit();
  10635. if ( cache[ 0 ] !== unit ) {
  10636. gl.uniform1i( this.addr, unit );
  10637. cache[ 0 ] = unit;
  10638. }
  10639. textures.setTextureCube( v || emptyCubeTexture, unit );
  10640. }
  10641. function setValueT2DArray1( gl, v, textures ) {
  10642. const cache = this.cache;
  10643. const unit = textures.allocateTextureUnit();
  10644. if ( cache[ 0 ] !== unit ) {
  10645. gl.uniform1i( this.addr, unit );
  10646. cache[ 0 ] = unit;
  10647. }
  10648. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  10649. }
  10650. // Helper to pick the right setter for the singular case
  10651. function getSingularSetter( type ) {
  10652. switch ( type ) {
  10653. case 0x1406: return setValueV1f; // FLOAT
  10654. case 0x8b50: return setValueV2f; // _VEC2
  10655. case 0x8b51: return setValueV3f; // _VEC3
  10656. case 0x8b52: return setValueV4f; // _VEC4
  10657. case 0x8b5a: return setValueM2; // _MAT2
  10658. case 0x8b5b: return setValueM3; // _MAT3
  10659. case 0x8b5c: return setValueM4; // _MAT4
  10660. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  10661. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  10662. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  10663. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  10664. case 0x1405: return setValueV1ui; // UINT
  10665. case 0x8dc6: return setValueV2ui; // _VEC2
  10666. case 0x8dc7: return setValueV3ui; // _VEC3
  10667. case 0x8dc8: return setValueV4ui; // _VEC4
  10668. case 0x8b5e: // SAMPLER_2D
  10669. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10670. case 0x8dca: // INT_SAMPLER_2D
  10671. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10672. case 0x8b62: // SAMPLER_2D_SHADOW
  10673. return setValueT1;
  10674. case 0x8b5f: // SAMPLER_3D
  10675. case 0x8dcb: // INT_SAMPLER_3D
  10676. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10677. return setValueT3D1;
  10678. case 0x8b60: // SAMPLER_CUBE
  10679. case 0x8dcc: // INT_SAMPLER_CUBE
  10680. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10681. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10682. return setValueT6;
  10683. case 0x8dc1: // SAMPLER_2D_ARRAY
  10684. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10685. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10686. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10687. return setValueT2DArray1;
  10688. }
  10689. }
  10690. // Array of scalars
  10691. function setValueV1fArray( gl, v ) {
  10692. gl.uniform1fv( this.addr, v );
  10693. }
  10694. // Array of vectors (from flat array or array of THREE.VectorN)
  10695. function setValueV2fArray( gl, v ) {
  10696. const data = flatten( v, this.size, 2 );
  10697. gl.uniform2fv( this.addr, data );
  10698. }
  10699. function setValueV3fArray( gl, v ) {
  10700. const data = flatten( v, this.size, 3 );
  10701. gl.uniform3fv( this.addr, data );
  10702. }
  10703. function setValueV4fArray( gl, v ) {
  10704. const data = flatten( v, this.size, 4 );
  10705. gl.uniform4fv( this.addr, data );
  10706. }
  10707. // Array of matrices (from flat array or array of THREE.MatrixN)
  10708. function setValueM2Array( gl, v ) {
  10709. const data = flatten( v, this.size, 4 );
  10710. gl.uniformMatrix2fv( this.addr, false, data );
  10711. }
  10712. function setValueM3Array( gl, v ) {
  10713. const data = flatten( v, this.size, 9 );
  10714. gl.uniformMatrix3fv( this.addr, false, data );
  10715. }
  10716. function setValueM4Array( gl, v ) {
  10717. const data = flatten( v, this.size, 16 );
  10718. gl.uniformMatrix4fv( this.addr, false, data );
  10719. }
  10720. // Array of integer / boolean
  10721. function setValueV1iArray( gl, v ) {
  10722. gl.uniform1iv( this.addr, v );
  10723. }
  10724. // Array of integer / boolean vectors (from flat array)
  10725. function setValueV2iArray( gl, v ) {
  10726. gl.uniform2iv( this.addr, v );
  10727. }
  10728. function setValueV3iArray( gl, v ) {
  10729. gl.uniform3iv( this.addr, v );
  10730. }
  10731. function setValueV4iArray( gl, v ) {
  10732. gl.uniform4iv( this.addr, v );
  10733. }
  10734. // Array of unsigned integer
  10735. function setValueV1uiArray( gl, v ) {
  10736. gl.uniform1uiv( this.addr, v );
  10737. }
  10738. // Array of unsigned integer vectors (from flat array)
  10739. function setValueV2uiArray( gl, v ) {
  10740. gl.uniform2uiv( this.addr, v );
  10741. }
  10742. function setValueV3uiArray( gl, v ) {
  10743. gl.uniform3uiv( this.addr, v );
  10744. }
  10745. function setValueV4uiArray( gl, v ) {
  10746. gl.uniform4uiv( this.addr, v );
  10747. }
  10748. // Array of textures (2D / 3D / Cube / 2DArray)
  10749. function setValueT1Array( gl, v, textures ) {
  10750. const cache = this.cache;
  10751. const n = v.length;
  10752. const units = allocTexUnits( textures, n );
  10753. if ( ! arraysEqual( cache, units ) ) {
  10754. gl.uniform1iv( this.addr, units );
  10755. copyArray( cache, units );
  10756. }
  10757. for ( let i = 0; i !== n; ++ i ) {
  10758. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  10759. }
  10760. }
  10761. function setValueT3DArray( gl, v, textures ) {
  10762. const cache = this.cache;
  10763. const n = v.length;
  10764. const units = allocTexUnits( textures, n );
  10765. if ( ! arraysEqual( cache, units ) ) {
  10766. gl.uniform1iv( this.addr, units );
  10767. copyArray( cache, units );
  10768. }
  10769. for ( let i = 0; i !== n; ++ i ) {
  10770. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  10771. }
  10772. }
  10773. function setValueT6Array( gl, v, textures ) {
  10774. const cache = this.cache;
  10775. const n = v.length;
  10776. const units = allocTexUnits( textures, n );
  10777. if ( ! arraysEqual( cache, units ) ) {
  10778. gl.uniform1iv( this.addr, units );
  10779. copyArray( cache, units );
  10780. }
  10781. for ( let i = 0; i !== n; ++ i ) {
  10782. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  10783. }
  10784. }
  10785. function setValueT2DArrayArray( gl, v, textures ) {
  10786. const cache = this.cache;
  10787. const n = v.length;
  10788. const units = allocTexUnits( textures, n );
  10789. if ( ! arraysEqual( cache, units ) ) {
  10790. gl.uniform1iv( this.addr, units );
  10791. copyArray( cache, units );
  10792. }
  10793. for ( let i = 0; i !== n; ++ i ) {
  10794. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  10795. }
  10796. }
  10797. // Helper to pick the right setter for a pure (bottom-level) array
  10798. function getPureArraySetter( type ) {
  10799. switch ( type ) {
  10800. case 0x1406: return setValueV1fArray; // FLOAT
  10801. case 0x8b50: return setValueV2fArray; // _VEC2
  10802. case 0x8b51: return setValueV3fArray; // _VEC3
  10803. case 0x8b52: return setValueV4fArray; // _VEC4
  10804. case 0x8b5a: return setValueM2Array; // _MAT2
  10805. case 0x8b5b: return setValueM3Array; // _MAT3
  10806. case 0x8b5c: return setValueM4Array; // _MAT4
  10807. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  10808. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  10809. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  10810. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  10811. case 0x1405: return setValueV1uiArray; // UINT
  10812. case 0x8dc6: return setValueV2uiArray; // _VEC2
  10813. case 0x8dc7: return setValueV3uiArray; // _VEC3
  10814. case 0x8dc8: return setValueV4uiArray; // _VEC4
  10815. case 0x8b5e: // SAMPLER_2D
  10816. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10817. case 0x8dca: // INT_SAMPLER_2D
  10818. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10819. case 0x8b62: // SAMPLER_2D_SHADOW
  10820. return setValueT1Array;
  10821. case 0x8b5f: // SAMPLER_3D
  10822. case 0x8dcb: // INT_SAMPLER_3D
  10823. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10824. return setValueT3DArray;
  10825. case 0x8b60: // SAMPLER_CUBE
  10826. case 0x8dcc: // INT_SAMPLER_CUBE
  10827. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10828. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10829. return setValueT6Array;
  10830. case 0x8dc1: // SAMPLER_2D_ARRAY
  10831. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10832. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10833. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10834. return setValueT2DArrayArray;
  10835. }
  10836. }
  10837. // --- Uniform Classes ---
  10838. class SingleUniform {
  10839. constructor( id, activeInfo, addr ) {
  10840. this.id = id;
  10841. this.addr = addr;
  10842. this.cache = [];
  10843. this.setValue = getSingularSetter( activeInfo.type );
  10844. // this.path = activeInfo.name; // DEBUG
  10845. }
  10846. }
  10847. class PureArrayUniform {
  10848. constructor( id, activeInfo, addr ) {
  10849. this.id = id;
  10850. this.addr = addr;
  10851. this.cache = [];
  10852. this.size = activeInfo.size;
  10853. this.setValue = getPureArraySetter( activeInfo.type );
  10854. // this.path = activeInfo.name; // DEBUG
  10855. }
  10856. }
  10857. class StructuredUniform {
  10858. constructor( id ) {
  10859. this.id = id;
  10860. this.seq = [];
  10861. this.map = {};
  10862. }
  10863. setValue( gl, value, textures ) {
  10864. const seq = this.seq;
  10865. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10866. const u = seq[ i ];
  10867. u.setValue( gl, value[ u.id ], textures );
  10868. }
  10869. }
  10870. }
  10871. // --- Top-level ---
  10872. // Parser - builds up the property tree from the path strings
  10873. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  10874. // extracts
  10875. // - the identifier (member name or array index)
  10876. // - followed by an optional right bracket (found when array index)
  10877. // - followed by an optional left bracket or dot (type of subscript)
  10878. //
  10879. // Note: These portions can be read in a non-overlapping fashion and
  10880. // allow straightforward parsing of the hierarchy that WebGL encodes
  10881. // in the uniform names.
  10882. function addUniform( container, uniformObject ) {
  10883. container.seq.push( uniformObject );
  10884. container.map[ uniformObject.id ] = uniformObject;
  10885. }
  10886. function parseUniform( activeInfo, addr, container ) {
  10887. const path = activeInfo.name,
  10888. pathLength = path.length;
  10889. // reset RegExp object, because of the early exit of a previous run
  10890. RePathPart.lastIndex = 0;
  10891. while ( true ) {
  10892. const match = RePathPart.exec( path ),
  10893. matchEnd = RePathPart.lastIndex;
  10894. let id = match[ 1 ];
  10895. const idIsIndex = match[ 2 ] === ']',
  10896. subscript = match[ 3 ];
  10897. if ( idIsIndex ) id = id | 0; // convert to integer
  10898. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  10899. // bare name or "pure" bottom-level array "[0]" suffix
  10900. addUniform( container, subscript === undefined ?
  10901. new SingleUniform( id, activeInfo, addr ) :
  10902. new PureArrayUniform( id, activeInfo, addr ) );
  10903. break;
  10904. } else {
  10905. // step into inner node / create it in case it doesn't exist
  10906. const map = container.map;
  10907. let next = map[ id ];
  10908. if ( next === undefined ) {
  10909. next = new StructuredUniform( id );
  10910. addUniform( container, next );
  10911. }
  10912. container = next;
  10913. }
  10914. }
  10915. }
  10916. // Root Container
  10917. class WebGLUniforms {
  10918. constructor( gl, program ) {
  10919. this.seq = [];
  10920. this.map = {};
  10921. const n = gl.getProgramParameter( program, 35718 );
  10922. for ( let i = 0; i < n; ++ i ) {
  10923. const info = gl.getActiveUniform( program, i ),
  10924. addr = gl.getUniformLocation( program, info.name );
  10925. parseUniform( info, addr, this );
  10926. }
  10927. }
  10928. setValue( gl, name, value, textures ) {
  10929. const u = this.map[ name ];
  10930. if ( u !== undefined ) u.setValue( gl, value, textures );
  10931. }
  10932. setOptional( gl, object, name ) {
  10933. const v = object[ name ];
  10934. if ( v !== undefined ) this.setValue( gl, name, v );
  10935. }
  10936. static upload( gl, seq, values, textures ) {
  10937. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10938. const u = seq[ i ],
  10939. v = values[ u.id ];
  10940. if ( v.needsUpdate !== false ) {
  10941. // note: always updating when .needsUpdate is undefined
  10942. u.setValue( gl, v.value, textures );
  10943. }
  10944. }
  10945. }
  10946. static seqWithValue( seq, values ) {
  10947. const r = [];
  10948. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10949. const u = seq[ i ];
  10950. if ( u.id in values ) r.push( u );
  10951. }
  10952. return r;
  10953. }
  10954. }
  10955. function WebGLShader( gl, type, string ) {
  10956. const shader = gl.createShader( type );
  10957. gl.shaderSource( shader, string );
  10958. gl.compileShader( shader );
  10959. return shader;
  10960. }
  10961. let programIdCount = 0;
  10962. function handleSource( string, errorLine ) {
  10963. const lines = string.split( '\n' );
  10964. const lines2 = [];
  10965. const from = Math.max( errorLine - 6, 0 );
  10966. const to = Math.min( errorLine + 6, lines.length );
  10967. for ( let i = from; i < to; i ++ ) {
  10968. const line = i + 1;
  10969. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  10970. }
  10971. return lines2.join( '\n' );
  10972. }
  10973. function getEncodingComponents( encoding ) {
  10974. switch ( encoding ) {
  10975. case LinearEncoding:
  10976. return [ 'Linear', '( value )' ];
  10977. case sRGBEncoding:
  10978. return [ 'sRGB', '( value )' ];
  10979. default:
  10980. console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding );
  10981. return [ 'Linear', '( value )' ];
  10982. }
  10983. }
  10984. function getShaderErrors( gl, shader, type ) {
  10985. const status = gl.getShaderParameter( shader, 35713 );
  10986. const errors = gl.getShaderInfoLog( shader ).trim();
  10987. if ( status && errors === '' ) return '';
  10988. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  10989. if ( errorMatches ) {
  10990. // --enable-privileged-webgl-extension
  10991. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10992. const errorLine = parseInt( errorMatches[ 1 ] );
  10993. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  10994. } else {
  10995. return errors;
  10996. }
  10997. }
  10998. function getTexelEncodingFunction( functionName, encoding ) {
  10999. const components = getEncodingComponents( encoding );
  11000. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  11001. }
  11002. function getToneMappingFunction( functionName, toneMapping ) {
  11003. let toneMappingName;
  11004. switch ( toneMapping ) {
  11005. case LinearToneMapping:
  11006. toneMappingName = 'Linear';
  11007. break;
  11008. case ReinhardToneMapping:
  11009. toneMappingName = 'Reinhard';
  11010. break;
  11011. case CineonToneMapping:
  11012. toneMappingName = 'OptimizedCineon';
  11013. break;
  11014. case ACESFilmicToneMapping:
  11015. toneMappingName = 'ACESFilmic';
  11016. break;
  11017. case CustomToneMapping:
  11018. toneMappingName = 'Custom';
  11019. break;
  11020. default:
  11021. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  11022. toneMappingName = 'Linear';
  11023. }
  11024. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11025. }
  11026. function generateExtensions( parameters ) {
  11027. const chunks = [
  11028. ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  11029. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  11030. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  11031. ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  11032. ];
  11033. return chunks.filter( filterEmptyLine ).join( '\n' );
  11034. }
  11035. function generateDefines( defines ) {
  11036. const chunks = [];
  11037. for ( const name in defines ) {
  11038. const value = defines[ name ];
  11039. if ( value === false ) continue;
  11040. chunks.push( '#define ' + name + ' ' + value );
  11041. }
  11042. return chunks.join( '\n' );
  11043. }
  11044. function fetchAttributeLocations( gl, program ) {
  11045. const attributes = {};
  11046. const n = gl.getProgramParameter( program, 35721 );
  11047. for ( let i = 0; i < n; i ++ ) {
  11048. const info = gl.getActiveAttrib( program, i );
  11049. const name = info.name;
  11050. let locationSize = 1;
  11051. if ( info.type === 35674 ) locationSize = 2;
  11052. if ( info.type === 35675 ) locationSize = 3;
  11053. if ( info.type === 35676 ) locationSize = 4;
  11054. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11055. attributes[ name ] = {
  11056. type: info.type,
  11057. location: gl.getAttribLocation( program, name ),
  11058. locationSize: locationSize
  11059. };
  11060. }
  11061. return attributes;
  11062. }
  11063. function filterEmptyLine( string ) {
  11064. return string !== '';
  11065. }
  11066. function replaceLightNums( string, parameters ) {
  11067. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  11068. return string
  11069. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  11070. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  11071. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  11072. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  11073. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  11074. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  11075. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  11076. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  11077. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  11078. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  11079. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  11080. }
  11081. function replaceClippingPlaneNums( string, parameters ) {
  11082. return string
  11083. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  11084. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  11085. }
  11086. // Resolve Includes
  11087. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11088. function resolveIncludes( string ) {
  11089. return string.replace( includePattern, includeReplacer );
  11090. }
  11091. function includeReplacer( match, include ) {
  11092. const string = ShaderChunk[ include ];
  11093. if ( string === undefined ) {
  11094. throw new Error( 'Can not resolve #include <' + include + '>' );
  11095. }
  11096. return resolveIncludes( string );
  11097. }
  11098. // Unroll Loops
  11099. 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;
  11100. function unrollLoops( string ) {
  11101. return string.replace( unrollLoopPattern, loopReplacer );
  11102. }
  11103. function loopReplacer( match, start, end, snippet ) {
  11104. let string = '';
  11105. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  11106. string += snippet
  11107. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  11108. .replace( /UNROLLED_LOOP_INDEX/g, i );
  11109. }
  11110. return string;
  11111. }
  11112. //
  11113. function generatePrecision( parameters ) {
  11114. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11115. if ( parameters.precision === 'highp' ) {
  11116. precisionstring += '\n#define HIGH_PRECISION';
  11117. } else if ( parameters.precision === 'mediump' ) {
  11118. precisionstring += '\n#define MEDIUM_PRECISION';
  11119. } else if ( parameters.precision === 'lowp' ) {
  11120. precisionstring += '\n#define LOW_PRECISION';
  11121. }
  11122. return precisionstring;
  11123. }
  11124. function generateShadowMapTypeDefine( parameters ) {
  11125. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11126. if ( parameters.shadowMapType === PCFShadowMap ) {
  11127. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11128. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  11129. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11130. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  11131. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11132. }
  11133. return shadowMapTypeDefine;
  11134. }
  11135. function generateEnvMapTypeDefine( parameters ) {
  11136. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11137. if ( parameters.envMap ) {
  11138. switch ( parameters.envMapMode ) {
  11139. case CubeReflectionMapping:
  11140. case CubeRefractionMapping:
  11141. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11142. break;
  11143. case CubeUVReflectionMapping:
  11144. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11145. break;
  11146. }
  11147. }
  11148. return envMapTypeDefine;
  11149. }
  11150. function generateEnvMapModeDefine( parameters ) {
  11151. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11152. if ( parameters.envMap ) {
  11153. switch ( parameters.envMapMode ) {
  11154. case CubeRefractionMapping:
  11155. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11156. break;
  11157. }
  11158. }
  11159. return envMapModeDefine;
  11160. }
  11161. function generateEnvMapBlendingDefine( parameters ) {
  11162. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11163. if ( parameters.envMap ) {
  11164. switch ( parameters.combine ) {
  11165. case MultiplyOperation:
  11166. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11167. break;
  11168. case MixOperation:
  11169. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11170. break;
  11171. case AddOperation:
  11172. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11173. break;
  11174. }
  11175. }
  11176. return envMapBlendingDefine;
  11177. }
  11178. function generateCubeUVSize( parameters ) {
  11179. const imageHeight = parameters.envMapCubeUVHeight;
  11180. if ( imageHeight === null ) return null;
  11181. const maxMip = Math.log2( imageHeight ) - 2;
  11182. const texelHeight = 1.0 / imageHeight;
  11183. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  11184. return { texelWidth, texelHeight, maxMip };
  11185. }
  11186. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  11187. // TODO Send this event to Three.js DevTools
  11188. // console.log( 'WebGLProgram', cacheKey );
  11189. const gl = renderer.getContext();
  11190. const defines = parameters.defines;
  11191. let vertexShader = parameters.vertexShader;
  11192. let fragmentShader = parameters.fragmentShader;
  11193. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  11194. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  11195. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  11196. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  11197. const envMapCubeUVSize = generateCubeUVSize( parameters );
  11198. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  11199. const customDefines = generateDefines( defines );
  11200. const program = gl.createProgram();
  11201. let prefixVertex, prefixFragment;
  11202. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11203. if ( parameters.isRawShaderMaterial ) {
  11204. prefixVertex = [
  11205. customDefines
  11206. ].filter( filterEmptyLine ).join( '\n' );
  11207. if ( prefixVertex.length > 0 ) {
  11208. prefixVertex += '\n';
  11209. }
  11210. prefixFragment = [
  11211. customExtensions,
  11212. customDefines
  11213. ].filter( filterEmptyLine ).join( '\n' );
  11214. if ( prefixFragment.length > 0 ) {
  11215. prefixFragment += '\n';
  11216. }
  11217. } else {
  11218. prefixVertex = [
  11219. generatePrecision( parameters ),
  11220. '#define SHADER_NAME ' + parameters.shaderName,
  11221. customDefines,
  11222. parameters.instancing ? '#define USE_INSTANCING' : '',
  11223. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  11224. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  11225. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11226. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11227. parameters.map ? '#define USE_MAP' : '',
  11228. parameters.envMap ? '#define USE_ENVMAP' : '',
  11229. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11230. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11231. parameters.aoMap ? '#define USE_AOMAP' : '',
  11232. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11233. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11234. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11235. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11236. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11237. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11238. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11239. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11240. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11241. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11242. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  11243. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11244. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  11245. parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '',
  11246. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11247. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11248. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11249. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11250. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11251. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11252. parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '',
  11253. parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '',
  11254. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11255. parameters.vertexColors ? '#define USE_COLOR' : '',
  11256. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11257. parameters.vertexUvs ? '#define USE_UV' : '',
  11258. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11259. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11260. parameters.skinning ? '#define USE_SKINNING' : '',
  11261. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  11262. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  11263. ( parameters.morphColors && parameters.isWebGL2 ) ? '#define USE_MORPHCOLORS' : '',
  11264. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE' : '',
  11265. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  11266. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  11267. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11268. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11269. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11270. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11271. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  11272. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11273. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11274. 'uniform mat4 modelMatrix;',
  11275. 'uniform mat4 modelViewMatrix;',
  11276. 'uniform mat4 projectionMatrix;',
  11277. 'uniform mat4 viewMatrix;',
  11278. 'uniform mat3 normalMatrix;',
  11279. 'uniform vec3 cameraPosition;',
  11280. 'uniform bool isOrthographic;',
  11281. '#ifdef USE_INSTANCING',
  11282. ' attribute mat4 instanceMatrix;',
  11283. '#endif',
  11284. '#ifdef USE_INSTANCING_COLOR',
  11285. ' attribute vec3 instanceColor;',
  11286. '#endif',
  11287. 'attribute vec3 position;',
  11288. 'attribute vec3 normal;',
  11289. 'attribute vec2 uv;',
  11290. '#ifdef USE_TANGENT',
  11291. ' attribute vec4 tangent;',
  11292. '#endif',
  11293. '#if defined( USE_COLOR_ALPHA )',
  11294. ' attribute vec4 color;',
  11295. '#elif defined( USE_COLOR )',
  11296. ' attribute vec3 color;',
  11297. '#endif',
  11298. '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )',
  11299. ' attribute vec3 morphTarget0;',
  11300. ' attribute vec3 morphTarget1;',
  11301. ' attribute vec3 morphTarget2;',
  11302. ' attribute vec3 morphTarget3;',
  11303. ' #ifdef USE_MORPHNORMALS',
  11304. ' attribute vec3 morphNormal0;',
  11305. ' attribute vec3 morphNormal1;',
  11306. ' attribute vec3 morphNormal2;',
  11307. ' attribute vec3 morphNormal3;',
  11308. ' #else',
  11309. ' attribute vec3 morphTarget4;',
  11310. ' attribute vec3 morphTarget5;',
  11311. ' attribute vec3 morphTarget6;',
  11312. ' attribute vec3 morphTarget7;',
  11313. ' #endif',
  11314. '#endif',
  11315. '#ifdef USE_SKINNING',
  11316. ' attribute vec4 skinIndex;',
  11317. ' attribute vec4 skinWeight;',
  11318. '#endif',
  11319. '\n'
  11320. ].filter( filterEmptyLine ).join( '\n' );
  11321. prefixFragment = [
  11322. customExtensions,
  11323. generatePrecision( parameters ),
  11324. '#define SHADER_NAME ' + parameters.shaderName,
  11325. customDefines,
  11326. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11327. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11328. parameters.map ? '#define USE_MAP' : '',
  11329. parameters.matcap ? '#define USE_MATCAP' : '',
  11330. parameters.envMap ? '#define USE_ENVMAP' : '',
  11331. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  11332. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11333. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  11334. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  11335. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  11336. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  11337. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11338. parameters.aoMap ? '#define USE_AOMAP' : '',
  11339. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11340. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11341. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11342. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11343. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11344. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  11345. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11346. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11347. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11348. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  11349. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11350. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11351. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11352. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  11353. parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '',
  11354. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11355. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11356. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11357. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  11358. parameters.sheen ? '#define USE_SHEEN' : '',
  11359. parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '',
  11360. parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '',
  11361. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11362. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11363. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11364. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  11365. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11366. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  11367. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11368. parameters.vertexUvs ? '#define USE_UV' : '',
  11369. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11370. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  11371. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11372. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11373. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11374. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11375. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11376. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  11377. parameters.useLegacyLights ? '#define LEGACY_LIGHTS' : '',
  11378. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11379. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11380. 'uniform mat4 viewMatrix;',
  11381. 'uniform vec3 cameraPosition;',
  11382. 'uniform bool isOrthographic;',
  11383. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  11384. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  11385. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  11386. parameters.dithering ? '#define DITHERING' : '',
  11387. parameters.opaque ? '#define OPAQUE' : '',
  11388. ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  11389. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),
  11390. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  11391. '\n'
  11392. ].filter( filterEmptyLine ).join( '\n' );
  11393. }
  11394. vertexShader = resolveIncludes( vertexShader );
  11395. vertexShader = replaceLightNums( vertexShader, parameters );
  11396. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  11397. fragmentShader = resolveIncludes( fragmentShader );
  11398. fragmentShader = replaceLightNums( fragmentShader, parameters );
  11399. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  11400. vertexShader = unrollLoops( vertexShader );
  11401. fragmentShader = unrollLoops( fragmentShader );
  11402. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  11403. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11404. versionString = '#version 300 es\n';
  11405. prefixVertex = [
  11406. 'precision mediump sampler2DArray;',
  11407. '#define attribute in',
  11408. '#define varying out',
  11409. '#define texture2D texture'
  11410. ].join( '\n' ) + '\n' + prefixVertex;
  11411. prefixFragment = [
  11412. '#define varying in',
  11413. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  11414. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  11415. '#define gl_FragDepthEXT gl_FragDepth',
  11416. '#define texture2D texture',
  11417. '#define textureCube texture',
  11418. '#define texture2DProj textureProj',
  11419. '#define texture2DLodEXT textureLod',
  11420. '#define texture2DProjLodEXT textureProjLod',
  11421. '#define textureCubeLodEXT textureLod',
  11422. '#define texture2DGradEXT textureGrad',
  11423. '#define texture2DProjGradEXT textureProjGrad',
  11424. '#define textureCubeGradEXT textureGrad'
  11425. ].join( '\n' ) + '\n' + prefixFragment;
  11426. }
  11427. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11428. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  11429. // console.log( '*VERTEX*', vertexGlsl );
  11430. // console.log( '*FRAGMENT*', fragmentGlsl );
  11431. const glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
  11432. const glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );
  11433. gl.attachShader( program, glVertexShader );
  11434. gl.attachShader( program, glFragmentShader );
  11435. // Force a particular attribute to index 0.
  11436. if ( parameters.index0AttributeName !== undefined ) {
  11437. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  11438. } else if ( parameters.morphTargets === true ) {
  11439. // programs with morphTargets displace position out of attribute 0
  11440. gl.bindAttribLocation( program, 0, 'position' );
  11441. }
  11442. gl.linkProgram( program );
  11443. // check for link errors
  11444. if ( renderer.debug.checkShaderErrors ) {
  11445. const programLog = gl.getProgramInfoLog( program ).trim();
  11446. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  11447. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  11448. let runnable = true;
  11449. let haveDiagnostics = true;
  11450. if ( gl.getProgramParameter( program, 35714 ) === false ) {
  11451. runnable = false;
  11452. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  11453. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  11454. console.error(
  11455. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  11456. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, 35715 ) + '\n\n' +
  11457. 'Program Info Log: ' + programLog + '\n' +
  11458. vertexErrors + '\n' +
  11459. fragmentErrors
  11460. );
  11461. } else if ( programLog !== '' ) {
  11462. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  11463. } else if ( vertexLog === '' || fragmentLog === '' ) {
  11464. haveDiagnostics = false;
  11465. }
  11466. if ( haveDiagnostics ) {
  11467. this.diagnostics = {
  11468. runnable: runnable,
  11469. programLog: programLog,
  11470. vertexShader: {
  11471. log: vertexLog,
  11472. prefix: prefixVertex
  11473. },
  11474. fragmentShader: {
  11475. log: fragmentLog,
  11476. prefix: prefixFragment
  11477. }
  11478. };
  11479. }
  11480. }
  11481. // Clean up
  11482. // Crashes in iOS9 and iOS10. #18402
  11483. // gl.detachShader( program, glVertexShader );
  11484. // gl.detachShader( program, glFragmentShader );
  11485. gl.deleteShader( glVertexShader );
  11486. gl.deleteShader( glFragmentShader );
  11487. // set up caching for uniform locations
  11488. let cachedUniforms;
  11489. this.getUniforms = function () {
  11490. if ( cachedUniforms === undefined ) {
  11491. cachedUniforms = new WebGLUniforms( gl, program );
  11492. }
  11493. return cachedUniforms;
  11494. };
  11495. // set up caching for attribute locations
  11496. let cachedAttributes;
  11497. this.getAttributes = function () {
  11498. if ( cachedAttributes === undefined ) {
  11499. cachedAttributes = fetchAttributeLocations( gl, program );
  11500. }
  11501. return cachedAttributes;
  11502. };
  11503. // free resource
  11504. this.destroy = function () {
  11505. bindingStates.releaseStatesOfProgram( this );
  11506. gl.deleteProgram( program );
  11507. this.program = undefined;
  11508. };
  11509. //
  11510. this.name = parameters.shaderName;
  11511. this.id = programIdCount ++;
  11512. this.cacheKey = cacheKey;
  11513. this.usedTimes = 1;
  11514. this.program = program;
  11515. this.vertexShader = glVertexShader;
  11516. this.fragmentShader = glFragmentShader;
  11517. return this;
  11518. }
  11519. let _id = 0;
  11520. class WebGLShaderCache {
  11521. constructor() {
  11522. this.shaderCache = new Map();
  11523. this.materialCache = new Map();
  11524. }
  11525. update( material ) {
  11526. const vertexShader = material.vertexShader;
  11527. const fragmentShader = material.fragmentShader;
  11528. const vertexShaderStage = this._getShaderStage( vertexShader );
  11529. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  11530. const materialShaders = this._getShaderCacheForMaterial( material );
  11531. if ( materialShaders.has( vertexShaderStage ) === false ) {
  11532. materialShaders.add( vertexShaderStage );
  11533. vertexShaderStage.usedTimes ++;
  11534. }
  11535. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  11536. materialShaders.add( fragmentShaderStage );
  11537. fragmentShaderStage.usedTimes ++;
  11538. }
  11539. return this;
  11540. }
  11541. remove( material ) {
  11542. const materialShaders = this.materialCache.get( material );
  11543. for ( const shaderStage of materialShaders ) {
  11544. shaderStage.usedTimes --;
  11545. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  11546. }
  11547. this.materialCache.delete( material );
  11548. return this;
  11549. }
  11550. getVertexShaderID( material ) {
  11551. return this._getShaderStage( material.vertexShader ).id;
  11552. }
  11553. getFragmentShaderID( material ) {
  11554. return this._getShaderStage( material.fragmentShader ).id;
  11555. }
  11556. dispose() {
  11557. this.shaderCache.clear();
  11558. this.materialCache.clear();
  11559. }
  11560. _getShaderCacheForMaterial( material ) {
  11561. const cache = this.materialCache;
  11562. let set = cache.get( material );
  11563. if ( set === undefined ) {
  11564. set = new Set();
  11565. cache.set( material, set );
  11566. }
  11567. return set;
  11568. }
  11569. _getShaderStage( code ) {
  11570. const cache = this.shaderCache;
  11571. let stage = cache.get( code );
  11572. if ( stage === undefined ) {
  11573. stage = new WebGLShaderStage( code );
  11574. cache.set( code, stage );
  11575. }
  11576. return stage;
  11577. }
  11578. }
  11579. class WebGLShaderStage {
  11580. constructor( code ) {
  11581. this.id = _id ++;
  11582. this.code = code;
  11583. this.usedTimes = 0;
  11584. }
  11585. }
  11586. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  11587. const _programLayers = new Layers();
  11588. const _customShaders = new WebGLShaderCache();
  11589. const programs = [];
  11590. const isWebGL2 = capabilities.isWebGL2;
  11591. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11592. const vertexTextures = capabilities.vertexTextures;
  11593. let precision = capabilities.precision;
  11594. const shaderIDs = {
  11595. MeshDepthMaterial: 'depth',
  11596. MeshDistanceMaterial: 'distanceRGBA',
  11597. MeshNormalMaterial: 'normal',
  11598. MeshBasicMaterial: 'basic',
  11599. MeshLambertMaterial: 'lambert',
  11600. MeshPhongMaterial: 'phong',
  11601. MeshToonMaterial: 'toon',
  11602. MeshStandardMaterial: 'physical',
  11603. MeshPhysicalMaterial: 'physical',
  11604. MeshMatcapMaterial: 'matcap',
  11605. LineBasicMaterial: 'basic',
  11606. LineDashedMaterial: 'dashed',
  11607. PointsMaterial: 'points',
  11608. ShadowMaterial: 'shadow',
  11609. SpriteMaterial: 'sprite'
  11610. };
  11611. function getParameters( material, lights, shadows, scene, object ) {
  11612. const fog = scene.fog;
  11613. const geometry = object.geometry;
  11614. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11615. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  11616. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  11617. const shaderID = shaderIDs[ material.type ];
  11618. // heuristics to create shader parameters according to lights in the scene
  11619. // (not to blow over maxLights budget)
  11620. if ( material.precision !== null ) {
  11621. precision = capabilities.getMaxPrecision( material.precision );
  11622. if ( precision !== material.precision ) {
  11623. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  11624. }
  11625. }
  11626. //
  11627. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11628. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11629. let morphTextureStride = 0;
  11630. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  11631. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  11632. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  11633. //
  11634. let vertexShader, fragmentShader;
  11635. let customVertexShaderID, customFragmentShaderID;
  11636. if ( shaderID ) {
  11637. const shader = ShaderLib[ shaderID ];
  11638. vertexShader = shader.vertexShader;
  11639. fragmentShader = shader.fragmentShader;
  11640. } else {
  11641. vertexShader = material.vertexShader;
  11642. fragmentShader = material.fragmentShader;
  11643. _customShaders.update( material );
  11644. customVertexShaderID = _customShaders.getVertexShaderID( material );
  11645. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  11646. }
  11647. const currentRenderTarget = renderer.getRenderTarget();
  11648. const useAlphaTest = material.alphaTest > 0;
  11649. const useClearcoat = material.clearcoat > 0;
  11650. const useIridescence = material.iridescence > 0;
  11651. const parameters = {
  11652. isWebGL2: isWebGL2,
  11653. shaderID: shaderID,
  11654. shaderName: material.type,
  11655. vertexShader: vertexShader,
  11656. fragmentShader: fragmentShader,
  11657. defines: material.defines,
  11658. customVertexShaderID: customVertexShaderID,
  11659. customFragmentShaderID: customFragmentShaderID,
  11660. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11661. glslVersion: material.glslVersion,
  11662. precision: precision,
  11663. instancing: object.isInstancedMesh === true,
  11664. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11665. supportsVertexTextures: vertexTextures,
  11666. outputEncoding: ( currentRenderTarget === null ) ? renderer.outputEncoding : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding ),
  11667. map: !! material.map,
  11668. matcap: !! material.matcap,
  11669. envMap: !! envMap,
  11670. envMapMode: envMap && envMap.mapping,
  11671. envMapCubeUVHeight: envMapCubeUVHeight,
  11672. lightMap: !! material.lightMap,
  11673. aoMap: !! material.aoMap,
  11674. emissiveMap: !! material.emissiveMap,
  11675. bumpMap: !! material.bumpMap,
  11676. normalMap: !! material.normalMap,
  11677. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11678. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11679. decodeVideoTexture: !! material.map && ( material.map.isVideoTexture === true ) && ( material.map.encoding === sRGBEncoding ),
  11680. clearcoat: useClearcoat,
  11681. clearcoatMap: useClearcoat && !! material.clearcoatMap,
  11682. clearcoatRoughnessMap: useClearcoat && !! material.clearcoatRoughnessMap,
  11683. clearcoatNormalMap: useClearcoat && !! material.clearcoatNormalMap,
  11684. iridescence: useIridescence,
  11685. iridescenceMap: useIridescence && !! material.iridescenceMap,
  11686. iridescenceThicknessMap: useIridescence && !! material.iridescenceThicknessMap,
  11687. displacementMap: !! material.displacementMap,
  11688. roughnessMap: !! material.roughnessMap,
  11689. metalnessMap: !! material.metalnessMap,
  11690. specularMap: !! material.specularMap,
  11691. specularIntensityMap: !! material.specularIntensityMap,
  11692. specularColorMap: !! material.specularColorMap,
  11693. opaque: material.transparent === false && material.blending === NormalBlending,
  11694. alphaMap: !! material.alphaMap,
  11695. alphaTest: useAlphaTest,
  11696. gradientMap: !! material.gradientMap,
  11697. sheen: material.sheen > 0,
  11698. sheenColorMap: !! material.sheenColorMap,
  11699. sheenRoughnessMap: !! material.sheenRoughnessMap,
  11700. transmission: material.transmission > 0,
  11701. transmissionMap: !! material.transmissionMap,
  11702. thicknessMap: !! material.thicknessMap,
  11703. combine: material.combine,
  11704. vertexTangents: ( !! material.normalMap && !! geometry.attributes.tangent ),
  11705. vertexColors: material.vertexColors,
  11706. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  11707. 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,
  11708. 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,
  11709. fog: !! fog,
  11710. useFog: material.fog === true,
  11711. fogExp2: ( fog && fog.isFogExp2 ),
  11712. flatShading: !! material.flatShading,
  11713. sizeAttenuation: material.sizeAttenuation,
  11714. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11715. skinning: object.isSkinnedMesh === true,
  11716. morphTargets: geometry.morphAttributes.position !== undefined,
  11717. morphNormals: geometry.morphAttributes.normal !== undefined,
  11718. morphColors: geometry.morphAttributes.color !== undefined,
  11719. morphTargetsCount: morphTargetsCount,
  11720. morphTextureStride: morphTextureStride,
  11721. numDirLights: lights.directional.length,
  11722. numPointLights: lights.point.length,
  11723. numSpotLights: lights.spot.length,
  11724. numSpotLightMaps: lights.spotLightMap.length,
  11725. numRectAreaLights: lights.rectArea.length,
  11726. numHemiLights: lights.hemi.length,
  11727. numDirLightShadows: lights.directionalShadowMap.length,
  11728. numPointLightShadows: lights.pointShadowMap.length,
  11729. numSpotLightShadows: lights.spotShadowMap.length,
  11730. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  11731. numClippingPlanes: clipping.numPlanes,
  11732. numClipIntersection: clipping.numIntersection,
  11733. dithering: material.dithering,
  11734. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11735. shadowMapType: renderer.shadowMap.type,
  11736. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11737. useLegacyLights: renderer.useLegacyLights,
  11738. premultipliedAlpha: material.premultipliedAlpha,
  11739. doubleSided: material.side === DoubleSide,
  11740. flipSided: material.side === BackSide,
  11741. useDepthPacking: !! material.depthPacking,
  11742. depthPacking: material.depthPacking || 0,
  11743. index0AttributeName: material.index0AttributeName,
  11744. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11745. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11746. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11747. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11748. rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ),
  11749. rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  11750. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  11751. customProgramCacheKey: material.customProgramCacheKey()
  11752. };
  11753. return parameters;
  11754. }
  11755. function getProgramCacheKey( parameters ) {
  11756. const array = [];
  11757. if ( parameters.shaderID ) {
  11758. array.push( parameters.shaderID );
  11759. } else {
  11760. array.push( parameters.customVertexShaderID );
  11761. array.push( parameters.customFragmentShaderID );
  11762. }
  11763. if ( parameters.defines !== undefined ) {
  11764. for ( const name in parameters.defines ) {
  11765. array.push( name );
  11766. array.push( parameters.defines[ name ] );
  11767. }
  11768. }
  11769. if ( parameters.isRawShaderMaterial === false ) {
  11770. getProgramCacheKeyParameters( array, parameters );
  11771. getProgramCacheKeyBooleans( array, parameters );
  11772. array.push( renderer.outputEncoding );
  11773. }
  11774. array.push( parameters.customProgramCacheKey );
  11775. return array.join();
  11776. }
  11777. function getProgramCacheKeyParameters( array, parameters ) {
  11778. array.push( parameters.precision );
  11779. array.push( parameters.outputEncoding );
  11780. array.push( parameters.envMapMode );
  11781. array.push( parameters.envMapCubeUVHeight );
  11782. array.push( parameters.combine );
  11783. array.push( parameters.vertexUvs );
  11784. array.push( parameters.fogExp2 );
  11785. array.push( parameters.sizeAttenuation );
  11786. array.push( parameters.morphTargetsCount );
  11787. array.push( parameters.morphAttributeCount );
  11788. array.push( parameters.numDirLights );
  11789. array.push( parameters.numPointLights );
  11790. array.push( parameters.numSpotLights );
  11791. array.push( parameters.numSpotLightMaps );
  11792. array.push( parameters.numHemiLights );
  11793. array.push( parameters.numRectAreaLights );
  11794. array.push( parameters.numDirLightShadows );
  11795. array.push( parameters.numPointLightShadows );
  11796. array.push( parameters.numSpotLightShadows );
  11797. array.push( parameters.numSpotLightShadowsWithMaps );
  11798. array.push( parameters.shadowMapType );
  11799. array.push( parameters.toneMapping );
  11800. array.push( parameters.numClippingPlanes );
  11801. array.push( parameters.numClipIntersection );
  11802. array.push( parameters.depthPacking );
  11803. }
  11804. function getProgramCacheKeyBooleans( array, parameters ) {
  11805. _programLayers.disableAll();
  11806. if ( parameters.isWebGL2 )
  11807. _programLayers.enable( 0 );
  11808. if ( parameters.supportsVertexTextures )
  11809. _programLayers.enable( 1 );
  11810. if ( parameters.instancing )
  11811. _programLayers.enable( 2 );
  11812. if ( parameters.instancingColor )
  11813. _programLayers.enable( 3 );
  11814. if ( parameters.map )
  11815. _programLayers.enable( 4 );
  11816. if ( parameters.matcap )
  11817. _programLayers.enable( 5 );
  11818. if ( parameters.envMap )
  11819. _programLayers.enable( 6 );
  11820. if ( parameters.lightMap )
  11821. _programLayers.enable( 7 );
  11822. if ( parameters.aoMap )
  11823. _programLayers.enable( 8 );
  11824. if ( parameters.emissiveMap )
  11825. _programLayers.enable( 9 );
  11826. if ( parameters.bumpMap )
  11827. _programLayers.enable( 10 );
  11828. if ( parameters.normalMap )
  11829. _programLayers.enable( 11 );
  11830. if ( parameters.objectSpaceNormalMap )
  11831. _programLayers.enable( 12 );
  11832. if ( parameters.tangentSpaceNormalMap )
  11833. _programLayers.enable( 13 );
  11834. if ( parameters.clearcoat )
  11835. _programLayers.enable( 14 );
  11836. if ( parameters.clearcoatMap )
  11837. _programLayers.enable( 15 );
  11838. if ( parameters.clearcoatRoughnessMap )
  11839. _programLayers.enable( 16 );
  11840. if ( parameters.clearcoatNormalMap )
  11841. _programLayers.enable( 17 );
  11842. if ( parameters.iridescence )
  11843. _programLayers.enable( 18 );
  11844. if ( parameters.iridescenceMap )
  11845. _programLayers.enable( 19 );
  11846. if ( parameters.iridescenceThicknessMap )
  11847. _programLayers.enable( 20 );
  11848. if ( parameters.displacementMap )
  11849. _programLayers.enable( 21 );
  11850. if ( parameters.specularMap )
  11851. _programLayers.enable( 22 );
  11852. if ( parameters.roughnessMap )
  11853. _programLayers.enable( 23 );
  11854. if ( parameters.metalnessMap )
  11855. _programLayers.enable( 24 );
  11856. if ( parameters.gradientMap )
  11857. _programLayers.enable( 25 );
  11858. if ( parameters.alphaMap )
  11859. _programLayers.enable( 26 );
  11860. if ( parameters.alphaTest )
  11861. _programLayers.enable( 27 );
  11862. if ( parameters.vertexColors )
  11863. _programLayers.enable( 28 );
  11864. if ( parameters.vertexAlphas )
  11865. _programLayers.enable( 29 );
  11866. if ( parameters.vertexUvs )
  11867. _programLayers.enable( 30 );
  11868. if ( parameters.vertexTangents )
  11869. _programLayers.enable( 31 );
  11870. if ( parameters.uvsVertexOnly )
  11871. _programLayers.enable( 32 );
  11872. array.push( _programLayers.mask );
  11873. _programLayers.disableAll();
  11874. if ( parameters.fog )
  11875. _programLayers.enable( 0 );
  11876. if ( parameters.useFog )
  11877. _programLayers.enable( 1 );
  11878. if ( parameters.flatShading )
  11879. _programLayers.enable( 2 );
  11880. if ( parameters.logarithmicDepthBuffer )
  11881. _programLayers.enable( 3 );
  11882. if ( parameters.skinning )
  11883. _programLayers.enable( 4 );
  11884. if ( parameters.morphTargets )
  11885. _programLayers.enable( 5 );
  11886. if ( parameters.morphNormals )
  11887. _programLayers.enable( 6 );
  11888. if ( parameters.morphColors )
  11889. _programLayers.enable( 7 );
  11890. if ( parameters.premultipliedAlpha )
  11891. _programLayers.enable( 8 );
  11892. if ( parameters.shadowMapEnabled )
  11893. _programLayers.enable( 9 );
  11894. if ( parameters.useLegacyLights )
  11895. _programLayers.enable( 10 );
  11896. if ( parameters.doubleSided )
  11897. _programLayers.enable( 11 );
  11898. if ( parameters.flipSided )
  11899. _programLayers.enable( 12 );
  11900. if ( parameters.useDepthPacking )
  11901. _programLayers.enable( 13 );
  11902. if ( parameters.dithering )
  11903. _programLayers.enable( 14 );
  11904. if ( parameters.specularIntensityMap )
  11905. _programLayers.enable( 15 );
  11906. if ( parameters.specularColorMap )
  11907. _programLayers.enable( 16 );
  11908. if ( parameters.transmission )
  11909. _programLayers.enable( 17 );
  11910. if ( parameters.transmissionMap )
  11911. _programLayers.enable( 18 );
  11912. if ( parameters.thicknessMap )
  11913. _programLayers.enable( 19 );
  11914. if ( parameters.sheen )
  11915. _programLayers.enable( 20 );
  11916. if ( parameters.sheenColorMap )
  11917. _programLayers.enable( 21 );
  11918. if ( parameters.sheenRoughnessMap )
  11919. _programLayers.enable( 22 );
  11920. if ( parameters.decodeVideoTexture )
  11921. _programLayers.enable( 23 );
  11922. if ( parameters.opaque )
  11923. _programLayers.enable( 24 );
  11924. array.push( _programLayers.mask );
  11925. }
  11926. function getUniforms( material ) {
  11927. const shaderID = shaderIDs[ material.type ];
  11928. let uniforms;
  11929. if ( shaderID ) {
  11930. const shader = ShaderLib[ shaderID ];
  11931. uniforms = UniformsUtils.clone( shader.uniforms );
  11932. } else {
  11933. uniforms = material.uniforms;
  11934. }
  11935. return uniforms;
  11936. }
  11937. function acquireProgram( parameters, cacheKey ) {
  11938. let program;
  11939. // Check if code has been already compiled
  11940. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  11941. const preexistingProgram = programs[ p ];
  11942. if ( preexistingProgram.cacheKey === cacheKey ) {
  11943. program = preexistingProgram;
  11944. ++ program.usedTimes;
  11945. break;
  11946. }
  11947. }
  11948. if ( program === undefined ) {
  11949. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  11950. programs.push( program );
  11951. }
  11952. return program;
  11953. }
  11954. function releaseProgram( program ) {
  11955. if ( -- program.usedTimes === 0 ) {
  11956. // Remove from unordered set
  11957. const i = programs.indexOf( program );
  11958. programs[ i ] = programs[ programs.length - 1 ];
  11959. programs.pop();
  11960. // Free WebGL resources
  11961. program.destroy();
  11962. }
  11963. }
  11964. function releaseShaderCache( material ) {
  11965. _customShaders.remove( material );
  11966. }
  11967. function dispose() {
  11968. _customShaders.dispose();
  11969. }
  11970. return {
  11971. getParameters: getParameters,
  11972. getProgramCacheKey: getProgramCacheKey,
  11973. getUniforms: getUniforms,
  11974. acquireProgram: acquireProgram,
  11975. releaseProgram: releaseProgram,
  11976. releaseShaderCache: releaseShaderCache,
  11977. // Exposed for resource monitoring & error feedback via renderer.info:
  11978. programs: programs,
  11979. dispose: dispose
  11980. };
  11981. }
  11982. function WebGLProperties() {
  11983. let properties = new WeakMap();
  11984. function get( object ) {
  11985. let map = properties.get( object );
  11986. if ( map === undefined ) {
  11987. map = {};
  11988. properties.set( object, map );
  11989. }
  11990. return map;
  11991. }
  11992. function remove( object ) {
  11993. properties.delete( object );
  11994. }
  11995. function update( object, key, value ) {
  11996. properties.get( object )[ key ] = value;
  11997. }
  11998. function dispose() {
  11999. properties = new WeakMap();
  12000. }
  12001. return {
  12002. get: get,
  12003. remove: remove,
  12004. update: update,
  12005. dispose: dispose
  12006. };
  12007. }
  12008. function painterSortStable( a, b ) {
  12009. if ( a.groupOrder !== b.groupOrder ) {
  12010. return a.groupOrder - b.groupOrder;
  12011. } else if ( a.renderOrder !== b.renderOrder ) {
  12012. return a.renderOrder - b.renderOrder;
  12013. } else if ( a.material.id !== b.material.id ) {
  12014. return a.material.id - b.material.id;
  12015. } else if ( a.z !== b.z ) {
  12016. return a.z - b.z;
  12017. } else {
  12018. return a.id - b.id;
  12019. }
  12020. }
  12021. function reversePainterSortStable( a, b ) {
  12022. if ( a.groupOrder !== b.groupOrder ) {
  12023. return a.groupOrder - b.groupOrder;
  12024. } else if ( a.renderOrder !== b.renderOrder ) {
  12025. return a.renderOrder - b.renderOrder;
  12026. } else if ( a.z !== b.z ) {
  12027. return b.z - a.z;
  12028. } else {
  12029. return a.id - b.id;
  12030. }
  12031. }
  12032. function WebGLRenderList() {
  12033. const renderItems = [];
  12034. let renderItemsIndex = 0;
  12035. const opaque = [];
  12036. const transmissive = [];
  12037. const transparent = [];
  12038. function init() {
  12039. renderItemsIndex = 0;
  12040. opaque.length = 0;
  12041. transmissive.length = 0;
  12042. transparent.length = 0;
  12043. }
  12044. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  12045. let renderItem = renderItems[ renderItemsIndex ];
  12046. if ( renderItem === undefined ) {
  12047. renderItem = {
  12048. id: object.id,
  12049. object: object,
  12050. geometry: geometry,
  12051. material: material,
  12052. groupOrder: groupOrder,
  12053. renderOrder: object.renderOrder,
  12054. z: z,
  12055. group: group
  12056. };
  12057. renderItems[ renderItemsIndex ] = renderItem;
  12058. } else {
  12059. renderItem.id = object.id;
  12060. renderItem.object = object;
  12061. renderItem.geometry = geometry;
  12062. renderItem.material = material;
  12063. renderItem.groupOrder = groupOrder;
  12064. renderItem.renderOrder = object.renderOrder;
  12065. renderItem.z = z;
  12066. renderItem.group = group;
  12067. }
  12068. renderItemsIndex ++;
  12069. return renderItem;
  12070. }
  12071. function push( object, geometry, material, groupOrder, z, group ) {
  12072. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12073. if ( material.transmission > 0.0 ) {
  12074. transmissive.push( renderItem );
  12075. } else if ( material.transparent === true ) {
  12076. transparent.push( renderItem );
  12077. } else {
  12078. opaque.push( renderItem );
  12079. }
  12080. }
  12081. function unshift( object, geometry, material, groupOrder, z, group ) {
  12082. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12083. if ( material.transmission > 0.0 ) {
  12084. transmissive.unshift( renderItem );
  12085. } else if ( material.transparent === true ) {
  12086. transparent.unshift( renderItem );
  12087. } else {
  12088. opaque.unshift( renderItem );
  12089. }
  12090. }
  12091. function sort( customOpaqueSort, customTransparentSort ) {
  12092. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  12093. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  12094. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  12095. }
  12096. function finish() {
  12097. // Clear references from inactive renderItems in the list
  12098. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  12099. const renderItem = renderItems[ i ];
  12100. if ( renderItem.id === null ) break;
  12101. renderItem.id = null;
  12102. renderItem.object = null;
  12103. renderItem.geometry = null;
  12104. renderItem.material = null;
  12105. renderItem.group = null;
  12106. }
  12107. }
  12108. return {
  12109. opaque: opaque,
  12110. transmissive: transmissive,
  12111. transparent: transparent,
  12112. init: init,
  12113. push: push,
  12114. unshift: unshift,
  12115. finish: finish,
  12116. sort: sort
  12117. };
  12118. }
  12119. function WebGLRenderLists() {
  12120. let lists = new WeakMap();
  12121. function get( scene, renderCallDepth ) {
  12122. const listArray = lists.get( scene );
  12123. let list;
  12124. if ( listArray === undefined ) {
  12125. list = new WebGLRenderList();
  12126. lists.set( scene, [ list ] );
  12127. } else {
  12128. if ( renderCallDepth >= listArray.length ) {
  12129. list = new WebGLRenderList();
  12130. listArray.push( list );
  12131. } else {
  12132. list = listArray[ renderCallDepth ];
  12133. }
  12134. }
  12135. return list;
  12136. }
  12137. function dispose() {
  12138. lists = new WeakMap();
  12139. }
  12140. return {
  12141. get: get,
  12142. dispose: dispose
  12143. };
  12144. }
  12145. function UniformsCache() {
  12146. const lights = {};
  12147. return {
  12148. get: function ( light ) {
  12149. if ( lights[ light.id ] !== undefined ) {
  12150. return lights[ light.id ];
  12151. }
  12152. let uniforms;
  12153. switch ( light.type ) {
  12154. case 'DirectionalLight':
  12155. uniforms = {
  12156. direction: new Vector3(),
  12157. color: new Color()
  12158. };
  12159. break;
  12160. case 'SpotLight':
  12161. uniforms = {
  12162. position: new Vector3(),
  12163. direction: new Vector3(),
  12164. color: new Color(),
  12165. distance: 0,
  12166. coneCos: 0,
  12167. penumbraCos: 0,
  12168. decay: 0
  12169. };
  12170. break;
  12171. case 'PointLight':
  12172. uniforms = {
  12173. position: new Vector3(),
  12174. color: new Color(),
  12175. distance: 0,
  12176. decay: 0
  12177. };
  12178. break;
  12179. case 'HemisphereLight':
  12180. uniforms = {
  12181. direction: new Vector3(),
  12182. skyColor: new Color(),
  12183. groundColor: new Color()
  12184. };
  12185. break;
  12186. case 'RectAreaLight':
  12187. uniforms = {
  12188. color: new Color(),
  12189. position: new Vector3(),
  12190. halfWidth: new Vector3(),
  12191. halfHeight: new Vector3()
  12192. };
  12193. break;
  12194. }
  12195. lights[ light.id ] = uniforms;
  12196. return uniforms;
  12197. }
  12198. };
  12199. }
  12200. function ShadowUniformsCache() {
  12201. const lights = {};
  12202. return {
  12203. get: function ( light ) {
  12204. if ( lights[ light.id ] !== undefined ) {
  12205. return lights[ light.id ];
  12206. }
  12207. let uniforms;
  12208. switch ( light.type ) {
  12209. case 'DirectionalLight':
  12210. uniforms = {
  12211. shadowBias: 0,
  12212. shadowNormalBias: 0,
  12213. shadowRadius: 1,
  12214. shadowMapSize: new Vector2()
  12215. };
  12216. break;
  12217. case 'SpotLight':
  12218. uniforms = {
  12219. shadowBias: 0,
  12220. shadowNormalBias: 0,
  12221. shadowRadius: 1,
  12222. shadowMapSize: new Vector2()
  12223. };
  12224. break;
  12225. case 'PointLight':
  12226. uniforms = {
  12227. shadowBias: 0,
  12228. shadowNormalBias: 0,
  12229. shadowRadius: 1,
  12230. shadowMapSize: new Vector2(),
  12231. shadowCameraNear: 1,
  12232. shadowCameraFar: 1000
  12233. };
  12234. break;
  12235. // TODO (abelnation): set RectAreaLight shadow uniforms
  12236. }
  12237. lights[ light.id ] = uniforms;
  12238. return uniforms;
  12239. }
  12240. };
  12241. }
  12242. let nextVersion = 0;
  12243. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  12244. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  12245. }
  12246. function WebGLLights( extensions, capabilities ) {
  12247. const cache = new UniformsCache();
  12248. const shadowCache = ShadowUniformsCache();
  12249. const state = {
  12250. version: 0,
  12251. hash: {
  12252. directionalLength: - 1,
  12253. pointLength: - 1,
  12254. spotLength: - 1,
  12255. rectAreaLength: - 1,
  12256. hemiLength: - 1,
  12257. numDirectionalShadows: - 1,
  12258. numPointShadows: - 1,
  12259. numSpotShadows: - 1,
  12260. numSpotMaps: - 1
  12261. },
  12262. ambient: [ 0, 0, 0 ],
  12263. probe: [],
  12264. directional: [],
  12265. directionalShadow: [],
  12266. directionalShadowMap: [],
  12267. directionalShadowMatrix: [],
  12268. spot: [],
  12269. spotLightMap: [],
  12270. spotShadow: [],
  12271. spotShadowMap: [],
  12272. spotLightMatrix: [],
  12273. rectArea: [],
  12274. rectAreaLTC1: null,
  12275. rectAreaLTC2: null,
  12276. point: [],
  12277. pointShadow: [],
  12278. pointShadowMap: [],
  12279. pointShadowMatrix: [],
  12280. hemi: [],
  12281. numSpotLightShadowsWithMaps: 0
  12282. };
  12283. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  12284. const vector3 = new Vector3();
  12285. const matrix4 = new Matrix4();
  12286. const matrix42 = new Matrix4();
  12287. function setup( lights, useLegacyLights ) {
  12288. let r = 0, g = 0, b = 0;
  12289. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  12290. let directionalLength = 0;
  12291. let pointLength = 0;
  12292. let spotLength = 0;
  12293. let rectAreaLength = 0;
  12294. let hemiLength = 0;
  12295. let numDirectionalShadows = 0;
  12296. let numPointShadows = 0;
  12297. let numSpotShadows = 0;
  12298. let numSpotMaps = 0;
  12299. let numSpotShadowsWithMaps = 0;
  12300. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  12301. lights.sort( shadowCastingAndTexturingLightsFirst );
  12302. // artist-friendly light intensity scaling factor
  12303. const scaleFactor = ( useLegacyLights === true ) ? Math.PI : 1;
  12304. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12305. const light = lights[ i ];
  12306. const color = light.color;
  12307. const intensity = light.intensity;
  12308. const distance = light.distance;
  12309. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  12310. if ( light.isAmbientLight ) {
  12311. r += color.r * intensity * scaleFactor;
  12312. g += color.g * intensity * scaleFactor;
  12313. b += color.b * intensity * scaleFactor;
  12314. } else if ( light.isLightProbe ) {
  12315. for ( let j = 0; j < 9; j ++ ) {
  12316. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  12317. }
  12318. } else if ( light.isDirectionalLight ) {
  12319. const uniforms = cache.get( light );
  12320. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12321. if ( light.castShadow ) {
  12322. const shadow = light.shadow;
  12323. const shadowUniforms = shadowCache.get( light );
  12324. shadowUniforms.shadowBias = shadow.bias;
  12325. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12326. shadowUniforms.shadowRadius = shadow.radius;
  12327. shadowUniforms.shadowMapSize = shadow.mapSize;
  12328. state.directionalShadow[ directionalLength ] = shadowUniforms;
  12329. state.directionalShadowMap[ directionalLength ] = shadowMap;
  12330. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  12331. numDirectionalShadows ++;
  12332. }
  12333. state.directional[ directionalLength ] = uniforms;
  12334. directionalLength ++;
  12335. } else if ( light.isSpotLight ) {
  12336. const uniforms = cache.get( light );
  12337. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12338. uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor );
  12339. uniforms.distance = distance;
  12340. uniforms.coneCos = Math.cos( light.angle );
  12341. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  12342. uniforms.decay = light.decay;
  12343. state.spot[ spotLength ] = uniforms;
  12344. const shadow = light.shadow;
  12345. if ( light.map ) {
  12346. state.spotLightMap[ numSpotMaps ] = light.map;
  12347. numSpotMaps ++;
  12348. // make sure the lightMatrix is up to date
  12349. // TODO : do it if required only
  12350. shadow.updateMatrices( light );
  12351. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  12352. }
  12353. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  12354. if ( light.castShadow ) {
  12355. const shadowUniforms = shadowCache.get( light );
  12356. shadowUniforms.shadowBias = shadow.bias;
  12357. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12358. shadowUniforms.shadowRadius = shadow.radius;
  12359. shadowUniforms.shadowMapSize = shadow.mapSize;
  12360. state.spotShadow[ spotLength ] = shadowUniforms;
  12361. state.spotShadowMap[ spotLength ] = shadowMap;
  12362. numSpotShadows ++;
  12363. }
  12364. spotLength ++;
  12365. } else if ( light.isRectAreaLight ) {
  12366. const uniforms = cache.get( light );
  12367. uniforms.color.copy( color ).multiplyScalar( intensity );
  12368. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12369. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12370. state.rectArea[ rectAreaLength ] = uniforms;
  12371. rectAreaLength ++;
  12372. } else if ( light.isPointLight ) {
  12373. const uniforms = cache.get( light );
  12374. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12375. uniforms.distance = light.distance;
  12376. uniforms.decay = light.decay;
  12377. if ( light.castShadow ) {
  12378. const shadow = light.shadow;
  12379. const shadowUniforms = shadowCache.get( light );
  12380. shadowUniforms.shadowBias = shadow.bias;
  12381. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12382. shadowUniforms.shadowRadius = shadow.radius;
  12383. shadowUniforms.shadowMapSize = shadow.mapSize;
  12384. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12385. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12386. state.pointShadow[ pointLength ] = shadowUniforms;
  12387. state.pointShadowMap[ pointLength ] = shadowMap;
  12388. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  12389. numPointShadows ++;
  12390. }
  12391. state.point[ pointLength ] = uniforms;
  12392. pointLength ++;
  12393. } else if ( light.isHemisphereLight ) {
  12394. const uniforms = cache.get( light );
  12395. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor );
  12396. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor );
  12397. state.hemi[ hemiLength ] = uniforms;
  12398. hemiLength ++;
  12399. }
  12400. }
  12401. if ( rectAreaLength > 0 ) {
  12402. if ( capabilities.isWebGL2 ) {
  12403. // WebGL 2
  12404. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12405. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12406. } else {
  12407. // WebGL 1
  12408. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  12409. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12410. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12411. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  12412. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12413. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12414. } else {
  12415. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  12416. }
  12417. }
  12418. }
  12419. state.ambient[ 0 ] = r;
  12420. state.ambient[ 1 ] = g;
  12421. state.ambient[ 2 ] = b;
  12422. const hash = state.hash;
  12423. if ( hash.directionalLength !== directionalLength ||
  12424. hash.pointLength !== pointLength ||
  12425. hash.spotLength !== spotLength ||
  12426. hash.rectAreaLength !== rectAreaLength ||
  12427. hash.hemiLength !== hemiLength ||
  12428. hash.numDirectionalShadows !== numDirectionalShadows ||
  12429. hash.numPointShadows !== numPointShadows ||
  12430. hash.numSpotShadows !== numSpotShadows ||
  12431. hash.numSpotMaps !== numSpotMaps ) {
  12432. state.directional.length = directionalLength;
  12433. state.spot.length = spotLength;
  12434. state.rectArea.length = rectAreaLength;
  12435. state.point.length = pointLength;
  12436. state.hemi.length = hemiLength;
  12437. state.directionalShadow.length = numDirectionalShadows;
  12438. state.directionalShadowMap.length = numDirectionalShadows;
  12439. state.pointShadow.length = numPointShadows;
  12440. state.pointShadowMap.length = numPointShadows;
  12441. state.spotShadow.length = numSpotShadows;
  12442. state.spotShadowMap.length = numSpotShadows;
  12443. state.directionalShadowMatrix.length = numDirectionalShadows;
  12444. state.pointShadowMatrix.length = numPointShadows;
  12445. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  12446. state.spotLightMap.length = numSpotMaps;
  12447. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  12448. hash.directionalLength = directionalLength;
  12449. hash.pointLength = pointLength;
  12450. hash.spotLength = spotLength;
  12451. hash.rectAreaLength = rectAreaLength;
  12452. hash.hemiLength = hemiLength;
  12453. hash.numDirectionalShadows = numDirectionalShadows;
  12454. hash.numPointShadows = numPointShadows;
  12455. hash.numSpotShadows = numSpotShadows;
  12456. hash.numSpotMaps = numSpotMaps;
  12457. state.version = nextVersion ++;
  12458. }
  12459. }
  12460. function setupView( lights, camera ) {
  12461. let directionalLength = 0;
  12462. let pointLength = 0;
  12463. let spotLength = 0;
  12464. let rectAreaLength = 0;
  12465. let hemiLength = 0;
  12466. const viewMatrix = camera.matrixWorldInverse;
  12467. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12468. const light = lights[ i ];
  12469. if ( light.isDirectionalLight ) {
  12470. const uniforms = state.directional[ directionalLength ];
  12471. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12472. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12473. uniforms.direction.sub( vector3 );
  12474. uniforms.direction.transformDirection( viewMatrix );
  12475. directionalLength ++;
  12476. } else if ( light.isSpotLight ) {
  12477. const uniforms = state.spot[ spotLength ];
  12478. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12479. uniforms.position.applyMatrix4( viewMatrix );
  12480. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12481. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12482. uniforms.direction.sub( vector3 );
  12483. uniforms.direction.transformDirection( viewMatrix );
  12484. spotLength ++;
  12485. } else if ( light.isRectAreaLight ) {
  12486. const uniforms = state.rectArea[ rectAreaLength ];
  12487. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12488. uniforms.position.applyMatrix4( viewMatrix );
  12489. // extract local rotation of light to derive width/height half vectors
  12490. matrix42.identity();
  12491. matrix4.copy( light.matrixWorld );
  12492. matrix4.premultiply( viewMatrix );
  12493. matrix42.extractRotation( matrix4 );
  12494. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12495. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12496. uniforms.halfWidth.applyMatrix4( matrix42 );
  12497. uniforms.halfHeight.applyMatrix4( matrix42 );
  12498. rectAreaLength ++;
  12499. } else if ( light.isPointLight ) {
  12500. const uniforms = state.point[ pointLength ];
  12501. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12502. uniforms.position.applyMatrix4( viewMatrix );
  12503. pointLength ++;
  12504. } else if ( light.isHemisphereLight ) {
  12505. const uniforms = state.hemi[ hemiLength ];
  12506. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12507. uniforms.direction.transformDirection( viewMatrix );
  12508. hemiLength ++;
  12509. }
  12510. }
  12511. }
  12512. return {
  12513. setup: setup,
  12514. setupView: setupView,
  12515. state: state
  12516. };
  12517. }
  12518. function WebGLRenderState( extensions, capabilities ) {
  12519. const lights = new WebGLLights( extensions, capabilities );
  12520. const lightsArray = [];
  12521. const shadowsArray = [];
  12522. function init() {
  12523. lightsArray.length = 0;
  12524. shadowsArray.length = 0;
  12525. }
  12526. function pushLight( light ) {
  12527. lightsArray.push( light );
  12528. }
  12529. function pushShadow( shadowLight ) {
  12530. shadowsArray.push( shadowLight );
  12531. }
  12532. function setupLights( useLegacyLights ) {
  12533. lights.setup( lightsArray, useLegacyLights );
  12534. }
  12535. function setupLightsView( camera ) {
  12536. lights.setupView( lightsArray, camera );
  12537. }
  12538. const state = {
  12539. lightsArray: lightsArray,
  12540. shadowsArray: shadowsArray,
  12541. lights: lights
  12542. };
  12543. return {
  12544. init: init,
  12545. state: state,
  12546. setupLights: setupLights,
  12547. setupLightsView: setupLightsView,
  12548. pushLight: pushLight,
  12549. pushShadow: pushShadow
  12550. };
  12551. }
  12552. function WebGLRenderStates( extensions, capabilities ) {
  12553. let renderStates = new WeakMap();
  12554. function get( scene, renderCallDepth = 0 ) {
  12555. const renderStateArray = renderStates.get( scene );
  12556. let renderState;
  12557. if ( renderStateArray === undefined ) {
  12558. renderState = new WebGLRenderState( extensions, capabilities );
  12559. renderStates.set( scene, [ renderState ] );
  12560. } else {
  12561. if ( renderCallDepth >= renderStateArray.length ) {
  12562. renderState = new WebGLRenderState( extensions, capabilities );
  12563. renderStateArray.push( renderState );
  12564. } else {
  12565. renderState = renderStateArray[ renderCallDepth ];
  12566. }
  12567. }
  12568. return renderState;
  12569. }
  12570. function dispose() {
  12571. renderStates = new WeakMap();
  12572. }
  12573. return {
  12574. get: get,
  12575. dispose: dispose
  12576. };
  12577. }
  12578. class MeshDepthMaterial extends Material {
  12579. constructor( parameters ) {
  12580. super();
  12581. this.isMeshDepthMaterial = true;
  12582. this.type = 'MeshDepthMaterial';
  12583. this.depthPacking = BasicDepthPacking;
  12584. this.map = null;
  12585. this.alphaMap = null;
  12586. this.displacementMap = null;
  12587. this.displacementScale = 1;
  12588. this.displacementBias = 0;
  12589. this.wireframe = false;
  12590. this.wireframeLinewidth = 1;
  12591. this.setValues( parameters );
  12592. }
  12593. copy( source ) {
  12594. super.copy( source );
  12595. this.depthPacking = source.depthPacking;
  12596. this.map = source.map;
  12597. this.alphaMap = source.alphaMap;
  12598. this.displacementMap = source.displacementMap;
  12599. this.displacementScale = source.displacementScale;
  12600. this.displacementBias = source.displacementBias;
  12601. this.wireframe = source.wireframe;
  12602. this.wireframeLinewidth = source.wireframeLinewidth;
  12603. return this;
  12604. }
  12605. }
  12606. class MeshDistanceMaterial extends Material {
  12607. constructor( parameters ) {
  12608. super();
  12609. this.isMeshDistanceMaterial = true;
  12610. this.type = 'MeshDistanceMaterial';
  12611. this.referencePosition = new Vector3();
  12612. this.nearDistance = 1;
  12613. this.farDistance = 1000;
  12614. this.map = null;
  12615. this.alphaMap = null;
  12616. this.displacementMap = null;
  12617. this.displacementScale = 1;
  12618. this.displacementBias = 0;
  12619. this.setValues( parameters );
  12620. }
  12621. copy( source ) {
  12622. super.copy( source );
  12623. this.referencePosition.copy( source.referencePosition );
  12624. this.nearDistance = source.nearDistance;
  12625. this.farDistance = source.farDistance;
  12626. this.map = source.map;
  12627. this.alphaMap = source.alphaMap;
  12628. this.displacementMap = source.displacementMap;
  12629. this.displacementScale = source.displacementScale;
  12630. this.displacementBias = source.displacementBias;
  12631. return this;
  12632. }
  12633. }
  12634. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12635. 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}";
  12636. function WebGLShadowMap( _renderer, _objects, _capabilities ) {
  12637. let _frustum = new Frustum();
  12638. const _shadowMapSize = new Vector2(),
  12639. _viewportSize = new Vector2(),
  12640. _viewport = new Vector4(),
  12641. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  12642. _distanceMaterial = new MeshDistanceMaterial(),
  12643. _materialCache = {},
  12644. _maxTextureSize = _capabilities.maxTextureSize;
  12645. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  12646. const shadowMaterialVertical = new ShaderMaterial( {
  12647. defines: {
  12648. VSM_SAMPLES: 8
  12649. },
  12650. uniforms: {
  12651. shadow_pass: { value: null },
  12652. resolution: { value: new Vector2() },
  12653. radius: { value: 4.0 }
  12654. },
  12655. vertexShader: vertex,
  12656. fragmentShader: fragment
  12657. } );
  12658. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12659. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12660. const fullScreenTri = new BufferGeometry();
  12661. fullScreenTri.setAttribute(
  12662. 'position',
  12663. new BufferAttribute(
  12664. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  12665. 3
  12666. )
  12667. );
  12668. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  12669. const scope = this;
  12670. this.enabled = false;
  12671. this.autoUpdate = true;
  12672. this.needsUpdate = false;
  12673. this.type = PCFShadowMap;
  12674. this.render = function ( lights, scene, camera ) {
  12675. if ( scope.enabled === false ) return;
  12676. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  12677. if ( lights.length === 0 ) return;
  12678. const currentRenderTarget = _renderer.getRenderTarget();
  12679. const activeCubeFace = _renderer.getActiveCubeFace();
  12680. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12681. const _state = _renderer.state;
  12682. // Set GL state for depth map.
  12683. _state.setBlending( NoBlending );
  12684. _state.buffers.color.setClear( 1, 1, 1, 1 );
  12685. _state.buffers.depth.setTest( true );
  12686. _state.setScissorTest( false );
  12687. // render depth map
  12688. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  12689. const light = lights[ i ];
  12690. const shadow = light.shadow;
  12691. if ( shadow === undefined ) {
  12692. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  12693. continue;
  12694. }
  12695. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  12696. _shadowMapSize.copy( shadow.mapSize );
  12697. const shadowFrameExtents = shadow.getFrameExtents();
  12698. _shadowMapSize.multiply( shadowFrameExtents );
  12699. _viewportSize.copy( shadow.mapSize );
  12700. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  12701. if ( _shadowMapSize.x > _maxTextureSize ) {
  12702. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  12703. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12704. shadow.mapSize.x = _viewportSize.x;
  12705. }
  12706. if ( _shadowMapSize.y > _maxTextureSize ) {
  12707. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  12708. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12709. shadow.mapSize.y = _viewportSize.y;
  12710. }
  12711. }
  12712. if ( shadow.map === null ) {
  12713. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  12714. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12715. shadow.map.texture.name = light.name + '.shadowMap';
  12716. shadow.camera.updateProjectionMatrix();
  12717. }
  12718. _renderer.setRenderTarget( shadow.map );
  12719. _renderer.clear();
  12720. const viewportCount = shadow.getViewportCount();
  12721. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  12722. const viewport = shadow.getViewport( vp );
  12723. _viewport.set(
  12724. _viewportSize.x * viewport.x,
  12725. _viewportSize.y * viewport.y,
  12726. _viewportSize.x * viewport.z,
  12727. _viewportSize.y * viewport.w
  12728. );
  12729. _state.viewport( _viewport );
  12730. shadow.updateMatrices( light, vp );
  12731. _frustum = shadow.getFrustum();
  12732. renderObject( scene, camera, shadow.camera, light, this.type );
  12733. }
  12734. // do blur pass for VSM
  12735. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  12736. VSMPass( shadow, camera );
  12737. }
  12738. shadow.needsUpdate = false;
  12739. }
  12740. scope.needsUpdate = false;
  12741. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  12742. };
  12743. function VSMPass( shadow, camera ) {
  12744. const geometry = _objects.update( fullScreenMesh );
  12745. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  12746. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  12747. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  12748. shadowMaterialVertical.needsUpdate = true;
  12749. shadowMaterialHorizontal.needsUpdate = true;
  12750. }
  12751. if ( shadow.mapPass === null ) {
  12752. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  12753. }
  12754. // vertical pass
  12755. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12756. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12757. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12758. _renderer.setRenderTarget( shadow.mapPass );
  12759. _renderer.clear();
  12760. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  12761. // horizontal pass
  12762. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12763. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  12764. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  12765. _renderer.setRenderTarget( shadow.map );
  12766. _renderer.clear();
  12767. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  12768. }
  12769. function getDepthMaterial( object, material, light, shadowCameraNear, shadowCameraFar, type ) {
  12770. let result = null;
  12771. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  12772. if ( customMaterial !== undefined ) {
  12773. result = customMaterial;
  12774. } else {
  12775. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  12776. if ( ( _renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  12777. ( material.displacementMap && material.displacementScale !== 0 ) ||
  12778. ( material.alphaMap && material.alphaTest > 0 ) ||
  12779. ( material.map && material.alphaTest > 0 ) ) {
  12780. // in this case we need a unique material instance reflecting the
  12781. // appropriate state
  12782. const keyA = result.uuid, keyB = material.uuid;
  12783. let materialsForVariant = _materialCache[ keyA ];
  12784. if ( materialsForVariant === undefined ) {
  12785. materialsForVariant = {};
  12786. _materialCache[ keyA ] = materialsForVariant;
  12787. }
  12788. let cachedMaterial = materialsForVariant[ keyB ];
  12789. if ( cachedMaterial === undefined ) {
  12790. cachedMaterial = result.clone();
  12791. materialsForVariant[ keyB ] = cachedMaterial;
  12792. }
  12793. result = cachedMaterial;
  12794. }
  12795. }
  12796. result.visible = material.visible;
  12797. result.wireframe = material.wireframe;
  12798. if ( type === VSMShadowMap ) {
  12799. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  12800. } else {
  12801. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  12802. }
  12803. result.alphaMap = material.alphaMap;
  12804. result.alphaTest = material.alphaTest;
  12805. result.map = material.map;
  12806. result.clipShadows = material.clipShadows;
  12807. result.clippingPlanes = material.clippingPlanes;
  12808. result.clipIntersection = material.clipIntersection;
  12809. result.displacementMap = material.displacementMap;
  12810. result.displacementScale = material.displacementScale;
  12811. result.displacementBias = material.displacementBias;
  12812. result.wireframeLinewidth = material.wireframeLinewidth;
  12813. result.linewidth = material.linewidth;
  12814. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  12815. result.referencePosition.setFromMatrixPosition( light.matrixWorld );
  12816. result.nearDistance = shadowCameraNear;
  12817. result.farDistance = shadowCameraFar;
  12818. }
  12819. return result;
  12820. }
  12821. function renderObject( object, camera, shadowCamera, light, type ) {
  12822. if ( object.visible === false ) return;
  12823. const visible = object.layers.test( camera.layers );
  12824. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  12825. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  12826. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  12827. const geometry = _objects.update( object );
  12828. const material = object.material;
  12829. if ( Array.isArray( material ) ) {
  12830. const groups = geometry.groups;
  12831. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  12832. const group = groups[ k ];
  12833. const groupMaterial = material[ group.materialIndex ];
  12834. if ( groupMaterial && groupMaterial.visible ) {
  12835. const depthMaterial = getDepthMaterial( object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );
  12836. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  12837. }
  12838. }
  12839. } else if ( material.visible ) {
  12840. const depthMaterial = getDepthMaterial( object, material, light, shadowCamera.near, shadowCamera.far, type );
  12841. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  12842. }
  12843. }
  12844. }
  12845. const children = object.children;
  12846. for ( let i = 0, l = children.length; i < l; i ++ ) {
  12847. renderObject( children[ i ], camera, shadowCamera, light, type );
  12848. }
  12849. }
  12850. }
  12851. function WebGLState( gl, extensions, capabilities ) {
  12852. const isWebGL2 = capabilities.isWebGL2;
  12853. function ColorBuffer() {
  12854. let locked = false;
  12855. const color = new Vector4();
  12856. let currentColorMask = null;
  12857. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  12858. return {
  12859. setMask: function ( colorMask ) {
  12860. if ( currentColorMask !== colorMask && ! locked ) {
  12861. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  12862. currentColorMask = colorMask;
  12863. }
  12864. },
  12865. setLocked: function ( lock ) {
  12866. locked = lock;
  12867. },
  12868. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  12869. if ( premultipliedAlpha === true ) {
  12870. r *= a; g *= a; b *= a;
  12871. }
  12872. color.set( r, g, b, a );
  12873. if ( currentColorClear.equals( color ) === false ) {
  12874. gl.clearColor( r, g, b, a );
  12875. currentColorClear.copy( color );
  12876. }
  12877. },
  12878. reset: function () {
  12879. locked = false;
  12880. currentColorMask = null;
  12881. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  12882. }
  12883. };
  12884. }
  12885. function DepthBuffer() {
  12886. let locked = false;
  12887. let currentDepthMask = null;
  12888. let currentDepthFunc = null;
  12889. let currentDepthClear = null;
  12890. return {
  12891. setTest: function ( depthTest ) {
  12892. if ( depthTest ) {
  12893. enable( 2929 );
  12894. } else {
  12895. disable( 2929 );
  12896. }
  12897. },
  12898. setMask: function ( depthMask ) {
  12899. if ( currentDepthMask !== depthMask && ! locked ) {
  12900. gl.depthMask( depthMask );
  12901. currentDepthMask = depthMask;
  12902. }
  12903. },
  12904. setFunc: function ( depthFunc ) {
  12905. if ( currentDepthFunc !== depthFunc ) {
  12906. switch ( depthFunc ) {
  12907. case NeverDepth:
  12908. gl.depthFunc( 512 );
  12909. break;
  12910. case AlwaysDepth:
  12911. gl.depthFunc( 519 );
  12912. break;
  12913. case LessDepth:
  12914. gl.depthFunc( 513 );
  12915. break;
  12916. case LessEqualDepth:
  12917. gl.depthFunc( 515 );
  12918. break;
  12919. case EqualDepth:
  12920. gl.depthFunc( 514 );
  12921. break;
  12922. case GreaterEqualDepth:
  12923. gl.depthFunc( 518 );
  12924. break;
  12925. case GreaterDepth:
  12926. gl.depthFunc( 516 );
  12927. break;
  12928. case NotEqualDepth:
  12929. gl.depthFunc( 517 );
  12930. break;
  12931. default:
  12932. gl.depthFunc( 515 );
  12933. }
  12934. currentDepthFunc = depthFunc;
  12935. }
  12936. },
  12937. setLocked: function ( lock ) {
  12938. locked = lock;
  12939. },
  12940. setClear: function ( depth ) {
  12941. if ( currentDepthClear !== depth ) {
  12942. gl.clearDepth( depth );
  12943. currentDepthClear = depth;
  12944. }
  12945. },
  12946. reset: function () {
  12947. locked = false;
  12948. currentDepthMask = null;
  12949. currentDepthFunc = null;
  12950. currentDepthClear = null;
  12951. }
  12952. };
  12953. }
  12954. function StencilBuffer() {
  12955. let locked = false;
  12956. let currentStencilMask = null;
  12957. let currentStencilFunc = null;
  12958. let currentStencilRef = null;
  12959. let currentStencilFuncMask = null;
  12960. let currentStencilFail = null;
  12961. let currentStencilZFail = null;
  12962. let currentStencilZPass = null;
  12963. let currentStencilClear = null;
  12964. return {
  12965. setTest: function ( stencilTest ) {
  12966. if ( ! locked ) {
  12967. if ( stencilTest ) {
  12968. enable( 2960 );
  12969. } else {
  12970. disable( 2960 );
  12971. }
  12972. }
  12973. },
  12974. setMask: function ( stencilMask ) {
  12975. if ( currentStencilMask !== stencilMask && ! locked ) {
  12976. gl.stencilMask( stencilMask );
  12977. currentStencilMask = stencilMask;
  12978. }
  12979. },
  12980. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  12981. if ( currentStencilFunc !== stencilFunc ||
  12982. currentStencilRef !== stencilRef ||
  12983. currentStencilFuncMask !== stencilMask ) {
  12984. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  12985. currentStencilFunc = stencilFunc;
  12986. currentStencilRef = stencilRef;
  12987. currentStencilFuncMask = stencilMask;
  12988. }
  12989. },
  12990. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  12991. if ( currentStencilFail !== stencilFail ||
  12992. currentStencilZFail !== stencilZFail ||
  12993. currentStencilZPass !== stencilZPass ) {
  12994. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  12995. currentStencilFail = stencilFail;
  12996. currentStencilZFail = stencilZFail;
  12997. currentStencilZPass = stencilZPass;
  12998. }
  12999. },
  13000. setLocked: function ( lock ) {
  13001. locked = lock;
  13002. },
  13003. setClear: function ( stencil ) {
  13004. if ( currentStencilClear !== stencil ) {
  13005. gl.clearStencil( stencil );
  13006. currentStencilClear = stencil;
  13007. }
  13008. },
  13009. reset: function () {
  13010. locked = false;
  13011. currentStencilMask = null;
  13012. currentStencilFunc = null;
  13013. currentStencilRef = null;
  13014. currentStencilFuncMask = null;
  13015. currentStencilFail = null;
  13016. currentStencilZFail = null;
  13017. currentStencilZPass = null;
  13018. currentStencilClear = null;
  13019. }
  13020. };
  13021. }
  13022. //
  13023. const colorBuffer = new ColorBuffer();
  13024. const depthBuffer = new DepthBuffer();
  13025. const stencilBuffer = new StencilBuffer();
  13026. const uboBindings = new WeakMap();
  13027. const uboProgramMap = new WeakMap();
  13028. let enabledCapabilities = {};
  13029. let currentBoundFramebuffers = {};
  13030. let currentDrawbuffers = new WeakMap();
  13031. let defaultDrawbuffers = [];
  13032. let currentProgram = null;
  13033. let currentBlendingEnabled = false;
  13034. let currentBlending = null;
  13035. let currentBlendEquation = null;
  13036. let currentBlendSrc = null;
  13037. let currentBlendDst = null;
  13038. let currentBlendEquationAlpha = null;
  13039. let currentBlendSrcAlpha = null;
  13040. let currentBlendDstAlpha = null;
  13041. let currentPremultipledAlpha = false;
  13042. let currentFlipSided = null;
  13043. let currentCullFace = null;
  13044. let currentLineWidth = null;
  13045. let currentPolygonOffsetFactor = null;
  13046. let currentPolygonOffsetUnits = null;
  13047. const maxTextures = gl.getParameter( 35661 );
  13048. let lineWidthAvailable = false;
  13049. let version = 0;
  13050. const glVersion = gl.getParameter( 7938 );
  13051. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  13052. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  13053. lineWidthAvailable = ( version >= 1.0 );
  13054. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  13055. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  13056. lineWidthAvailable = ( version >= 2.0 );
  13057. }
  13058. let currentTextureSlot = null;
  13059. let currentBoundTextures = {};
  13060. const scissorParam = gl.getParameter( 3088 );
  13061. const viewportParam = gl.getParameter( 2978 );
  13062. const currentScissor = new Vector4().fromArray( scissorParam );
  13063. const currentViewport = new Vector4().fromArray( viewportParam );
  13064. function createTexture( type, target, count ) {
  13065. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  13066. const texture = gl.createTexture();
  13067. gl.bindTexture( type, texture );
  13068. gl.texParameteri( type, 10241, 9728 );
  13069. gl.texParameteri( type, 10240, 9728 );
  13070. for ( let i = 0; i < count; i ++ ) {
  13071. gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );
  13072. }
  13073. return texture;
  13074. }
  13075. const emptyTextures = {};
  13076. emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
  13077. emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );
  13078. // init
  13079. colorBuffer.setClear( 0, 0, 0, 1 );
  13080. depthBuffer.setClear( 1 );
  13081. stencilBuffer.setClear( 0 );
  13082. enable( 2929 );
  13083. depthBuffer.setFunc( LessEqualDepth );
  13084. setFlipSided( false );
  13085. setCullFace( CullFaceBack );
  13086. enable( 2884 );
  13087. setBlending( NoBlending );
  13088. //
  13089. function enable( id ) {
  13090. if ( enabledCapabilities[ id ] !== true ) {
  13091. gl.enable( id );
  13092. enabledCapabilities[ id ] = true;
  13093. }
  13094. }
  13095. function disable( id ) {
  13096. if ( enabledCapabilities[ id ] !== false ) {
  13097. gl.disable( id );
  13098. enabledCapabilities[ id ] = false;
  13099. }
  13100. }
  13101. function bindFramebuffer( target, framebuffer ) {
  13102. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  13103. gl.bindFramebuffer( target, framebuffer );
  13104. currentBoundFramebuffers[ target ] = framebuffer;
  13105. if ( isWebGL2 ) {
  13106. // 36009 is equivalent to 36160
  13107. if ( target === 36009 ) {
  13108. currentBoundFramebuffers[ 36160 ] = framebuffer;
  13109. }
  13110. if ( target === 36160 ) {
  13111. currentBoundFramebuffers[ 36009 ] = framebuffer;
  13112. }
  13113. }
  13114. return true;
  13115. }
  13116. return false;
  13117. }
  13118. function drawBuffers( renderTarget, framebuffer ) {
  13119. let drawBuffers = defaultDrawbuffers;
  13120. let needsUpdate = false;
  13121. if ( renderTarget ) {
  13122. drawBuffers = currentDrawbuffers.get( framebuffer );
  13123. if ( drawBuffers === undefined ) {
  13124. drawBuffers = [];
  13125. currentDrawbuffers.set( framebuffer, drawBuffers );
  13126. }
  13127. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13128. const textures = renderTarget.texture;
  13129. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== 36064 ) {
  13130. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13131. drawBuffers[ i ] = 36064 + i;
  13132. }
  13133. drawBuffers.length = textures.length;
  13134. needsUpdate = true;
  13135. }
  13136. } else {
  13137. if ( drawBuffers[ 0 ] !== 36064 ) {
  13138. drawBuffers[ 0 ] = 36064;
  13139. needsUpdate = true;
  13140. }
  13141. }
  13142. } else {
  13143. if ( drawBuffers[ 0 ] !== 1029 ) {
  13144. drawBuffers[ 0 ] = 1029;
  13145. needsUpdate = true;
  13146. }
  13147. }
  13148. if ( needsUpdate ) {
  13149. if ( capabilities.isWebGL2 ) {
  13150. gl.drawBuffers( drawBuffers );
  13151. } else {
  13152. extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers );
  13153. }
  13154. }
  13155. }
  13156. function useProgram( program ) {
  13157. if ( currentProgram !== program ) {
  13158. gl.useProgram( program );
  13159. currentProgram = program;
  13160. return true;
  13161. }
  13162. return false;
  13163. }
  13164. const equationToGL = {
  13165. [ AddEquation ]: 32774,
  13166. [ SubtractEquation ]: 32778,
  13167. [ ReverseSubtractEquation ]: 32779
  13168. };
  13169. if ( isWebGL2 ) {
  13170. equationToGL[ MinEquation ] = 32775;
  13171. equationToGL[ MaxEquation ] = 32776;
  13172. } else {
  13173. const extension = extensions.get( 'EXT_blend_minmax' );
  13174. if ( extension !== null ) {
  13175. equationToGL[ MinEquation ] = extension.MIN_EXT;
  13176. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  13177. }
  13178. }
  13179. const factorToGL = {
  13180. [ ZeroFactor ]: 0,
  13181. [ OneFactor ]: 1,
  13182. [ SrcColorFactor ]: 768,
  13183. [ SrcAlphaFactor ]: 770,
  13184. [ SrcAlphaSaturateFactor ]: 776,
  13185. [ DstColorFactor ]: 774,
  13186. [ DstAlphaFactor ]: 772,
  13187. [ OneMinusSrcColorFactor ]: 769,
  13188. [ OneMinusSrcAlphaFactor ]: 771,
  13189. [ OneMinusDstColorFactor ]: 775,
  13190. [ OneMinusDstAlphaFactor ]: 773
  13191. };
  13192. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  13193. if ( blending === NoBlending ) {
  13194. if ( currentBlendingEnabled === true ) {
  13195. disable( 3042 );
  13196. currentBlendingEnabled = false;
  13197. }
  13198. return;
  13199. }
  13200. if ( currentBlendingEnabled === false ) {
  13201. enable( 3042 );
  13202. currentBlendingEnabled = true;
  13203. }
  13204. if ( blending !== CustomBlending ) {
  13205. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  13206. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  13207. gl.blendEquation( 32774 );
  13208. currentBlendEquation = AddEquation;
  13209. currentBlendEquationAlpha = AddEquation;
  13210. }
  13211. if ( premultipliedAlpha ) {
  13212. switch ( blending ) {
  13213. case NormalBlending:
  13214. gl.blendFuncSeparate( 1, 771, 1, 771 );
  13215. break;
  13216. case AdditiveBlending:
  13217. gl.blendFunc( 1, 1 );
  13218. break;
  13219. case SubtractiveBlending:
  13220. gl.blendFuncSeparate( 0, 769, 0, 1 );
  13221. break;
  13222. case MultiplyBlending:
  13223. gl.blendFuncSeparate( 0, 768, 0, 770 );
  13224. break;
  13225. default:
  13226. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13227. break;
  13228. }
  13229. } else {
  13230. switch ( blending ) {
  13231. case NormalBlending:
  13232. gl.blendFuncSeparate( 770, 771, 1, 771 );
  13233. break;
  13234. case AdditiveBlending:
  13235. gl.blendFunc( 770, 1 );
  13236. break;
  13237. case SubtractiveBlending:
  13238. gl.blendFuncSeparate( 0, 769, 0, 1 );
  13239. break;
  13240. case MultiplyBlending:
  13241. gl.blendFunc( 0, 768 );
  13242. break;
  13243. default:
  13244. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13245. break;
  13246. }
  13247. }
  13248. currentBlendSrc = null;
  13249. currentBlendDst = null;
  13250. currentBlendSrcAlpha = null;
  13251. currentBlendDstAlpha = null;
  13252. currentBlending = blending;
  13253. currentPremultipledAlpha = premultipliedAlpha;
  13254. }
  13255. return;
  13256. }
  13257. // custom blending
  13258. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13259. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13260. blendDstAlpha = blendDstAlpha || blendDst;
  13261. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  13262. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  13263. currentBlendEquation = blendEquation;
  13264. currentBlendEquationAlpha = blendEquationAlpha;
  13265. }
  13266. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  13267. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  13268. currentBlendSrc = blendSrc;
  13269. currentBlendDst = blendDst;
  13270. currentBlendSrcAlpha = blendSrcAlpha;
  13271. currentBlendDstAlpha = blendDstAlpha;
  13272. }
  13273. currentBlending = blending;
  13274. currentPremultipledAlpha = false;
  13275. }
  13276. function setMaterial( material, frontFaceCW ) {
  13277. material.side === DoubleSide
  13278. ? disable( 2884 )
  13279. : enable( 2884 );
  13280. let flipSided = ( material.side === BackSide );
  13281. if ( frontFaceCW ) flipSided = ! flipSided;
  13282. setFlipSided( flipSided );
  13283. ( material.blending === NormalBlending && material.transparent === false )
  13284. ? setBlending( NoBlending )
  13285. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  13286. depthBuffer.setFunc( material.depthFunc );
  13287. depthBuffer.setTest( material.depthTest );
  13288. depthBuffer.setMask( material.depthWrite );
  13289. colorBuffer.setMask( material.colorWrite );
  13290. const stencilWrite = material.stencilWrite;
  13291. stencilBuffer.setTest( stencilWrite );
  13292. if ( stencilWrite ) {
  13293. stencilBuffer.setMask( material.stencilWriteMask );
  13294. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  13295. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  13296. }
  13297. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13298. material.alphaToCoverage === true
  13299. ? enable( 32926 )
  13300. : disable( 32926 );
  13301. }
  13302. //
  13303. function setFlipSided( flipSided ) {
  13304. if ( currentFlipSided !== flipSided ) {
  13305. if ( flipSided ) {
  13306. gl.frontFace( 2304 );
  13307. } else {
  13308. gl.frontFace( 2305 );
  13309. }
  13310. currentFlipSided = flipSided;
  13311. }
  13312. }
  13313. function setCullFace( cullFace ) {
  13314. if ( cullFace !== CullFaceNone ) {
  13315. enable( 2884 );
  13316. if ( cullFace !== currentCullFace ) {
  13317. if ( cullFace === CullFaceBack ) {
  13318. gl.cullFace( 1029 );
  13319. } else if ( cullFace === CullFaceFront ) {
  13320. gl.cullFace( 1028 );
  13321. } else {
  13322. gl.cullFace( 1032 );
  13323. }
  13324. }
  13325. } else {
  13326. disable( 2884 );
  13327. }
  13328. currentCullFace = cullFace;
  13329. }
  13330. function setLineWidth( width ) {
  13331. if ( width !== currentLineWidth ) {
  13332. if ( lineWidthAvailable ) gl.lineWidth( width );
  13333. currentLineWidth = width;
  13334. }
  13335. }
  13336. function setPolygonOffset( polygonOffset, factor, units ) {
  13337. if ( polygonOffset ) {
  13338. enable( 32823 );
  13339. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  13340. gl.polygonOffset( factor, units );
  13341. currentPolygonOffsetFactor = factor;
  13342. currentPolygonOffsetUnits = units;
  13343. }
  13344. } else {
  13345. disable( 32823 );
  13346. }
  13347. }
  13348. function setScissorTest( scissorTest ) {
  13349. if ( scissorTest ) {
  13350. enable( 3089 );
  13351. } else {
  13352. disable( 3089 );
  13353. }
  13354. }
  13355. // texture
  13356. function activeTexture( webglSlot ) {
  13357. if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1;
  13358. if ( currentTextureSlot !== webglSlot ) {
  13359. gl.activeTexture( webglSlot );
  13360. currentTextureSlot = webglSlot;
  13361. }
  13362. }
  13363. function bindTexture( webglType, webglTexture, webglSlot ) {
  13364. if ( webglSlot === undefined ) {
  13365. if ( currentTextureSlot === null ) {
  13366. webglSlot = 33984 + maxTextures - 1;
  13367. } else {
  13368. webglSlot = currentTextureSlot;
  13369. }
  13370. }
  13371. let boundTexture = currentBoundTextures[ webglSlot ];
  13372. if ( boundTexture === undefined ) {
  13373. boundTexture = { type: undefined, texture: undefined };
  13374. currentBoundTextures[ webglSlot ] = boundTexture;
  13375. }
  13376. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  13377. if ( currentTextureSlot !== webglSlot ) {
  13378. gl.activeTexture( webglSlot );
  13379. currentTextureSlot = webglSlot;
  13380. }
  13381. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  13382. boundTexture.type = webglType;
  13383. boundTexture.texture = webglTexture;
  13384. }
  13385. }
  13386. function unbindTexture() {
  13387. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  13388. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  13389. gl.bindTexture( boundTexture.type, null );
  13390. boundTexture.type = undefined;
  13391. boundTexture.texture = undefined;
  13392. }
  13393. }
  13394. function compressedTexImage2D() {
  13395. try {
  13396. gl.compressedTexImage2D.apply( gl, arguments );
  13397. } catch ( error ) {
  13398. console.error( 'THREE.WebGLState:', error );
  13399. }
  13400. }
  13401. function compressedTexImage3D() {
  13402. try {
  13403. gl.compressedTexImage3D.apply( gl, arguments );
  13404. } catch ( error ) {
  13405. console.error( 'THREE.WebGLState:', error );
  13406. }
  13407. }
  13408. function texSubImage2D() {
  13409. try {
  13410. gl.texSubImage2D.apply( gl, arguments );
  13411. } catch ( error ) {
  13412. console.error( 'THREE.WebGLState:', error );
  13413. }
  13414. }
  13415. function texSubImage3D() {
  13416. try {
  13417. gl.texSubImage3D.apply( gl, arguments );
  13418. } catch ( error ) {
  13419. console.error( 'THREE.WebGLState:', error );
  13420. }
  13421. }
  13422. function compressedTexSubImage2D() {
  13423. try {
  13424. gl.compressedTexSubImage2D.apply( gl, arguments );
  13425. } catch ( error ) {
  13426. console.error( 'THREE.WebGLState:', error );
  13427. }
  13428. }
  13429. function compressedTexSubImage3D() {
  13430. try {
  13431. gl.compressedTexSubImage3D.apply( gl, arguments );
  13432. } catch ( error ) {
  13433. console.error( 'THREE.WebGLState:', error );
  13434. }
  13435. }
  13436. function texStorage2D() {
  13437. try {
  13438. gl.texStorage2D.apply( gl, arguments );
  13439. } catch ( error ) {
  13440. console.error( 'THREE.WebGLState:', error );
  13441. }
  13442. }
  13443. function texStorage3D() {
  13444. try {
  13445. gl.texStorage3D.apply( gl, arguments );
  13446. } catch ( error ) {
  13447. console.error( 'THREE.WebGLState:', error );
  13448. }
  13449. }
  13450. function texImage2D() {
  13451. try {
  13452. gl.texImage2D.apply( gl, arguments );
  13453. } catch ( error ) {
  13454. console.error( 'THREE.WebGLState:', error );
  13455. }
  13456. }
  13457. function texImage3D() {
  13458. try {
  13459. gl.texImage3D.apply( gl, arguments );
  13460. } catch ( error ) {
  13461. console.error( 'THREE.WebGLState:', error );
  13462. }
  13463. }
  13464. //
  13465. function scissor( scissor ) {
  13466. if ( currentScissor.equals( scissor ) === false ) {
  13467. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  13468. currentScissor.copy( scissor );
  13469. }
  13470. }
  13471. function viewport( viewport ) {
  13472. if ( currentViewport.equals( viewport ) === false ) {
  13473. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  13474. currentViewport.copy( viewport );
  13475. }
  13476. }
  13477. function updateUBOMapping( uniformsGroup, program ) {
  13478. let mapping = uboProgramMap.get( program );
  13479. if ( mapping === undefined ) {
  13480. mapping = new WeakMap();
  13481. uboProgramMap.set( program, mapping );
  13482. }
  13483. let blockIndex = mapping.get( uniformsGroup );
  13484. if ( blockIndex === undefined ) {
  13485. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  13486. mapping.set( uniformsGroup, blockIndex );
  13487. }
  13488. }
  13489. function uniformBlockBinding( uniformsGroup, program ) {
  13490. const mapping = uboProgramMap.get( program );
  13491. const blockIndex = mapping.get( uniformsGroup );
  13492. if ( uboBindings.get( program ) !== blockIndex ) {
  13493. // bind shader specific block index to global block point
  13494. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  13495. uboBindings.set( program, blockIndex );
  13496. }
  13497. }
  13498. //
  13499. function reset() {
  13500. // reset state
  13501. gl.disable( 3042 );
  13502. gl.disable( 2884 );
  13503. gl.disable( 2929 );
  13504. gl.disable( 32823 );
  13505. gl.disable( 3089 );
  13506. gl.disable( 2960 );
  13507. gl.disable( 32926 );
  13508. gl.blendEquation( 32774 );
  13509. gl.blendFunc( 1, 0 );
  13510. gl.blendFuncSeparate( 1, 0, 1, 0 );
  13511. gl.colorMask( true, true, true, true );
  13512. gl.clearColor( 0, 0, 0, 0 );
  13513. gl.depthMask( true );
  13514. gl.depthFunc( 513 );
  13515. gl.clearDepth( 1 );
  13516. gl.stencilMask( 0xffffffff );
  13517. gl.stencilFunc( 519, 0, 0xffffffff );
  13518. gl.stencilOp( 7680, 7680, 7680 );
  13519. gl.clearStencil( 0 );
  13520. gl.cullFace( 1029 );
  13521. gl.frontFace( 2305 );
  13522. gl.polygonOffset( 0, 0 );
  13523. gl.activeTexture( 33984 );
  13524. gl.bindFramebuffer( 36160, null );
  13525. if ( isWebGL2 === true ) {
  13526. gl.bindFramebuffer( 36009, null );
  13527. gl.bindFramebuffer( 36008, null );
  13528. }
  13529. gl.useProgram( null );
  13530. gl.lineWidth( 1 );
  13531. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  13532. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  13533. // reset internals
  13534. enabledCapabilities = {};
  13535. currentTextureSlot = null;
  13536. currentBoundTextures = {};
  13537. currentBoundFramebuffers = {};
  13538. currentDrawbuffers = new WeakMap();
  13539. defaultDrawbuffers = [];
  13540. currentProgram = null;
  13541. currentBlendingEnabled = false;
  13542. currentBlending = null;
  13543. currentBlendEquation = null;
  13544. currentBlendSrc = null;
  13545. currentBlendDst = null;
  13546. currentBlendEquationAlpha = null;
  13547. currentBlendSrcAlpha = null;
  13548. currentBlendDstAlpha = null;
  13549. currentPremultipledAlpha = false;
  13550. currentFlipSided = null;
  13551. currentCullFace = null;
  13552. currentLineWidth = null;
  13553. currentPolygonOffsetFactor = null;
  13554. currentPolygonOffsetUnits = null;
  13555. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13556. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13557. colorBuffer.reset();
  13558. depthBuffer.reset();
  13559. stencilBuffer.reset();
  13560. }
  13561. return {
  13562. buffers: {
  13563. color: colorBuffer,
  13564. depth: depthBuffer,
  13565. stencil: stencilBuffer
  13566. },
  13567. enable: enable,
  13568. disable: disable,
  13569. bindFramebuffer: bindFramebuffer,
  13570. drawBuffers: drawBuffers,
  13571. useProgram: useProgram,
  13572. setBlending: setBlending,
  13573. setMaterial: setMaterial,
  13574. setFlipSided: setFlipSided,
  13575. setCullFace: setCullFace,
  13576. setLineWidth: setLineWidth,
  13577. setPolygonOffset: setPolygonOffset,
  13578. setScissorTest: setScissorTest,
  13579. activeTexture: activeTexture,
  13580. bindTexture: bindTexture,
  13581. unbindTexture: unbindTexture,
  13582. compressedTexImage2D: compressedTexImage2D,
  13583. compressedTexImage3D: compressedTexImage3D,
  13584. texImage2D: texImage2D,
  13585. texImage3D: texImage3D,
  13586. updateUBOMapping: updateUBOMapping,
  13587. uniformBlockBinding: uniformBlockBinding,
  13588. texStorage2D: texStorage2D,
  13589. texStorage3D: texStorage3D,
  13590. texSubImage2D: texSubImage2D,
  13591. texSubImage3D: texSubImage3D,
  13592. compressedTexSubImage2D: compressedTexSubImage2D,
  13593. compressedTexSubImage3D: compressedTexSubImage3D,
  13594. scissor: scissor,
  13595. viewport: viewport,
  13596. reset: reset
  13597. };
  13598. }
  13599. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  13600. const isWebGL2 = capabilities.isWebGL2;
  13601. const maxTextures = capabilities.maxTextures;
  13602. const maxCubemapSize = capabilities.maxCubemapSize;
  13603. const maxTextureSize = capabilities.maxTextureSize;
  13604. const maxSamples = capabilities.maxSamples;
  13605. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  13606. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  13607. const _videoTextures = new WeakMap();
  13608. let _canvas;
  13609. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  13610. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13611. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13612. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13613. let useOffscreenCanvas = false;
  13614. try {
  13615. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  13616. // eslint-disable-next-line compat/compat
  13617. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  13618. } catch ( err ) {
  13619. // Ignore any errors
  13620. }
  13621. function createCanvas( width, height ) {
  13622. // Use OffscreenCanvas when available. Specially needed in web workers
  13623. return useOffscreenCanvas ?
  13624. // eslint-disable-next-line compat/compat
  13625. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  13626. }
  13627. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  13628. let scale = 1;
  13629. // handle case if texture exceeds max size
  13630. if ( image.width > maxSize || image.height > maxSize ) {
  13631. scale = maxSize / Math.max( image.width, image.height );
  13632. }
  13633. // only perform resize if necessary
  13634. if ( scale < 1 || needsPowerOfTwo === true ) {
  13635. // only perform resize for certain image types
  13636. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  13637. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  13638. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  13639. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13640. const width = floor( scale * image.width );
  13641. const height = floor( scale * image.height );
  13642. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  13643. // cube textures can't reuse the same canvas
  13644. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  13645. canvas.width = width;
  13646. canvas.height = height;
  13647. const context = canvas.getContext( '2d' );
  13648. context.drawImage( image, 0, 0, width, height );
  13649. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  13650. return canvas;
  13651. } else {
  13652. if ( 'data' in image ) {
  13653. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  13654. }
  13655. return image;
  13656. }
  13657. }
  13658. return image;
  13659. }
  13660. function isPowerOfTwo$1( image ) {
  13661. return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height );
  13662. }
  13663. function textureNeedsPowerOfTwo( texture ) {
  13664. if ( isWebGL2 ) return false;
  13665. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  13666. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  13667. }
  13668. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  13669. return texture.generateMipmaps && supportsMips &&
  13670. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13671. }
  13672. function generateMipmap( target ) {
  13673. _gl.generateMipmap( target );
  13674. }
  13675. function getInternalFormat( internalFormatName, glFormat, glType, encoding, forceLinearEncoding = false ) {
  13676. if ( isWebGL2 === false ) return glFormat;
  13677. if ( internalFormatName !== null ) {
  13678. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  13679. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  13680. }
  13681. let internalFormat = glFormat;
  13682. if ( glFormat === 6403 ) {
  13683. if ( glType === 5126 ) internalFormat = 33326;
  13684. if ( glType === 5131 ) internalFormat = 33325;
  13685. if ( glType === 5121 ) internalFormat = 33321;
  13686. }
  13687. if ( glFormat === 33319 ) {
  13688. if ( glType === 5126 ) internalFormat = 33328;
  13689. if ( glType === 5131 ) internalFormat = 33327;
  13690. if ( glType === 5121 ) internalFormat = 33323;
  13691. }
  13692. if ( glFormat === 6408 ) {
  13693. if ( glType === 5126 ) internalFormat = 34836;
  13694. if ( glType === 5131 ) internalFormat = 34842;
  13695. if ( glType === 5121 ) internalFormat = ( encoding === sRGBEncoding && forceLinearEncoding === false ) ? 35907 : 32856;
  13696. if ( glType === 32819 ) internalFormat = 32854;
  13697. if ( glType === 32820 ) internalFormat = 32855;
  13698. }
  13699. if ( internalFormat === 33325 || internalFormat === 33326 ||
  13700. internalFormat === 33327 || internalFormat === 33328 ||
  13701. internalFormat === 34842 || internalFormat === 34836 ) {
  13702. extensions.get( 'EXT_color_buffer_float' );
  13703. }
  13704. return internalFormat;
  13705. }
  13706. function getMipLevels( texture, image, supportsMips ) {
  13707. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  13708. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  13709. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  13710. // user-defined mipmaps
  13711. return texture.mipmaps.length;
  13712. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  13713. return image.mipmaps.length;
  13714. } else {
  13715. // texture without mipmaps (only base level)
  13716. return 1;
  13717. }
  13718. }
  13719. // Fallback filters for non-power-of-2 textures
  13720. function filterFallback( f ) {
  13721. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  13722. return 9728;
  13723. }
  13724. return 9729;
  13725. }
  13726. //
  13727. function onTextureDispose( event ) {
  13728. const texture = event.target;
  13729. texture.removeEventListener( 'dispose', onTextureDispose );
  13730. deallocateTexture( texture );
  13731. if ( texture.isVideoTexture ) {
  13732. _videoTextures.delete( texture );
  13733. }
  13734. }
  13735. function onRenderTargetDispose( event ) {
  13736. const renderTarget = event.target;
  13737. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  13738. deallocateRenderTarget( renderTarget );
  13739. }
  13740. //
  13741. function deallocateTexture( texture ) {
  13742. const textureProperties = properties.get( texture );
  13743. if ( textureProperties.__webglInit === undefined ) return;
  13744. // check if it's necessary to remove the WebGLTexture object
  13745. const source = texture.source;
  13746. const webglTextures = _sources.get( source );
  13747. if ( webglTextures ) {
  13748. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  13749. webglTexture.usedTimes --;
  13750. // the WebGLTexture object is not used anymore, remove it
  13751. if ( webglTexture.usedTimes === 0 ) {
  13752. deleteTexture( texture );
  13753. }
  13754. // remove the weak map entry if no WebGLTexture uses the source anymore
  13755. if ( Object.keys( webglTextures ).length === 0 ) {
  13756. _sources.delete( source );
  13757. }
  13758. }
  13759. properties.remove( texture );
  13760. }
  13761. function deleteTexture( texture ) {
  13762. const textureProperties = properties.get( texture );
  13763. _gl.deleteTexture( textureProperties.__webglTexture );
  13764. const source = texture.source;
  13765. const webglTextures = _sources.get( source );
  13766. delete webglTextures[ textureProperties.__cacheKey ];
  13767. info.memory.textures --;
  13768. }
  13769. function deallocateRenderTarget( renderTarget ) {
  13770. const texture = renderTarget.texture;
  13771. const renderTargetProperties = properties.get( renderTarget );
  13772. const textureProperties = properties.get( texture );
  13773. if ( textureProperties.__webglTexture !== undefined ) {
  13774. _gl.deleteTexture( textureProperties.__webglTexture );
  13775. info.memory.textures --;
  13776. }
  13777. if ( renderTarget.depthTexture ) {
  13778. renderTarget.depthTexture.dispose();
  13779. }
  13780. if ( renderTarget.isWebGLCubeRenderTarget ) {
  13781. for ( let i = 0; i < 6; i ++ ) {
  13782. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  13783. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  13784. }
  13785. } else {
  13786. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  13787. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  13788. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  13789. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  13790. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  13791. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  13792. }
  13793. }
  13794. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  13795. }
  13796. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13797. for ( let i = 0, il = texture.length; i < il; i ++ ) {
  13798. const attachmentProperties = properties.get( texture[ i ] );
  13799. if ( attachmentProperties.__webglTexture ) {
  13800. _gl.deleteTexture( attachmentProperties.__webglTexture );
  13801. info.memory.textures --;
  13802. }
  13803. properties.remove( texture[ i ] );
  13804. }
  13805. }
  13806. properties.remove( texture );
  13807. properties.remove( renderTarget );
  13808. }
  13809. //
  13810. let textureUnits = 0;
  13811. function resetTextureUnits() {
  13812. textureUnits = 0;
  13813. }
  13814. function allocateTextureUnit() {
  13815. const textureUnit = textureUnits;
  13816. if ( textureUnit >= maxTextures ) {
  13817. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  13818. }
  13819. textureUnits += 1;
  13820. return textureUnit;
  13821. }
  13822. function getTextureCacheKey( texture ) {
  13823. const array = [];
  13824. array.push( texture.wrapS );
  13825. array.push( texture.wrapT );
  13826. array.push( texture.wrapR || 0 );
  13827. array.push( texture.magFilter );
  13828. array.push( texture.minFilter );
  13829. array.push( texture.anisotropy );
  13830. array.push( texture.internalFormat );
  13831. array.push( texture.format );
  13832. array.push( texture.type );
  13833. array.push( texture.generateMipmaps );
  13834. array.push( texture.premultiplyAlpha );
  13835. array.push( texture.flipY );
  13836. array.push( texture.unpackAlignment );
  13837. array.push( texture.encoding );
  13838. return array.join();
  13839. }
  13840. //
  13841. function setTexture2D( texture, slot ) {
  13842. const textureProperties = properties.get( texture );
  13843. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  13844. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  13845. const image = texture.image;
  13846. if ( image === null ) {
  13847. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  13848. } else if ( image.complete === false ) {
  13849. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  13850. } else {
  13851. uploadTexture( textureProperties, texture, slot );
  13852. return;
  13853. }
  13854. }
  13855. state.bindTexture( 3553, textureProperties.__webglTexture, 33984 + slot );
  13856. }
  13857. function setTexture2DArray( texture, slot ) {
  13858. const textureProperties = properties.get( texture );
  13859. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13860. uploadTexture( textureProperties, texture, slot );
  13861. return;
  13862. }
  13863. state.bindTexture( 35866, textureProperties.__webglTexture, 33984 + slot );
  13864. }
  13865. function setTexture3D( texture, slot ) {
  13866. const textureProperties = properties.get( texture );
  13867. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13868. uploadTexture( textureProperties, texture, slot );
  13869. return;
  13870. }
  13871. state.bindTexture( 32879, textureProperties.__webglTexture, 33984 + slot );
  13872. }
  13873. function setTextureCube( texture, slot ) {
  13874. const textureProperties = properties.get( texture );
  13875. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13876. uploadCubeTexture( textureProperties, texture, slot );
  13877. return;
  13878. }
  13879. state.bindTexture( 34067, textureProperties.__webglTexture, 33984 + slot );
  13880. }
  13881. const wrappingToGL = {
  13882. [ RepeatWrapping ]: 10497,
  13883. [ ClampToEdgeWrapping ]: 33071,
  13884. [ MirroredRepeatWrapping ]: 33648
  13885. };
  13886. const filterToGL = {
  13887. [ NearestFilter ]: 9728,
  13888. [ NearestMipmapNearestFilter ]: 9984,
  13889. [ NearestMipmapLinearFilter ]: 9986,
  13890. [ LinearFilter ]: 9729,
  13891. [ LinearMipmapNearestFilter ]: 9985,
  13892. [ LinearMipmapLinearFilter ]: 9987
  13893. };
  13894. function setTextureParameters( textureType, texture, supportsMips ) {
  13895. if ( supportsMips ) {
  13896. _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] );
  13897. _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] );
  13898. if ( textureType === 32879 || textureType === 35866 ) {
  13899. _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] );
  13900. }
  13901. _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] );
  13902. _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] );
  13903. } else {
  13904. _gl.texParameteri( textureType, 10242, 33071 );
  13905. _gl.texParameteri( textureType, 10243, 33071 );
  13906. if ( textureType === 32879 || textureType === 35866 ) {
  13907. _gl.texParameteri( textureType, 32882, 33071 );
  13908. }
  13909. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  13910. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  13911. }
  13912. _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
  13913. _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );
  13914. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  13915. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  13916. }
  13917. }
  13918. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  13919. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  13920. if ( texture.magFilter === NearestFilter ) return;
  13921. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  13922. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  13923. if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only
  13924. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  13925. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  13926. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  13927. }
  13928. }
  13929. }
  13930. function initTexture( textureProperties, texture ) {
  13931. let forceUpload = false;
  13932. if ( textureProperties.__webglInit === undefined ) {
  13933. textureProperties.__webglInit = true;
  13934. texture.addEventListener( 'dispose', onTextureDispose );
  13935. }
  13936. // create Source <-> WebGLTextures mapping if necessary
  13937. const source = texture.source;
  13938. let webglTextures = _sources.get( source );
  13939. if ( webglTextures === undefined ) {
  13940. webglTextures = {};
  13941. _sources.set( source, webglTextures );
  13942. }
  13943. // check if there is already a WebGLTexture object for the given texture parameters
  13944. const textureCacheKey = getTextureCacheKey( texture );
  13945. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  13946. // if not, create a new instance of WebGLTexture
  13947. if ( webglTextures[ textureCacheKey ] === undefined ) {
  13948. // create new entry
  13949. webglTextures[ textureCacheKey ] = {
  13950. texture: _gl.createTexture(),
  13951. usedTimes: 0
  13952. };
  13953. info.memory.textures ++;
  13954. // when a new instance of WebGLTexture was created, a texture upload is required
  13955. // even if the image contents are identical
  13956. forceUpload = true;
  13957. }
  13958. webglTextures[ textureCacheKey ].usedTimes ++;
  13959. // every time the texture cache key changes, it's necessary to check if an instance of
  13960. // WebGLTexture can be deleted in order to avoid a memory leak.
  13961. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  13962. if ( webglTexture !== undefined ) {
  13963. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  13964. if ( webglTexture.usedTimes === 0 ) {
  13965. deleteTexture( texture );
  13966. }
  13967. }
  13968. // store references to cache key and WebGLTexture object
  13969. textureProperties.__cacheKey = textureCacheKey;
  13970. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  13971. }
  13972. return forceUpload;
  13973. }
  13974. function uploadTexture( textureProperties, texture, slot ) {
  13975. let textureType = 3553;
  13976. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = 35866;
  13977. if ( texture.isData3DTexture ) textureType = 32879;
  13978. const forceUpload = initTexture( textureProperties, texture );
  13979. const source = texture.source;
  13980. state.bindTexture( textureType, textureProperties.__webglTexture, 33984 + slot );
  13981. const sourceProperties = properties.get( source );
  13982. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  13983. state.activeTexture( 33984 + slot );
  13984. _gl.pixelStorei( 37440, texture.flipY );
  13985. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  13986. _gl.pixelStorei( 3317, texture.unpackAlignment );
  13987. _gl.pixelStorei( 37443, 0 );
  13988. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false;
  13989. let image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  13990. image = verifyColorSpace( texture, image );
  13991. const supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  13992. glFormat = utils.convert( texture.format, texture.encoding );
  13993. let glType = utils.convert( texture.type ),
  13994. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture );
  13995. setTextureParameters( textureType, texture, supportsMips );
  13996. let mipmap;
  13997. const mipmaps = texture.mipmaps;
  13998. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  13999. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14000. const levels = getMipLevels( texture, image, supportsMips );
  14001. if ( texture.isDepthTexture ) {
  14002. // populate depth texture with dummy data
  14003. glInternalFormat = 6402;
  14004. if ( isWebGL2 ) {
  14005. if ( texture.type === FloatType ) {
  14006. glInternalFormat = 36012;
  14007. } else if ( texture.type === UnsignedIntType ) {
  14008. glInternalFormat = 33190;
  14009. } else if ( texture.type === UnsignedInt248Type ) {
  14010. glInternalFormat = 35056;
  14011. } else {
  14012. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  14013. }
  14014. } else {
  14015. if ( texture.type === FloatType ) {
  14016. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  14017. }
  14018. }
  14019. // validation checks for WebGL 1
  14020. if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {
  14021. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14022. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  14023. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14024. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  14025. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  14026. texture.type = UnsignedIntType;
  14027. glType = utils.convert( texture.type );
  14028. }
  14029. }
  14030. if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) {
  14031. // Depth stencil textures need the DEPTH_STENCIL internal format
  14032. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14033. glInternalFormat = 34041;
  14034. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14035. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  14036. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14037. if ( texture.type !== UnsignedInt248Type ) {
  14038. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  14039. texture.type = UnsignedInt248Type;
  14040. glType = utils.convert( texture.type );
  14041. }
  14042. }
  14043. //
  14044. if ( allocateMemory ) {
  14045. if ( useTexStorage ) {
  14046. state.texStorage2D( 3553, 1, glInternalFormat, image.width, image.height );
  14047. } else {
  14048. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  14049. }
  14050. }
  14051. } else if ( texture.isDataTexture ) {
  14052. // use manually created mipmaps if available
  14053. // if there are no manual mipmaps
  14054. // set 0 level mipmap and then use GL to generate other mipmap levels
  14055. if ( mipmaps.length > 0 && supportsMips ) {
  14056. if ( useTexStorage && allocateMemory ) {
  14057. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14058. }
  14059. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14060. mipmap = mipmaps[ i ];
  14061. if ( useTexStorage ) {
  14062. state.texSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14063. } else {
  14064. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14065. }
  14066. }
  14067. texture.generateMipmaps = false;
  14068. } else {
  14069. if ( useTexStorage ) {
  14070. if ( allocateMemory ) {
  14071. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  14072. }
  14073. state.texSubImage2D( 3553, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  14074. } else {
  14075. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14076. }
  14077. }
  14078. } else if ( texture.isCompressedTexture ) {
  14079. if ( texture.isCompressedArrayTexture ) {
  14080. if ( useTexStorage && allocateMemory ) {
  14081. state.texStorage3D( 35866, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  14082. }
  14083. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14084. mipmap = mipmaps[ i ];
  14085. if ( texture.format !== RGBAFormat ) {
  14086. if ( glFormat !== null ) {
  14087. if ( useTexStorage ) {
  14088. state.compressedTexSubImage3D( 35866, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  14089. } else {
  14090. state.compressedTexImage3D( 35866, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  14091. }
  14092. } else {
  14093. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14094. }
  14095. } else {
  14096. if ( useTexStorage ) {
  14097. state.texSubImage3D( 35866, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  14098. } else {
  14099. state.texImage3D( 35866, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  14100. }
  14101. }
  14102. }
  14103. } else {
  14104. if ( useTexStorage && allocateMemory ) {
  14105. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14106. }
  14107. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14108. mipmap = mipmaps[ i ];
  14109. if ( texture.format !== RGBAFormat ) {
  14110. if ( glFormat !== null ) {
  14111. if ( useTexStorage ) {
  14112. state.compressedTexSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14113. } else {
  14114. state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14115. }
  14116. } else {
  14117. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14118. }
  14119. } else {
  14120. if ( useTexStorage ) {
  14121. state.texSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14122. } else {
  14123. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14124. }
  14125. }
  14126. }
  14127. }
  14128. } else if ( texture.isDataArrayTexture ) {
  14129. if ( useTexStorage ) {
  14130. if ( allocateMemory ) {
  14131. state.texStorage3D( 35866, levels, glInternalFormat, image.width, image.height, image.depth );
  14132. }
  14133. state.texSubImage3D( 35866, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14134. } else {
  14135. state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14136. }
  14137. } else if ( texture.isData3DTexture ) {
  14138. if ( useTexStorage ) {
  14139. if ( allocateMemory ) {
  14140. state.texStorage3D( 32879, levels, glInternalFormat, image.width, image.height, image.depth );
  14141. }
  14142. state.texSubImage3D( 32879, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14143. } else {
  14144. state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14145. }
  14146. } else if ( texture.isFramebufferTexture ) {
  14147. if ( allocateMemory ) {
  14148. if ( useTexStorage ) {
  14149. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  14150. } else {
  14151. let width = image.width, height = image.height;
  14152. for ( let i = 0; i < levels; i ++ ) {
  14153. state.texImage2D( 3553, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  14154. width >>= 1;
  14155. height >>= 1;
  14156. }
  14157. }
  14158. }
  14159. } else {
  14160. // regular Texture (image, video, canvas)
  14161. // use manually created mipmaps if available
  14162. // if there are no manual mipmaps
  14163. // set 0 level mipmap and then use GL to generate other mipmap levels
  14164. if ( mipmaps.length > 0 && supportsMips ) {
  14165. if ( useTexStorage && allocateMemory ) {
  14166. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14167. }
  14168. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14169. mipmap = mipmaps[ i ];
  14170. if ( useTexStorage ) {
  14171. state.texSubImage2D( 3553, i, 0, 0, glFormat, glType, mipmap );
  14172. } else {
  14173. state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );
  14174. }
  14175. }
  14176. texture.generateMipmaps = false;
  14177. } else {
  14178. if ( useTexStorage ) {
  14179. if ( allocateMemory ) {
  14180. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  14181. }
  14182. state.texSubImage2D( 3553, 0, 0, 0, glFormat, glType, image );
  14183. } else {
  14184. state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
  14185. }
  14186. }
  14187. }
  14188. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14189. generateMipmap( textureType );
  14190. }
  14191. sourceProperties.__version = source.version;
  14192. if ( texture.onUpdate ) texture.onUpdate( texture );
  14193. }
  14194. textureProperties.__version = texture.version;
  14195. }
  14196. function uploadCubeTexture( textureProperties, texture, slot ) {
  14197. if ( texture.image.length !== 6 ) return;
  14198. const forceUpload = initTexture( textureProperties, texture );
  14199. const source = texture.source;
  14200. state.bindTexture( 34067, textureProperties.__webglTexture, 33984 + slot );
  14201. const sourceProperties = properties.get( source );
  14202. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14203. state.activeTexture( 33984 + slot );
  14204. _gl.pixelStorei( 37440, texture.flipY );
  14205. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  14206. _gl.pixelStorei( 3317, texture.unpackAlignment );
  14207. _gl.pixelStorei( 37443, 0 );
  14208. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  14209. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  14210. const cubeImage = [];
  14211. for ( let i = 0; i < 6; i ++ ) {
  14212. if ( ! isCompressed && ! isDataTexture ) {
  14213. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  14214. } else {
  14215. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  14216. }
  14217. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  14218. }
  14219. const image = cubeImage[ 0 ],
  14220. supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14221. glFormat = utils.convert( texture.format, texture.encoding ),
  14222. glType = utils.convert( texture.type ),
  14223. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14224. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  14225. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14226. let levels = getMipLevels( texture, image, supportsMips );
  14227. setTextureParameters( 34067, texture, supportsMips );
  14228. let mipmaps;
  14229. if ( isCompressed ) {
  14230. if ( useTexStorage && allocateMemory ) {
  14231. state.texStorage2D( 34067, levels, glInternalFormat, image.width, image.height );
  14232. }
  14233. for ( let i = 0; i < 6; i ++ ) {
  14234. mipmaps = cubeImage[ i ].mipmaps;
  14235. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14236. const mipmap = mipmaps[ j ];
  14237. if ( texture.format !== RGBAFormat ) {
  14238. if ( glFormat !== null ) {
  14239. if ( useTexStorage ) {
  14240. state.compressedTexSubImage2D( 34069 + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14241. } else {
  14242. state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14243. }
  14244. } else {
  14245. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  14246. }
  14247. } else {
  14248. if ( useTexStorage ) {
  14249. state.texSubImage2D( 34069 + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14250. } else {
  14251. state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14252. }
  14253. }
  14254. }
  14255. }
  14256. } else {
  14257. mipmaps = texture.mipmaps;
  14258. if ( useTexStorage && allocateMemory ) {
  14259. // TODO: Uniformly handle mipmap definitions
  14260. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  14261. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  14262. if ( mipmaps.length > 0 ) levels ++;
  14263. state.texStorage2D( 34067, levels, glInternalFormat, cubeImage[ 0 ].width, cubeImage[ 0 ].height );
  14264. }
  14265. for ( let i = 0; i < 6; i ++ ) {
  14266. if ( isDataTexture ) {
  14267. if ( useTexStorage ) {
  14268. state.texSubImage2D( 34069 + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  14269. } else {
  14270. state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  14271. }
  14272. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14273. const mipmap = mipmaps[ j ];
  14274. const mipmapImage = mipmap.image[ i ].image;
  14275. if ( useTexStorage ) {
  14276. state.texSubImage2D( 34069 + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  14277. } else {
  14278. state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  14279. }
  14280. }
  14281. } else {
  14282. if ( useTexStorage ) {
  14283. state.texSubImage2D( 34069 + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  14284. } else {
  14285. state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  14286. }
  14287. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14288. const mipmap = mipmaps[ j ];
  14289. if ( useTexStorage ) {
  14290. state.texSubImage2D( 34069 + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  14291. } else {
  14292. state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  14293. }
  14294. }
  14295. }
  14296. }
  14297. }
  14298. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14299. // We assume images for cube map have the same size.
  14300. generateMipmap( 34067 );
  14301. }
  14302. sourceProperties.__version = source.version;
  14303. if ( texture.onUpdate ) texture.onUpdate( texture );
  14304. }
  14305. textureProperties.__version = texture.version;
  14306. }
  14307. // Render targets
  14308. // Setup storage for target texture and bind it to correct framebuffer
  14309. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) {
  14310. const glFormat = utils.convert( texture.format, texture.encoding );
  14311. const glType = utils.convert( texture.type );
  14312. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14313. const renderTargetProperties = properties.get( renderTarget );
  14314. if ( ! renderTargetProperties.__hasExternalTextures ) {
  14315. if ( textureTarget === 32879 || textureTarget === 35866 ) {
  14316. state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null );
  14317. } else {
  14318. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14319. }
  14320. }
  14321. state.bindFramebuffer( 36160, framebuffer );
  14322. if ( useMultisampledRTT( renderTarget ) ) {
  14323. multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  14324. } else if ( textureTarget === 3553 || ( textureTarget >= 34069 && textureTarget <= 34074 ) ) { // see #24753
  14325. _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 );
  14326. }
  14327. state.bindFramebuffer( 36160, null );
  14328. }
  14329. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14330. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  14331. _gl.bindRenderbuffer( 36161, renderbuffer );
  14332. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14333. let glInternalFormat = 33189;
  14334. if ( isMultisample || useMultisampledRTT( renderTarget ) ) {
  14335. const depthTexture = renderTarget.depthTexture;
  14336. if ( depthTexture && depthTexture.isDepthTexture ) {
  14337. if ( depthTexture.type === FloatType ) {
  14338. glInternalFormat = 36012;
  14339. } else if ( depthTexture.type === UnsignedIntType ) {
  14340. glInternalFormat = 33190;
  14341. }
  14342. }
  14343. const samples = getRenderTargetSamples( renderTarget );
  14344. if ( useMultisampledRTT( renderTarget ) ) {
  14345. multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14346. } else {
  14347. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14348. }
  14349. } else {
  14350. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  14351. }
  14352. _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );
  14353. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14354. const samples = getRenderTargetSamples( renderTarget );
  14355. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14356. _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  14357. } else if ( useMultisampledRTT( renderTarget ) ) {
  14358. multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  14359. } else {
  14360. _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );
  14361. }
  14362. _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );
  14363. } else {
  14364. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14365. for ( let i = 0; i < textures.length; i ++ ) {
  14366. const texture = textures[ i ];
  14367. const glFormat = utils.convert( texture.format, texture.encoding );
  14368. const glType = utils.convert( texture.type );
  14369. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14370. const samples = getRenderTargetSamples( renderTarget );
  14371. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14372. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14373. } else if ( useMultisampledRTT( renderTarget ) ) {
  14374. multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14375. } else {
  14376. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  14377. }
  14378. }
  14379. }
  14380. _gl.bindRenderbuffer( 36161, null );
  14381. }
  14382. // Setup resources for a Depth Texture for a FBO (needs an extension)
  14383. function setupDepthTexture( framebuffer, renderTarget ) {
  14384. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  14385. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  14386. state.bindFramebuffer( 36160, framebuffer );
  14387. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  14388. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  14389. }
  14390. // upload an empty depth texture with framebuffer size
  14391. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  14392. renderTarget.depthTexture.image.width !== renderTarget.width ||
  14393. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  14394. renderTarget.depthTexture.image.width = renderTarget.width;
  14395. renderTarget.depthTexture.image.height = renderTarget.height;
  14396. renderTarget.depthTexture.needsUpdate = true;
  14397. }
  14398. setTexture2D( renderTarget.depthTexture, 0 );
  14399. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  14400. const samples = getRenderTargetSamples( renderTarget );
  14401. if ( renderTarget.depthTexture.format === DepthFormat ) {
  14402. if ( useMultisampledRTT( renderTarget ) ) {
  14403. multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, 36096, 3553, webglDepthTexture, 0, samples );
  14404. } else {
  14405. _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );
  14406. }
  14407. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  14408. if ( useMultisampledRTT( renderTarget ) ) {
  14409. multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, 33306, 3553, webglDepthTexture, 0, samples );
  14410. } else {
  14411. _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );
  14412. }
  14413. } else {
  14414. throw new Error( 'Unknown depthTexture format' );
  14415. }
  14416. }
  14417. // Setup GL resources for a non-texture depth buffer
  14418. function setupDepthRenderbuffer( renderTarget ) {
  14419. const renderTargetProperties = properties.get( renderTarget );
  14420. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14421. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  14422. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  14423. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  14424. } else {
  14425. if ( isCube ) {
  14426. renderTargetProperties.__webglDepthbuffer = [];
  14427. for ( let i = 0; i < 6; i ++ ) {
  14428. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
  14429. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  14430. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  14431. }
  14432. } else {
  14433. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  14434. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14435. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  14436. }
  14437. }
  14438. state.bindFramebuffer( 36160, null );
  14439. }
  14440. // rebind framebuffer with external textures
  14441. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  14442. const renderTargetProperties = properties.get( renderTarget );
  14443. if ( colorTexture !== undefined ) {
  14444. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, 36064, 3553 );
  14445. }
  14446. if ( depthTexture !== undefined ) {
  14447. setupDepthRenderbuffer( renderTarget );
  14448. }
  14449. }
  14450. // Set up GL resources for the render target
  14451. function setupRenderTarget( renderTarget ) {
  14452. const texture = renderTarget.texture;
  14453. const renderTargetProperties = properties.get( renderTarget );
  14454. const textureProperties = properties.get( texture );
  14455. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14456. if ( renderTarget.isWebGLMultipleRenderTargets !== true ) {
  14457. if ( textureProperties.__webglTexture === undefined ) {
  14458. textureProperties.__webglTexture = _gl.createTexture();
  14459. }
  14460. textureProperties.__version = texture.version;
  14461. info.memory.textures ++;
  14462. }
  14463. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14464. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  14465. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14466. // Setup framebuffer
  14467. if ( isCube ) {
  14468. renderTargetProperties.__webglFramebuffer = [];
  14469. for ( let i = 0; i < 6; i ++ ) {
  14470. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14471. }
  14472. } else {
  14473. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14474. if ( isMultipleRenderTargets ) {
  14475. if ( capabilities.drawBuffers ) {
  14476. const textures = renderTarget.texture;
  14477. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14478. const attachmentProperties = properties.get( textures[ i ] );
  14479. if ( attachmentProperties.__webglTexture === undefined ) {
  14480. attachmentProperties.__webglTexture = _gl.createTexture();
  14481. info.memory.textures ++;
  14482. }
  14483. }
  14484. } else {
  14485. console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' );
  14486. }
  14487. }
  14488. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  14489. const textures = isMultipleRenderTargets ? texture : [ texture ];
  14490. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14491. renderTargetProperties.__webglColorRenderbuffer = [];
  14492. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  14493. for ( let i = 0; i < textures.length; i ++ ) {
  14494. const texture = textures[ i ];
  14495. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  14496. _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14497. const glFormat = utils.convert( texture.format, texture.encoding );
  14498. const glType = utils.convert( texture.type );
  14499. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, renderTarget.isXRRenderTarget === true );
  14500. const samples = getRenderTargetSamples( renderTarget );
  14501. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14502. _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14503. }
  14504. _gl.bindRenderbuffer( 36161, null );
  14505. if ( renderTarget.depthBuffer ) {
  14506. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14507. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  14508. }
  14509. state.bindFramebuffer( 36160, null );
  14510. }
  14511. }
  14512. // Setup color buffer
  14513. if ( isCube ) {
  14514. state.bindTexture( 34067, textureProperties.__webglTexture );
  14515. setTextureParameters( 34067, texture, supportsMips );
  14516. for ( let i = 0; i < 6; i ++ ) {
  14517. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, 36064, 34069 + i );
  14518. }
  14519. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14520. generateMipmap( 34067 );
  14521. }
  14522. state.unbindTexture();
  14523. } else if ( isMultipleRenderTargets ) {
  14524. const textures = renderTarget.texture;
  14525. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14526. const attachment = textures[ i ];
  14527. const attachmentProperties = properties.get( attachment );
  14528. state.bindTexture( 3553, attachmentProperties.__webglTexture );
  14529. setTextureParameters( 3553, attachment, supportsMips );
  14530. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, 36064 + i, 3553 );
  14531. if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) {
  14532. generateMipmap( 3553 );
  14533. }
  14534. }
  14535. state.unbindTexture();
  14536. } else {
  14537. let glTextureType = 3553;
  14538. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  14539. if ( isWebGL2 ) {
  14540. glTextureType = renderTarget.isWebGL3DRenderTarget ? 32879 : 35866;
  14541. } else {
  14542. console.error( 'THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.' );
  14543. }
  14544. }
  14545. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  14546. setTextureParameters( glTextureType, texture, supportsMips );
  14547. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, 36064, glTextureType );
  14548. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14549. generateMipmap( glTextureType );
  14550. }
  14551. state.unbindTexture();
  14552. }
  14553. // Setup depth and stencil buffers
  14554. if ( renderTarget.depthBuffer ) {
  14555. setupDepthRenderbuffer( renderTarget );
  14556. }
  14557. }
  14558. function updateRenderTargetMipmap( renderTarget ) {
  14559. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14560. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14561. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14562. const texture = textures[ i ];
  14563. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14564. const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  14565. const webglTexture = properties.get( texture ).__webglTexture;
  14566. state.bindTexture( target, webglTexture );
  14567. generateMipmap( target );
  14568. state.unbindTexture();
  14569. }
  14570. }
  14571. }
  14572. function updateMultisampleRenderTarget( renderTarget ) {
  14573. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  14574. const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [ renderTarget.texture ];
  14575. const width = renderTarget.width;
  14576. const height = renderTarget.height;
  14577. let mask = 16384;
  14578. const invalidationArray = [];
  14579. const depthStyle = renderTarget.stencilBuffer ? 33306 : 36096;
  14580. const renderTargetProperties = properties.get( renderTarget );
  14581. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  14582. // If MRT we need to remove FBO attachments
  14583. if ( isMultipleRenderTargets ) {
  14584. for ( let i = 0; i < textures.length; i ++ ) {
  14585. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  14586. _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, null );
  14587. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  14588. _gl.framebufferTexture2D( 36009, 36064 + i, 3553, null, 0 );
  14589. }
  14590. }
  14591. state.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
  14592. state.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );
  14593. for ( let i = 0; i < textures.length; i ++ ) {
  14594. invalidationArray.push( 36064 + i );
  14595. if ( renderTarget.depthBuffer ) {
  14596. invalidationArray.push( depthStyle );
  14597. }
  14598. const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false;
  14599. if ( ignoreDepthValues === false ) {
  14600. if ( renderTarget.depthBuffer ) mask |= 256;
  14601. if ( renderTarget.stencilBuffer ) mask |= 1024;
  14602. }
  14603. if ( isMultipleRenderTargets ) {
  14604. _gl.framebufferRenderbuffer( 36008, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14605. }
  14606. if ( ignoreDepthValues === true ) {
  14607. _gl.invalidateFramebuffer( 36008, [ depthStyle ] );
  14608. _gl.invalidateFramebuffer( 36009, [ depthStyle ] );
  14609. }
  14610. if ( isMultipleRenderTargets ) {
  14611. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  14612. _gl.framebufferTexture2D( 36009, 36064, 3553, webglTexture, 0 );
  14613. }
  14614. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );
  14615. if ( supportsInvalidateFramebuffer ) {
  14616. _gl.invalidateFramebuffer( 36008, invalidationArray );
  14617. }
  14618. }
  14619. state.bindFramebuffer( 36008, null );
  14620. state.bindFramebuffer( 36009, null );
  14621. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  14622. if ( isMultipleRenderTargets ) {
  14623. for ( let i = 0; i < textures.length; i ++ ) {
  14624. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  14625. _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14626. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  14627. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  14628. _gl.framebufferTexture2D( 36009, 36064 + i, 3553, webglTexture, 0 );
  14629. }
  14630. }
  14631. state.bindFramebuffer( 36009, renderTargetProperties.__webglMultisampledFramebuffer );
  14632. }
  14633. }
  14634. function getRenderTargetSamples( renderTarget ) {
  14635. return Math.min( maxSamples, renderTarget.samples );
  14636. }
  14637. function useMultisampledRTT( renderTarget ) {
  14638. const renderTargetProperties = properties.get( renderTarget );
  14639. return isWebGL2 && renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  14640. }
  14641. function updateVideoTexture( texture ) {
  14642. const frame = info.render.frame;
  14643. // Check the last frame we updated the VideoTexture
  14644. if ( _videoTextures.get( texture ) !== frame ) {
  14645. _videoTextures.set( texture, frame );
  14646. texture.update();
  14647. }
  14648. }
  14649. function verifyColorSpace( texture, image ) {
  14650. const encoding = texture.encoding;
  14651. const format = texture.format;
  14652. const type = texture.type;
  14653. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat ) return image;
  14654. if ( encoding !== LinearEncoding ) {
  14655. // sRGB
  14656. if ( encoding === sRGBEncoding ) {
  14657. if ( isWebGL2 === false ) {
  14658. // in WebGL 1, try to use EXT_sRGB extension and unsized formats
  14659. if ( extensions.has( 'EXT_sRGB' ) === true && format === RGBAFormat ) {
  14660. texture.format = _SRGBAFormat;
  14661. // it's not possible to generate mips in WebGL 1 with this extension
  14662. texture.minFilter = LinearFilter;
  14663. texture.generateMipmaps = false;
  14664. } else {
  14665. // slow fallback (CPU decode)
  14666. image = ImageUtils.sRGBToLinear( image );
  14667. }
  14668. } else {
  14669. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  14670. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  14671. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  14672. }
  14673. }
  14674. } else {
  14675. console.error( 'THREE.WebGLTextures: Unsupported texture encoding:', encoding );
  14676. }
  14677. }
  14678. return image;
  14679. }
  14680. //
  14681. this.allocateTextureUnit = allocateTextureUnit;
  14682. this.resetTextureUnits = resetTextureUnits;
  14683. this.setTexture2D = setTexture2D;
  14684. this.setTexture2DArray = setTexture2DArray;
  14685. this.setTexture3D = setTexture3D;
  14686. this.setTextureCube = setTextureCube;
  14687. this.rebindTextures = rebindTextures;
  14688. this.setupRenderTarget = setupRenderTarget;
  14689. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14690. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14691. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  14692. this.setupFrameBufferTexture = setupFrameBufferTexture;
  14693. this.useMultisampledRTT = useMultisampledRTT;
  14694. }
  14695. function WebGLUtils( gl, extensions, capabilities ) {
  14696. const isWebGL2 = capabilities.isWebGL2;
  14697. function convert( p, encoding = null ) {
  14698. let extension;
  14699. if ( p === UnsignedByteType ) return 5121;
  14700. if ( p === UnsignedShort4444Type ) return 32819;
  14701. if ( p === UnsignedShort5551Type ) return 32820;
  14702. if ( p === ByteType ) return 5120;
  14703. if ( p === ShortType ) return 5122;
  14704. if ( p === UnsignedShortType ) return 5123;
  14705. if ( p === IntType ) return 5124;
  14706. if ( p === UnsignedIntType ) return 5125;
  14707. if ( p === FloatType ) return 5126;
  14708. if ( p === HalfFloatType ) {
  14709. if ( isWebGL2 ) return 5131;
  14710. extension = extensions.get( 'OES_texture_half_float' );
  14711. if ( extension !== null ) {
  14712. return extension.HALF_FLOAT_OES;
  14713. } else {
  14714. return null;
  14715. }
  14716. }
  14717. if ( p === AlphaFormat ) return 6406;
  14718. if ( p === RGBAFormat ) return 6408;
  14719. if ( p === LuminanceFormat ) return 6409;
  14720. if ( p === LuminanceAlphaFormat ) return 6410;
  14721. if ( p === DepthFormat ) return 6402;
  14722. if ( p === DepthStencilFormat ) return 34041;
  14723. // WebGL 1 sRGB fallback
  14724. if ( p === _SRGBAFormat ) {
  14725. extension = extensions.get( 'EXT_sRGB' );
  14726. if ( extension !== null ) {
  14727. return extension.SRGB_ALPHA_EXT;
  14728. } else {
  14729. return null;
  14730. }
  14731. }
  14732. // WebGL2 formats.
  14733. if ( p === RedFormat ) return 6403;
  14734. if ( p === RedIntegerFormat ) return 36244;
  14735. if ( p === RGFormat ) return 33319;
  14736. if ( p === RGIntegerFormat ) return 33320;
  14737. if ( p === RGBAIntegerFormat ) return 36249;
  14738. // S3TC
  14739. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  14740. if ( encoding === sRGBEncoding ) {
  14741. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  14742. if ( extension !== null ) {
  14743. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  14744. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  14745. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  14746. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  14747. } else {
  14748. return null;
  14749. }
  14750. } else {
  14751. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  14752. if ( extension !== null ) {
  14753. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14754. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14755. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14756. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14757. } else {
  14758. return null;
  14759. }
  14760. }
  14761. }
  14762. // PVRTC
  14763. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  14764. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  14765. if ( extension !== null ) {
  14766. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14767. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14768. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14769. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14770. } else {
  14771. return null;
  14772. }
  14773. }
  14774. // ETC1
  14775. if ( p === RGB_ETC1_Format ) {
  14776. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  14777. if ( extension !== null ) {
  14778. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14779. } else {
  14780. return null;
  14781. }
  14782. }
  14783. // ETC2
  14784. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  14785. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  14786. if ( extension !== null ) {
  14787. if ( p === RGB_ETC2_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  14788. if ( p === RGBA_ETC2_EAC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  14789. } else {
  14790. return null;
  14791. }
  14792. }
  14793. // ASTC
  14794. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  14795. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  14796. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  14797. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  14798. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  14799. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  14800. if ( extension !== null ) {
  14801. if ( p === RGBA_ASTC_4x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  14802. if ( p === RGBA_ASTC_5x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  14803. if ( p === RGBA_ASTC_5x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  14804. if ( p === RGBA_ASTC_6x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  14805. if ( p === RGBA_ASTC_6x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  14806. if ( p === RGBA_ASTC_8x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  14807. if ( p === RGBA_ASTC_8x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  14808. if ( p === RGBA_ASTC_8x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  14809. if ( p === RGBA_ASTC_10x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  14810. if ( p === RGBA_ASTC_10x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  14811. if ( p === RGBA_ASTC_10x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  14812. if ( p === RGBA_ASTC_10x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  14813. if ( p === RGBA_ASTC_12x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  14814. if ( p === RGBA_ASTC_12x12_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  14815. } else {
  14816. return null;
  14817. }
  14818. }
  14819. // BPTC
  14820. if ( p === RGBA_BPTC_Format ) {
  14821. extension = extensions.get( 'EXT_texture_compression_bptc' );
  14822. if ( extension !== null ) {
  14823. if ( p === RGBA_BPTC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  14824. } else {
  14825. return null;
  14826. }
  14827. }
  14828. // RGTC
  14829. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  14830. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  14831. if ( extension !== null ) {
  14832. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  14833. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  14834. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  14835. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  14836. } else {
  14837. return null;
  14838. }
  14839. }
  14840. //
  14841. if ( p === UnsignedInt248Type ) {
  14842. if ( isWebGL2 ) return 34042;
  14843. extension = extensions.get( 'WEBGL_depth_texture' );
  14844. if ( extension !== null ) {
  14845. return extension.UNSIGNED_INT_24_8_WEBGL;
  14846. } else {
  14847. return null;
  14848. }
  14849. }
  14850. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  14851. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  14852. }
  14853. return { convert: convert };
  14854. }
  14855. class ArrayCamera extends PerspectiveCamera {
  14856. constructor( array = [] ) {
  14857. super();
  14858. this.isArrayCamera = true;
  14859. this.cameras = array;
  14860. }
  14861. }
  14862. class Group extends Object3D {
  14863. constructor() {
  14864. super();
  14865. this.isGroup = true;
  14866. this.type = 'Group';
  14867. }
  14868. }
  14869. const _moveEvent = { type: 'move' };
  14870. class WebXRController {
  14871. constructor() {
  14872. this._targetRay = null;
  14873. this._grip = null;
  14874. this._hand = null;
  14875. }
  14876. getHandSpace() {
  14877. if ( this._hand === null ) {
  14878. this._hand = new Group();
  14879. this._hand.matrixAutoUpdate = false;
  14880. this._hand.visible = false;
  14881. this._hand.joints = {};
  14882. this._hand.inputState = { pinching: false };
  14883. }
  14884. return this._hand;
  14885. }
  14886. getTargetRaySpace() {
  14887. if ( this._targetRay === null ) {
  14888. this._targetRay = new Group();
  14889. this._targetRay.matrixAutoUpdate = false;
  14890. this._targetRay.visible = false;
  14891. this._targetRay.hasLinearVelocity = false;
  14892. this._targetRay.linearVelocity = new Vector3();
  14893. this._targetRay.hasAngularVelocity = false;
  14894. this._targetRay.angularVelocity = new Vector3();
  14895. }
  14896. return this._targetRay;
  14897. }
  14898. getGripSpace() {
  14899. if ( this._grip === null ) {
  14900. this._grip = new Group();
  14901. this._grip.matrixAutoUpdate = false;
  14902. this._grip.visible = false;
  14903. this._grip.hasLinearVelocity = false;
  14904. this._grip.linearVelocity = new Vector3();
  14905. this._grip.hasAngularVelocity = false;
  14906. this._grip.angularVelocity = new Vector3();
  14907. }
  14908. return this._grip;
  14909. }
  14910. dispatchEvent( event ) {
  14911. if ( this._targetRay !== null ) {
  14912. this._targetRay.dispatchEvent( event );
  14913. }
  14914. if ( this._grip !== null ) {
  14915. this._grip.dispatchEvent( event );
  14916. }
  14917. if ( this._hand !== null ) {
  14918. this._hand.dispatchEvent( event );
  14919. }
  14920. return this;
  14921. }
  14922. connect( inputSource ) {
  14923. if ( inputSource && inputSource.hand ) {
  14924. const hand = this._hand;
  14925. if ( hand ) {
  14926. for ( const inputjoint of inputSource.hand.values() ) {
  14927. // Initialize hand with joints when connected
  14928. this._getHandJoint( hand, inputjoint );
  14929. }
  14930. }
  14931. }
  14932. this.dispatchEvent( { type: 'connected', data: inputSource } );
  14933. return this;
  14934. }
  14935. disconnect( inputSource ) {
  14936. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  14937. if ( this._targetRay !== null ) {
  14938. this._targetRay.visible = false;
  14939. }
  14940. if ( this._grip !== null ) {
  14941. this._grip.visible = false;
  14942. }
  14943. if ( this._hand !== null ) {
  14944. this._hand.visible = false;
  14945. }
  14946. return this;
  14947. }
  14948. update( inputSource, frame, referenceSpace ) {
  14949. let inputPose = null;
  14950. let gripPose = null;
  14951. let handPose = null;
  14952. const targetRay = this._targetRay;
  14953. const grip = this._grip;
  14954. const hand = this._hand;
  14955. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  14956. if ( hand && inputSource.hand ) {
  14957. handPose = true;
  14958. for ( const inputjoint of inputSource.hand.values() ) {
  14959. // Update the joints groups with the XRJoint poses
  14960. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  14961. // The transform of this joint will be updated with the joint pose on each frame
  14962. const joint = this._getHandJoint( hand, inputjoint );
  14963. if ( jointPose !== null ) {
  14964. joint.matrix.fromArray( jointPose.transform.matrix );
  14965. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  14966. joint.jointRadius = jointPose.radius;
  14967. }
  14968. joint.visible = jointPose !== null;
  14969. }
  14970. // Custom events
  14971. // Check pinchz
  14972. const indexTip = hand.joints[ 'index-finger-tip' ];
  14973. const thumbTip = hand.joints[ 'thumb-tip' ];
  14974. const distance = indexTip.position.distanceTo( thumbTip.position );
  14975. const distanceToPinch = 0.02;
  14976. const threshold = 0.005;
  14977. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  14978. hand.inputState.pinching = false;
  14979. this.dispatchEvent( {
  14980. type: 'pinchend',
  14981. handedness: inputSource.handedness,
  14982. target: this
  14983. } );
  14984. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  14985. hand.inputState.pinching = true;
  14986. this.dispatchEvent( {
  14987. type: 'pinchstart',
  14988. handedness: inputSource.handedness,
  14989. target: this
  14990. } );
  14991. }
  14992. } else {
  14993. if ( grip !== null && inputSource.gripSpace ) {
  14994. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  14995. if ( gripPose !== null ) {
  14996. grip.matrix.fromArray( gripPose.transform.matrix );
  14997. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  14998. if ( gripPose.linearVelocity ) {
  14999. grip.hasLinearVelocity = true;
  15000. grip.linearVelocity.copy( gripPose.linearVelocity );
  15001. } else {
  15002. grip.hasLinearVelocity = false;
  15003. }
  15004. if ( gripPose.angularVelocity ) {
  15005. grip.hasAngularVelocity = true;
  15006. grip.angularVelocity.copy( gripPose.angularVelocity );
  15007. } else {
  15008. grip.hasAngularVelocity = false;
  15009. }
  15010. }
  15011. }
  15012. }
  15013. if ( targetRay !== null ) {
  15014. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  15015. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  15016. if ( inputPose === null && gripPose !== null ) {
  15017. inputPose = gripPose;
  15018. }
  15019. if ( inputPose !== null ) {
  15020. targetRay.matrix.fromArray( inputPose.transform.matrix );
  15021. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  15022. if ( inputPose.linearVelocity ) {
  15023. targetRay.hasLinearVelocity = true;
  15024. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  15025. } else {
  15026. targetRay.hasLinearVelocity = false;
  15027. }
  15028. if ( inputPose.angularVelocity ) {
  15029. targetRay.hasAngularVelocity = true;
  15030. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  15031. } else {
  15032. targetRay.hasAngularVelocity = false;
  15033. }
  15034. this.dispatchEvent( _moveEvent );
  15035. }
  15036. }
  15037. }
  15038. if ( targetRay !== null ) {
  15039. targetRay.visible = ( inputPose !== null );
  15040. }
  15041. if ( grip !== null ) {
  15042. grip.visible = ( gripPose !== null );
  15043. }
  15044. if ( hand !== null ) {
  15045. hand.visible = ( handPose !== null );
  15046. }
  15047. return this;
  15048. }
  15049. // private method
  15050. _getHandJoint( hand, inputjoint ) {
  15051. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  15052. const joint = new Group();
  15053. joint.matrixAutoUpdate = false;
  15054. joint.visible = false;
  15055. hand.joints[ inputjoint.jointName ] = joint;
  15056. hand.add( joint );
  15057. }
  15058. return hand.joints[ inputjoint.jointName ];
  15059. }
  15060. }
  15061. class DepthTexture extends Texture {
  15062. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  15063. format = format !== undefined ? format : DepthFormat;
  15064. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  15065. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  15066. }
  15067. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  15068. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  15069. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  15070. this.isDepthTexture = true;
  15071. this.image = { width: width, height: height };
  15072. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  15073. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  15074. this.flipY = false;
  15075. this.generateMipmaps = false;
  15076. }
  15077. }
  15078. class WebXRManager extends EventDispatcher {
  15079. constructor( renderer, gl ) {
  15080. super();
  15081. const scope = this;
  15082. let session = null;
  15083. let framebufferScaleFactor = 1.0;
  15084. let referenceSpace = null;
  15085. let referenceSpaceType = 'local-floor';
  15086. // Set default foveation to maximum.
  15087. let foveation = 1.0;
  15088. let customReferenceSpace = null;
  15089. let pose = null;
  15090. let glBinding = null;
  15091. let glProjLayer = null;
  15092. let glBaseLayer = null;
  15093. let xrFrame = null;
  15094. const attributes = gl.getContextAttributes();
  15095. let initialRenderTarget = null;
  15096. let newRenderTarget = null;
  15097. const controllers = [];
  15098. const controllerInputSources = [];
  15099. const planes = new Set();
  15100. const planesLastChangedTimes = new Map();
  15101. //
  15102. const cameraL = new PerspectiveCamera();
  15103. cameraL.layers.enable( 1 );
  15104. cameraL.viewport = new Vector4();
  15105. const cameraR = new PerspectiveCamera();
  15106. cameraR.layers.enable( 2 );
  15107. cameraR.viewport = new Vector4();
  15108. const cameras = [ cameraL, cameraR ];
  15109. const cameraVR = new ArrayCamera();
  15110. cameraVR.layers.enable( 1 );
  15111. cameraVR.layers.enable( 2 );
  15112. let _currentDepthNear = null;
  15113. let _currentDepthFar = null;
  15114. //
  15115. this.cameraAutoUpdate = true;
  15116. this.enabled = false;
  15117. this.isPresenting = false;
  15118. this.getController = function ( index ) {
  15119. let controller = controllers[ index ];
  15120. if ( controller === undefined ) {
  15121. controller = new WebXRController();
  15122. controllers[ index ] = controller;
  15123. }
  15124. return controller.getTargetRaySpace();
  15125. };
  15126. this.getControllerGrip = function ( index ) {
  15127. let controller = controllers[ index ];
  15128. if ( controller === undefined ) {
  15129. controller = new WebXRController();
  15130. controllers[ index ] = controller;
  15131. }
  15132. return controller.getGripSpace();
  15133. };
  15134. this.getHand = function ( index ) {
  15135. let controller = controllers[ index ];
  15136. if ( controller === undefined ) {
  15137. controller = new WebXRController();
  15138. controllers[ index ] = controller;
  15139. }
  15140. return controller.getHandSpace();
  15141. };
  15142. //
  15143. function onSessionEvent( event ) {
  15144. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  15145. if ( controllerIndex === - 1 ) {
  15146. return;
  15147. }
  15148. const controller = controllers[ controllerIndex ];
  15149. if ( controller !== undefined ) {
  15150. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  15151. }
  15152. }
  15153. function onSessionEnd() {
  15154. session.removeEventListener( 'select', onSessionEvent );
  15155. session.removeEventListener( 'selectstart', onSessionEvent );
  15156. session.removeEventListener( 'selectend', onSessionEvent );
  15157. session.removeEventListener( 'squeeze', onSessionEvent );
  15158. session.removeEventListener( 'squeezestart', onSessionEvent );
  15159. session.removeEventListener( 'squeezeend', onSessionEvent );
  15160. session.removeEventListener( 'end', onSessionEnd );
  15161. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  15162. for ( let i = 0; i < controllers.length; i ++ ) {
  15163. const inputSource = controllerInputSources[ i ];
  15164. if ( inputSource === null ) continue;
  15165. controllerInputSources[ i ] = null;
  15166. controllers[ i ].disconnect( inputSource );
  15167. }
  15168. _currentDepthNear = null;
  15169. _currentDepthFar = null;
  15170. // restore framebuffer/rendering state
  15171. renderer.setRenderTarget( initialRenderTarget );
  15172. glBaseLayer = null;
  15173. glProjLayer = null;
  15174. glBinding = null;
  15175. session = null;
  15176. newRenderTarget = null;
  15177. //
  15178. animation.stop();
  15179. scope.isPresenting = false;
  15180. scope.dispatchEvent( { type: 'sessionend' } );
  15181. }
  15182. this.setFramebufferScaleFactor = function ( value ) {
  15183. framebufferScaleFactor = value;
  15184. if ( scope.isPresenting === true ) {
  15185. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  15186. }
  15187. };
  15188. this.setReferenceSpaceType = function ( value ) {
  15189. referenceSpaceType = value;
  15190. if ( scope.isPresenting === true ) {
  15191. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  15192. }
  15193. };
  15194. this.getReferenceSpace = function () {
  15195. return customReferenceSpace || referenceSpace;
  15196. };
  15197. this.setReferenceSpace = function ( space ) {
  15198. customReferenceSpace = space;
  15199. };
  15200. this.getBaseLayer = function () {
  15201. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  15202. };
  15203. this.getBinding = function () {
  15204. return glBinding;
  15205. };
  15206. this.getFrame = function () {
  15207. return xrFrame;
  15208. };
  15209. this.getSession = function () {
  15210. return session;
  15211. };
  15212. this.setSession = async function ( value ) {
  15213. session = value;
  15214. if ( session !== null ) {
  15215. initialRenderTarget = renderer.getRenderTarget();
  15216. session.addEventListener( 'select', onSessionEvent );
  15217. session.addEventListener( 'selectstart', onSessionEvent );
  15218. session.addEventListener( 'selectend', onSessionEvent );
  15219. session.addEventListener( 'squeeze', onSessionEvent );
  15220. session.addEventListener( 'squeezestart', onSessionEvent );
  15221. session.addEventListener( 'squeezeend', onSessionEvent );
  15222. session.addEventListener( 'end', onSessionEnd );
  15223. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  15224. if ( attributes.xrCompatible !== true ) {
  15225. await gl.makeXRCompatible();
  15226. }
  15227. if ( ( session.renderState.layers === undefined ) || ( renderer.capabilities.isWebGL2 === false ) ) {
  15228. const layerInit = {
  15229. antialias: ( session.renderState.layers === undefined ) ? attributes.antialias : true,
  15230. alpha: attributes.alpha,
  15231. depth: attributes.depth,
  15232. stencil: attributes.stencil,
  15233. framebufferScaleFactor: framebufferScaleFactor
  15234. };
  15235. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  15236. session.updateRenderState( { baseLayer: glBaseLayer } );
  15237. newRenderTarget = new WebGLRenderTarget(
  15238. glBaseLayer.framebufferWidth,
  15239. glBaseLayer.framebufferHeight,
  15240. {
  15241. format: RGBAFormat,
  15242. type: UnsignedByteType,
  15243. encoding: renderer.outputEncoding,
  15244. stencilBuffer: attributes.stencil
  15245. }
  15246. );
  15247. } else {
  15248. let depthFormat = null;
  15249. let depthType = null;
  15250. let glDepthFormat = null;
  15251. if ( attributes.depth ) {
  15252. glDepthFormat = attributes.stencil ? 35056 : 33190;
  15253. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  15254. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  15255. }
  15256. const projectionlayerInit = {
  15257. colorFormat: 32856,
  15258. depthFormat: glDepthFormat,
  15259. scaleFactor: framebufferScaleFactor
  15260. };
  15261. glBinding = new XRWebGLBinding( session, gl );
  15262. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  15263. session.updateRenderState( { layers: [ glProjLayer ] } );
  15264. newRenderTarget = new WebGLRenderTarget(
  15265. glProjLayer.textureWidth,
  15266. glProjLayer.textureHeight,
  15267. {
  15268. format: RGBAFormat,
  15269. type: UnsignedByteType,
  15270. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  15271. stencilBuffer: attributes.stencil,
  15272. encoding: renderer.outputEncoding,
  15273. samples: attributes.antialias ? 4 : 0
  15274. } );
  15275. const renderTargetProperties = renderer.properties.get( newRenderTarget );
  15276. renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues;
  15277. }
  15278. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  15279. this.setFoveation( foveation );
  15280. customReferenceSpace = null;
  15281. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  15282. animation.setContext( session );
  15283. animation.start();
  15284. scope.isPresenting = true;
  15285. scope.dispatchEvent( { type: 'sessionstart' } );
  15286. }
  15287. };
  15288. function onInputSourcesChange( event ) {
  15289. // Notify disconnected
  15290. for ( let i = 0; i < event.removed.length; i ++ ) {
  15291. const inputSource = event.removed[ i ];
  15292. const index = controllerInputSources.indexOf( inputSource );
  15293. if ( index >= 0 ) {
  15294. controllerInputSources[ index ] = null;
  15295. controllers[ index ].disconnect( inputSource );
  15296. }
  15297. }
  15298. // Notify connected
  15299. for ( let i = 0; i < event.added.length; i ++ ) {
  15300. const inputSource = event.added[ i ];
  15301. let controllerIndex = controllerInputSources.indexOf( inputSource );
  15302. if ( controllerIndex === - 1 ) {
  15303. // Assign input source a controller that currently has no input source
  15304. for ( let i = 0; i < controllers.length; i ++ ) {
  15305. if ( i >= controllerInputSources.length ) {
  15306. controllerInputSources.push( inputSource );
  15307. controllerIndex = i;
  15308. break;
  15309. } else if ( controllerInputSources[ i ] === null ) {
  15310. controllerInputSources[ i ] = inputSource;
  15311. controllerIndex = i;
  15312. break;
  15313. }
  15314. }
  15315. // If all controllers do currently receive input we ignore new ones
  15316. if ( controllerIndex === - 1 ) break;
  15317. }
  15318. const controller = controllers[ controllerIndex ];
  15319. if ( controller ) {
  15320. controller.connect( inputSource );
  15321. }
  15322. }
  15323. }
  15324. //
  15325. const cameraLPos = new Vector3();
  15326. const cameraRPos = new Vector3();
  15327. /**
  15328. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15329. * the cameras' projection and world matrices have already been set.
  15330. * And that near and far planes are identical for both cameras.
  15331. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15332. */
  15333. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  15334. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  15335. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  15336. const ipd = cameraLPos.distanceTo( cameraRPos );
  15337. const projL = cameraL.projectionMatrix.elements;
  15338. const projR = cameraR.projectionMatrix.elements;
  15339. // VR systems will have identical far and near planes, and
  15340. // most likely identical top and bottom frustum extents.
  15341. // Use the left camera for these values.
  15342. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  15343. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  15344. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  15345. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  15346. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  15347. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  15348. const left = near * leftFov;
  15349. const right = near * rightFov;
  15350. // Calculate the new camera's position offset from the
  15351. // left camera. xOffset should be roughly half `ipd`.
  15352. const zOffset = ipd / ( - leftFov + rightFov );
  15353. const xOffset = zOffset * - leftFov;
  15354. // TODO: Better way to apply this offset?
  15355. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  15356. camera.translateX( xOffset );
  15357. camera.translateZ( zOffset );
  15358. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  15359. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15360. // Find the union of the frustum values of the cameras and scale
  15361. // the values so that the near plane's position does not change in world space,
  15362. // although must now be relative to the new union camera.
  15363. const near2 = near + zOffset;
  15364. const far2 = far + zOffset;
  15365. const left2 = left - xOffset;
  15366. const right2 = right + ( ipd - xOffset );
  15367. const top2 = topFov * far / far2 * near2;
  15368. const bottom2 = bottomFov * far / far2 * near2;
  15369. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  15370. }
  15371. function updateCamera( camera, parent ) {
  15372. if ( parent === null ) {
  15373. camera.matrixWorld.copy( camera.matrix );
  15374. } else {
  15375. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  15376. }
  15377. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15378. }
  15379. this.updateCamera = function ( camera ) {
  15380. if ( session === null ) return;
  15381. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  15382. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  15383. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  15384. // Note that the new renderState won't apply until the next frame. See #18320
  15385. session.updateRenderState( {
  15386. depthNear: cameraVR.near,
  15387. depthFar: cameraVR.far
  15388. } );
  15389. _currentDepthNear = cameraVR.near;
  15390. _currentDepthFar = cameraVR.far;
  15391. }
  15392. const parent = camera.parent;
  15393. const cameras = cameraVR.cameras;
  15394. updateCamera( cameraVR, parent );
  15395. for ( let i = 0; i < cameras.length; i ++ ) {
  15396. updateCamera( cameras[ i ], parent );
  15397. }
  15398. cameraVR.matrixWorld.decompose( cameraVR.position, cameraVR.quaternion, cameraVR.scale );
  15399. // update user camera and its children
  15400. camera.matrix.copy( cameraVR.matrix );
  15401. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  15402. const children = camera.children;
  15403. for ( let i = 0, l = children.length; i < l; i ++ ) {
  15404. children[ i ].updateMatrixWorld( true );
  15405. }
  15406. // update projection matrix for proper view frustum culling
  15407. if ( cameras.length === 2 ) {
  15408. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  15409. } else {
  15410. // assume single camera setup (AR)
  15411. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  15412. }
  15413. };
  15414. this.getCamera = function () {
  15415. return cameraVR;
  15416. };
  15417. this.getFoveation = function () {
  15418. if ( glProjLayer === null && glBaseLayer === null ) {
  15419. return undefined;
  15420. }
  15421. return foveation;
  15422. };
  15423. this.setFoveation = function ( value ) {
  15424. // 0 = no foveation = full resolution
  15425. // 1 = maximum foveation = the edges render at lower resolution
  15426. foveation = value;
  15427. if ( glProjLayer !== null ) {
  15428. glProjLayer.fixedFoveation = value;
  15429. }
  15430. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  15431. glBaseLayer.fixedFoveation = value;
  15432. }
  15433. };
  15434. this.getPlanes = function () {
  15435. return planes;
  15436. };
  15437. // Animation Loop
  15438. let onAnimationFrameCallback = null;
  15439. function onAnimationFrame( time, frame ) {
  15440. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  15441. xrFrame = frame;
  15442. if ( pose !== null ) {
  15443. const views = pose.views;
  15444. if ( glBaseLayer !== null ) {
  15445. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  15446. renderer.setRenderTarget( newRenderTarget );
  15447. }
  15448. let cameraVRNeedsUpdate = false;
  15449. // check if it's necessary to rebuild cameraVR's camera list
  15450. if ( views.length !== cameraVR.cameras.length ) {
  15451. cameraVR.cameras.length = 0;
  15452. cameraVRNeedsUpdate = true;
  15453. }
  15454. for ( let i = 0; i < views.length; i ++ ) {
  15455. const view = views[ i ];
  15456. let viewport = null;
  15457. if ( glBaseLayer !== null ) {
  15458. viewport = glBaseLayer.getViewport( view );
  15459. } else {
  15460. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  15461. viewport = glSubImage.viewport;
  15462. // For side-by-side projection, we only produce a single texture for both eyes.
  15463. if ( i === 0 ) {
  15464. renderer.setRenderTargetTextures(
  15465. newRenderTarget,
  15466. glSubImage.colorTexture,
  15467. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  15468. renderer.setRenderTarget( newRenderTarget );
  15469. }
  15470. }
  15471. let camera = cameras[ i ];
  15472. if ( camera === undefined ) {
  15473. camera = new PerspectiveCamera();
  15474. camera.layers.enable( i );
  15475. camera.viewport = new Vector4();
  15476. cameras[ i ] = camera;
  15477. }
  15478. camera.matrix.fromArray( view.transform.matrix );
  15479. camera.projectionMatrix.fromArray( view.projectionMatrix );
  15480. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  15481. if ( i === 0 ) {
  15482. cameraVR.matrix.copy( camera.matrix );
  15483. }
  15484. if ( cameraVRNeedsUpdate === true ) {
  15485. cameraVR.cameras.push( camera );
  15486. }
  15487. }
  15488. }
  15489. //
  15490. for ( let i = 0; i < controllers.length; i ++ ) {
  15491. const inputSource = controllerInputSources[ i ];
  15492. const controller = controllers[ i ];
  15493. if ( inputSource !== null && controller !== undefined ) {
  15494. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  15495. }
  15496. }
  15497. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  15498. if ( frame.detectedPlanes ) {
  15499. scope.dispatchEvent( { type: 'planesdetected', data: frame.detectedPlanes } );
  15500. let planesToRemove = null;
  15501. for ( const plane of planes ) {
  15502. if ( ! frame.detectedPlanes.has( plane ) ) {
  15503. if ( planesToRemove === null ) {
  15504. planesToRemove = [];
  15505. }
  15506. planesToRemove.push( plane );
  15507. }
  15508. }
  15509. if ( planesToRemove !== null ) {
  15510. for ( const plane of planesToRemove ) {
  15511. planes.delete( plane );
  15512. planesLastChangedTimes.delete( plane );
  15513. scope.dispatchEvent( { type: 'planeremoved', data: plane } );
  15514. }
  15515. }
  15516. for ( const plane of frame.detectedPlanes ) {
  15517. if ( ! planes.has( plane ) ) {
  15518. planes.add( plane );
  15519. planesLastChangedTimes.set( plane, frame.lastChangedTime );
  15520. scope.dispatchEvent( { type: 'planeadded', data: plane } );
  15521. } else {
  15522. const lastKnownTime = planesLastChangedTimes.get( plane );
  15523. if ( plane.lastChangedTime > lastKnownTime ) {
  15524. planesLastChangedTimes.set( plane, plane.lastChangedTime );
  15525. scope.dispatchEvent( { type: 'planechanged', data: plane } );
  15526. }
  15527. }
  15528. }
  15529. }
  15530. xrFrame = null;
  15531. }
  15532. const animation = new WebGLAnimation();
  15533. animation.setAnimationLoop( onAnimationFrame );
  15534. this.setAnimationLoop = function ( callback ) {
  15535. onAnimationFrameCallback = callback;
  15536. };
  15537. this.dispose = function () {};
  15538. }
  15539. }
  15540. function WebGLMaterials( renderer, properties ) {
  15541. function refreshFogUniforms( uniforms, fog ) {
  15542. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  15543. if ( fog.isFog ) {
  15544. uniforms.fogNear.value = fog.near;
  15545. uniforms.fogFar.value = fog.far;
  15546. } else if ( fog.isFogExp2 ) {
  15547. uniforms.fogDensity.value = fog.density;
  15548. }
  15549. }
  15550. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  15551. if ( material.isMeshBasicMaterial ) {
  15552. refreshUniformsCommon( uniforms, material );
  15553. } else if ( material.isMeshLambertMaterial ) {
  15554. refreshUniformsCommon( uniforms, material );
  15555. } else if ( material.isMeshToonMaterial ) {
  15556. refreshUniformsCommon( uniforms, material );
  15557. refreshUniformsToon( uniforms, material );
  15558. } else if ( material.isMeshPhongMaterial ) {
  15559. refreshUniformsCommon( uniforms, material );
  15560. refreshUniformsPhong( uniforms, material );
  15561. } else if ( material.isMeshStandardMaterial ) {
  15562. refreshUniformsCommon( uniforms, material );
  15563. refreshUniformsStandard( uniforms, material );
  15564. if ( material.isMeshPhysicalMaterial ) {
  15565. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  15566. }
  15567. } else if ( material.isMeshMatcapMaterial ) {
  15568. refreshUniformsCommon( uniforms, material );
  15569. refreshUniformsMatcap( uniforms, material );
  15570. } else if ( material.isMeshDepthMaterial ) {
  15571. refreshUniformsCommon( uniforms, material );
  15572. } else if ( material.isMeshDistanceMaterial ) {
  15573. refreshUniformsCommon( uniforms, material );
  15574. refreshUniformsDistance( uniforms, material );
  15575. } else if ( material.isMeshNormalMaterial ) {
  15576. refreshUniformsCommon( uniforms, material );
  15577. } else if ( material.isLineBasicMaterial ) {
  15578. refreshUniformsLine( uniforms, material );
  15579. if ( material.isLineDashedMaterial ) {
  15580. refreshUniformsDash( uniforms, material );
  15581. }
  15582. } else if ( material.isPointsMaterial ) {
  15583. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  15584. } else if ( material.isSpriteMaterial ) {
  15585. refreshUniformsSprites( uniforms, material );
  15586. } else if ( material.isShadowMaterial ) {
  15587. uniforms.color.value.copy( material.color );
  15588. uniforms.opacity.value = material.opacity;
  15589. } else if ( material.isShaderMaterial ) {
  15590. material.uniformsNeedUpdate = false; // #15581
  15591. }
  15592. }
  15593. function refreshUniformsCommon( uniforms, material ) {
  15594. uniforms.opacity.value = material.opacity;
  15595. if ( material.color ) {
  15596. uniforms.diffuse.value.copy( material.color );
  15597. }
  15598. if ( material.emissive ) {
  15599. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  15600. }
  15601. if ( material.map ) {
  15602. uniforms.map.value = material.map;
  15603. }
  15604. if ( material.alphaMap ) {
  15605. uniforms.alphaMap.value = material.alphaMap;
  15606. }
  15607. if ( material.bumpMap ) {
  15608. uniforms.bumpMap.value = material.bumpMap;
  15609. uniforms.bumpScale.value = material.bumpScale;
  15610. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  15611. }
  15612. if ( material.displacementMap ) {
  15613. uniforms.displacementMap.value = material.displacementMap;
  15614. uniforms.displacementScale.value = material.displacementScale;
  15615. uniforms.displacementBias.value = material.displacementBias;
  15616. }
  15617. if ( material.emissiveMap ) {
  15618. uniforms.emissiveMap.value = material.emissiveMap;
  15619. }
  15620. if ( material.normalMap ) {
  15621. uniforms.normalMap.value = material.normalMap;
  15622. uniforms.normalScale.value.copy( material.normalScale );
  15623. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  15624. }
  15625. if ( material.specularMap ) {
  15626. uniforms.specularMap.value = material.specularMap;
  15627. }
  15628. if ( material.alphaTest > 0 ) {
  15629. uniforms.alphaTest.value = material.alphaTest;
  15630. }
  15631. const envMap = properties.get( material ).envMap;
  15632. if ( envMap ) {
  15633. uniforms.envMap.value = envMap;
  15634. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  15635. uniforms.reflectivity.value = material.reflectivity;
  15636. uniforms.ior.value = material.ior;
  15637. uniforms.refractionRatio.value = material.refractionRatio;
  15638. }
  15639. if ( material.lightMap ) {
  15640. uniforms.lightMap.value = material.lightMap;
  15641. // artist-friendly light intensity scaling factor
  15642. const scaleFactor = ( renderer.useLegacyLights === true ) ? Math.PI : 1;
  15643. uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor;
  15644. }
  15645. if ( material.aoMap ) {
  15646. uniforms.aoMap.value = material.aoMap;
  15647. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15648. }
  15649. // uv repeat and offset setting priorities
  15650. // 1. color map
  15651. // 2. specular map
  15652. // 3. displacementMap map
  15653. // 4. normal map
  15654. // 5. bump map
  15655. // 6. roughnessMap map
  15656. // 7. metalnessMap map
  15657. // 8. alphaMap map
  15658. // 9. emissiveMap map
  15659. // 10. clearcoat map
  15660. // 11. clearcoat normal map
  15661. // 12. clearcoat roughnessMap map
  15662. // 13. iridescence map
  15663. // 14. iridescence thickness map
  15664. // 15. specular intensity map
  15665. // 16. specular tint map
  15666. // 17. transmission map
  15667. // 18. thickness map
  15668. let uvScaleMap;
  15669. if ( material.map ) {
  15670. uvScaleMap = material.map;
  15671. } else if ( material.specularMap ) {
  15672. uvScaleMap = material.specularMap;
  15673. } else if ( material.displacementMap ) {
  15674. uvScaleMap = material.displacementMap;
  15675. } else if ( material.normalMap ) {
  15676. uvScaleMap = material.normalMap;
  15677. } else if ( material.bumpMap ) {
  15678. uvScaleMap = material.bumpMap;
  15679. } else if ( material.roughnessMap ) {
  15680. uvScaleMap = material.roughnessMap;
  15681. } else if ( material.metalnessMap ) {
  15682. uvScaleMap = material.metalnessMap;
  15683. } else if ( material.alphaMap ) {
  15684. uvScaleMap = material.alphaMap;
  15685. } else if ( material.emissiveMap ) {
  15686. uvScaleMap = material.emissiveMap;
  15687. } else if ( material.clearcoatMap ) {
  15688. uvScaleMap = material.clearcoatMap;
  15689. } else if ( material.clearcoatNormalMap ) {
  15690. uvScaleMap = material.clearcoatNormalMap;
  15691. } else if ( material.clearcoatRoughnessMap ) {
  15692. uvScaleMap = material.clearcoatRoughnessMap;
  15693. } else if ( material.iridescenceMap ) {
  15694. uvScaleMap = material.iridescenceMap;
  15695. } else if ( material.iridescenceThicknessMap ) {
  15696. uvScaleMap = material.iridescenceThicknessMap;
  15697. } else if ( material.specularIntensityMap ) {
  15698. uvScaleMap = material.specularIntensityMap;
  15699. } else if ( material.specularColorMap ) {
  15700. uvScaleMap = material.specularColorMap;
  15701. } else if ( material.transmissionMap ) {
  15702. uvScaleMap = material.transmissionMap;
  15703. } else if ( material.thicknessMap ) {
  15704. uvScaleMap = material.thicknessMap;
  15705. } else if ( material.sheenColorMap ) {
  15706. uvScaleMap = material.sheenColorMap;
  15707. } else if ( material.sheenRoughnessMap ) {
  15708. uvScaleMap = material.sheenRoughnessMap;
  15709. }
  15710. if ( uvScaleMap !== undefined ) {
  15711. // backwards compatibility
  15712. if ( uvScaleMap.isWebGLRenderTarget ) {
  15713. uvScaleMap = uvScaleMap.texture;
  15714. }
  15715. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15716. uvScaleMap.updateMatrix();
  15717. }
  15718. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15719. }
  15720. // uv repeat and offset setting priorities for uv2
  15721. // 1. ao map
  15722. // 2. light map
  15723. let uv2ScaleMap;
  15724. if ( material.aoMap ) {
  15725. uv2ScaleMap = material.aoMap;
  15726. } else if ( material.lightMap ) {
  15727. uv2ScaleMap = material.lightMap;
  15728. }
  15729. if ( uv2ScaleMap !== undefined ) {
  15730. // backwards compatibility
  15731. if ( uv2ScaleMap.isWebGLRenderTarget ) {
  15732. uv2ScaleMap = uv2ScaleMap.texture;
  15733. }
  15734. if ( uv2ScaleMap.matrixAutoUpdate === true ) {
  15735. uv2ScaleMap.updateMatrix();
  15736. }
  15737. uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );
  15738. }
  15739. }
  15740. function refreshUniformsLine( uniforms, material ) {
  15741. uniforms.diffuse.value.copy( material.color );
  15742. uniforms.opacity.value = material.opacity;
  15743. }
  15744. function refreshUniformsDash( uniforms, material ) {
  15745. uniforms.dashSize.value = material.dashSize;
  15746. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15747. uniforms.scale.value = material.scale;
  15748. }
  15749. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  15750. uniforms.diffuse.value.copy( material.color );
  15751. uniforms.opacity.value = material.opacity;
  15752. uniforms.size.value = material.size * pixelRatio;
  15753. uniforms.scale.value = height * 0.5;
  15754. if ( material.map ) {
  15755. uniforms.map.value = material.map;
  15756. }
  15757. if ( material.alphaMap ) {
  15758. uniforms.alphaMap.value = material.alphaMap;
  15759. }
  15760. if ( material.alphaTest > 0 ) {
  15761. uniforms.alphaTest.value = material.alphaTest;
  15762. }
  15763. // uv repeat and offset setting priorities
  15764. // 1. color map
  15765. // 2. alpha map
  15766. let uvScaleMap;
  15767. if ( material.map ) {
  15768. uvScaleMap = material.map;
  15769. } else if ( material.alphaMap ) {
  15770. uvScaleMap = material.alphaMap;
  15771. }
  15772. if ( uvScaleMap !== undefined ) {
  15773. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15774. uvScaleMap.updateMatrix();
  15775. }
  15776. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15777. }
  15778. }
  15779. function refreshUniformsSprites( uniforms, material ) {
  15780. uniforms.diffuse.value.copy( material.color );
  15781. uniforms.opacity.value = material.opacity;
  15782. uniforms.rotation.value = material.rotation;
  15783. if ( material.map ) {
  15784. uniforms.map.value = material.map;
  15785. }
  15786. if ( material.alphaMap ) {
  15787. uniforms.alphaMap.value = material.alphaMap;
  15788. }
  15789. if ( material.alphaTest > 0 ) {
  15790. uniforms.alphaTest.value = material.alphaTest;
  15791. }
  15792. // uv repeat and offset setting priorities
  15793. // 1. color map
  15794. // 2. alpha map
  15795. let uvScaleMap;
  15796. if ( material.map ) {
  15797. uvScaleMap = material.map;
  15798. } else if ( material.alphaMap ) {
  15799. uvScaleMap = material.alphaMap;
  15800. }
  15801. if ( uvScaleMap !== undefined ) {
  15802. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15803. uvScaleMap.updateMatrix();
  15804. }
  15805. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15806. }
  15807. }
  15808. function refreshUniformsPhong( uniforms, material ) {
  15809. uniforms.specular.value.copy( material.specular );
  15810. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  15811. }
  15812. function refreshUniformsToon( uniforms, material ) {
  15813. if ( material.gradientMap ) {
  15814. uniforms.gradientMap.value = material.gradientMap;
  15815. }
  15816. }
  15817. function refreshUniformsStandard( uniforms, material ) {
  15818. uniforms.roughness.value = material.roughness;
  15819. uniforms.metalness.value = material.metalness;
  15820. if ( material.roughnessMap ) {
  15821. uniforms.roughnessMap.value = material.roughnessMap;
  15822. }
  15823. if ( material.metalnessMap ) {
  15824. uniforms.metalnessMap.value = material.metalnessMap;
  15825. }
  15826. const envMap = properties.get( material ).envMap;
  15827. if ( envMap ) {
  15828. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15829. uniforms.envMapIntensity.value = material.envMapIntensity;
  15830. }
  15831. }
  15832. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  15833. uniforms.ior.value = material.ior; // also part of uniforms common
  15834. if ( material.sheen > 0 ) {
  15835. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  15836. uniforms.sheenRoughness.value = material.sheenRoughness;
  15837. if ( material.sheenColorMap ) {
  15838. uniforms.sheenColorMap.value = material.sheenColorMap;
  15839. }
  15840. if ( material.sheenRoughnessMap ) {
  15841. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  15842. }
  15843. }
  15844. if ( material.clearcoat > 0 ) {
  15845. uniforms.clearcoat.value = material.clearcoat;
  15846. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  15847. if ( material.clearcoatMap ) {
  15848. uniforms.clearcoatMap.value = material.clearcoatMap;
  15849. }
  15850. if ( material.clearcoatRoughnessMap ) {
  15851. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  15852. }
  15853. if ( material.clearcoatNormalMap ) {
  15854. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  15855. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  15856. if ( material.side === BackSide ) {
  15857. uniforms.clearcoatNormalScale.value.negate();
  15858. }
  15859. }
  15860. }
  15861. if ( material.iridescence > 0 ) {
  15862. uniforms.iridescence.value = material.iridescence;
  15863. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  15864. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  15865. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  15866. if ( material.iridescenceMap ) {
  15867. uniforms.iridescenceMap.value = material.iridescenceMap;
  15868. }
  15869. if ( material.iridescenceThicknessMap ) {
  15870. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  15871. }
  15872. }
  15873. if ( material.transmission > 0 ) {
  15874. uniforms.transmission.value = material.transmission;
  15875. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  15876. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  15877. if ( material.transmissionMap ) {
  15878. uniforms.transmissionMap.value = material.transmissionMap;
  15879. }
  15880. uniforms.thickness.value = material.thickness;
  15881. if ( material.thicknessMap ) {
  15882. uniforms.thicknessMap.value = material.thicknessMap;
  15883. }
  15884. uniforms.attenuationDistance.value = material.attenuationDistance;
  15885. uniforms.attenuationColor.value.copy( material.attenuationColor );
  15886. }
  15887. uniforms.specularIntensity.value = material.specularIntensity;
  15888. uniforms.specularColor.value.copy( material.specularColor );
  15889. if ( material.specularIntensityMap ) {
  15890. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  15891. }
  15892. if ( material.specularColorMap ) {
  15893. uniforms.specularColorMap.value = material.specularColorMap;
  15894. }
  15895. }
  15896. function refreshUniformsMatcap( uniforms, material ) {
  15897. if ( material.matcap ) {
  15898. uniforms.matcap.value = material.matcap;
  15899. }
  15900. }
  15901. function refreshUniformsDistance( uniforms, material ) {
  15902. uniforms.referencePosition.value.copy( material.referencePosition );
  15903. uniforms.nearDistance.value = material.nearDistance;
  15904. uniforms.farDistance.value = material.farDistance;
  15905. }
  15906. return {
  15907. refreshFogUniforms: refreshFogUniforms,
  15908. refreshMaterialUniforms: refreshMaterialUniforms
  15909. };
  15910. }
  15911. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  15912. let buffers = {};
  15913. let updateList = {};
  15914. let allocatedBindingPoints = [];
  15915. const maxBindingPoints = ( capabilities.isWebGL2 ) ? gl.getParameter( 35375 ) : 0; // binding points are global whereas block indices are per shader program
  15916. function bind( uniformsGroup, program ) {
  15917. const webglProgram = program.program;
  15918. state.uniformBlockBinding( uniformsGroup, webglProgram );
  15919. }
  15920. function update( uniformsGroup, program ) {
  15921. let buffer = buffers[ uniformsGroup.id ];
  15922. if ( buffer === undefined ) {
  15923. prepareUniformsGroup( uniformsGroup );
  15924. buffer = createBuffer( uniformsGroup );
  15925. buffers[ uniformsGroup.id ] = buffer;
  15926. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  15927. }
  15928. // ensure to update the binding points/block indices mapping for this program
  15929. const webglProgram = program.program;
  15930. state.updateUBOMapping( uniformsGroup, webglProgram );
  15931. // update UBO once per frame
  15932. const frame = info.render.frame;
  15933. if ( updateList[ uniformsGroup.id ] !== frame ) {
  15934. updateBufferData( uniformsGroup );
  15935. updateList[ uniformsGroup.id ] = frame;
  15936. }
  15937. }
  15938. function createBuffer( uniformsGroup ) {
  15939. // the setup of an UBO is independent of a particular shader program but global
  15940. const bindingPointIndex = allocateBindingPointIndex();
  15941. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  15942. const buffer = gl.createBuffer();
  15943. const size = uniformsGroup.__size;
  15944. const usage = uniformsGroup.usage;
  15945. gl.bindBuffer( 35345, buffer );
  15946. gl.bufferData( 35345, size, usage );
  15947. gl.bindBuffer( 35345, null );
  15948. gl.bindBufferBase( 35345, bindingPointIndex, buffer );
  15949. return buffer;
  15950. }
  15951. function allocateBindingPointIndex() {
  15952. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  15953. if ( allocatedBindingPoints.indexOf( i ) === - 1 ) {
  15954. allocatedBindingPoints.push( i );
  15955. return i;
  15956. }
  15957. }
  15958. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  15959. return 0;
  15960. }
  15961. function updateBufferData( uniformsGroup ) {
  15962. const buffer = buffers[ uniformsGroup.id ];
  15963. const uniforms = uniformsGroup.uniforms;
  15964. const cache = uniformsGroup.__cache;
  15965. gl.bindBuffer( 35345, buffer );
  15966. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  15967. const uniform = uniforms[ i ];
  15968. // partly update the buffer if necessary
  15969. if ( hasUniformChanged( uniform, i, cache ) === true ) {
  15970. const offset = uniform.__offset;
  15971. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  15972. let arrayOffset = 0;
  15973. for ( let i = 0; i < values.length; i ++ ) {
  15974. const value = values[ i ];
  15975. const info = getUniformSize( value );
  15976. if ( typeof value === 'number' ) {
  15977. uniform.__data[ 0 ] = value;
  15978. gl.bufferSubData( 35345, offset + arrayOffset, uniform.__data );
  15979. } else if ( value.isMatrix3 ) {
  15980. // manually converting 3x3 to 3x4
  15981. uniform.__data[ 0 ] = value.elements[ 0 ];
  15982. uniform.__data[ 1 ] = value.elements[ 1 ];
  15983. uniform.__data[ 2 ] = value.elements[ 2 ];
  15984. uniform.__data[ 3 ] = value.elements[ 0 ];
  15985. uniform.__data[ 4 ] = value.elements[ 3 ];
  15986. uniform.__data[ 5 ] = value.elements[ 4 ];
  15987. uniform.__data[ 6 ] = value.elements[ 5 ];
  15988. uniform.__data[ 7 ] = value.elements[ 0 ];
  15989. uniform.__data[ 8 ] = value.elements[ 6 ];
  15990. uniform.__data[ 9 ] = value.elements[ 7 ];
  15991. uniform.__data[ 10 ] = value.elements[ 8 ];
  15992. uniform.__data[ 11 ] = value.elements[ 0 ];
  15993. } else {
  15994. value.toArray( uniform.__data, arrayOffset );
  15995. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  15996. }
  15997. }
  15998. gl.bufferSubData( 35345, offset, uniform.__data );
  15999. }
  16000. }
  16001. gl.bindBuffer( 35345, null );
  16002. }
  16003. function hasUniformChanged( uniform, index, cache ) {
  16004. const value = uniform.value;
  16005. if ( cache[ index ] === undefined ) {
  16006. // cache entry does not exist so far
  16007. if ( typeof value === 'number' ) {
  16008. cache[ index ] = value;
  16009. } else {
  16010. const values = Array.isArray( value ) ? value : [ value ];
  16011. const tempValues = [];
  16012. for ( let i = 0; i < values.length; i ++ ) {
  16013. tempValues.push( values[ i ].clone() );
  16014. }
  16015. cache[ index ] = tempValues;
  16016. }
  16017. return true;
  16018. } else {
  16019. // compare current value with cached entry
  16020. if ( typeof value === 'number' ) {
  16021. if ( cache[ index ] !== value ) {
  16022. cache[ index ] = value;
  16023. return true;
  16024. }
  16025. } else {
  16026. const cachedObjects = Array.isArray( cache[ index ] ) ? cache[ index ] : [ cache[ index ] ];
  16027. const values = Array.isArray( value ) ? value : [ value ];
  16028. for ( let i = 0; i < cachedObjects.length; i ++ ) {
  16029. const cachedObject = cachedObjects[ i ];
  16030. if ( cachedObject.equals( values[ i ] ) === false ) {
  16031. cachedObject.copy( values[ i ] );
  16032. return true;
  16033. }
  16034. }
  16035. }
  16036. }
  16037. return false;
  16038. }
  16039. function prepareUniformsGroup( uniformsGroup ) {
  16040. // determine total buffer size according to the STD140 layout
  16041. // Hint: STD140 is the only supported layout in WebGL 2
  16042. const uniforms = uniformsGroup.uniforms;
  16043. let offset = 0; // global buffer offset in bytes
  16044. const chunkSize = 16; // size of a chunk in bytes
  16045. let chunkOffset = 0; // offset within a single chunk in bytes
  16046. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  16047. const uniform = uniforms[ i ];
  16048. const infos = {
  16049. boundary: 0, // bytes
  16050. storage: 0 // bytes
  16051. };
  16052. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  16053. for ( let j = 0, jl = values.length; j < jl; j ++ ) {
  16054. const value = values[ j ];
  16055. const info = getUniformSize( value );
  16056. infos.boundary += info.boundary;
  16057. infos.storage += info.storage;
  16058. }
  16059. // the following two properties will be used for partial buffer updates
  16060. uniform.__data = new Float32Array( infos.storage / Float32Array.BYTES_PER_ELEMENT );
  16061. uniform.__offset = offset;
  16062. //
  16063. if ( i > 0 ) {
  16064. chunkOffset = offset % chunkSize;
  16065. const remainingSizeInChunk = chunkSize - chunkOffset;
  16066. // check for chunk overflow
  16067. if ( chunkOffset !== 0 && ( remainingSizeInChunk - infos.boundary ) < 0 ) {
  16068. // add padding and adjust offset
  16069. offset += ( chunkSize - chunkOffset );
  16070. uniform.__offset = offset;
  16071. }
  16072. }
  16073. offset += infos.storage;
  16074. }
  16075. // ensure correct final padding
  16076. chunkOffset = offset % chunkSize;
  16077. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  16078. //
  16079. uniformsGroup.__size = offset;
  16080. uniformsGroup.__cache = {};
  16081. return this;
  16082. }
  16083. function getUniformSize( value ) {
  16084. const info = {
  16085. boundary: 0, // bytes
  16086. storage: 0 // bytes
  16087. };
  16088. // determine sizes according to STD140
  16089. if ( typeof value === 'number' ) {
  16090. // float/int
  16091. info.boundary = 4;
  16092. info.storage = 4;
  16093. } else if ( value.isVector2 ) {
  16094. // vec2
  16095. info.boundary = 8;
  16096. info.storage = 8;
  16097. } else if ( value.isVector3 || value.isColor ) {
  16098. // vec3
  16099. info.boundary = 16;
  16100. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  16101. } else if ( value.isVector4 ) {
  16102. // vec4
  16103. info.boundary = 16;
  16104. info.storage = 16;
  16105. } else if ( value.isMatrix3 ) {
  16106. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  16107. info.boundary = 48;
  16108. info.storage = 48;
  16109. } else if ( value.isMatrix4 ) {
  16110. // mat4
  16111. info.boundary = 64;
  16112. info.storage = 64;
  16113. } else if ( value.isTexture ) {
  16114. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  16115. } else {
  16116. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  16117. }
  16118. return info;
  16119. }
  16120. function onUniformsGroupsDispose( event ) {
  16121. const uniformsGroup = event.target;
  16122. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  16123. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  16124. allocatedBindingPoints.splice( index, 1 );
  16125. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  16126. delete buffers[ uniformsGroup.id ];
  16127. delete updateList[ uniformsGroup.id ];
  16128. }
  16129. function dispose() {
  16130. for ( const id in buffers ) {
  16131. gl.deleteBuffer( buffers[ id ] );
  16132. }
  16133. allocatedBindingPoints = [];
  16134. buffers = {};
  16135. updateList = {};
  16136. }
  16137. return {
  16138. bind: bind,
  16139. update: update,
  16140. dispose: dispose
  16141. };
  16142. }
  16143. function createCanvasElement() {
  16144. const canvas = createElementNS( 'canvas' );
  16145. canvas.style.display = 'block';
  16146. return canvas;
  16147. }
  16148. function WebGLRenderer( parameters = {} ) {
  16149. this.isWebGLRenderer = true;
  16150. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  16151. _context = parameters.context !== undefined ? parameters.context : null,
  16152. _depth = parameters.depth !== undefined ? parameters.depth : true,
  16153. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  16154. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  16155. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  16156. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  16157. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  16158. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  16159. let _alpha;
  16160. if ( _context !== null ) {
  16161. _alpha = _context.getContextAttributes().alpha;
  16162. } else {
  16163. _alpha = parameters.alpha !== undefined ? parameters.alpha : false;
  16164. }
  16165. let currentRenderList = null;
  16166. let currentRenderState = null;
  16167. // render() can be called from within a callback triggered by another render.
  16168. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  16169. const renderListStack = [];
  16170. const renderStateStack = [];
  16171. // public properties
  16172. this.domElement = _canvas;
  16173. // Debug configuration container
  16174. this.debug = {
  16175. /**
  16176. * Enables error checking and reporting when shader programs are being compiled
  16177. * @type {boolean}
  16178. */
  16179. checkShaderErrors: true
  16180. };
  16181. // clearing
  16182. this.autoClear = true;
  16183. this.autoClearColor = true;
  16184. this.autoClearDepth = true;
  16185. this.autoClearStencil = true;
  16186. // scene graph
  16187. this.sortObjects = true;
  16188. // user-defined clipping
  16189. this.clippingPlanes = [];
  16190. this.localClippingEnabled = false;
  16191. // physically based shading
  16192. this.outputEncoding = LinearEncoding;
  16193. // physical lights
  16194. this.useLegacyLights = true;
  16195. // tone mapping
  16196. this.toneMapping = NoToneMapping;
  16197. this.toneMappingExposure = 1.0;
  16198. // internal properties
  16199. const _this = this;
  16200. let _isContextLost = false;
  16201. // internal state cache
  16202. let _currentActiveCubeFace = 0;
  16203. let _currentActiveMipmapLevel = 0;
  16204. let _currentRenderTarget = null;
  16205. let _currentMaterialId = - 1;
  16206. let _currentCamera = null;
  16207. const _currentViewport = new Vector4();
  16208. const _currentScissor = new Vector4();
  16209. let _currentScissorTest = null;
  16210. //
  16211. let _width = _canvas.width;
  16212. let _height = _canvas.height;
  16213. let _pixelRatio = 1;
  16214. let _opaqueSort = null;
  16215. let _transparentSort = null;
  16216. const _viewport = new Vector4( 0, 0, _width, _height );
  16217. const _scissor = new Vector4( 0, 0, _width, _height );
  16218. let _scissorTest = false;
  16219. // frustum
  16220. const _frustum = new Frustum();
  16221. // clipping
  16222. let _clippingEnabled = false;
  16223. let _localClippingEnabled = false;
  16224. // transmission
  16225. let _transmissionRenderTarget = null;
  16226. // camera matrices cache
  16227. const _projScreenMatrix = new Matrix4();
  16228. const _vector3 = new Vector3();
  16229. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  16230. function getTargetPixelRatio() {
  16231. return _currentRenderTarget === null ? _pixelRatio : 1;
  16232. }
  16233. // initialize
  16234. let _gl = _context;
  16235. function getContext( contextNames, contextAttributes ) {
  16236. for ( let i = 0; i < contextNames.length; i ++ ) {
  16237. const contextName = contextNames[ i ];
  16238. const context = _canvas.getContext( contextName, contextAttributes );
  16239. if ( context !== null ) return context;
  16240. }
  16241. return null;
  16242. }
  16243. try {
  16244. const contextAttributes = {
  16245. alpha: true,
  16246. depth: _depth,
  16247. stencil: _stencil,
  16248. antialias: _antialias,
  16249. premultipliedAlpha: _premultipliedAlpha,
  16250. preserveDrawingBuffer: _preserveDrawingBuffer,
  16251. powerPreference: _powerPreference,
  16252. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  16253. };
  16254. // OffscreenCanvas does not have setAttribute, see #22811
  16255. if ( 'setAttribute' in _canvas ) _canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  16256. // event listeners must be registered before WebGL context is created, see #12753
  16257. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  16258. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  16259. _canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16260. if ( _gl === null ) {
  16261. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  16262. if ( _this.isWebGL1Renderer === true ) {
  16263. contextNames.shift();
  16264. }
  16265. _gl = getContext( contextNames, contextAttributes );
  16266. if ( _gl === null ) {
  16267. if ( getContext( contextNames ) ) {
  16268. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  16269. } else {
  16270. throw new Error( 'Error creating WebGL context.' );
  16271. }
  16272. }
  16273. }
  16274. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  16275. if ( _gl.getShaderPrecisionFormat === undefined ) {
  16276. _gl.getShaderPrecisionFormat = function () {
  16277. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  16278. };
  16279. }
  16280. } catch ( error ) {
  16281. console.error( 'THREE.WebGLRenderer: ' + error.message );
  16282. throw error;
  16283. }
  16284. let extensions, capabilities, state, info;
  16285. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  16286. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  16287. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  16288. let utils, bindingStates, uniformsGroups;
  16289. function initGLContext() {
  16290. extensions = new WebGLExtensions( _gl );
  16291. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  16292. extensions.init( capabilities );
  16293. utils = new WebGLUtils( _gl, extensions, capabilities );
  16294. state = new WebGLState( _gl, extensions, capabilities );
  16295. info = new WebGLInfo();
  16296. properties = new WebGLProperties();
  16297. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  16298. cubemaps = new WebGLCubeMaps( _this );
  16299. cubeuvmaps = new WebGLCubeUVMaps( _this );
  16300. attributes = new WebGLAttributes( _gl, capabilities );
  16301. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  16302. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  16303. objects = new WebGLObjects( _gl, geometries, attributes, info );
  16304. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  16305. clipping = new WebGLClipping( properties );
  16306. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  16307. materials = new WebGLMaterials( _this, properties );
  16308. renderLists = new WebGLRenderLists();
  16309. renderStates = new WebGLRenderStates( extensions, capabilities );
  16310. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, _premultipliedAlpha );
  16311. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  16312. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  16313. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  16314. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  16315. info.programs = programCache.programs;
  16316. _this.capabilities = capabilities;
  16317. _this.extensions = extensions;
  16318. _this.properties = properties;
  16319. _this.renderLists = renderLists;
  16320. _this.shadowMap = shadowMap;
  16321. _this.state = state;
  16322. _this.info = info;
  16323. }
  16324. initGLContext();
  16325. // xr
  16326. const xr = new WebXRManager( _this, _gl );
  16327. this.xr = xr;
  16328. // API
  16329. this.getContext = function () {
  16330. return _gl;
  16331. };
  16332. this.getContextAttributes = function () {
  16333. return _gl.getContextAttributes();
  16334. };
  16335. this.forceContextLoss = function () {
  16336. const extension = extensions.get( 'WEBGL_lose_context' );
  16337. if ( extension ) extension.loseContext();
  16338. };
  16339. this.forceContextRestore = function () {
  16340. const extension = extensions.get( 'WEBGL_lose_context' );
  16341. if ( extension ) extension.restoreContext();
  16342. };
  16343. this.getPixelRatio = function () {
  16344. return _pixelRatio;
  16345. };
  16346. this.setPixelRatio = function ( value ) {
  16347. if ( value === undefined ) return;
  16348. _pixelRatio = value;
  16349. this.setSize( _width, _height, false );
  16350. };
  16351. this.getSize = function ( target ) {
  16352. return target.set( _width, _height );
  16353. };
  16354. this.setSize = function ( width, height, updateStyle = true ) {
  16355. if ( xr.isPresenting ) {
  16356. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  16357. return;
  16358. }
  16359. _width = width;
  16360. _height = height;
  16361. _canvas.width = Math.floor( width * _pixelRatio );
  16362. _canvas.height = Math.floor( height * _pixelRatio );
  16363. if ( updateStyle === true ) {
  16364. _canvas.style.width = width + 'px';
  16365. _canvas.style.height = height + 'px';
  16366. }
  16367. this.setViewport( 0, 0, width, height );
  16368. };
  16369. this.getDrawingBufferSize = function ( target ) {
  16370. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  16371. };
  16372. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  16373. _width = width;
  16374. _height = height;
  16375. _pixelRatio = pixelRatio;
  16376. _canvas.width = Math.floor( width * pixelRatio );
  16377. _canvas.height = Math.floor( height * pixelRatio );
  16378. this.setViewport( 0, 0, width, height );
  16379. };
  16380. this.getCurrentViewport = function ( target ) {
  16381. return target.copy( _currentViewport );
  16382. };
  16383. this.getViewport = function ( target ) {
  16384. return target.copy( _viewport );
  16385. };
  16386. this.setViewport = function ( x, y, width, height ) {
  16387. if ( x.isVector4 ) {
  16388. _viewport.set( x.x, x.y, x.z, x.w );
  16389. } else {
  16390. _viewport.set( x, y, width, height );
  16391. }
  16392. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  16393. };
  16394. this.getScissor = function ( target ) {
  16395. return target.copy( _scissor );
  16396. };
  16397. this.setScissor = function ( x, y, width, height ) {
  16398. if ( x.isVector4 ) {
  16399. _scissor.set( x.x, x.y, x.z, x.w );
  16400. } else {
  16401. _scissor.set( x, y, width, height );
  16402. }
  16403. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  16404. };
  16405. this.getScissorTest = function () {
  16406. return _scissorTest;
  16407. };
  16408. this.setScissorTest = function ( boolean ) {
  16409. state.setScissorTest( _scissorTest = boolean );
  16410. };
  16411. this.setOpaqueSort = function ( method ) {
  16412. _opaqueSort = method;
  16413. };
  16414. this.setTransparentSort = function ( method ) {
  16415. _transparentSort = method;
  16416. };
  16417. // Clearing
  16418. this.getClearColor = function ( target ) {
  16419. return target.copy( background.getClearColor() );
  16420. };
  16421. this.setClearColor = function () {
  16422. background.setClearColor.apply( background, arguments );
  16423. };
  16424. this.getClearAlpha = function () {
  16425. return background.getClearAlpha();
  16426. };
  16427. this.setClearAlpha = function () {
  16428. background.setClearAlpha.apply( background, arguments );
  16429. };
  16430. this.clear = function ( color = true, depth = true, stencil = true ) {
  16431. let bits = 0;
  16432. if ( color ) bits |= 16384;
  16433. if ( depth ) bits |= 256;
  16434. if ( stencil ) bits |= 1024;
  16435. _gl.clear( bits );
  16436. };
  16437. this.clearColor = function () {
  16438. this.clear( true, false, false );
  16439. };
  16440. this.clearDepth = function () {
  16441. this.clear( false, true, false );
  16442. };
  16443. this.clearStencil = function () {
  16444. this.clear( false, false, true );
  16445. };
  16446. //
  16447. this.dispose = function () {
  16448. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  16449. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  16450. _canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16451. renderLists.dispose();
  16452. renderStates.dispose();
  16453. properties.dispose();
  16454. cubemaps.dispose();
  16455. cubeuvmaps.dispose();
  16456. objects.dispose();
  16457. bindingStates.dispose();
  16458. uniformsGroups.dispose();
  16459. programCache.dispose();
  16460. xr.dispose();
  16461. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  16462. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  16463. if ( _transmissionRenderTarget ) {
  16464. _transmissionRenderTarget.dispose();
  16465. _transmissionRenderTarget = null;
  16466. }
  16467. animation.stop();
  16468. };
  16469. // Events
  16470. function onContextLost( event ) {
  16471. event.preventDefault();
  16472. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  16473. _isContextLost = true;
  16474. }
  16475. function onContextRestore( /* event */ ) {
  16476. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  16477. _isContextLost = false;
  16478. const infoAutoReset = info.autoReset;
  16479. const shadowMapEnabled = shadowMap.enabled;
  16480. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  16481. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  16482. const shadowMapType = shadowMap.type;
  16483. initGLContext();
  16484. info.autoReset = infoAutoReset;
  16485. shadowMap.enabled = shadowMapEnabled;
  16486. shadowMap.autoUpdate = shadowMapAutoUpdate;
  16487. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  16488. shadowMap.type = shadowMapType;
  16489. }
  16490. function onContextCreationError( event ) {
  16491. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  16492. }
  16493. function onMaterialDispose( event ) {
  16494. const material = event.target;
  16495. material.removeEventListener( 'dispose', onMaterialDispose );
  16496. deallocateMaterial( material );
  16497. }
  16498. // Buffer deallocation
  16499. function deallocateMaterial( material ) {
  16500. releaseMaterialProgramReferences( material );
  16501. properties.remove( material );
  16502. }
  16503. function releaseMaterialProgramReferences( material ) {
  16504. const programs = properties.get( material ).programs;
  16505. if ( programs !== undefined ) {
  16506. programs.forEach( function ( program ) {
  16507. programCache.releaseProgram( program );
  16508. } );
  16509. if ( material.isShaderMaterial ) {
  16510. programCache.releaseShaderCache( material );
  16511. }
  16512. }
  16513. }
  16514. // Buffer rendering
  16515. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  16516. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  16517. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  16518. const program = setProgram( camera, scene, geometry, material, object );
  16519. state.setMaterial( material, frontFaceCW );
  16520. //
  16521. let index = geometry.index;
  16522. let rangeFactor = 1;
  16523. if ( material.wireframe === true ) {
  16524. index = geometries.getWireframeAttribute( geometry );
  16525. rangeFactor = 2;
  16526. }
  16527. //
  16528. const drawRange = geometry.drawRange;
  16529. const position = geometry.attributes.position;
  16530. let drawStart = drawRange.start * rangeFactor;
  16531. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  16532. if ( group !== null ) {
  16533. drawStart = Math.max( drawStart, group.start * rangeFactor );
  16534. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  16535. }
  16536. if ( index !== null ) {
  16537. drawStart = Math.max( drawStart, 0 );
  16538. drawEnd = Math.min( drawEnd, index.count );
  16539. } else if ( position !== undefined && position !== null ) {
  16540. drawStart = Math.max( drawStart, 0 );
  16541. drawEnd = Math.min( drawEnd, position.count );
  16542. }
  16543. const drawCount = drawEnd - drawStart;
  16544. if ( drawCount < 0 || drawCount === Infinity ) return;
  16545. //
  16546. bindingStates.setup( object, material, program, geometry, index );
  16547. let attribute;
  16548. let renderer = bufferRenderer;
  16549. if ( index !== null ) {
  16550. attribute = attributes.get( index );
  16551. renderer = indexedBufferRenderer;
  16552. renderer.setIndex( attribute );
  16553. }
  16554. //
  16555. if ( object.isMesh ) {
  16556. if ( material.wireframe === true ) {
  16557. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  16558. renderer.setMode( 1 );
  16559. } else {
  16560. renderer.setMode( 4 );
  16561. }
  16562. } else if ( object.isLine ) {
  16563. let lineWidth = material.linewidth;
  16564. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  16565. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  16566. if ( object.isLineSegments ) {
  16567. renderer.setMode( 1 );
  16568. } else if ( object.isLineLoop ) {
  16569. renderer.setMode( 2 );
  16570. } else {
  16571. renderer.setMode( 3 );
  16572. }
  16573. } else if ( object.isPoints ) {
  16574. renderer.setMode( 0 );
  16575. } else if ( object.isSprite ) {
  16576. renderer.setMode( 4 );
  16577. }
  16578. if ( object.isInstancedMesh ) {
  16579. renderer.renderInstances( drawStart, drawCount, object.count );
  16580. } else if ( geometry.isInstancedBufferGeometry ) {
  16581. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  16582. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  16583. renderer.renderInstances( drawStart, drawCount, instanceCount );
  16584. } else {
  16585. renderer.render( drawStart, drawCount );
  16586. }
  16587. };
  16588. // Compile
  16589. this.compile = function ( scene, camera ) {
  16590. function prepare( material, scene, object ) {
  16591. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  16592. material.side = BackSide;
  16593. material.needsUpdate = true;
  16594. getProgram( material, scene, object );
  16595. material.side = FrontSide;
  16596. material.needsUpdate = true;
  16597. getProgram( material, scene, object );
  16598. material.side = DoubleSide;
  16599. } else {
  16600. getProgram( material, scene, object );
  16601. }
  16602. }
  16603. currentRenderState = renderStates.get( scene );
  16604. currentRenderState.init();
  16605. renderStateStack.push( currentRenderState );
  16606. scene.traverseVisible( function ( object ) {
  16607. if ( object.isLight && object.layers.test( camera.layers ) ) {
  16608. currentRenderState.pushLight( object );
  16609. if ( object.castShadow ) {
  16610. currentRenderState.pushShadow( object );
  16611. }
  16612. }
  16613. } );
  16614. currentRenderState.setupLights( _this.useLegacyLights );
  16615. scene.traverse( function ( object ) {
  16616. const material = object.material;
  16617. if ( material ) {
  16618. if ( Array.isArray( material ) ) {
  16619. for ( let i = 0; i < material.length; i ++ ) {
  16620. const material2 = material[ i ];
  16621. prepare( material2, scene, object );
  16622. }
  16623. } else {
  16624. prepare( material, scene, object );
  16625. }
  16626. }
  16627. } );
  16628. renderStateStack.pop();
  16629. currentRenderState = null;
  16630. };
  16631. // Animation Loop
  16632. let onAnimationFrameCallback = null;
  16633. function onAnimationFrame( time ) {
  16634. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  16635. }
  16636. function onXRSessionStart() {
  16637. animation.stop();
  16638. }
  16639. function onXRSessionEnd() {
  16640. animation.start();
  16641. }
  16642. const animation = new WebGLAnimation();
  16643. animation.setAnimationLoop( onAnimationFrame );
  16644. if ( typeof self !== 'undefined' ) animation.setContext( self );
  16645. this.setAnimationLoop = function ( callback ) {
  16646. onAnimationFrameCallback = callback;
  16647. xr.setAnimationLoop( callback );
  16648. ( callback === null ) ? animation.stop() : animation.start();
  16649. };
  16650. xr.addEventListener( 'sessionstart', onXRSessionStart );
  16651. xr.addEventListener( 'sessionend', onXRSessionEnd );
  16652. // Rendering
  16653. this.render = function ( scene, camera ) {
  16654. if ( camera !== undefined && camera.isCamera !== true ) {
  16655. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  16656. return;
  16657. }
  16658. if ( _isContextLost === true ) return;
  16659. // update scene graph
  16660. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  16661. // update camera matrices and frustum
  16662. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  16663. if ( xr.enabled === true && xr.isPresenting === true ) {
  16664. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  16665. camera = xr.getCamera(); // use XR camera for rendering
  16666. }
  16667. //
  16668. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  16669. currentRenderState = renderStates.get( scene, renderStateStack.length );
  16670. currentRenderState.init();
  16671. renderStateStack.push( currentRenderState );
  16672. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16673. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  16674. _localClippingEnabled = this.localClippingEnabled;
  16675. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  16676. currentRenderList = renderLists.get( scene, renderListStack.length );
  16677. currentRenderList.init();
  16678. renderListStack.push( currentRenderList );
  16679. projectObject( scene, camera, 0, _this.sortObjects );
  16680. currentRenderList.finish();
  16681. if ( _this.sortObjects === true ) {
  16682. currentRenderList.sort( _opaqueSort, _transparentSort );
  16683. }
  16684. //
  16685. if ( _clippingEnabled === true ) clipping.beginShadows();
  16686. const shadowsArray = currentRenderState.state.shadowsArray;
  16687. shadowMap.render( shadowsArray, scene, camera );
  16688. if ( _clippingEnabled === true ) clipping.endShadows();
  16689. //
  16690. if ( this.info.autoReset === true ) this.info.reset();
  16691. //
  16692. background.render( currentRenderList, scene );
  16693. // render scene
  16694. currentRenderState.setupLights( _this.useLegacyLights );
  16695. if ( camera.isArrayCamera ) {
  16696. const cameras = camera.cameras;
  16697. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  16698. const camera2 = cameras[ i ];
  16699. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  16700. }
  16701. } else {
  16702. renderScene( currentRenderList, scene, camera );
  16703. }
  16704. //
  16705. if ( _currentRenderTarget !== null ) {
  16706. // resolve multisample renderbuffers to a single-sample texture if necessary
  16707. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  16708. // Generate mipmap if we're using any kind of mipmap filtering
  16709. textures.updateRenderTargetMipmap( _currentRenderTarget );
  16710. }
  16711. //
  16712. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  16713. // _gl.finish();
  16714. bindingStates.resetDefaultState();
  16715. _currentMaterialId = - 1;
  16716. _currentCamera = null;
  16717. renderStateStack.pop();
  16718. if ( renderStateStack.length > 0 ) {
  16719. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  16720. } else {
  16721. currentRenderState = null;
  16722. }
  16723. renderListStack.pop();
  16724. if ( renderListStack.length > 0 ) {
  16725. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  16726. } else {
  16727. currentRenderList = null;
  16728. }
  16729. };
  16730. function projectObject( object, camera, groupOrder, sortObjects ) {
  16731. if ( object.visible === false ) return;
  16732. const visible = object.layers.test( camera.layers );
  16733. if ( visible ) {
  16734. if ( object.isGroup ) {
  16735. groupOrder = object.renderOrder;
  16736. } else if ( object.isLOD ) {
  16737. if ( object.autoUpdate === true ) object.update( camera );
  16738. } else if ( object.isLight ) {
  16739. currentRenderState.pushLight( object );
  16740. if ( object.castShadow ) {
  16741. currentRenderState.pushShadow( object );
  16742. }
  16743. } else if ( object.isSprite ) {
  16744. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  16745. if ( sortObjects ) {
  16746. _vector3.setFromMatrixPosition( object.matrixWorld )
  16747. .applyMatrix4( _projScreenMatrix );
  16748. }
  16749. const geometry = objects.update( object );
  16750. const material = object.material;
  16751. if ( material.visible ) {
  16752. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  16753. }
  16754. }
  16755. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  16756. if ( object.isSkinnedMesh ) {
  16757. // update skeleton only once in a frame
  16758. if ( object.skeleton.frame !== info.render.frame ) {
  16759. object.skeleton.update();
  16760. object.skeleton.frame = info.render.frame;
  16761. }
  16762. }
  16763. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  16764. if ( sortObjects ) {
  16765. _vector3.setFromMatrixPosition( object.matrixWorld )
  16766. .applyMatrix4( _projScreenMatrix );
  16767. }
  16768. const geometry = objects.update( object );
  16769. const material = object.material;
  16770. if ( Array.isArray( material ) ) {
  16771. const groups = geometry.groups;
  16772. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  16773. const group = groups[ i ];
  16774. const groupMaterial = material[ group.materialIndex ];
  16775. if ( groupMaterial && groupMaterial.visible ) {
  16776. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  16777. }
  16778. }
  16779. } else if ( material.visible ) {
  16780. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  16781. }
  16782. }
  16783. }
  16784. }
  16785. const children = object.children;
  16786. for ( let i = 0, l = children.length; i < l; i ++ ) {
  16787. projectObject( children[ i ], camera, groupOrder, sortObjects );
  16788. }
  16789. }
  16790. function renderScene( currentRenderList, scene, camera, viewport ) {
  16791. const opaqueObjects = currentRenderList.opaque;
  16792. const transmissiveObjects = currentRenderList.transmissive;
  16793. const transparentObjects = currentRenderList.transparent;
  16794. currentRenderState.setupLightsView( camera );
  16795. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  16796. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, scene, camera );
  16797. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  16798. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  16799. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  16800. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  16801. // Ensure depth buffer writing is enabled so it can be cleared on next render
  16802. state.buffers.depth.setTest( true );
  16803. state.buffers.depth.setMask( true );
  16804. state.buffers.color.setMask( true );
  16805. state.setPolygonOffset( false );
  16806. }
  16807. function renderTransmissionPass( opaqueObjects, scene, camera ) {
  16808. const isWebGL2 = capabilities.isWebGL2;
  16809. if ( _transmissionRenderTarget === null ) {
  16810. _transmissionRenderTarget = new WebGLRenderTarget( 1024, 1024, {
  16811. generateMipmaps: true,
  16812. type: extensions.has( 'EXT_color_buffer_half_float' ) ? HalfFloatType : UnsignedByteType,
  16813. minFilter: LinearMipmapLinearFilter,
  16814. samples: ( isWebGL2 && _antialias === true ) ? 4 : 0
  16815. } );
  16816. }
  16817. //
  16818. const currentRenderTarget = _this.getRenderTarget();
  16819. _this.setRenderTarget( _transmissionRenderTarget );
  16820. _this.clear();
  16821. // Turn off the features which can affect the frag color for opaque objects pass.
  16822. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  16823. const currentToneMapping = _this.toneMapping;
  16824. _this.toneMapping = NoToneMapping;
  16825. renderObjects( opaqueObjects, scene, camera );
  16826. _this.toneMapping = currentToneMapping;
  16827. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  16828. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  16829. _this.setRenderTarget( currentRenderTarget );
  16830. }
  16831. function renderObjects( renderList, scene, camera ) {
  16832. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  16833. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  16834. const renderItem = renderList[ i ];
  16835. const object = renderItem.object;
  16836. const geometry = renderItem.geometry;
  16837. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  16838. const group = renderItem.group;
  16839. if ( object.layers.test( camera.layers ) ) {
  16840. renderObject( object, scene, camera, geometry, material, group );
  16841. }
  16842. }
  16843. }
  16844. function renderObject( object, scene, camera, geometry, material, group ) {
  16845. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  16846. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  16847. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  16848. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  16849. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  16850. material.side = BackSide;
  16851. material.needsUpdate = true;
  16852. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16853. material.side = FrontSide;
  16854. material.needsUpdate = true;
  16855. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16856. material.side = DoubleSide;
  16857. } else {
  16858. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16859. }
  16860. object.onAfterRender( _this, scene, camera, geometry, material, group );
  16861. }
  16862. function getProgram( material, scene, object ) {
  16863. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16864. const materialProperties = properties.get( material );
  16865. const lights = currentRenderState.state.lights;
  16866. const shadowsArray = currentRenderState.state.shadowsArray;
  16867. const lightsStateVersion = lights.state.version;
  16868. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  16869. const programCacheKey = programCache.getProgramCacheKey( parameters );
  16870. let programs = materialProperties.programs;
  16871. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  16872. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  16873. materialProperties.fog = scene.fog;
  16874. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  16875. if ( programs === undefined ) {
  16876. // new material
  16877. material.addEventListener( 'dispose', onMaterialDispose );
  16878. programs = new Map();
  16879. materialProperties.programs = programs;
  16880. }
  16881. let program = programs.get( programCacheKey );
  16882. if ( program !== undefined ) {
  16883. // early out if program and light state is identical
  16884. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  16885. updateCommonMaterialProperties( material, parameters );
  16886. return program;
  16887. }
  16888. } else {
  16889. parameters.uniforms = programCache.getUniforms( material );
  16890. material.onBuild( object, parameters, _this );
  16891. material.onBeforeCompile( parameters, _this );
  16892. program = programCache.acquireProgram( parameters, programCacheKey );
  16893. programs.set( programCacheKey, program );
  16894. materialProperties.uniforms = parameters.uniforms;
  16895. }
  16896. const uniforms = materialProperties.uniforms;
  16897. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  16898. uniforms.clippingPlanes = clipping.uniform;
  16899. }
  16900. updateCommonMaterialProperties( material, parameters );
  16901. // store the light setup it was created for
  16902. materialProperties.needsLights = materialNeedsLights( material );
  16903. materialProperties.lightsStateVersion = lightsStateVersion;
  16904. if ( materialProperties.needsLights ) {
  16905. // wire up the material to this renderer's lighting state
  16906. uniforms.ambientLightColor.value = lights.state.ambient;
  16907. uniforms.lightProbe.value = lights.state.probe;
  16908. uniforms.directionalLights.value = lights.state.directional;
  16909. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  16910. uniforms.spotLights.value = lights.state.spot;
  16911. uniforms.spotLightShadows.value = lights.state.spotShadow;
  16912. uniforms.rectAreaLights.value = lights.state.rectArea;
  16913. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  16914. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  16915. uniforms.pointLights.value = lights.state.point;
  16916. uniforms.pointLightShadows.value = lights.state.pointShadow;
  16917. uniforms.hemisphereLights.value = lights.state.hemi;
  16918. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  16919. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  16920. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  16921. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  16922. uniforms.spotLightMap.value = lights.state.spotLightMap;
  16923. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  16924. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  16925. // TODO (abelnation): add area lights shadow info to uniforms
  16926. }
  16927. const progUniforms = program.getUniforms();
  16928. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  16929. materialProperties.currentProgram = program;
  16930. materialProperties.uniformsList = uniformsList;
  16931. return program;
  16932. }
  16933. function updateCommonMaterialProperties( material, parameters ) {
  16934. const materialProperties = properties.get( material );
  16935. materialProperties.outputEncoding = parameters.outputEncoding;
  16936. materialProperties.instancing = parameters.instancing;
  16937. materialProperties.skinning = parameters.skinning;
  16938. materialProperties.morphTargets = parameters.morphTargets;
  16939. materialProperties.morphNormals = parameters.morphNormals;
  16940. materialProperties.morphColors = parameters.morphColors;
  16941. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  16942. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  16943. materialProperties.numIntersection = parameters.numClipIntersection;
  16944. materialProperties.vertexAlphas = parameters.vertexAlphas;
  16945. materialProperties.vertexTangents = parameters.vertexTangents;
  16946. materialProperties.toneMapping = parameters.toneMapping;
  16947. }
  16948. function setProgram( camera, scene, geometry, material, object ) {
  16949. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16950. textures.resetTextureUnits();
  16951. const fog = scene.fog;
  16952. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  16953. const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding );
  16954. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  16955. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  16956. const vertexTangents = !! material.normalMap && !! geometry.attributes.tangent;
  16957. const morphTargets = !! geometry.morphAttributes.position;
  16958. const morphNormals = !! geometry.morphAttributes.normal;
  16959. const morphColors = !! geometry.morphAttributes.color;
  16960. const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping;
  16961. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  16962. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  16963. const materialProperties = properties.get( material );
  16964. const lights = currentRenderState.state.lights;
  16965. if ( _clippingEnabled === true ) {
  16966. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  16967. const useCache =
  16968. camera === _currentCamera &&
  16969. material.id === _currentMaterialId;
  16970. // we might want to call this function with some ClippingGroup
  16971. // object instead of the material, once it becomes feasible
  16972. // (#8465, #8379)
  16973. clipping.setState( material, camera, useCache );
  16974. }
  16975. }
  16976. //
  16977. let needsProgramChange = false;
  16978. if ( material.version === materialProperties.__version ) {
  16979. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  16980. needsProgramChange = true;
  16981. } else if ( materialProperties.outputEncoding !== encoding ) {
  16982. needsProgramChange = true;
  16983. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  16984. needsProgramChange = true;
  16985. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  16986. needsProgramChange = true;
  16987. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  16988. needsProgramChange = true;
  16989. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  16990. needsProgramChange = true;
  16991. } else if ( materialProperties.envMap !== envMap ) {
  16992. needsProgramChange = true;
  16993. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  16994. needsProgramChange = true;
  16995. } else if ( materialProperties.numClippingPlanes !== undefined &&
  16996. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  16997. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  16998. needsProgramChange = true;
  16999. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  17000. needsProgramChange = true;
  17001. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  17002. needsProgramChange = true;
  17003. } else if ( materialProperties.morphTargets !== morphTargets ) {
  17004. needsProgramChange = true;
  17005. } else if ( materialProperties.morphNormals !== morphNormals ) {
  17006. needsProgramChange = true;
  17007. } else if ( materialProperties.morphColors !== morphColors ) {
  17008. needsProgramChange = true;
  17009. } else if ( materialProperties.toneMapping !== toneMapping ) {
  17010. needsProgramChange = true;
  17011. } else if ( capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount ) {
  17012. needsProgramChange = true;
  17013. }
  17014. } else {
  17015. needsProgramChange = true;
  17016. materialProperties.__version = material.version;
  17017. }
  17018. //
  17019. let program = materialProperties.currentProgram;
  17020. if ( needsProgramChange === true ) {
  17021. program = getProgram( material, scene, object );
  17022. }
  17023. let refreshProgram = false;
  17024. let refreshMaterial = false;
  17025. let refreshLights = false;
  17026. const p_uniforms = program.getUniforms(),
  17027. m_uniforms = materialProperties.uniforms;
  17028. if ( state.useProgram( program.program ) ) {
  17029. refreshProgram = true;
  17030. refreshMaterial = true;
  17031. refreshLights = true;
  17032. }
  17033. if ( material.id !== _currentMaterialId ) {
  17034. _currentMaterialId = material.id;
  17035. refreshMaterial = true;
  17036. }
  17037. if ( refreshProgram || _currentCamera !== camera ) {
  17038. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  17039. if ( capabilities.logarithmicDepthBuffer ) {
  17040. p_uniforms.setValue( _gl, 'logDepthBufFC',
  17041. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  17042. }
  17043. if ( _currentCamera !== camera ) {
  17044. _currentCamera = camera;
  17045. // lighting uniforms depend on the camera so enforce an update
  17046. // now, in case this material supports lights - or later, when
  17047. // the next material that does gets activated:
  17048. refreshMaterial = true; // set to true on material change
  17049. refreshLights = true; // remains set until update done
  17050. }
  17051. // load material specific uniforms
  17052. // (shader material also gets them for the sake of genericity)
  17053. if ( material.isShaderMaterial ||
  17054. material.isMeshPhongMaterial ||
  17055. material.isMeshToonMaterial ||
  17056. material.isMeshStandardMaterial ||
  17057. material.envMap ) {
  17058. const uCamPos = p_uniforms.map.cameraPosition;
  17059. if ( uCamPos !== undefined ) {
  17060. uCamPos.setValue( _gl,
  17061. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  17062. }
  17063. }
  17064. if ( material.isMeshPhongMaterial ||
  17065. material.isMeshToonMaterial ||
  17066. material.isMeshLambertMaterial ||
  17067. material.isMeshBasicMaterial ||
  17068. material.isMeshStandardMaterial ||
  17069. material.isShaderMaterial ) {
  17070. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  17071. }
  17072. if ( material.isMeshPhongMaterial ||
  17073. material.isMeshToonMaterial ||
  17074. material.isMeshLambertMaterial ||
  17075. material.isMeshBasicMaterial ||
  17076. material.isMeshStandardMaterial ||
  17077. material.isShaderMaterial ||
  17078. material.isShadowMaterial ||
  17079. object.isSkinnedMesh ) {
  17080. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  17081. }
  17082. }
  17083. // skinning and morph target uniforms must be set even if material didn't change
  17084. // auto-setting of texture unit for bone and morph texture must go before other textures
  17085. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  17086. if ( object.isSkinnedMesh ) {
  17087. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  17088. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  17089. const skeleton = object.skeleton;
  17090. if ( skeleton ) {
  17091. if ( capabilities.floatVertexTextures ) {
  17092. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  17093. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  17094. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  17095. } else {
  17096. console.warn( 'THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.' );
  17097. }
  17098. }
  17099. }
  17100. const morphAttributes = geometry.morphAttributes;
  17101. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined && capabilities.isWebGL2 === true ) ) {
  17102. morphtargets.update( object, geometry, program );
  17103. }
  17104. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  17105. materialProperties.receiveShadow = object.receiveShadow;
  17106. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  17107. }
  17108. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  17109. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  17110. m_uniforms.envMap.value = envMap;
  17111. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  17112. }
  17113. if ( refreshMaterial ) {
  17114. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  17115. if ( materialProperties.needsLights ) {
  17116. // the current material requires lighting info
  17117. // note: all lighting uniforms are always set correctly
  17118. // they simply reference the renderer's state for their
  17119. // values
  17120. //
  17121. // use the current material's .needsUpdate flags to set
  17122. // the GL state when required
  17123. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  17124. }
  17125. // refresh uniforms common to several materials
  17126. if ( fog && material.fog === true ) {
  17127. materials.refreshFogUniforms( m_uniforms, fog );
  17128. }
  17129. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget );
  17130. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17131. }
  17132. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  17133. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17134. material.uniformsNeedUpdate = false;
  17135. }
  17136. if ( material.isSpriteMaterial ) {
  17137. p_uniforms.setValue( _gl, 'center', object.center );
  17138. }
  17139. // common matrices
  17140. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  17141. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  17142. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  17143. // UBOs
  17144. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  17145. const groups = material.uniformsGroups;
  17146. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17147. if ( capabilities.isWebGL2 ) {
  17148. const group = groups[ i ];
  17149. uniformsGroups.update( group, program );
  17150. uniformsGroups.bind( group, program );
  17151. } else {
  17152. console.warn( 'THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.' );
  17153. }
  17154. }
  17155. }
  17156. return program;
  17157. }
  17158. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  17159. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  17160. uniforms.ambientLightColor.needsUpdate = value;
  17161. uniforms.lightProbe.needsUpdate = value;
  17162. uniforms.directionalLights.needsUpdate = value;
  17163. uniforms.directionalLightShadows.needsUpdate = value;
  17164. uniforms.pointLights.needsUpdate = value;
  17165. uniforms.pointLightShadows.needsUpdate = value;
  17166. uniforms.spotLights.needsUpdate = value;
  17167. uniforms.spotLightShadows.needsUpdate = value;
  17168. uniforms.rectAreaLights.needsUpdate = value;
  17169. uniforms.hemisphereLights.needsUpdate = value;
  17170. }
  17171. function materialNeedsLights( material ) {
  17172. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  17173. material.isMeshStandardMaterial || material.isShadowMaterial ||
  17174. ( material.isShaderMaterial && material.lights === true );
  17175. }
  17176. this.getActiveCubeFace = function () {
  17177. return _currentActiveCubeFace;
  17178. };
  17179. this.getActiveMipmapLevel = function () {
  17180. return _currentActiveMipmapLevel;
  17181. };
  17182. this.getRenderTarget = function () {
  17183. return _currentRenderTarget;
  17184. };
  17185. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  17186. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  17187. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  17188. const renderTargetProperties = properties.get( renderTarget );
  17189. renderTargetProperties.__hasExternalTextures = true;
  17190. if ( renderTargetProperties.__hasExternalTextures ) {
  17191. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  17192. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  17193. // The multisample_render_to_texture extension doesn't work properly if there
  17194. // are midframe flushes and an external depth buffer. Disable use of the extension.
  17195. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  17196. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  17197. renderTargetProperties.__useRenderToTexture = false;
  17198. }
  17199. }
  17200. }
  17201. };
  17202. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  17203. const renderTargetProperties = properties.get( renderTarget );
  17204. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  17205. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  17206. };
  17207. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  17208. _currentRenderTarget = renderTarget;
  17209. _currentActiveCubeFace = activeCubeFace;
  17210. _currentActiveMipmapLevel = activeMipmapLevel;
  17211. let useDefaultFramebuffer = true;
  17212. let framebuffer = null;
  17213. let isCube = false;
  17214. let isRenderTarget3D = false;
  17215. if ( renderTarget ) {
  17216. const renderTargetProperties = properties.get( renderTarget );
  17217. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  17218. // We need to make sure to rebind the framebuffer.
  17219. state.bindFramebuffer( 36160, null );
  17220. useDefaultFramebuffer = false;
  17221. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  17222. textures.setupRenderTarget( renderTarget );
  17223. } else if ( renderTargetProperties.__hasExternalTextures ) {
  17224. // Color and depth texture must be rebound in order for the swapchain to update.
  17225. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  17226. }
  17227. const texture = renderTarget.texture;
  17228. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  17229. isRenderTarget3D = true;
  17230. }
  17231. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17232. if ( renderTarget.isWebGLCubeRenderTarget ) {
  17233. framebuffer = __webglFramebuffer[ activeCubeFace ];
  17234. isCube = true;
  17235. } else if ( ( capabilities.isWebGL2 && renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  17236. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  17237. } else {
  17238. framebuffer = __webglFramebuffer;
  17239. }
  17240. _currentViewport.copy( renderTarget.viewport );
  17241. _currentScissor.copy( renderTarget.scissor );
  17242. _currentScissorTest = renderTarget.scissorTest;
  17243. } else {
  17244. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  17245. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  17246. _currentScissorTest = _scissorTest;
  17247. }
  17248. const framebufferBound = state.bindFramebuffer( 36160, framebuffer );
  17249. if ( framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer ) {
  17250. state.drawBuffers( renderTarget, framebuffer );
  17251. }
  17252. state.viewport( _currentViewport );
  17253. state.scissor( _currentScissor );
  17254. state.setScissorTest( _currentScissorTest );
  17255. if ( isCube ) {
  17256. const textureProperties = properties.get( renderTarget.texture );
  17257. _gl.framebufferTexture2D( 36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  17258. } else if ( isRenderTarget3D ) {
  17259. const textureProperties = properties.get( renderTarget.texture );
  17260. const layer = activeCubeFace || 0;
  17261. _gl.framebufferTextureLayer( 36160, 36064, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  17262. }
  17263. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  17264. };
  17265. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  17266. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  17267. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  17268. return;
  17269. }
  17270. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17271. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  17272. framebuffer = framebuffer[ activeCubeFaceIndex ];
  17273. }
  17274. if ( framebuffer ) {
  17275. state.bindFramebuffer( 36160, framebuffer );
  17276. try {
  17277. const texture = renderTarget.texture;
  17278. const textureFormat = texture.format;
  17279. const textureType = texture.type;
  17280. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {
  17281. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  17282. return;
  17283. }
  17284. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) );
  17285. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // Edge and Chrome Mac < 52 (#9513)
  17286. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  17287. ! halfFloatSupportedByExt ) {
  17288. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  17289. return;
  17290. }
  17291. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  17292. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  17293. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  17294. }
  17295. } finally {
  17296. // restore framebuffer of current render target if necessary
  17297. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  17298. state.bindFramebuffer( 36160, framebuffer );
  17299. }
  17300. }
  17301. };
  17302. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  17303. const levelScale = Math.pow( 2, - level );
  17304. const width = Math.floor( texture.image.width * levelScale );
  17305. const height = Math.floor( texture.image.height * levelScale );
  17306. textures.setTexture2D( texture, 0 );
  17307. _gl.copyTexSubImage2D( 3553, level, 0, 0, position.x, position.y, width, height );
  17308. state.unbindTexture();
  17309. };
  17310. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  17311. const width = srcTexture.image.width;
  17312. const height = srcTexture.image.height;
  17313. const glFormat = utils.convert( dstTexture.format );
  17314. const glType = utils.convert( dstTexture.type );
  17315. textures.setTexture2D( dstTexture, 0 );
  17316. // As another texture upload may have changed pixelStorei
  17317. // parameters, make sure they are correct for the dstTexture
  17318. _gl.pixelStorei( 37440, dstTexture.flipY );
  17319. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  17320. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  17321. if ( srcTexture.isDataTexture ) {
  17322. _gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  17323. } else {
  17324. if ( srcTexture.isCompressedTexture ) {
  17325. _gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  17326. } else {
  17327. _gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image );
  17328. }
  17329. }
  17330. // Generate mipmaps only when copying level 0
  17331. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 );
  17332. state.unbindTexture();
  17333. };
  17334. this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {
  17335. if ( _this.isWebGL1Renderer ) {
  17336. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' );
  17337. return;
  17338. }
  17339. const width = sourceBox.max.x - sourceBox.min.x + 1;
  17340. const height = sourceBox.max.y - sourceBox.min.y + 1;
  17341. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  17342. const glFormat = utils.convert( dstTexture.format );
  17343. const glType = utils.convert( dstTexture.type );
  17344. let glTarget;
  17345. if ( dstTexture.isData3DTexture ) {
  17346. textures.setTexture3D( dstTexture, 0 );
  17347. glTarget = 32879;
  17348. } else if ( dstTexture.isDataArrayTexture ) {
  17349. textures.setTexture2DArray( dstTexture, 0 );
  17350. glTarget = 35866;
  17351. } else {
  17352. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  17353. return;
  17354. }
  17355. _gl.pixelStorei( 37440, dstTexture.flipY );
  17356. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  17357. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  17358. const unpackRowLen = _gl.getParameter( 3314 );
  17359. const unpackImageHeight = _gl.getParameter( 32878 );
  17360. const unpackSkipPixels = _gl.getParameter( 3316 );
  17361. const unpackSkipRows = _gl.getParameter( 3315 );
  17362. const unpackSkipImages = _gl.getParameter( 32877 );
  17363. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image;
  17364. _gl.pixelStorei( 3314, image.width );
  17365. _gl.pixelStorei( 32878, image.height );
  17366. _gl.pixelStorei( 3316, sourceBox.min.x );
  17367. _gl.pixelStorei( 3315, sourceBox.min.y );
  17368. _gl.pixelStorei( 32877, sourceBox.min.z );
  17369. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  17370. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data );
  17371. } else {
  17372. if ( srcTexture.isCompressedArrayTexture ) {
  17373. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' );
  17374. _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data );
  17375. } else {
  17376. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image );
  17377. }
  17378. }
  17379. _gl.pixelStorei( 3314, unpackRowLen );
  17380. _gl.pixelStorei( 32878, unpackImageHeight );
  17381. _gl.pixelStorei( 3316, unpackSkipPixels );
  17382. _gl.pixelStorei( 3315, unpackSkipRows );
  17383. _gl.pixelStorei( 32877, unpackSkipImages );
  17384. // Generate mipmaps only when copying level 0
  17385. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  17386. state.unbindTexture();
  17387. };
  17388. this.initTexture = function ( texture ) {
  17389. if ( texture.isCubeTexture ) {
  17390. textures.setTextureCube( texture, 0 );
  17391. } else if ( texture.isData3DTexture ) {
  17392. textures.setTexture3D( texture, 0 );
  17393. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  17394. textures.setTexture2DArray( texture, 0 );
  17395. } else {
  17396. textures.setTexture2D( texture, 0 );
  17397. }
  17398. state.unbindTexture();
  17399. };
  17400. this.resetState = function () {
  17401. _currentActiveCubeFace = 0;
  17402. _currentActiveMipmapLevel = 0;
  17403. _currentRenderTarget = null;
  17404. state.reset();
  17405. bindingStates.reset();
  17406. };
  17407. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17408. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17409. }
  17410. }
  17411. Object.defineProperties( WebGLRenderer.prototype, {
  17412. // @deprecated since r150
  17413. physicallyCorrectLights: {
  17414. get: function () {
  17415. console.warn( 'THREE.WebGLRenderer: the property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead.' );
  17416. return ! this.useLegacyLights;
  17417. },
  17418. set: function ( value ) {
  17419. console.warn( 'THREE.WebGLRenderer: the property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead.' );
  17420. this.useLegacyLights = ! value;
  17421. }
  17422. }
  17423. } );
  17424. class WebGL1Renderer extends WebGLRenderer {}
  17425. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  17426. class FogExp2 {
  17427. constructor( color, density = 0.00025 ) {
  17428. this.isFogExp2 = true;
  17429. this.name = '';
  17430. this.color = new Color( color );
  17431. this.density = density;
  17432. }
  17433. clone() {
  17434. return new FogExp2( this.color, this.density );
  17435. }
  17436. toJSON( /* meta */ ) {
  17437. return {
  17438. type: 'FogExp2',
  17439. color: this.color.getHex(),
  17440. density: this.density
  17441. };
  17442. }
  17443. }
  17444. class Fog {
  17445. constructor( color, near = 1, far = 1000 ) {
  17446. this.isFog = true;
  17447. this.name = '';
  17448. this.color = new Color( color );
  17449. this.near = near;
  17450. this.far = far;
  17451. }
  17452. clone() {
  17453. return new Fog( this.color, this.near, this.far );
  17454. }
  17455. toJSON( /* meta */ ) {
  17456. return {
  17457. type: 'Fog',
  17458. color: this.color.getHex(),
  17459. near: this.near,
  17460. far: this.far
  17461. };
  17462. }
  17463. }
  17464. class Scene extends Object3D {
  17465. constructor() {
  17466. super();
  17467. this.isScene = true;
  17468. this.type = 'Scene';
  17469. this.background = null;
  17470. this.environment = null;
  17471. this.fog = null;
  17472. this.backgroundBlurriness = 0;
  17473. this.backgroundIntensity = 1;
  17474. this.overrideMaterial = null;
  17475. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17476. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17477. }
  17478. }
  17479. copy( source, recursive ) {
  17480. super.copy( source, recursive );
  17481. if ( source.background !== null ) this.background = source.background.clone();
  17482. if ( source.environment !== null ) this.environment = source.environment.clone();
  17483. if ( source.fog !== null ) this.fog = source.fog.clone();
  17484. this.backgroundBlurriness = source.backgroundBlurriness;
  17485. this.backgroundIntensity = source.backgroundIntensity;
  17486. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17487. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17488. return this;
  17489. }
  17490. toJSON( meta ) {
  17491. const data = super.toJSON( meta );
  17492. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17493. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  17494. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  17495. return data;
  17496. }
  17497. // @deprecated
  17498. get autoUpdate() {
  17499. console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' );
  17500. return this.matrixWorldAutoUpdate;
  17501. }
  17502. set autoUpdate( value ) {
  17503. console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' );
  17504. this.matrixWorldAutoUpdate = value;
  17505. }
  17506. }
  17507. class InterleavedBuffer {
  17508. constructor( array, stride ) {
  17509. this.isInterleavedBuffer = true;
  17510. this.array = array;
  17511. this.stride = stride;
  17512. this.count = array !== undefined ? array.length / stride : 0;
  17513. this.usage = StaticDrawUsage;
  17514. this.updateRange = { offset: 0, count: - 1 };
  17515. this.version = 0;
  17516. this.uuid = generateUUID();
  17517. }
  17518. onUploadCallback() {}
  17519. set needsUpdate( value ) {
  17520. if ( value === true ) this.version ++;
  17521. }
  17522. setUsage( value ) {
  17523. this.usage = value;
  17524. return this;
  17525. }
  17526. copy( source ) {
  17527. this.array = new source.array.constructor( source.array );
  17528. this.count = source.count;
  17529. this.stride = source.stride;
  17530. this.usage = source.usage;
  17531. return this;
  17532. }
  17533. copyAt( index1, attribute, index2 ) {
  17534. index1 *= this.stride;
  17535. index2 *= attribute.stride;
  17536. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17537. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  17538. }
  17539. return this;
  17540. }
  17541. set( value, offset = 0 ) {
  17542. this.array.set( value, offset );
  17543. return this;
  17544. }
  17545. clone( data ) {
  17546. if ( data.arrayBuffers === undefined ) {
  17547. data.arrayBuffers = {};
  17548. }
  17549. if ( this.array.buffer._uuid === undefined ) {
  17550. this.array.buffer._uuid = generateUUID();
  17551. }
  17552. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17553. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17554. }
  17555. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17556. const ib = new this.constructor( array, this.stride );
  17557. ib.setUsage( this.usage );
  17558. return ib;
  17559. }
  17560. onUpload( callback ) {
  17561. this.onUploadCallback = callback;
  17562. return this;
  17563. }
  17564. toJSON( data ) {
  17565. if ( data.arrayBuffers === undefined ) {
  17566. data.arrayBuffers = {};
  17567. }
  17568. // generate UUID for array buffer if necessary
  17569. if ( this.array.buffer._uuid === undefined ) {
  17570. this.array.buffer._uuid = generateUUID();
  17571. }
  17572. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17573. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17574. }
  17575. //
  17576. return {
  17577. uuid: this.uuid,
  17578. buffer: this.array.buffer._uuid,
  17579. type: this.array.constructor.name,
  17580. stride: this.stride
  17581. };
  17582. }
  17583. }
  17584. const _vector$6 = /*@__PURE__*/ new Vector3();
  17585. class InterleavedBufferAttribute {
  17586. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17587. this.isInterleavedBufferAttribute = true;
  17588. this.name = '';
  17589. this.data = interleavedBuffer;
  17590. this.itemSize = itemSize;
  17591. this.offset = offset;
  17592. this.normalized = normalized;
  17593. }
  17594. get count() {
  17595. return this.data.count;
  17596. }
  17597. get array() {
  17598. return this.data.array;
  17599. }
  17600. set needsUpdate( value ) {
  17601. this.data.needsUpdate = value;
  17602. }
  17603. applyMatrix4( m ) {
  17604. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17605. _vector$6.fromBufferAttribute( this, i );
  17606. _vector$6.applyMatrix4( m );
  17607. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17608. }
  17609. return this;
  17610. }
  17611. applyNormalMatrix( m ) {
  17612. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17613. _vector$6.fromBufferAttribute( this, i );
  17614. _vector$6.applyNormalMatrix( m );
  17615. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17616. }
  17617. return this;
  17618. }
  17619. transformDirection( m ) {
  17620. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17621. _vector$6.fromBufferAttribute( this, i );
  17622. _vector$6.transformDirection( m );
  17623. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17624. }
  17625. return this;
  17626. }
  17627. setX( index, x ) {
  17628. if ( this.normalized ) x = normalize( x, this.array );
  17629. this.data.array[ index * this.data.stride + this.offset ] = x;
  17630. return this;
  17631. }
  17632. setY( index, y ) {
  17633. if ( this.normalized ) y = normalize( y, this.array );
  17634. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17635. return this;
  17636. }
  17637. setZ( index, z ) {
  17638. if ( this.normalized ) z = normalize( z, this.array );
  17639. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17640. return this;
  17641. }
  17642. setW( index, w ) {
  17643. if ( this.normalized ) w = normalize( w, this.array );
  17644. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17645. return this;
  17646. }
  17647. getX( index ) {
  17648. let x = this.data.array[ index * this.data.stride + this.offset ];
  17649. if ( this.normalized ) x = denormalize( x, this.array );
  17650. return x;
  17651. }
  17652. getY( index ) {
  17653. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17654. if ( this.normalized ) y = denormalize( y, this.array );
  17655. return y;
  17656. }
  17657. getZ( index ) {
  17658. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  17659. if ( this.normalized ) z = denormalize( z, this.array );
  17660. return z;
  17661. }
  17662. getW( index ) {
  17663. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  17664. if ( this.normalized ) w = denormalize( w, this.array );
  17665. return w;
  17666. }
  17667. setXY( index, x, y ) {
  17668. index = index * this.data.stride + this.offset;
  17669. if ( this.normalized ) {
  17670. x = normalize( x, this.array );
  17671. y = normalize( y, this.array );
  17672. }
  17673. this.data.array[ index + 0 ] = x;
  17674. this.data.array[ index + 1 ] = y;
  17675. return this;
  17676. }
  17677. setXYZ( index, x, y, z ) {
  17678. index = index * this.data.stride + this.offset;
  17679. if ( this.normalized ) {
  17680. x = normalize( x, this.array );
  17681. y = normalize( y, this.array );
  17682. z = normalize( z, this.array );
  17683. }
  17684. this.data.array[ index + 0 ] = x;
  17685. this.data.array[ index + 1 ] = y;
  17686. this.data.array[ index + 2 ] = z;
  17687. return this;
  17688. }
  17689. setXYZW( index, x, y, z, w ) {
  17690. index = index * this.data.stride + this.offset;
  17691. if ( this.normalized ) {
  17692. x = normalize( x, this.array );
  17693. y = normalize( y, this.array );
  17694. z = normalize( z, this.array );
  17695. w = normalize( w, this.array );
  17696. }
  17697. this.data.array[ index + 0 ] = x;
  17698. this.data.array[ index + 1 ] = y;
  17699. this.data.array[ index + 2 ] = z;
  17700. this.data.array[ index + 3 ] = w;
  17701. return this;
  17702. }
  17703. clone( data ) {
  17704. if ( data === undefined ) {
  17705. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  17706. const array = [];
  17707. for ( let i = 0; i < this.count; i ++ ) {
  17708. const index = i * this.data.stride + this.offset;
  17709. for ( let j = 0; j < this.itemSize; j ++ ) {
  17710. array.push( this.data.array[ index + j ] );
  17711. }
  17712. }
  17713. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17714. } else {
  17715. if ( data.interleavedBuffers === undefined ) {
  17716. data.interleavedBuffers = {};
  17717. }
  17718. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17719. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17720. }
  17721. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17722. }
  17723. }
  17724. toJSON( data ) {
  17725. if ( data === undefined ) {
  17726. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  17727. const array = [];
  17728. for ( let i = 0; i < this.count; i ++ ) {
  17729. const index = i * this.data.stride + this.offset;
  17730. for ( let j = 0; j < this.itemSize; j ++ ) {
  17731. array.push( this.data.array[ index + j ] );
  17732. }
  17733. }
  17734. // de-interleave data and save it as an ordinary buffer attribute for now
  17735. return {
  17736. itemSize: this.itemSize,
  17737. type: this.array.constructor.name,
  17738. array: array,
  17739. normalized: this.normalized
  17740. };
  17741. } else {
  17742. // save as true interleaved attribute
  17743. if ( data.interleavedBuffers === undefined ) {
  17744. data.interleavedBuffers = {};
  17745. }
  17746. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17747. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17748. }
  17749. return {
  17750. isInterleavedBufferAttribute: true,
  17751. itemSize: this.itemSize,
  17752. data: this.data.uuid,
  17753. offset: this.offset,
  17754. normalized: this.normalized
  17755. };
  17756. }
  17757. }
  17758. }
  17759. class SpriteMaterial extends Material {
  17760. constructor( parameters ) {
  17761. super();
  17762. this.isSpriteMaterial = true;
  17763. this.type = 'SpriteMaterial';
  17764. this.color = new Color( 0xffffff );
  17765. this.map = null;
  17766. this.alphaMap = null;
  17767. this.rotation = 0;
  17768. this.sizeAttenuation = true;
  17769. this.transparent = true;
  17770. this.fog = true;
  17771. this.setValues( parameters );
  17772. }
  17773. copy( source ) {
  17774. super.copy( source );
  17775. this.color.copy( source.color );
  17776. this.map = source.map;
  17777. this.alphaMap = source.alphaMap;
  17778. this.rotation = source.rotation;
  17779. this.sizeAttenuation = source.sizeAttenuation;
  17780. this.fog = source.fog;
  17781. return this;
  17782. }
  17783. }
  17784. let _geometry;
  17785. const _intersectPoint = /*@__PURE__*/ new Vector3();
  17786. const _worldScale = /*@__PURE__*/ new Vector3();
  17787. const _mvPosition = /*@__PURE__*/ new Vector3();
  17788. const _alignedPosition = /*@__PURE__*/ new Vector2();
  17789. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  17790. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  17791. const _vA = /*@__PURE__*/ new Vector3();
  17792. const _vB = /*@__PURE__*/ new Vector3();
  17793. const _vC = /*@__PURE__*/ new Vector3();
  17794. const _uvA = /*@__PURE__*/ new Vector2();
  17795. const _uvB = /*@__PURE__*/ new Vector2();
  17796. const _uvC = /*@__PURE__*/ new Vector2();
  17797. class Sprite extends Object3D {
  17798. constructor( material ) {
  17799. super();
  17800. this.isSprite = true;
  17801. this.type = 'Sprite';
  17802. if ( _geometry === undefined ) {
  17803. _geometry = new BufferGeometry();
  17804. const float32Array = new Float32Array( [
  17805. - 0.5, - 0.5, 0, 0, 0,
  17806. 0.5, - 0.5, 0, 1, 0,
  17807. 0.5, 0.5, 0, 1, 1,
  17808. - 0.5, 0.5, 0, 0, 1
  17809. ] );
  17810. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  17811. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  17812. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  17813. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  17814. }
  17815. this.geometry = _geometry;
  17816. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  17817. this.center = new Vector2( 0.5, 0.5 );
  17818. }
  17819. raycast( raycaster, intersects ) {
  17820. if ( raycaster.camera === null ) {
  17821. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  17822. }
  17823. _worldScale.setFromMatrixScale( this.matrixWorld );
  17824. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  17825. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  17826. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  17827. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  17828. _worldScale.multiplyScalar( - _mvPosition.z );
  17829. }
  17830. const rotation = this.material.rotation;
  17831. let sin, cos;
  17832. if ( rotation !== 0 ) {
  17833. cos = Math.cos( rotation );
  17834. sin = Math.sin( rotation );
  17835. }
  17836. const center = this.center;
  17837. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17838. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17839. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17840. _uvA.set( 0, 0 );
  17841. _uvB.set( 1, 0 );
  17842. _uvC.set( 1, 1 );
  17843. // check first triangle
  17844. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  17845. if ( intersect === null ) {
  17846. // check second triangle
  17847. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17848. _uvB.set( 0, 1 );
  17849. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  17850. if ( intersect === null ) {
  17851. return;
  17852. }
  17853. }
  17854. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  17855. if ( distance < raycaster.near || distance > raycaster.far ) return;
  17856. intersects.push( {
  17857. distance: distance,
  17858. point: _intersectPoint.clone(),
  17859. uv: Triangle.getUV( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  17860. face: null,
  17861. object: this
  17862. } );
  17863. }
  17864. copy( source, recursive ) {
  17865. super.copy( source, recursive );
  17866. if ( source.center !== undefined ) this.center.copy( source.center );
  17867. this.material = source.material;
  17868. return this;
  17869. }
  17870. }
  17871. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  17872. // compute position in camera space
  17873. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  17874. // to check if rotation is not zero
  17875. if ( sin !== undefined ) {
  17876. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  17877. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  17878. } else {
  17879. _rotatedPosition.copy( _alignedPosition );
  17880. }
  17881. vertexPosition.copy( mvPosition );
  17882. vertexPosition.x += _rotatedPosition.x;
  17883. vertexPosition.y += _rotatedPosition.y;
  17884. // transform to world space
  17885. vertexPosition.applyMatrix4( _viewWorldMatrix );
  17886. }
  17887. const _v1$2 = /*@__PURE__*/ new Vector3();
  17888. const _v2$1 = /*@__PURE__*/ new Vector3();
  17889. class LOD extends Object3D {
  17890. constructor() {
  17891. super();
  17892. this._currentLevel = 0;
  17893. this.type = 'LOD';
  17894. Object.defineProperties( this, {
  17895. levels: {
  17896. enumerable: true,
  17897. value: []
  17898. },
  17899. isLOD: {
  17900. value: true,
  17901. }
  17902. } );
  17903. this.autoUpdate = true;
  17904. }
  17905. copy( source ) {
  17906. super.copy( source, false );
  17907. const levels = source.levels;
  17908. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  17909. const level = levels[ i ];
  17910. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  17911. }
  17912. this.autoUpdate = source.autoUpdate;
  17913. return this;
  17914. }
  17915. addLevel( object, distance = 0, hysteresis = 0 ) {
  17916. distance = Math.abs( distance );
  17917. const levels = this.levels;
  17918. let l;
  17919. for ( l = 0; l < levels.length; l ++ ) {
  17920. if ( distance < levels[ l ].distance ) {
  17921. break;
  17922. }
  17923. }
  17924. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  17925. this.add( object );
  17926. return this;
  17927. }
  17928. getCurrentLevel() {
  17929. return this._currentLevel;
  17930. }
  17931. getObjectForDistance( distance ) {
  17932. const levels = this.levels;
  17933. if ( levels.length > 0 ) {
  17934. let i, l;
  17935. for ( i = 1, l = levels.length; i < l; i ++ ) {
  17936. let levelDistance = levels[ i ].distance;
  17937. if ( levels[ i ].object.visible ) {
  17938. levelDistance -= levelDistance * levels[ i ].hysteresis;
  17939. }
  17940. if ( distance < levelDistance ) {
  17941. break;
  17942. }
  17943. }
  17944. return levels[ i - 1 ].object;
  17945. }
  17946. return null;
  17947. }
  17948. raycast( raycaster, intersects ) {
  17949. const levels = this.levels;
  17950. if ( levels.length > 0 ) {
  17951. _v1$2.setFromMatrixPosition( this.matrixWorld );
  17952. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  17953. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  17954. }
  17955. }
  17956. update( camera ) {
  17957. const levels = this.levels;
  17958. if ( levels.length > 1 ) {
  17959. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  17960. _v2$1.setFromMatrixPosition( this.matrixWorld );
  17961. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  17962. levels[ 0 ].object.visible = true;
  17963. let i, l;
  17964. for ( i = 1, l = levels.length; i < l; i ++ ) {
  17965. let levelDistance = levels[ i ].distance;
  17966. if ( levels[ i ].object.visible ) {
  17967. levelDistance -= levelDistance * levels[ i ].hysteresis;
  17968. }
  17969. if ( distance >= levelDistance ) {
  17970. levels[ i - 1 ].object.visible = false;
  17971. levels[ i ].object.visible = true;
  17972. } else {
  17973. break;
  17974. }
  17975. }
  17976. this._currentLevel = i - 1;
  17977. for ( ; i < l; i ++ ) {
  17978. levels[ i ].object.visible = false;
  17979. }
  17980. }
  17981. }
  17982. toJSON( meta ) {
  17983. const data = super.toJSON( meta );
  17984. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  17985. data.object.levels = [];
  17986. const levels = this.levels;
  17987. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  17988. const level = levels[ i ];
  17989. data.object.levels.push( {
  17990. object: level.object.uuid,
  17991. distance: level.distance,
  17992. hysteresis: level.hysteresis
  17993. } );
  17994. }
  17995. return data;
  17996. }
  17997. }
  17998. const _basePosition = /*@__PURE__*/ new Vector3();
  17999. const _skinIndex = /*@__PURE__*/ new Vector4();
  18000. const _skinWeight = /*@__PURE__*/ new Vector4();
  18001. const _vector$5 = /*@__PURE__*/ new Vector3();
  18002. const _matrix = /*@__PURE__*/ new Matrix4();
  18003. class SkinnedMesh extends Mesh {
  18004. constructor( geometry, material ) {
  18005. super( geometry, material );
  18006. this.isSkinnedMesh = true;
  18007. this.type = 'SkinnedMesh';
  18008. this.bindMode = 'attached';
  18009. this.bindMatrix = new Matrix4();
  18010. this.bindMatrixInverse = new Matrix4();
  18011. }
  18012. copy( source, recursive ) {
  18013. super.copy( source, recursive );
  18014. this.bindMode = source.bindMode;
  18015. this.bindMatrix.copy( source.bindMatrix );
  18016. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18017. this.skeleton = source.skeleton;
  18018. return this;
  18019. }
  18020. bind( skeleton, bindMatrix ) {
  18021. this.skeleton = skeleton;
  18022. if ( bindMatrix === undefined ) {
  18023. this.updateMatrixWorld( true );
  18024. this.skeleton.calculateInverses();
  18025. bindMatrix = this.matrixWorld;
  18026. }
  18027. this.bindMatrix.copy( bindMatrix );
  18028. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18029. }
  18030. pose() {
  18031. this.skeleton.pose();
  18032. }
  18033. normalizeSkinWeights() {
  18034. const vector = new Vector4();
  18035. const skinWeight = this.geometry.attributes.skinWeight;
  18036. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18037. vector.fromBufferAttribute( skinWeight, i );
  18038. const scale = 1.0 / vector.manhattanLength();
  18039. if ( scale !== Infinity ) {
  18040. vector.multiplyScalar( scale );
  18041. } else {
  18042. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18043. }
  18044. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18045. }
  18046. }
  18047. updateMatrixWorld( force ) {
  18048. super.updateMatrixWorld( force );
  18049. if ( this.bindMode === 'attached' ) {
  18050. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18051. } else if ( this.bindMode === 'detached' ) {
  18052. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18053. } else {
  18054. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18055. }
  18056. }
  18057. boneTransform( index, target ) {
  18058. const skeleton = this.skeleton;
  18059. const geometry = this.geometry;
  18060. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18061. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18062. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  18063. target.set( 0, 0, 0 );
  18064. for ( let i = 0; i < 4; i ++ ) {
  18065. const weight = _skinWeight.getComponent( i );
  18066. if ( weight !== 0 ) {
  18067. const boneIndex = _skinIndex.getComponent( i );
  18068. _matrix.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18069. target.addScaledVector( _vector$5.copy( _basePosition ).applyMatrix4( _matrix ), weight );
  18070. }
  18071. }
  18072. return target.applyMatrix4( this.bindMatrixInverse );
  18073. }
  18074. }
  18075. class Bone extends Object3D {
  18076. constructor() {
  18077. super();
  18078. this.isBone = true;
  18079. this.type = 'Bone';
  18080. }
  18081. }
  18082. class DataTexture extends Texture {
  18083. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding ) {
  18084. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  18085. this.isDataTexture = true;
  18086. this.image = { data: data, width: width, height: height };
  18087. this.generateMipmaps = false;
  18088. this.flipY = false;
  18089. this.unpackAlignment = 1;
  18090. }
  18091. }
  18092. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18093. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18094. class Skeleton {
  18095. constructor( bones = [], boneInverses = [] ) {
  18096. this.uuid = generateUUID();
  18097. this.bones = bones.slice( 0 );
  18098. this.boneInverses = boneInverses;
  18099. this.boneMatrices = null;
  18100. this.boneTexture = null;
  18101. this.boneTextureSize = 0;
  18102. this.frame = - 1;
  18103. this.init();
  18104. }
  18105. init() {
  18106. const bones = this.bones;
  18107. const boneInverses = this.boneInverses;
  18108. this.boneMatrices = new Float32Array( bones.length * 16 );
  18109. // calculate inverse bone matrices if necessary
  18110. if ( boneInverses.length === 0 ) {
  18111. this.calculateInverses();
  18112. } else {
  18113. // handle special case
  18114. if ( bones.length !== boneInverses.length ) {
  18115. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18116. this.boneInverses = [];
  18117. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18118. this.boneInverses.push( new Matrix4() );
  18119. }
  18120. }
  18121. }
  18122. }
  18123. calculateInverses() {
  18124. this.boneInverses.length = 0;
  18125. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18126. const inverse = new Matrix4();
  18127. if ( this.bones[ i ] ) {
  18128. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18129. }
  18130. this.boneInverses.push( inverse );
  18131. }
  18132. }
  18133. pose() {
  18134. // recover the bind-time world matrices
  18135. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18136. const bone = this.bones[ i ];
  18137. if ( bone ) {
  18138. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18139. }
  18140. }
  18141. // compute the local matrices, positions, rotations and scales
  18142. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18143. const bone = this.bones[ i ];
  18144. if ( bone ) {
  18145. if ( bone.parent && bone.parent.isBone ) {
  18146. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18147. bone.matrix.multiply( bone.matrixWorld );
  18148. } else {
  18149. bone.matrix.copy( bone.matrixWorld );
  18150. }
  18151. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18152. }
  18153. }
  18154. }
  18155. update() {
  18156. const bones = this.bones;
  18157. const boneInverses = this.boneInverses;
  18158. const boneMatrices = this.boneMatrices;
  18159. const boneTexture = this.boneTexture;
  18160. // flatten bone matrices to array
  18161. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18162. // compute the offset between the current and the original transform
  18163. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18164. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18165. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18166. }
  18167. if ( boneTexture !== null ) {
  18168. boneTexture.needsUpdate = true;
  18169. }
  18170. }
  18171. clone() {
  18172. return new Skeleton( this.bones, this.boneInverses );
  18173. }
  18174. computeBoneTexture() {
  18175. // layout (1 matrix = 4 pixels)
  18176. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18177. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18178. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18179. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18180. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18181. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18182. size = ceilPowerOfTwo( size );
  18183. size = Math.max( size, 4 );
  18184. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18185. boneMatrices.set( this.boneMatrices ); // copy current values
  18186. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18187. boneTexture.needsUpdate = true;
  18188. this.boneMatrices = boneMatrices;
  18189. this.boneTexture = boneTexture;
  18190. this.boneTextureSize = size;
  18191. return this;
  18192. }
  18193. getBoneByName( name ) {
  18194. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18195. const bone = this.bones[ i ];
  18196. if ( bone.name === name ) {
  18197. return bone;
  18198. }
  18199. }
  18200. return undefined;
  18201. }
  18202. dispose( ) {
  18203. if ( this.boneTexture !== null ) {
  18204. this.boneTexture.dispose();
  18205. this.boneTexture = null;
  18206. }
  18207. }
  18208. fromJSON( json, bones ) {
  18209. this.uuid = json.uuid;
  18210. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18211. const uuid = json.bones[ i ];
  18212. let bone = bones[ uuid ];
  18213. if ( bone === undefined ) {
  18214. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  18215. bone = new Bone();
  18216. }
  18217. this.bones.push( bone );
  18218. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18219. }
  18220. this.init();
  18221. return this;
  18222. }
  18223. toJSON() {
  18224. const data = {
  18225. metadata: {
  18226. version: 4.5,
  18227. type: 'Skeleton',
  18228. generator: 'Skeleton.toJSON'
  18229. },
  18230. bones: [],
  18231. boneInverses: []
  18232. };
  18233. data.uuid = this.uuid;
  18234. const bones = this.bones;
  18235. const boneInverses = this.boneInverses;
  18236. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18237. const bone = bones[ i ];
  18238. data.bones.push( bone.uuid );
  18239. const boneInverse = boneInverses[ i ];
  18240. data.boneInverses.push( boneInverse.toArray() );
  18241. }
  18242. return data;
  18243. }
  18244. }
  18245. class InstancedBufferAttribute extends BufferAttribute {
  18246. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18247. super( array, itemSize, normalized );
  18248. this.isInstancedBufferAttribute = true;
  18249. this.meshPerAttribute = meshPerAttribute;
  18250. }
  18251. copy( source ) {
  18252. super.copy( source );
  18253. this.meshPerAttribute = source.meshPerAttribute;
  18254. return this;
  18255. }
  18256. toJSON() {
  18257. const data = super.toJSON();
  18258. data.meshPerAttribute = this.meshPerAttribute;
  18259. data.isInstancedBufferAttribute = true;
  18260. return data;
  18261. }
  18262. }
  18263. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18264. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18265. const _instanceIntersects = [];
  18266. const _identity = /*@__PURE__*/ new Matrix4();
  18267. const _mesh = /*@__PURE__*/ new Mesh();
  18268. class InstancedMesh extends Mesh {
  18269. constructor( geometry, material, count ) {
  18270. super( geometry, material );
  18271. this.isInstancedMesh = true;
  18272. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18273. this.instanceColor = null;
  18274. this.count = count;
  18275. this.frustumCulled = false;
  18276. for ( let i = 0; i < count; i ++ ) {
  18277. this.setMatrixAt( i, _identity );
  18278. }
  18279. }
  18280. copy( source, recursive ) {
  18281. super.copy( source, recursive );
  18282. this.instanceMatrix.copy( source.instanceMatrix );
  18283. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  18284. this.count = source.count;
  18285. return this;
  18286. }
  18287. getColorAt( index, color ) {
  18288. color.fromArray( this.instanceColor.array, index * 3 );
  18289. }
  18290. getMatrixAt( index, matrix ) {
  18291. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  18292. }
  18293. raycast( raycaster, intersects ) {
  18294. const matrixWorld = this.matrixWorld;
  18295. const raycastTimes = this.count;
  18296. _mesh.geometry = this.geometry;
  18297. _mesh.material = this.material;
  18298. if ( _mesh.material === undefined ) return;
  18299. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  18300. // calculate the world matrix for each instance
  18301. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  18302. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  18303. // the mesh represents this single instance
  18304. _mesh.matrixWorld = _instanceWorldMatrix;
  18305. _mesh.raycast( raycaster, _instanceIntersects );
  18306. // process the result of raycast
  18307. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  18308. const intersect = _instanceIntersects[ i ];
  18309. intersect.instanceId = instanceId;
  18310. intersect.object = this;
  18311. intersects.push( intersect );
  18312. }
  18313. _instanceIntersects.length = 0;
  18314. }
  18315. }
  18316. setColorAt( index, color ) {
  18317. if ( this.instanceColor === null ) {
  18318. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  18319. }
  18320. color.toArray( this.instanceColor.array, index * 3 );
  18321. }
  18322. setMatrixAt( index, matrix ) {
  18323. matrix.toArray( this.instanceMatrix.array, index * 16 );
  18324. }
  18325. updateMorphTargets() {
  18326. }
  18327. dispose() {
  18328. this.dispatchEvent( { type: 'dispose' } );
  18329. }
  18330. }
  18331. class LineBasicMaterial extends Material {
  18332. constructor( parameters ) {
  18333. super();
  18334. this.isLineBasicMaterial = true;
  18335. this.type = 'LineBasicMaterial';
  18336. this.color = new Color( 0xffffff );
  18337. this.linewidth = 1;
  18338. this.linecap = 'round';
  18339. this.linejoin = 'round';
  18340. this.fog = true;
  18341. this.setValues( parameters );
  18342. }
  18343. copy( source ) {
  18344. super.copy( source );
  18345. this.color.copy( source.color );
  18346. this.linewidth = source.linewidth;
  18347. this.linecap = source.linecap;
  18348. this.linejoin = source.linejoin;
  18349. this.fog = source.fog;
  18350. return this;
  18351. }
  18352. }
  18353. const _start$1 = /*@__PURE__*/ new Vector3();
  18354. const _end$1 = /*@__PURE__*/ new Vector3();
  18355. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  18356. const _ray$1 = /*@__PURE__*/ new Ray();
  18357. const _sphere$1 = /*@__PURE__*/ new Sphere();
  18358. class Line extends Object3D {
  18359. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  18360. super();
  18361. this.isLine = true;
  18362. this.type = 'Line';
  18363. this.geometry = geometry;
  18364. this.material = material;
  18365. this.updateMorphTargets();
  18366. }
  18367. copy( source, recursive ) {
  18368. super.copy( source, recursive );
  18369. this.material = source.material;
  18370. this.geometry = source.geometry;
  18371. return this;
  18372. }
  18373. computeLineDistances() {
  18374. const geometry = this.geometry;
  18375. // we assume non-indexed geometry
  18376. if ( geometry.index === null ) {
  18377. const positionAttribute = geometry.attributes.position;
  18378. const lineDistances = [ 0 ];
  18379. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  18380. _start$1.fromBufferAttribute( positionAttribute, i - 1 );
  18381. _end$1.fromBufferAttribute( positionAttribute, i );
  18382. lineDistances[ i ] = lineDistances[ i - 1 ];
  18383. lineDistances[ i ] += _start$1.distanceTo( _end$1 );
  18384. }
  18385. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  18386. } else {
  18387. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  18388. }
  18389. return this;
  18390. }
  18391. raycast( raycaster, intersects ) {
  18392. const geometry = this.geometry;
  18393. const matrixWorld = this.matrixWorld;
  18394. const threshold = raycaster.params.Line.threshold;
  18395. const drawRange = geometry.drawRange;
  18396. // Checking boundingSphere distance to ray
  18397. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18398. _sphere$1.copy( geometry.boundingSphere );
  18399. _sphere$1.applyMatrix4( matrixWorld );
  18400. _sphere$1.radius += threshold;
  18401. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  18402. //
  18403. _inverseMatrix$1.copy( matrixWorld ).invert();
  18404. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  18405. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18406. const localThresholdSq = localThreshold * localThreshold;
  18407. const vStart = new Vector3();
  18408. const vEnd = new Vector3();
  18409. const interSegment = new Vector3();
  18410. const interRay = new Vector3();
  18411. const step = this.isLineSegments ? 2 : 1;
  18412. const index = geometry.index;
  18413. const attributes = geometry.attributes;
  18414. const positionAttribute = attributes.position;
  18415. if ( index !== null ) {
  18416. const start = Math.max( 0, drawRange.start );
  18417. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  18418. for ( let i = start, l = end - 1; i < l; i += step ) {
  18419. const a = index.getX( i );
  18420. const b = index.getX( i + 1 );
  18421. vStart.fromBufferAttribute( positionAttribute, a );
  18422. vEnd.fromBufferAttribute( positionAttribute, b );
  18423. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18424. if ( distSq > localThresholdSq ) continue;
  18425. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18426. const distance = raycaster.ray.origin.distanceTo( interRay );
  18427. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18428. intersects.push( {
  18429. distance: distance,
  18430. // What do we want? intersection point on the ray or on the segment??
  18431. // point: raycaster.ray.at( distance ),
  18432. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18433. index: i,
  18434. face: null,
  18435. faceIndex: null,
  18436. object: this
  18437. } );
  18438. }
  18439. } else {
  18440. const start = Math.max( 0, drawRange.start );
  18441. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  18442. for ( let i = start, l = end - 1; i < l; i += step ) {
  18443. vStart.fromBufferAttribute( positionAttribute, i );
  18444. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  18445. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18446. if ( distSq > localThresholdSq ) continue;
  18447. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18448. const distance = raycaster.ray.origin.distanceTo( interRay );
  18449. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18450. intersects.push( {
  18451. distance: distance,
  18452. // What do we want? intersection point on the ray or on the segment??
  18453. // point: raycaster.ray.at( distance ),
  18454. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18455. index: i,
  18456. face: null,
  18457. faceIndex: null,
  18458. object: this
  18459. } );
  18460. }
  18461. }
  18462. }
  18463. updateMorphTargets() {
  18464. const geometry = this.geometry;
  18465. const morphAttributes = geometry.morphAttributes;
  18466. const keys = Object.keys( morphAttributes );
  18467. if ( keys.length > 0 ) {
  18468. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  18469. if ( morphAttribute !== undefined ) {
  18470. this.morphTargetInfluences = [];
  18471. this.morphTargetDictionary = {};
  18472. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  18473. const name = morphAttribute[ m ].name || String( m );
  18474. this.morphTargetInfluences.push( 0 );
  18475. this.morphTargetDictionary[ name ] = m;
  18476. }
  18477. }
  18478. }
  18479. }
  18480. }
  18481. const _start = /*@__PURE__*/ new Vector3();
  18482. const _end = /*@__PURE__*/ new Vector3();
  18483. class LineSegments extends Line {
  18484. constructor( geometry, material ) {
  18485. super( geometry, material );
  18486. this.isLineSegments = true;
  18487. this.type = 'LineSegments';
  18488. }
  18489. computeLineDistances() {
  18490. const geometry = this.geometry;
  18491. // we assume non-indexed geometry
  18492. if ( geometry.index === null ) {
  18493. const positionAttribute = geometry.attributes.position;
  18494. const lineDistances = [];
  18495. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  18496. _start.fromBufferAttribute( positionAttribute, i );
  18497. _end.fromBufferAttribute( positionAttribute, i + 1 );
  18498. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  18499. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  18500. }
  18501. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  18502. } else {
  18503. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  18504. }
  18505. return this;
  18506. }
  18507. }
  18508. class LineLoop extends Line {
  18509. constructor( geometry, material ) {
  18510. super( geometry, material );
  18511. this.isLineLoop = true;
  18512. this.type = 'LineLoop';
  18513. }
  18514. }
  18515. class PointsMaterial extends Material {
  18516. constructor( parameters ) {
  18517. super();
  18518. this.isPointsMaterial = true;
  18519. this.type = 'PointsMaterial';
  18520. this.color = new Color( 0xffffff );
  18521. this.map = null;
  18522. this.alphaMap = null;
  18523. this.size = 1;
  18524. this.sizeAttenuation = true;
  18525. this.fog = true;
  18526. this.setValues( parameters );
  18527. }
  18528. copy( source ) {
  18529. super.copy( source );
  18530. this.color.copy( source.color );
  18531. this.map = source.map;
  18532. this.alphaMap = source.alphaMap;
  18533. this.size = source.size;
  18534. this.sizeAttenuation = source.sizeAttenuation;
  18535. this.fog = source.fog;
  18536. return this;
  18537. }
  18538. }
  18539. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  18540. const _ray = /*@__PURE__*/ new Ray();
  18541. const _sphere = /*@__PURE__*/ new Sphere();
  18542. const _position$2 = /*@__PURE__*/ new Vector3();
  18543. class Points extends Object3D {
  18544. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  18545. super();
  18546. this.isPoints = true;
  18547. this.type = 'Points';
  18548. this.geometry = geometry;
  18549. this.material = material;
  18550. this.updateMorphTargets();
  18551. }
  18552. copy( source, recursive ) {
  18553. super.copy( source, recursive );
  18554. this.material = source.material;
  18555. this.geometry = source.geometry;
  18556. return this;
  18557. }
  18558. raycast( raycaster, intersects ) {
  18559. const geometry = this.geometry;
  18560. const matrixWorld = this.matrixWorld;
  18561. const threshold = raycaster.params.Points.threshold;
  18562. const drawRange = geometry.drawRange;
  18563. // Checking boundingSphere distance to ray
  18564. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18565. _sphere.copy( geometry.boundingSphere );
  18566. _sphere.applyMatrix4( matrixWorld );
  18567. _sphere.radius += threshold;
  18568. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  18569. //
  18570. _inverseMatrix.copy( matrixWorld ).invert();
  18571. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  18572. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18573. const localThresholdSq = localThreshold * localThreshold;
  18574. const index = geometry.index;
  18575. const attributes = geometry.attributes;
  18576. const positionAttribute = attributes.position;
  18577. if ( index !== null ) {
  18578. const start = Math.max( 0, drawRange.start );
  18579. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  18580. for ( let i = start, il = end; i < il; i ++ ) {
  18581. const a = index.getX( i );
  18582. _position$2.fromBufferAttribute( positionAttribute, a );
  18583. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  18584. }
  18585. } else {
  18586. const start = Math.max( 0, drawRange.start );
  18587. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  18588. for ( let i = start, l = end; i < l; i ++ ) {
  18589. _position$2.fromBufferAttribute( positionAttribute, i );
  18590. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  18591. }
  18592. }
  18593. }
  18594. updateMorphTargets() {
  18595. const geometry = this.geometry;
  18596. const morphAttributes = geometry.morphAttributes;
  18597. const keys = Object.keys( morphAttributes );
  18598. if ( keys.length > 0 ) {
  18599. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  18600. if ( morphAttribute !== undefined ) {
  18601. this.morphTargetInfluences = [];
  18602. this.morphTargetDictionary = {};
  18603. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  18604. const name = morphAttribute[ m ].name || String( m );
  18605. this.morphTargetInfluences.push( 0 );
  18606. this.morphTargetDictionary[ name ] = m;
  18607. }
  18608. }
  18609. }
  18610. }
  18611. }
  18612. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  18613. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  18614. if ( rayPointDistanceSq < localThresholdSq ) {
  18615. const intersectPoint = new Vector3();
  18616. _ray.closestPointToPoint( point, intersectPoint );
  18617. intersectPoint.applyMatrix4( matrixWorld );
  18618. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  18619. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18620. intersects.push( {
  18621. distance: distance,
  18622. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  18623. point: intersectPoint,
  18624. index: index,
  18625. face: null,
  18626. object: object
  18627. } );
  18628. }
  18629. }
  18630. class VideoTexture extends Texture {
  18631. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18632. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18633. this.isVideoTexture = true;
  18634. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  18635. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  18636. this.generateMipmaps = false;
  18637. const scope = this;
  18638. function updateVideo() {
  18639. scope.needsUpdate = true;
  18640. video.requestVideoFrameCallback( updateVideo );
  18641. }
  18642. if ( 'requestVideoFrameCallback' in video ) {
  18643. video.requestVideoFrameCallback( updateVideo );
  18644. }
  18645. }
  18646. clone() {
  18647. return new this.constructor( this.image ).copy( this );
  18648. }
  18649. update() {
  18650. const video = this.image;
  18651. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  18652. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  18653. this.needsUpdate = true;
  18654. }
  18655. }
  18656. }
  18657. class FramebufferTexture extends Texture {
  18658. constructor( width, height, format ) {
  18659. super( { width, height } );
  18660. this.isFramebufferTexture = true;
  18661. this.format = format;
  18662. this.magFilter = NearestFilter;
  18663. this.minFilter = NearestFilter;
  18664. this.generateMipmaps = false;
  18665. this.needsUpdate = true;
  18666. }
  18667. }
  18668. class CompressedTexture extends Texture {
  18669. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  18670. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  18671. this.isCompressedTexture = true;
  18672. this.image = { width: width, height: height };
  18673. this.mipmaps = mipmaps;
  18674. // no flipping for cube textures
  18675. // (also flipping doesn't work for compressed textures )
  18676. this.flipY = false;
  18677. // can't generate mipmaps for compressed textures
  18678. // mips must be embedded in DDS files
  18679. this.generateMipmaps = false;
  18680. }
  18681. }
  18682. class CompressedArrayTexture extends CompressedTexture {
  18683. constructor( mipmaps, width, height, depth, format, type ) {
  18684. super( mipmaps, width, height, format, type );
  18685. this.isCompressedArrayTexture = true;
  18686. this.image.depth = depth;
  18687. this.wrapR = ClampToEdgeWrapping;
  18688. }
  18689. }
  18690. class CanvasTexture extends Texture {
  18691. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18692. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18693. this.isCanvasTexture = true;
  18694. this.needsUpdate = true;
  18695. }
  18696. }
  18697. /**
  18698. * Extensible curve object.
  18699. *
  18700. * Some common of curve methods:
  18701. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  18702. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  18703. * .getPoints(), .getSpacedPoints()
  18704. * .getLength()
  18705. * .updateArcLengths()
  18706. *
  18707. * This following curves inherit from THREE.Curve:
  18708. *
  18709. * -- 2D curves --
  18710. * THREE.ArcCurve
  18711. * THREE.CubicBezierCurve
  18712. * THREE.EllipseCurve
  18713. * THREE.LineCurve
  18714. * THREE.QuadraticBezierCurve
  18715. * THREE.SplineCurve
  18716. *
  18717. * -- 3D curves --
  18718. * THREE.CatmullRomCurve3
  18719. * THREE.CubicBezierCurve3
  18720. * THREE.LineCurve3
  18721. * THREE.QuadraticBezierCurve3
  18722. *
  18723. * A series of curves can be represented as a THREE.CurvePath.
  18724. *
  18725. **/
  18726. class Curve {
  18727. constructor() {
  18728. this.type = 'Curve';
  18729. this.arcLengthDivisions = 200;
  18730. }
  18731. // Virtual base class method to overwrite and implement in subclasses
  18732. // - t [0 .. 1]
  18733. getPoint( /* t, optionalTarget */ ) {
  18734. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  18735. return null;
  18736. }
  18737. // Get point at relative position in curve according to arc length
  18738. // - u [0 .. 1]
  18739. getPointAt( u, optionalTarget ) {
  18740. const t = this.getUtoTmapping( u );
  18741. return this.getPoint( t, optionalTarget );
  18742. }
  18743. // Get sequence of points using getPoint( t )
  18744. getPoints( divisions = 5 ) {
  18745. const points = [];
  18746. for ( let d = 0; d <= divisions; d ++ ) {
  18747. points.push( this.getPoint( d / divisions ) );
  18748. }
  18749. return points;
  18750. }
  18751. // Get sequence of points using getPointAt( u )
  18752. getSpacedPoints( divisions = 5 ) {
  18753. const points = [];
  18754. for ( let d = 0; d <= divisions; d ++ ) {
  18755. points.push( this.getPointAt( d / divisions ) );
  18756. }
  18757. return points;
  18758. }
  18759. // Get total curve arc length
  18760. getLength() {
  18761. const lengths = this.getLengths();
  18762. return lengths[ lengths.length - 1 ];
  18763. }
  18764. // Get list of cumulative segment lengths
  18765. getLengths( divisions = this.arcLengthDivisions ) {
  18766. if ( this.cacheArcLengths &&
  18767. ( this.cacheArcLengths.length === divisions + 1 ) &&
  18768. ! this.needsUpdate ) {
  18769. return this.cacheArcLengths;
  18770. }
  18771. this.needsUpdate = false;
  18772. const cache = [];
  18773. let current, last = this.getPoint( 0 );
  18774. let sum = 0;
  18775. cache.push( 0 );
  18776. for ( let p = 1; p <= divisions; p ++ ) {
  18777. current = this.getPoint( p / divisions );
  18778. sum += current.distanceTo( last );
  18779. cache.push( sum );
  18780. last = current;
  18781. }
  18782. this.cacheArcLengths = cache;
  18783. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  18784. }
  18785. updateArcLengths() {
  18786. this.needsUpdate = true;
  18787. this.getLengths();
  18788. }
  18789. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  18790. getUtoTmapping( u, distance ) {
  18791. const arcLengths = this.getLengths();
  18792. let i = 0;
  18793. const il = arcLengths.length;
  18794. let targetArcLength; // The targeted u distance value to get
  18795. if ( distance ) {
  18796. targetArcLength = distance;
  18797. } else {
  18798. targetArcLength = u * arcLengths[ il - 1 ];
  18799. }
  18800. // binary search for the index with largest value smaller than target u distance
  18801. let low = 0, high = il - 1, comparison;
  18802. while ( low <= high ) {
  18803. 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
  18804. comparison = arcLengths[ i ] - targetArcLength;
  18805. if ( comparison < 0 ) {
  18806. low = i + 1;
  18807. } else if ( comparison > 0 ) {
  18808. high = i - 1;
  18809. } else {
  18810. high = i;
  18811. break;
  18812. // DONE
  18813. }
  18814. }
  18815. i = high;
  18816. if ( arcLengths[ i ] === targetArcLength ) {
  18817. return i / ( il - 1 );
  18818. }
  18819. // we could get finer grain at lengths, or use simple interpolation between two points
  18820. const lengthBefore = arcLengths[ i ];
  18821. const lengthAfter = arcLengths[ i + 1 ];
  18822. const segmentLength = lengthAfter - lengthBefore;
  18823. // determine where we are between the 'before' and 'after' points
  18824. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  18825. // add that fractional amount to t
  18826. const t = ( i + segmentFraction ) / ( il - 1 );
  18827. return t;
  18828. }
  18829. // Returns a unit vector tangent at t
  18830. // In case any sub curve does not implement its tangent derivation,
  18831. // 2 points a small delta apart will be used to find its gradient
  18832. // which seems to give a reasonable approximation
  18833. getTangent( t, optionalTarget ) {
  18834. const delta = 0.0001;
  18835. let t1 = t - delta;
  18836. let t2 = t + delta;
  18837. // Capping in case of danger
  18838. if ( t1 < 0 ) t1 = 0;
  18839. if ( t2 > 1 ) t2 = 1;
  18840. const pt1 = this.getPoint( t1 );
  18841. const pt2 = this.getPoint( t2 );
  18842. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  18843. tangent.copy( pt2 ).sub( pt1 ).normalize();
  18844. return tangent;
  18845. }
  18846. getTangentAt( u, optionalTarget ) {
  18847. const t = this.getUtoTmapping( u );
  18848. return this.getTangent( t, optionalTarget );
  18849. }
  18850. computeFrenetFrames( segments, closed ) {
  18851. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18852. const normal = new Vector3();
  18853. const tangents = [];
  18854. const normals = [];
  18855. const binormals = [];
  18856. const vec = new Vector3();
  18857. const mat = new Matrix4();
  18858. // compute the tangent vectors for each segment on the curve
  18859. for ( let i = 0; i <= segments; i ++ ) {
  18860. const u = i / segments;
  18861. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  18862. }
  18863. // select an initial normal vector perpendicular to the first tangent vector,
  18864. // and in the direction of the minimum tangent xyz component
  18865. normals[ 0 ] = new Vector3();
  18866. binormals[ 0 ] = new Vector3();
  18867. let min = Number.MAX_VALUE;
  18868. const tx = Math.abs( tangents[ 0 ].x );
  18869. const ty = Math.abs( tangents[ 0 ].y );
  18870. const tz = Math.abs( tangents[ 0 ].z );
  18871. if ( tx <= min ) {
  18872. min = tx;
  18873. normal.set( 1, 0, 0 );
  18874. }
  18875. if ( ty <= min ) {
  18876. min = ty;
  18877. normal.set( 0, 1, 0 );
  18878. }
  18879. if ( tz <= min ) {
  18880. normal.set( 0, 0, 1 );
  18881. }
  18882. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  18883. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  18884. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  18885. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  18886. for ( let i = 1; i <= segments; i ++ ) {
  18887. normals[ i ] = normals[ i - 1 ].clone();
  18888. binormals[ i ] = binormals[ i - 1 ].clone();
  18889. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  18890. if ( vec.length() > Number.EPSILON ) {
  18891. vec.normalize();
  18892. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  18893. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  18894. }
  18895. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18896. }
  18897. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18898. if ( closed === true ) {
  18899. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  18900. theta /= segments;
  18901. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  18902. theta = - theta;
  18903. }
  18904. for ( let i = 1; i <= segments; i ++ ) {
  18905. // twist a little...
  18906. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  18907. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18908. }
  18909. }
  18910. return {
  18911. tangents: tangents,
  18912. normals: normals,
  18913. binormals: binormals
  18914. };
  18915. }
  18916. clone() {
  18917. return new this.constructor().copy( this );
  18918. }
  18919. copy( source ) {
  18920. this.arcLengthDivisions = source.arcLengthDivisions;
  18921. return this;
  18922. }
  18923. toJSON() {
  18924. const data = {
  18925. metadata: {
  18926. version: 4.5,
  18927. type: 'Curve',
  18928. generator: 'Curve.toJSON'
  18929. }
  18930. };
  18931. data.arcLengthDivisions = this.arcLengthDivisions;
  18932. data.type = this.type;
  18933. return data;
  18934. }
  18935. fromJSON( json ) {
  18936. this.arcLengthDivisions = json.arcLengthDivisions;
  18937. return this;
  18938. }
  18939. }
  18940. class EllipseCurve extends Curve {
  18941. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  18942. super();
  18943. this.isEllipseCurve = true;
  18944. this.type = 'EllipseCurve';
  18945. this.aX = aX;
  18946. this.aY = aY;
  18947. this.xRadius = xRadius;
  18948. this.yRadius = yRadius;
  18949. this.aStartAngle = aStartAngle;
  18950. this.aEndAngle = aEndAngle;
  18951. this.aClockwise = aClockwise;
  18952. this.aRotation = aRotation;
  18953. }
  18954. getPoint( t, optionalTarget ) {
  18955. const point = optionalTarget || new Vector2();
  18956. const twoPi = Math.PI * 2;
  18957. let deltaAngle = this.aEndAngle - this.aStartAngle;
  18958. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  18959. // ensures that deltaAngle is 0 .. 2 PI
  18960. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  18961. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  18962. if ( deltaAngle < Number.EPSILON ) {
  18963. if ( samePoints ) {
  18964. deltaAngle = 0;
  18965. } else {
  18966. deltaAngle = twoPi;
  18967. }
  18968. }
  18969. if ( this.aClockwise === true && ! samePoints ) {
  18970. if ( deltaAngle === twoPi ) {
  18971. deltaAngle = - twoPi;
  18972. } else {
  18973. deltaAngle = deltaAngle - twoPi;
  18974. }
  18975. }
  18976. const angle = this.aStartAngle + t * deltaAngle;
  18977. let x = this.aX + this.xRadius * Math.cos( angle );
  18978. let y = this.aY + this.yRadius * Math.sin( angle );
  18979. if ( this.aRotation !== 0 ) {
  18980. const cos = Math.cos( this.aRotation );
  18981. const sin = Math.sin( this.aRotation );
  18982. const tx = x - this.aX;
  18983. const ty = y - this.aY;
  18984. // Rotate the point about the center of the ellipse.
  18985. x = tx * cos - ty * sin + this.aX;
  18986. y = tx * sin + ty * cos + this.aY;
  18987. }
  18988. return point.set( x, y );
  18989. }
  18990. copy( source ) {
  18991. super.copy( source );
  18992. this.aX = source.aX;
  18993. this.aY = source.aY;
  18994. this.xRadius = source.xRadius;
  18995. this.yRadius = source.yRadius;
  18996. this.aStartAngle = source.aStartAngle;
  18997. this.aEndAngle = source.aEndAngle;
  18998. this.aClockwise = source.aClockwise;
  18999. this.aRotation = source.aRotation;
  19000. return this;
  19001. }
  19002. toJSON() {
  19003. const data = super.toJSON();
  19004. data.aX = this.aX;
  19005. data.aY = this.aY;
  19006. data.xRadius = this.xRadius;
  19007. data.yRadius = this.yRadius;
  19008. data.aStartAngle = this.aStartAngle;
  19009. data.aEndAngle = this.aEndAngle;
  19010. data.aClockwise = this.aClockwise;
  19011. data.aRotation = this.aRotation;
  19012. return data;
  19013. }
  19014. fromJSON( json ) {
  19015. super.fromJSON( json );
  19016. this.aX = json.aX;
  19017. this.aY = json.aY;
  19018. this.xRadius = json.xRadius;
  19019. this.yRadius = json.yRadius;
  19020. this.aStartAngle = json.aStartAngle;
  19021. this.aEndAngle = json.aEndAngle;
  19022. this.aClockwise = json.aClockwise;
  19023. this.aRotation = json.aRotation;
  19024. return this;
  19025. }
  19026. }
  19027. class ArcCurve extends EllipseCurve {
  19028. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19029. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  19030. this.isArcCurve = true;
  19031. this.type = 'ArcCurve';
  19032. }
  19033. }
  19034. /**
  19035. * Centripetal CatmullRom Curve - which is useful for avoiding
  19036. * cusps and self-intersections in non-uniform catmull rom curves.
  19037. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  19038. *
  19039. * curve.type accepts centripetal(default), chordal and catmullrom
  19040. * curve.tension is used for catmullrom which defaults to 0.5
  19041. */
  19042. /*
  19043. Based on an optimized c++ solution in
  19044. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  19045. - http://ideone.com/NoEbVM
  19046. This CubicPoly class could be used for reusing some variables and calculations,
  19047. but for three.js curve use, it could be possible inlined and flatten into a single function call
  19048. which can be placed in CurveUtils.
  19049. */
  19050. function CubicPoly() {
  19051. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  19052. /*
  19053. * Compute coefficients for a cubic polynomial
  19054. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  19055. * such that
  19056. * p(0) = x0, p(1) = x1
  19057. * and
  19058. * p'(0) = t0, p'(1) = t1.
  19059. */
  19060. function init( x0, x1, t0, t1 ) {
  19061. c0 = x0;
  19062. c1 = t0;
  19063. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  19064. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  19065. }
  19066. return {
  19067. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  19068. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  19069. },
  19070. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  19071. // compute tangents when parameterized in [t1,t2]
  19072. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  19073. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  19074. // rescale tangents for parametrization in [0,1]
  19075. t1 *= dt1;
  19076. t2 *= dt1;
  19077. init( x1, x2, t1, t2 );
  19078. },
  19079. calc: function ( t ) {
  19080. const t2 = t * t;
  19081. const t3 = t2 * t;
  19082. return c0 + c1 * t + c2 * t2 + c3 * t3;
  19083. }
  19084. };
  19085. }
  19086. //
  19087. const tmp = /*@__PURE__*/ new Vector3();
  19088. const px = /*@__PURE__*/ new CubicPoly();
  19089. const py = /*@__PURE__*/ new CubicPoly();
  19090. const pz = /*@__PURE__*/ new CubicPoly();
  19091. class CatmullRomCurve3 extends Curve {
  19092. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  19093. super();
  19094. this.isCatmullRomCurve3 = true;
  19095. this.type = 'CatmullRomCurve3';
  19096. this.points = points;
  19097. this.closed = closed;
  19098. this.curveType = curveType;
  19099. this.tension = tension;
  19100. }
  19101. getPoint( t, optionalTarget = new Vector3() ) {
  19102. const point = optionalTarget;
  19103. const points = this.points;
  19104. const l = points.length;
  19105. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  19106. let intPoint = Math.floor( p );
  19107. let weight = p - intPoint;
  19108. if ( this.closed ) {
  19109. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  19110. } else if ( weight === 0 && intPoint === l - 1 ) {
  19111. intPoint = l - 2;
  19112. weight = 1;
  19113. }
  19114. let p0, p3; // 4 points (p1 & p2 defined below)
  19115. if ( this.closed || intPoint > 0 ) {
  19116. p0 = points[ ( intPoint - 1 ) % l ];
  19117. } else {
  19118. // extrapolate first point
  19119. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  19120. p0 = tmp;
  19121. }
  19122. const p1 = points[ intPoint % l ];
  19123. const p2 = points[ ( intPoint + 1 ) % l ];
  19124. if ( this.closed || intPoint + 2 < l ) {
  19125. p3 = points[ ( intPoint + 2 ) % l ];
  19126. } else {
  19127. // extrapolate last point
  19128. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  19129. p3 = tmp;
  19130. }
  19131. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  19132. // init Centripetal / Chordal Catmull-Rom
  19133. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  19134. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  19135. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  19136. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  19137. // safety check for repeated points
  19138. if ( dt1 < 1e-4 ) dt1 = 1.0;
  19139. if ( dt0 < 1e-4 ) dt0 = dt1;
  19140. if ( dt2 < 1e-4 ) dt2 = dt1;
  19141. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  19142. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  19143. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  19144. } else if ( this.curveType === 'catmullrom' ) {
  19145. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  19146. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  19147. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  19148. }
  19149. point.set(
  19150. px.calc( weight ),
  19151. py.calc( weight ),
  19152. pz.calc( weight )
  19153. );
  19154. return point;
  19155. }
  19156. copy( source ) {
  19157. super.copy( source );
  19158. this.points = [];
  19159. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19160. const point = source.points[ i ];
  19161. this.points.push( point.clone() );
  19162. }
  19163. this.closed = source.closed;
  19164. this.curveType = source.curveType;
  19165. this.tension = source.tension;
  19166. return this;
  19167. }
  19168. toJSON() {
  19169. const data = super.toJSON();
  19170. data.points = [];
  19171. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19172. const point = this.points[ i ];
  19173. data.points.push( point.toArray() );
  19174. }
  19175. data.closed = this.closed;
  19176. data.curveType = this.curveType;
  19177. data.tension = this.tension;
  19178. return data;
  19179. }
  19180. fromJSON( json ) {
  19181. super.fromJSON( json );
  19182. this.points = [];
  19183. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  19184. const point = json.points[ i ];
  19185. this.points.push( new Vector3().fromArray( point ) );
  19186. }
  19187. this.closed = json.closed;
  19188. this.curveType = json.curveType;
  19189. this.tension = json.tension;
  19190. return this;
  19191. }
  19192. }
  19193. /**
  19194. * Bezier Curves formulas obtained from
  19195. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  19196. */
  19197. function CatmullRom( t, p0, p1, p2, p3 ) {
  19198. const v0 = ( p2 - p0 ) * 0.5;
  19199. const v1 = ( p3 - p1 ) * 0.5;
  19200. const t2 = t * t;
  19201. const t3 = t * t2;
  19202. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  19203. }
  19204. //
  19205. function QuadraticBezierP0( t, p ) {
  19206. const k = 1 - t;
  19207. return k * k * p;
  19208. }
  19209. function QuadraticBezierP1( t, p ) {
  19210. return 2 * ( 1 - t ) * t * p;
  19211. }
  19212. function QuadraticBezierP2( t, p ) {
  19213. return t * t * p;
  19214. }
  19215. function QuadraticBezier( t, p0, p1, p2 ) {
  19216. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  19217. QuadraticBezierP2( t, p2 );
  19218. }
  19219. //
  19220. function CubicBezierP0( t, p ) {
  19221. const k = 1 - t;
  19222. return k * k * k * p;
  19223. }
  19224. function CubicBezierP1( t, p ) {
  19225. const k = 1 - t;
  19226. return 3 * k * k * t * p;
  19227. }
  19228. function CubicBezierP2( t, p ) {
  19229. return 3 * ( 1 - t ) * t * t * p;
  19230. }
  19231. function CubicBezierP3( t, p ) {
  19232. return t * t * t * p;
  19233. }
  19234. function CubicBezier( t, p0, p1, p2, p3 ) {
  19235. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  19236. CubicBezierP3( t, p3 );
  19237. }
  19238. class CubicBezierCurve extends Curve {
  19239. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  19240. super();
  19241. this.isCubicBezierCurve = true;
  19242. this.type = 'CubicBezierCurve';
  19243. this.v0 = v0;
  19244. this.v1 = v1;
  19245. this.v2 = v2;
  19246. this.v3 = v3;
  19247. }
  19248. getPoint( t, optionalTarget = new Vector2() ) {
  19249. const point = optionalTarget;
  19250. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19251. point.set(
  19252. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19253. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  19254. );
  19255. return point;
  19256. }
  19257. copy( source ) {
  19258. super.copy( source );
  19259. this.v0.copy( source.v0 );
  19260. this.v1.copy( source.v1 );
  19261. this.v2.copy( source.v2 );
  19262. this.v3.copy( source.v3 );
  19263. return this;
  19264. }
  19265. toJSON() {
  19266. const data = super.toJSON();
  19267. data.v0 = this.v0.toArray();
  19268. data.v1 = this.v1.toArray();
  19269. data.v2 = this.v2.toArray();
  19270. data.v3 = this.v3.toArray();
  19271. return data;
  19272. }
  19273. fromJSON( json ) {
  19274. super.fromJSON( json );
  19275. this.v0.fromArray( json.v0 );
  19276. this.v1.fromArray( json.v1 );
  19277. this.v2.fromArray( json.v2 );
  19278. this.v3.fromArray( json.v3 );
  19279. return this;
  19280. }
  19281. }
  19282. class CubicBezierCurve3 extends Curve {
  19283. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  19284. super();
  19285. this.isCubicBezierCurve3 = true;
  19286. this.type = 'CubicBezierCurve3';
  19287. this.v0 = v0;
  19288. this.v1 = v1;
  19289. this.v2 = v2;
  19290. this.v3 = v3;
  19291. }
  19292. getPoint( t, optionalTarget = new Vector3() ) {
  19293. const point = optionalTarget;
  19294. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19295. point.set(
  19296. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19297. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  19298. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  19299. );
  19300. return point;
  19301. }
  19302. copy( source ) {
  19303. super.copy( source );
  19304. this.v0.copy( source.v0 );
  19305. this.v1.copy( source.v1 );
  19306. this.v2.copy( source.v2 );
  19307. this.v3.copy( source.v3 );
  19308. return this;
  19309. }
  19310. toJSON() {
  19311. const data = super.toJSON();
  19312. data.v0 = this.v0.toArray();
  19313. data.v1 = this.v1.toArray();
  19314. data.v2 = this.v2.toArray();
  19315. data.v3 = this.v3.toArray();
  19316. return data;
  19317. }
  19318. fromJSON( json ) {
  19319. super.fromJSON( json );
  19320. this.v0.fromArray( json.v0 );
  19321. this.v1.fromArray( json.v1 );
  19322. this.v2.fromArray( json.v2 );
  19323. this.v3.fromArray( json.v3 );
  19324. return this;
  19325. }
  19326. }
  19327. class LineCurve extends Curve {
  19328. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  19329. super();
  19330. this.isLineCurve = true;
  19331. this.type = 'LineCurve';
  19332. this.v1 = v1;
  19333. this.v2 = v2;
  19334. }
  19335. getPoint( t, optionalTarget = new Vector2() ) {
  19336. const point = optionalTarget;
  19337. if ( t === 1 ) {
  19338. point.copy( this.v2 );
  19339. } else {
  19340. point.copy( this.v2 ).sub( this.v1 );
  19341. point.multiplyScalar( t ).add( this.v1 );
  19342. }
  19343. return point;
  19344. }
  19345. // Line curve is linear, so we can overwrite default getPointAt
  19346. getPointAt( u, optionalTarget ) {
  19347. return this.getPoint( u, optionalTarget );
  19348. }
  19349. getTangent( t, optionalTarget = new Vector2() ) {
  19350. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  19351. }
  19352. getTangentAt( u, optionalTarget ) {
  19353. return this.getTangent( u, optionalTarget );
  19354. }
  19355. copy( source ) {
  19356. super.copy( source );
  19357. this.v1.copy( source.v1 );
  19358. this.v2.copy( source.v2 );
  19359. return this;
  19360. }
  19361. toJSON() {
  19362. const data = super.toJSON();
  19363. data.v1 = this.v1.toArray();
  19364. data.v2 = this.v2.toArray();
  19365. return data;
  19366. }
  19367. fromJSON( json ) {
  19368. super.fromJSON( json );
  19369. this.v1.fromArray( json.v1 );
  19370. this.v2.fromArray( json.v2 );
  19371. return this;
  19372. }
  19373. }
  19374. class LineCurve3 extends Curve {
  19375. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  19376. super();
  19377. this.isLineCurve3 = true;
  19378. this.type = 'LineCurve3';
  19379. this.v1 = v1;
  19380. this.v2 = v2;
  19381. }
  19382. getPoint( t, optionalTarget = new Vector3() ) {
  19383. const point = optionalTarget;
  19384. if ( t === 1 ) {
  19385. point.copy( this.v2 );
  19386. } else {
  19387. point.copy( this.v2 ).sub( this.v1 );
  19388. point.multiplyScalar( t ).add( this.v1 );
  19389. }
  19390. return point;
  19391. }
  19392. // Line curve is linear, so we can overwrite default getPointAt
  19393. getPointAt( u, optionalTarget ) {
  19394. return this.getPoint( u, optionalTarget );
  19395. }
  19396. getTangent( t, optionalTarget = new Vector3() ) {
  19397. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  19398. }
  19399. getTangentAt( u, optionalTarget ) {
  19400. return this.getTangent( u, optionalTarget );
  19401. }
  19402. copy( source ) {
  19403. super.copy( source );
  19404. this.v1.copy( source.v1 );
  19405. this.v2.copy( source.v2 );
  19406. return this;
  19407. }
  19408. toJSON() {
  19409. const data = super.toJSON();
  19410. data.v1 = this.v1.toArray();
  19411. data.v2 = this.v2.toArray();
  19412. return data;
  19413. }
  19414. fromJSON( json ) {
  19415. super.fromJSON( json );
  19416. this.v1.fromArray( json.v1 );
  19417. this.v2.fromArray( json.v2 );
  19418. return this;
  19419. }
  19420. }
  19421. class QuadraticBezierCurve extends Curve {
  19422. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  19423. super();
  19424. this.isQuadraticBezierCurve = true;
  19425. this.type = 'QuadraticBezierCurve';
  19426. this.v0 = v0;
  19427. this.v1 = v1;
  19428. this.v2 = v2;
  19429. }
  19430. getPoint( t, optionalTarget = new Vector2() ) {
  19431. const point = optionalTarget;
  19432. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19433. point.set(
  19434. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19435. QuadraticBezier( t, v0.y, v1.y, v2.y )
  19436. );
  19437. return point;
  19438. }
  19439. copy( source ) {
  19440. super.copy( source );
  19441. this.v0.copy( source.v0 );
  19442. this.v1.copy( source.v1 );
  19443. this.v2.copy( source.v2 );
  19444. return this;
  19445. }
  19446. toJSON() {
  19447. const data = super.toJSON();
  19448. data.v0 = this.v0.toArray();
  19449. data.v1 = this.v1.toArray();
  19450. data.v2 = this.v2.toArray();
  19451. return data;
  19452. }
  19453. fromJSON( json ) {
  19454. super.fromJSON( json );
  19455. this.v0.fromArray( json.v0 );
  19456. this.v1.fromArray( json.v1 );
  19457. this.v2.fromArray( json.v2 );
  19458. return this;
  19459. }
  19460. }
  19461. class QuadraticBezierCurve3 extends Curve {
  19462. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  19463. super();
  19464. this.isQuadraticBezierCurve3 = true;
  19465. this.type = 'QuadraticBezierCurve3';
  19466. this.v0 = v0;
  19467. this.v1 = v1;
  19468. this.v2 = v2;
  19469. }
  19470. getPoint( t, optionalTarget = new Vector3() ) {
  19471. const point = optionalTarget;
  19472. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19473. point.set(
  19474. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19475. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  19476. QuadraticBezier( t, v0.z, v1.z, v2.z )
  19477. );
  19478. return point;
  19479. }
  19480. copy( source ) {
  19481. super.copy( source );
  19482. this.v0.copy( source.v0 );
  19483. this.v1.copy( source.v1 );
  19484. this.v2.copy( source.v2 );
  19485. return this;
  19486. }
  19487. toJSON() {
  19488. const data = super.toJSON();
  19489. data.v0 = this.v0.toArray();
  19490. data.v1 = this.v1.toArray();
  19491. data.v2 = this.v2.toArray();
  19492. return data;
  19493. }
  19494. fromJSON( json ) {
  19495. super.fromJSON( json );
  19496. this.v0.fromArray( json.v0 );
  19497. this.v1.fromArray( json.v1 );
  19498. this.v2.fromArray( json.v2 );
  19499. return this;
  19500. }
  19501. }
  19502. class SplineCurve extends Curve {
  19503. constructor( points = [] ) {
  19504. super();
  19505. this.isSplineCurve = true;
  19506. this.type = 'SplineCurve';
  19507. this.points = points;
  19508. }
  19509. getPoint( t, optionalTarget = new Vector2() ) {
  19510. const point = optionalTarget;
  19511. const points = this.points;
  19512. const p = ( points.length - 1 ) * t;
  19513. const intPoint = Math.floor( p );
  19514. const weight = p - intPoint;
  19515. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  19516. const p1 = points[ intPoint ];
  19517. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  19518. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  19519. point.set(
  19520. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  19521. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  19522. );
  19523. return point;
  19524. }
  19525. copy( source ) {
  19526. super.copy( source );
  19527. this.points = [];
  19528. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19529. const point = source.points[ i ];
  19530. this.points.push( point.clone() );
  19531. }
  19532. return this;
  19533. }
  19534. toJSON() {
  19535. const data = super.toJSON();
  19536. data.points = [];
  19537. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19538. const point = this.points[ i ];
  19539. data.points.push( point.toArray() );
  19540. }
  19541. return data;
  19542. }
  19543. fromJSON( json ) {
  19544. super.fromJSON( json );
  19545. this.points = [];
  19546. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  19547. const point = json.points[ i ];
  19548. this.points.push( new Vector2().fromArray( point ) );
  19549. }
  19550. return this;
  19551. }
  19552. }
  19553. var Curves = /*#__PURE__*/Object.freeze({
  19554. __proto__: null,
  19555. ArcCurve: ArcCurve,
  19556. CatmullRomCurve3: CatmullRomCurve3,
  19557. CubicBezierCurve: CubicBezierCurve,
  19558. CubicBezierCurve3: CubicBezierCurve3,
  19559. EllipseCurve: EllipseCurve,
  19560. LineCurve: LineCurve,
  19561. LineCurve3: LineCurve3,
  19562. QuadraticBezierCurve: QuadraticBezierCurve,
  19563. QuadraticBezierCurve3: QuadraticBezierCurve3,
  19564. SplineCurve: SplineCurve
  19565. });
  19566. /**************************************************************
  19567. * Curved Path - a curve path is simply a array of connected
  19568. * curves, but retains the api of a curve
  19569. **************************************************************/
  19570. class CurvePath extends Curve {
  19571. constructor() {
  19572. super();
  19573. this.type = 'CurvePath';
  19574. this.curves = [];
  19575. this.autoClose = false; // Automatically closes the path
  19576. }
  19577. add( curve ) {
  19578. this.curves.push( curve );
  19579. }
  19580. closePath() {
  19581. // Add a line curve if start and end of lines are not connected
  19582. const startPoint = this.curves[ 0 ].getPoint( 0 );
  19583. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  19584. if ( ! startPoint.equals( endPoint ) ) {
  19585. this.curves.push( new LineCurve( endPoint, startPoint ) );
  19586. }
  19587. }
  19588. // To get accurate point with reference to
  19589. // entire path distance at time t,
  19590. // following has to be done:
  19591. // 1. Length of each sub path have to be known
  19592. // 2. Locate and identify type of curve
  19593. // 3. Get t for the curve
  19594. // 4. Return curve.getPointAt(t')
  19595. getPoint( t, optionalTarget ) {
  19596. const d = t * this.getLength();
  19597. const curveLengths = this.getCurveLengths();
  19598. let i = 0;
  19599. // To think about boundaries points.
  19600. while ( i < curveLengths.length ) {
  19601. if ( curveLengths[ i ] >= d ) {
  19602. const diff = curveLengths[ i ] - d;
  19603. const curve = this.curves[ i ];
  19604. const segmentLength = curve.getLength();
  19605. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  19606. return curve.getPointAt( u, optionalTarget );
  19607. }
  19608. i ++;
  19609. }
  19610. return null;
  19611. // loop where sum != 0, sum > d , sum+1 <d
  19612. }
  19613. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  19614. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  19615. // getPoint() depends on getLength
  19616. getLength() {
  19617. const lens = this.getCurveLengths();
  19618. return lens[ lens.length - 1 ];
  19619. }
  19620. // cacheLengths must be recalculated.
  19621. updateArcLengths() {
  19622. this.needsUpdate = true;
  19623. this.cacheLengths = null;
  19624. this.getCurveLengths();
  19625. }
  19626. // Compute lengths and cache them
  19627. // We cannot overwrite getLengths() because UtoT mapping uses it.
  19628. getCurveLengths() {
  19629. // We use cache values if curves and cache array are same length
  19630. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  19631. return this.cacheLengths;
  19632. }
  19633. // Get length of sub-curve
  19634. // Push sums into cached array
  19635. const lengths = [];
  19636. let sums = 0;
  19637. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19638. sums += this.curves[ i ].getLength();
  19639. lengths.push( sums );
  19640. }
  19641. this.cacheLengths = lengths;
  19642. return lengths;
  19643. }
  19644. getSpacedPoints( divisions = 40 ) {
  19645. const points = [];
  19646. for ( let i = 0; i <= divisions; i ++ ) {
  19647. points.push( this.getPoint( i / divisions ) );
  19648. }
  19649. if ( this.autoClose ) {
  19650. points.push( points[ 0 ] );
  19651. }
  19652. return points;
  19653. }
  19654. getPoints( divisions = 12 ) {
  19655. const points = [];
  19656. let last;
  19657. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  19658. const curve = curves[ i ];
  19659. const resolution = curve.isEllipseCurve ? divisions * 2
  19660. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  19661. : curve.isSplineCurve ? divisions * curve.points.length
  19662. : divisions;
  19663. const pts = curve.getPoints( resolution );
  19664. for ( let j = 0; j < pts.length; j ++ ) {
  19665. const point = pts[ j ];
  19666. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  19667. points.push( point );
  19668. last = point;
  19669. }
  19670. }
  19671. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  19672. points.push( points[ 0 ] );
  19673. }
  19674. return points;
  19675. }
  19676. copy( source ) {
  19677. super.copy( source );
  19678. this.curves = [];
  19679. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  19680. const curve = source.curves[ i ];
  19681. this.curves.push( curve.clone() );
  19682. }
  19683. this.autoClose = source.autoClose;
  19684. return this;
  19685. }
  19686. toJSON() {
  19687. const data = super.toJSON();
  19688. data.autoClose = this.autoClose;
  19689. data.curves = [];
  19690. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19691. const curve = this.curves[ i ];
  19692. data.curves.push( curve.toJSON() );
  19693. }
  19694. return data;
  19695. }
  19696. fromJSON( json ) {
  19697. super.fromJSON( json );
  19698. this.autoClose = json.autoClose;
  19699. this.curves = [];
  19700. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  19701. const curve = json.curves[ i ];
  19702. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  19703. }
  19704. return this;
  19705. }
  19706. }
  19707. class Path extends CurvePath {
  19708. constructor( points ) {
  19709. super();
  19710. this.type = 'Path';
  19711. this.currentPoint = new Vector2();
  19712. if ( points ) {
  19713. this.setFromPoints( points );
  19714. }
  19715. }
  19716. setFromPoints( points ) {
  19717. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  19718. for ( let i = 1, l = points.length; i < l; i ++ ) {
  19719. this.lineTo( points[ i ].x, points[ i ].y );
  19720. }
  19721. return this;
  19722. }
  19723. moveTo( x, y ) {
  19724. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  19725. return this;
  19726. }
  19727. lineTo( x, y ) {
  19728. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  19729. this.curves.push( curve );
  19730. this.currentPoint.set( x, y );
  19731. return this;
  19732. }
  19733. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  19734. const curve = new QuadraticBezierCurve(
  19735. this.currentPoint.clone(),
  19736. new Vector2( aCPx, aCPy ),
  19737. new Vector2( aX, aY )
  19738. );
  19739. this.curves.push( curve );
  19740. this.currentPoint.set( aX, aY );
  19741. return this;
  19742. }
  19743. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  19744. const curve = new CubicBezierCurve(
  19745. this.currentPoint.clone(),
  19746. new Vector2( aCP1x, aCP1y ),
  19747. new Vector2( aCP2x, aCP2y ),
  19748. new Vector2( aX, aY )
  19749. );
  19750. this.curves.push( curve );
  19751. this.currentPoint.set( aX, aY );
  19752. return this;
  19753. }
  19754. splineThru( pts /*Array of Vector*/ ) {
  19755. const npts = [ this.currentPoint.clone() ].concat( pts );
  19756. const curve = new SplineCurve( npts );
  19757. this.curves.push( curve );
  19758. this.currentPoint.copy( pts[ pts.length - 1 ] );
  19759. return this;
  19760. }
  19761. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19762. const x0 = this.currentPoint.x;
  19763. const y0 = this.currentPoint.y;
  19764. this.absarc( aX + x0, aY + y0, aRadius,
  19765. aStartAngle, aEndAngle, aClockwise );
  19766. return this;
  19767. }
  19768. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19769. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  19770. return this;
  19771. }
  19772. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  19773. const x0 = this.currentPoint.x;
  19774. const y0 = this.currentPoint.y;
  19775. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  19776. return this;
  19777. }
  19778. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  19779. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  19780. if ( this.curves.length > 0 ) {
  19781. // if a previous curve is present, attempt to join
  19782. const firstPoint = curve.getPoint( 0 );
  19783. if ( ! firstPoint.equals( this.currentPoint ) ) {
  19784. this.lineTo( firstPoint.x, firstPoint.y );
  19785. }
  19786. }
  19787. this.curves.push( curve );
  19788. const lastPoint = curve.getPoint( 1 );
  19789. this.currentPoint.copy( lastPoint );
  19790. return this;
  19791. }
  19792. copy( source ) {
  19793. super.copy( source );
  19794. this.currentPoint.copy( source.currentPoint );
  19795. return this;
  19796. }
  19797. toJSON() {
  19798. const data = super.toJSON();
  19799. data.currentPoint = this.currentPoint.toArray();
  19800. return data;
  19801. }
  19802. fromJSON( json ) {
  19803. super.fromJSON( json );
  19804. this.currentPoint.fromArray( json.currentPoint );
  19805. return this;
  19806. }
  19807. }
  19808. class LatheGeometry extends BufferGeometry {
  19809. 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 ) {
  19810. super();
  19811. this.type = 'LatheGeometry';
  19812. this.parameters = {
  19813. points: points,
  19814. segments: segments,
  19815. phiStart: phiStart,
  19816. phiLength: phiLength
  19817. };
  19818. segments = Math.floor( segments );
  19819. // clamp phiLength so it's in range of [ 0, 2PI ]
  19820. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  19821. // buffers
  19822. const indices = [];
  19823. const vertices = [];
  19824. const uvs = [];
  19825. const initNormals = [];
  19826. const normals = [];
  19827. // helper variables
  19828. const inverseSegments = 1.0 / segments;
  19829. const vertex = new Vector3();
  19830. const uv = new Vector2();
  19831. const normal = new Vector3();
  19832. const curNormal = new Vector3();
  19833. const prevNormal = new Vector3();
  19834. let dx = 0;
  19835. let dy = 0;
  19836. // pre-compute normals for initial "meridian"
  19837. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  19838. switch ( j ) {
  19839. case 0: // special handling for 1st vertex on path
  19840. dx = points[ j + 1 ].x - points[ j ].x;
  19841. dy = points[ j + 1 ].y - points[ j ].y;
  19842. normal.x = dy * 1.0;
  19843. normal.y = - dx;
  19844. normal.z = dy * 0.0;
  19845. prevNormal.copy( normal );
  19846. normal.normalize();
  19847. initNormals.push( normal.x, normal.y, normal.z );
  19848. break;
  19849. case ( points.length - 1 ): // special handling for last Vertex on path
  19850. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  19851. break;
  19852. default: // default handling for all vertices in between
  19853. dx = points[ j + 1 ].x - points[ j ].x;
  19854. dy = points[ j + 1 ].y - points[ j ].y;
  19855. normal.x = dy * 1.0;
  19856. normal.y = - dx;
  19857. normal.z = dy * 0.0;
  19858. curNormal.copy( normal );
  19859. normal.x += prevNormal.x;
  19860. normal.y += prevNormal.y;
  19861. normal.z += prevNormal.z;
  19862. normal.normalize();
  19863. initNormals.push( normal.x, normal.y, normal.z );
  19864. prevNormal.copy( curNormal );
  19865. }
  19866. }
  19867. // generate vertices, uvs and normals
  19868. for ( let i = 0; i <= segments; i ++ ) {
  19869. const phi = phiStart + i * inverseSegments * phiLength;
  19870. const sin = Math.sin( phi );
  19871. const cos = Math.cos( phi );
  19872. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  19873. // vertex
  19874. vertex.x = points[ j ].x * sin;
  19875. vertex.y = points[ j ].y;
  19876. vertex.z = points[ j ].x * cos;
  19877. vertices.push( vertex.x, vertex.y, vertex.z );
  19878. // uv
  19879. uv.x = i / segments;
  19880. uv.y = j / ( points.length - 1 );
  19881. uvs.push( uv.x, uv.y );
  19882. // normal
  19883. const x = initNormals[ 3 * j + 0 ] * sin;
  19884. const y = initNormals[ 3 * j + 1 ];
  19885. const z = initNormals[ 3 * j + 0 ] * cos;
  19886. normals.push( x, y, z );
  19887. }
  19888. }
  19889. // indices
  19890. for ( let i = 0; i < segments; i ++ ) {
  19891. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  19892. const base = j + i * points.length;
  19893. const a = base;
  19894. const b = base + points.length;
  19895. const c = base + points.length + 1;
  19896. const d = base + 1;
  19897. // faces
  19898. indices.push( a, b, d );
  19899. indices.push( c, d, b );
  19900. }
  19901. }
  19902. // build geometry
  19903. this.setIndex( indices );
  19904. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19905. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19906. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19907. }
  19908. copy( source ) {
  19909. super.copy( source );
  19910. this.parameters = Object.assign( {}, source.parameters );
  19911. return this;
  19912. }
  19913. static fromJSON( data ) {
  19914. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  19915. }
  19916. }
  19917. class CapsuleGeometry extends LatheGeometry {
  19918. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  19919. const path = new Path();
  19920. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  19921. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  19922. super( path.getPoints( capSegments ), radialSegments );
  19923. this.type = 'CapsuleGeometry';
  19924. this.parameters = {
  19925. radius: radius,
  19926. height: length,
  19927. capSegments: capSegments,
  19928. radialSegments: radialSegments,
  19929. };
  19930. }
  19931. static fromJSON( data ) {
  19932. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  19933. }
  19934. }
  19935. class CircleGeometry extends BufferGeometry {
  19936. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19937. super();
  19938. this.type = 'CircleGeometry';
  19939. this.parameters = {
  19940. radius: radius,
  19941. segments: segments,
  19942. thetaStart: thetaStart,
  19943. thetaLength: thetaLength
  19944. };
  19945. segments = Math.max( 3, segments );
  19946. // buffers
  19947. const indices = [];
  19948. const vertices = [];
  19949. const normals = [];
  19950. const uvs = [];
  19951. // helper variables
  19952. const vertex = new Vector3();
  19953. const uv = new Vector2();
  19954. // center point
  19955. vertices.push( 0, 0, 0 );
  19956. normals.push( 0, 0, 1 );
  19957. uvs.push( 0.5, 0.5 );
  19958. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  19959. const segment = thetaStart + s / segments * thetaLength;
  19960. // vertex
  19961. vertex.x = radius * Math.cos( segment );
  19962. vertex.y = radius * Math.sin( segment );
  19963. vertices.push( vertex.x, vertex.y, vertex.z );
  19964. // normal
  19965. normals.push( 0, 0, 1 );
  19966. // uvs
  19967. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  19968. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  19969. uvs.push( uv.x, uv.y );
  19970. }
  19971. // indices
  19972. for ( let i = 1; i <= segments; i ++ ) {
  19973. indices.push( i, i + 1, 0 );
  19974. }
  19975. // build geometry
  19976. this.setIndex( indices );
  19977. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19978. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19979. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19980. }
  19981. copy( source ) {
  19982. super.copy( source );
  19983. this.parameters = Object.assign( {}, source.parameters );
  19984. return this;
  19985. }
  19986. static fromJSON( data ) {
  19987. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  19988. }
  19989. }
  19990. class CylinderGeometry extends BufferGeometry {
  19991. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19992. super();
  19993. this.type = 'CylinderGeometry';
  19994. this.parameters = {
  19995. radiusTop: radiusTop,
  19996. radiusBottom: radiusBottom,
  19997. height: height,
  19998. radialSegments: radialSegments,
  19999. heightSegments: heightSegments,
  20000. openEnded: openEnded,
  20001. thetaStart: thetaStart,
  20002. thetaLength: thetaLength
  20003. };
  20004. const scope = this;
  20005. radialSegments = Math.floor( radialSegments );
  20006. heightSegments = Math.floor( heightSegments );
  20007. // buffers
  20008. const indices = [];
  20009. const vertices = [];
  20010. const normals = [];
  20011. const uvs = [];
  20012. // helper variables
  20013. let index = 0;
  20014. const indexArray = [];
  20015. const halfHeight = height / 2;
  20016. let groupStart = 0;
  20017. // generate geometry
  20018. generateTorso();
  20019. if ( openEnded === false ) {
  20020. if ( radiusTop > 0 ) generateCap( true );
  20021. if ( radiusBottom > 0 ) generateCap( false );
  20022. }
  20023. // build geometry
  20024. this.setIndex( indices );
  20025. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20026. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20027. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20028. function generateTorso() {
  20029. const normal = new Vector3();
  20030. const vertex = new Vector3();
  20031. let groupCount = 0;
  20032. // this will be used to calculate the normal
  20033. const slope = ( radiusBottom - radiusTop ) / height;
  20034. // generate vertices, normals and uvs
  20035. for ( let y = 0; y <= heightSegments; y ++ ) {
  20036. const indexRow = [];
  20037. const v = y / heightSegments;
  20038. // calculate the radius of the current row
  20039. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  20040. for ( let x = 0; x <= radialSegments; x ++ ) {
  20041. const u = x / radialSegments;
  20042. const theta = u * thetaLength + thetaStart;
  20043. const sinTheta = Math.sin( theta );
  20044. const cosTheta = Math.cos( theta );
  20045. // vertex
  20046. vertex.x = radius * sinTheta;
  20047. vertex.y = - v * height + halfHeight;
  20048. vertex.z = radius * cosTheta;
  20049. vertices.push( vertex.x, vertex.y, vertex.z );
  20050. // normal
  20051. normal.set( sinTheta, slope, cosTheta ).normalize();
  20052. normals.push( normal.x, normal.y, normal.z );
  20053. // uv
  20054. uvs.push( u, 1 - v );
  20055. // save index of vertex in respective row
  20056. indexRow.push( index ++ );
  20057. }
  20058. // now save vertices of the row in our index array
  20059. indexArray.push( indexRow );
  20060. }
  20061. // generate indices
  20062. for ( let x = 0; x < radialSegments; x ++ ) {
  20063. for ( let y = 0; y < heightSegments; y ++ ) {
  20064. // we use the index array to access the correct indices
  20065. const a = indexArray[ y ][ x ];
  20066. const b = indexArray[ y + 1 ][ x ];
  20067. const c = indexArray[ y + 1 ][ x + 1 ];
  20068. const d = indexArray[ y ][ x + 1 ];
  20069. // faces
  20070. indices.push( a, b, d );
  20071. indices.push( b, c, d );
  20072. // update group counter
  20073. groupCount += 6;
  20074. }
  20075. }
  20076. // add a group to the geometry. this will ensure multi material support
  20077. scope.addGroup( groupStart, groupCount, 0 );
  20078. // calculate new start value for groups
  20079. groupStart += groupCount;
  20080. }
  20081. function generateCap( top ) {
  20082. // save the index of the first center vertex
  20083. const centerIndexStart = index;
  20084. const uv = new Vector2();
  20085. const vertex = new Vector3();
  20086. let groupCount = 0;
  20087. const radius = ( top === true ) ? radiusTop : radiusBottom;
  20088. const sign = ( top === true ) ? 1 : - 1;
  20089. // first we generate the center vertex data of the cap.
  20090. // because the geometry needs one set of uvs per face,
  20091. // we must generate a center vertex per face/segment
  20092. for ( let x = 1; x <= radialSegments; x ++ ) {
  20093. // vertex
  20094. vertices.push( 0, halfHeight * sign, 0 );
  20095. // normal
  20096. normals.push( 0, sign, 0 );
  20097. // uv
  20098. uvs.push( 0.5, 0.5 );
  20099. // increase index
  20100. index ++;
  20101. }
  20102. // save the index of the last center vertex
  20103. const centerIndexEnd = index;
  20104. // now we generate the surrounding vertices, normals and uvs
  20105. for ( let x = 0; x <= radialSegments; x ++ ) {
  20106. const u = x / radialSegments;
  20107. const theta = u * thetaLength + thetaStart;
  20108. const cosTheta = Math.cos( theta );
  20109. const sinTheta = Math.sin( theta );
  20110. // vertex
  20111. vertex.x = radius * sinTheta;
  20112. vertex.y = halfHeight * sign;
  20113. vertex.z = radius * cosTheta;
  20114. vertices.push( vertex.x, vertex.y, vertex.z );
  20115. // normal
  20116. normals.push( 0, sign, 0 );
  20117. // uv
  20118. uv.x = ( cosTheta * 0.5 ) + 0.5;
  20119. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  20120. uvs.push( uv.x, uv.y );
  20121. // increase index
  20122. index ++;
  20123. }
  20124. // generate indices
  20125. for ( let x = 0; x < radialSegments; x ++ ) {
  20126. const c = centerIndexStart + x;
  20127. const i = centerIndexEnd + x;
  20128. if ( top === true ) {
  20129. // face top
  20130. indices.push( i, i + 1, c );
  20131. } else {
  20132. // face bottom
  20133. indices.push( i + 1, i, c );
  20134. }
  20135. groupCount += 3;
  20136. }
  20137. // add a group to the geometry. this will ensure multi material support
  20138. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  20139. // calculate new start value for groups
  20140. groupStart += groupCount;
  20141. }
  20142. }
  20143. copy( source ) {
  20144. super.copy( source );
  20145. this.parameters = Object.assign( {}, source.parameters );
  20146. return this;
  20147. }
  20148. static fromJSON( data ) {
  20149. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  20150. }
  20151. }
  20152. class ConeGeometry extends CylinderGeometry {
  20153. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20154. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  20155. this.type = 'ConeGeometry';
  20156. this.parameters = {
  20157. radius: radius,
  20158. height: height,
  20159. radialSegments: radialSegments,
  20160. heightSegments: heightSegments,
  20161. openEnded: openEnded,
  20162. thetaStart: thetaStart,
  20163. thetaLength: thetaLength
  20164. };
  20165. }
  20166. static fromJSON( data ) {
  20167. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  20168. }
  20169. }
  20170. class PolyhedronGeometry extends BufferGeometry {
  20171. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  20172. super();
  20173. this.type = 'PolyhedronGeometry';
  20174. this.parameters = {
  20175. vertices: vertices,
  20176. indices: indices,
  20177. radius: radius,
  20178. detail: detail
  20179. };
  20180. // default buffer data
  20181. const vertexBuffer = [];
  20182. const uvBuffer = [];
  20183. // the subdivision creates the vertex buffer data
  20184. subdivide( detail );
  20185. // all vertices should lie on a conceptual sphere with a given radius
  20186. applyRadius( radius );
  20187. // finally, create the uv data
  20188. generateUVs();
  20189. // build non-indexed geometry
  20190. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  20191. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  20192. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  20193. if ( detail === 0 ) {
  20194. this.computeVertexNormals(); // flat normals
  20195. } else {
  20196. this.normalizeNormals(); // smooth normals
  20197. }
  20198. // helper functions
  20199. function subdivide( detail ) {
  20200. const a = new Vector3();
  20201. const b = new Vector3();
  20202. const c = new Vector3();
  20203. // iterate over all faces and apply a subdivision with the given detail value
  20204. for ( let i = 0; i < indices.length; i += 3 ) {
  20205. // get the vertices of the face
  20206. getVertexByIndex( indices[ i + 0 ], a );
  20207. getVertexByIndex( indices[ i + 1 ], b );
  20208. getVertexByIndex( indices[ i + 2 ], c );
  20209. // perform subdivision
  20210. subdivideFace( a, b, c, detail );
  20211. }
  20212. }
  20213. function subdivideFace( a, b, c, detail ) {
  20214. const cols = detail + 1;
  20215. // we use this multidimensional array as a data structure for creating the subdivision
  20216. const v = [];
  20217. // construct all of the vertices for this subdivision
  20218. for ( let i = 0; i <= cols; i ++ ) {
  20219. v[ i ] = [];
  20220. const aj = a.clone().lerp( c, i / cols );
  20221. const bj = b.clone().lerp( c, i / cols );
  20222. const rows = cols - i;
  20223. for ( let j = 0; j <= rows; j ++ ) {
  20224. if ( j === 0 && i === cols ) {
  20225. v[ i ][ j ] = aj;
  20226. } else {
  20227. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  20228. }
  20229. }
  20230. }
  20231. // construct all of the faces
  20232. for ( let i = 0; i < cols; i ++ ) {
  20233. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  20234. const k = Math.floor( j / 2 );
  20235. if ( j % 2 === 0 ) {
  20236. pushVertex( v[ i ][ k + 1 ] );
  20237. pushVertex( v[ i + 1 ][ k ] );
  20238. pushVertex( v[ i ][ k ] );
  20239. } else {
  20240. pushVertex( v[ i ][ k + 1 ] );
  20241. pushVertex( v[ i + 1 ][ k + 1 ] );
  20242. pushVertex( v[ i + 1 ][ k ] );
  20243. }
  20244. }
  20245. }
  20246. }
  20247. function applyRadius( radius ) {
  20248. const vertex = new Vector3();
  20249. // iterate over the entire buffer and apply the radius to each vertex
  20250. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  20251. vertex.x = vertexBuffer[ i + 0 ];
  20252. vertex.y = vertexBuffer[ i + 1 ];
  20253. vertex.z = vertexBuffer[ i + 2 ];
  20254. vertex.normalize().multiplyScalar( radius );
  20255. vertexBuffer[ i + 0 ] = vertex.x;
  20256. vertexBuffer[ i + 1 ] = vertex.y;
  20257. vertexBuffer[ i + 2 ] = vertex.z;
  20258. }
  20259. }
  20260. function generateUVs() {
  20261. const vertex = new Vector3();
  20262. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  20263. vertex.x = vertexBuffer[ i + 0 ];
  20264. vertex.y = vertexBuffer[ i + 1 ];
  20265. vertex.z = vertexBuffer[ i + 2 ];
  20266. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  20267. const v = inclination( vertex ) / Math.PI + 0.5;
  20268. uvBuffer.push( u, 1 - v );
  20269. }
  20270. correctUVs();
  20271. correctSeam();
  20272. }
  20273. function correctSeam() {
  20274. // handle case when face straddles the seam, see #3269
  20275. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  20276. // uv data of a single face
  20277. const x0 = uvBuffer[ i + 0 ];
  20278. const x1 = uvBuffer[ i + 2 ];
  20279. const x2 = uvBuffer[ i + 4 ];
  20280. const max = Math.max( x0, x1, x2 );
  20281. const min = Math.min( x0, x1, x2 );
  20282. // 0.9 is somewhat arbitrary
  20283. if ( max > 0.9 && min < 0.1 ) {
  20284. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  20285. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  20286. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  20287. }
  20288. }
  20289. }
  20290. function pushVertex( vertex ) {
  20291. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  20292. }
  20293. function getVertexByIndex( index, vertex ) {
  20294. const stride = index * 3;
  20295. vertex.x = vertices[ stride + 0 ];
  20296. vertex.y = vertices[ stride + 1 ];
  20297. vertex.z = vertices[ stride + 2 ];
  20298. }
  20299. function correctUVs() {
  20300. const a = new Vector3();
  20301. const b = new Vector3();
  20302. const c = new Vector3();
  20303. const centroid = new Vector3();
  20304. const uvA = new Vector2();
  20305. const uvB = new Vector2();
  20306. const uvC = new Vector2();
  20307. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  20308. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  20309. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  20310. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  20311. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  20312. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  20313. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  20314. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  20315. const azi = azimuth( centroid );
  20316. correctUV( uvA, j + 0, a, azi );
  20317. correctUV( uvB, j + 2, b, azi );
  20318. correctUV( uvC, j + 4, c, azi );
  20319. }
  20320. }
  20321. function correctUV( uv, stride, vector, azimuth ) {
  20322. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  20323. uvBuffer[ stride ] = uv.x - 1;
  20324. }
  20325. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  20326. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  20327. }
  20328. }
  20329. // Angle around the Y axis, counter-clockwise when looking from above.
  20330. function azimuth( vector ) {
  20331. return Math.atan2( vector.z, - vector.x );
  20332. }
  20333. // Angle above the XZ plane.
  20334. function inclination( vector ) {
  20335. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20336. }
  20337. }
  20338. copy( source ) {
  20339. super.copy( source );
  20340. this.parameters = Object.assign( {}, source.parameters );
  20341. return this;
  20342. }
  20343. static fromJSON( data ) {
  20344. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  20345. }
  20346. }
  20347. class DodecahedronGeometry extends PolyhedronGeometry {
  20348. constructor( radius = 1, detail = 0 ) {
  20349. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20350. const r = 1 / t;
  20351. const vertices = [
  20352. // (±1, ±1, ±1)
  20353. - 1, - 1, - 1, - 1, - 1, 1,
  20354. - 1, 1, - 1, - 1, 1, 1,
  20355. 1, - 1, - 1, 1, - 1, 1,
  20356. 1, 1, - 1, 1, 1, 1,
  20357. // (0, ±1/φ, ±φ)
  20358. 0, - r, - t, 0, - r, t,
  20359. 0, r, - t, 0, r, t,
  20360. // (±1/φ, ±φ, 0)
  20361. - r, - t, 0, - r, t, 0,
  20362. r, - t, 0, r, t, 0,
  20363. // (±φ, 0, ±1/φ)
  20364. - t, 0, - r, t, 0, - r,
  20365. - t, 0, r, t, 0, r
  20366. ];
  20367. const indices = [
  20368. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  20369. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  20370. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  20371. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  20372. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  20373. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  20374. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  20375. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  20376. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  20377. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  20378. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  20379. 1, 12, 14, 1, 14, 5, 1, 5, 9
  20380. ];
  20381. super( vertices, indices, radius, detail );
  20382. this.type = 'DodecahedronGeometry';
  20383. this.parameters = {
  20384. radius: radius,
  20385. detail: detail
  20386. };
  20387. }
  20388. static fromJSON( data ) {
  20389. return new DodecahedronGeometry( data.radius, data.detail );
  20390. }
  20391. }
  20392. const _v0 = /*@__PURE__*/ new Vector3();
  20393. const _v1$1 = /*@__PURE__*/ new Vector3();
  20394. const _normal = /*@__PURE__*/ new Vector3();
  20395. const _triangle = /*@__PURE__*/ new Triangle();
  20396. class EdgesGeometry extends BufferGeometry {
  20397. constructor( geometry = null, thresholdAngle = 1 ) {
  20398. super();
  20399. this.type = 'EdgesGeometry';
  20400. this.parameters = {
  20401. geometry: geometry,
  20402. thresholdAngle: thresholdAngle
  20403. };
  20404. if ( geometry !== null ) {
  20405. const precisionPoints = 4;
  20406. const precision = Math.pow( 10, precisionPoints );
  20407. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  20408. const indexAttr = geometry.getIndex();
  20409. const positionAttr = geometry.getAttribute( 'position' );
  20410. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  20411. const indexArr = [ 0, 0, 0 ];
  20412. const vertKeys = [ 'a', 'b', 'c' ];
  20413. const hashes = new Array( 3 );
  20414. const edgeData = {};
  20415. const vertices = [];
  20416. for ( let i = 0; i < indexCount; i += 3 ) {
  20417. if ( indexAttr ) {
  20418. indexArr[ 0 ] = indexAttr.getX( i );
  20419. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  20420. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  20421. } else {
  20422. indexArr[ 0 ] = i;
  20423. indexArr[ 1 ] = i + 1;
  20424. indexArr[ 2 ] = i + 2;
  20425. }
  20426. const { a, b, c } = _triangle;
  20427. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  20428. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  20429. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  20430. _triangle.getNormal( _normal );
  20431. // create hashes for the edge from the vertices
  20432. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  20433. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  20434. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  20435. // skip degenerate triangles
  20436. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  20437. continue;
  20438. }
  20439. // iterate over every edge
  20440. for ( let j = 0; j < 3; j ++ ) {
  20441. // get the first and next vertex making up the edge
  20442. const jNext = ( j + 1 ) % 3;
  20443. const vecHash0 = hashes[ j ];
  20444. const vecHash1 = hashes[ jNext ];
  20445. const v0 = _triangle[ vertKeys[ j ] ];
  20446. const v1 = _triangle[ vertKeys[ jNext ] ];
  20447. const hash = `${ vecHash0 }_${ vecHash1 }`;
  20448. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  20449. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  20450. // if we found a sibling edge add it into the vertex array if
  20451. // it meets the angle threshold and delete the edge from the map.
  20452. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  20453. vertices.push( v0.x, v0.y, v0.z );
  20454. vertices.push( v1.x, v1.y, v1.z );
  20455. }
  20456. edgeData[ reverseHash ] = null;
  20457. } else if ( ! ( hash in edgeData ) ) {
  20458. // if we've already got an edge here then skip adding a new one
  20459. edgeData[ hash ] = {
  20460. index0: indexArr[ j ],
  20461. index1: indexArr[ jNext ],
  20462. normal: _normal.clone(),
  20463. };
  20464. }
  20465. }
  20466. }
  20467. // iterate over all remaining, unmatched edges and add them to the vertex array
  20468. for ( const key in edgeData ) {
  20469. if ( edgeData[ key ] ) {
  20470. const { index0, index1 } = edgeData[ key ];
  20471. _v0.fromBufferAttribute( positionAttr, index0 );
  20472. _v1$1.fromBufferAttribute( positionAttr, index1 );
  20473. vertices.push( _v0.x, _v0.y, _v0.z );
  20474. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  20475. }
  20476. }
  20477. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20478. }
  20479. }
  20480. copy( source ) {
  20481. super.copy( source );
  20482. this.parameters = Object.assign( {}, source.parameters );
  20483. return this;
  20484. }
  20485. }
  20486. class Shape extends Path {
  20487. constructor( points ) {
  20488. super( points );
  20489. this.uuid = generateUUID();
  20490. this.type = 'Shape';
  20491. this.holes = [];
  20492. }
  20493. getPointsHoles( divisions ) {
  20494. const holesPts = [];
  20495. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20496. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  20497. }
  20498. return holesPts;
  20499. }
  20500. // get points of shape and holes (keypoints based on segments parameter)
  20501. extractPoints( divisions ) {
  20502. return {
  20503. shape: this.getPoints( divisions ),
  20504. holes: this.getPointsHoles( divisions )
  20505. };
  20506. }
  20507. copy( source ) {
  20508. super.copy( source );
  20509. this.holes = [];
  20510. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  20511. const hole = source.holes[ i ];
  20512. this.holes.push( hole.clone() );
  20513. }
  20514. return this;
  20515. }
  20516. toJSON() {
  20517. const data = super.toJSON();
  20518. data.uuid = this.uuid;
  20519. data.holes = [];
  20520. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20521. const hole = this.holes[ i ];
  20522. data.holes.push( hole.toJSON() );
  20523. }
  20524. return data;
  20525. }
  20526. fromJSON( json ) {
  20527. super.fromJSON( json );
  20528. this.uuid = json.uuid;
  20529. this.holes = [];
  20530. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  20531. const hole = json.holes[ i ];
  20532. this.holes.push( new Path().fromJSON( hole ) );
  20533. }
  20534. return this;
  20535. }
  20536. }
  20537. /**
  20538. * Port from https://github.com/mapbox/earcut (v2.2.4)
  20539. */
  20540. const Earcut = {
  20541. triangulate: function ( data, holeIndices, dim = 2 ) {
  20542. const hasHoles = holeIndices && holeIndices.length;
  20543. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  20544. let outerNode = linkedList( data, 0, outerLen, dim, true );
  20545. const triangles = [];
  20546. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  20547. let minX, minY, maxX, maxY, x, y, invSize;
  20548. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  20549. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  20550. if ( data.length > 80 * dim ) {
  20551. minX = maxX = data[ 0 ];
  20552. minY = maxY = data[ 1 ];
  20553. for ( let i = dim; i < outerLen; i += dim ) {
  20554. x = data[ i ];
  20555. y = data[ i + 1 ];
  20556. if ( x < minX ) minX = x;
  20557. if ( y < minY ) minY = y;
  20558. if ( x > maxX ) maxX = x;
  20559. if ( y > maxY ) maxY = y;
  20560. }
  20561. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  20562. invSize = Math.max( maxX - minX, maxY - minY );
  20563. invSize = invSize !== 0 ? 32767 / invSize : 0;
  20564. }
  20565. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  20566. return triangles;
  20567. }
  20568. };
  20569. // create a circular doubly linked list from polygon points in the specified winding order
  20570. function linkedList( data, start, end, dim, clockwise ) {
  20571. let i, last;
  20572. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  20573. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20574. } else {
  20575. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20576. }
  20577. if ( last && equals( last, last.next ) ) {
  20578. removeNode( last );
  20579. last = last.next;
  20580. }
  20581. return last;
  20582. }
  20583. // eliminate colinear or duplicate points
  20584. function filterPoints( start, end ) {
  20585. if ( ! start ) return start;
  20586. if ( ! end ) end = start;
  20587. let p = start,
  20588. again;
  20589. do {
  20590. again = false;
  20591. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  20592. removeNode( p );
  20593. p = end = p.prev;
  20594. if ( p === p.next ) break;
  20595. again = true;
  20596. } else {
  20597. p = p.next;
  20598. }
  20599. } while ( again || p !== end );
  20600. return end;
  20601. }
  20602. // main ear slicing loop which triangulates a polygon (given as a linked list)
  20603. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  20604. if ( ! ear ) return;
  20605. // interlink polygon nodes in z-order
  20606. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  20607. let stop = ear,
  20608. prev, next;
  20609. // iterate through ears, slicing them one by one
  20610. while ( ear.prev !== ear.next ) {
  20611. prev = ear.prev;
  20612. next = ear.next;
  20613. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  20614. // cut off the triangle
  20615. triangles.push( prev.i / dim | 0 );
  20616. triangles.push( ear.i / dim | 0 );
  20617. triangles.push( next.i / dim | 0 );
  20618. removeNode( ear );
  20619. // skipping the next vertex leads to less sliver triangles
  20620. ear = next.next;
  20621. stop = next.next;
  20622. continue;
  20623. }
  20624. ear = next;
  20625. // if we looped through the whole remaining polygon and can't find any more ears
  20626. if ( ear === stop ) {
  20627. // try filtering points and slicing again
  20628. if ( ! pass ) {
  20629. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  20630. // if this didn't work, try curing all small self-intersections locally
  20631. } else if ( pass === 1 ) {
  20632. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  20633. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  20634. // as a last resort, try splitting the remaining polygon into two
  20635. } else if ( pass === 2 ) {
  20636. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  20637. }
  20638. break;
  20639. }
  20640. }
  20641. }
  20642. // check whether a polygon node forms a valid ear with adjacent nodes
  20643. function isEar( ear ) {
  20644. const a = ear.prev,
  20645. b = ear,
  20646. c = ear.next;
  20647. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20648. // now make sure we don't have other points inside the potential ear
  20649. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  20650. // triangle bbox; min & max are calculated like this for speed
  20651. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  20652. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  20653. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  20654. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  20655. let p = c.next;
  20656. while ( p !== a ) {
  20657. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  20658. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  20659. area( p.prev, p, p.next ) >= 0 ) return false;
  20660. p = p.next;
  20661. }
  20662. return true;
  20663. }
  20664. function isEarHashed( ear, minX, minY, invSize ) {
  20665. const a = ear.prev,
  20666. b = ear,
  20667. c = ear.next;
  20668. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20669. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  20670. // triangle bbox; min & max are calculated like this for speed
  20671. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  20672. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  20673. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  20674. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  20675. // z-order range for the current triangle bbox;
  20676. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  20677. maxZ = zOrder( x1, y1, minX, minY, invSize );
  20678. let p = ear.prevZ,
  20679. n = ear.nextZ;
  20680. // look for points inside the triangle in both directions
  20681. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  20682. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  20683. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  20684. p = p.prevZ;
  20685. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  20686. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  20687. n = n.nextZ;
  20688. }
  20689. // look for remaining points in decreasing z-order
  20690. while ( p && p.z >= minZ ) {
  20691. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  20692. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  20693. p = p.prevZ;
  20694. }
  20695. // look for remaining points in increasing z-order
  20696. while ( n && n.z <= maxZ ) {
  20697. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  20698. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  20699. n = n.nextZ;
  20700. }
  20701. return true;
  20702. }
  20703. // go through all polygon nodes and cure small local self-intersections
  20704. function cureLocalIntersections( start, triangles, dim ) {
  20705. let p = start;
  20706. do {
  20707. const a = p.prev,
  20708. b = p.next.next;
  20709. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  20710. triangles.push( a.i / dim | 0 );
  20711. triangles.push( p.i / dim | 0 );
  20712. triangles.push( b.i / dim | 0 );
  20713. // remove two nodes involved
  20714. removeNode( p );
  20715. removeNode( p.next );
  20716. p = start = b;
  20717. }
  20718. p = p.next;
  20719. } while ( p !== start );
  20720. return filterPoints( p );
  20721. }
  20722. // try splitting polygon into two and triangulate them independently
  20723. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  20724. // look for a valid diagonal that divides the polygon into two
  20725. let a = start;
  20726. do {
  20727. let b = a.next.next;
  20728. while ( b !== a.prev ) {
  20729. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  20730. // split the polygon in two by the diagonal
  20731. let c = splitPolygon( a, b );
  20732. // filter colinear points around the cuts
  20733. a = filterPoints( a, a.next );
  20734. c = filterPoints( c, c.next );
  20735. // run earcut on each half
  20736. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  20737. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  20738. return;
  20739. }
  20740. b = b.next;
  20741. }
  20742. a = a.next;
  20743. } while ( a !== start );
  20744. }
  20745. // link every hole into the outer loop, producing a single-ring polygon without holes
  20746. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  20747. const queue = [];
  20748. let i, len, start, end, list;
  20749. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  20750. start = holeIndices[ i ] * dim;
  20751. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  20752. list = linkedList( data, start, end, dim, false );
  20753. if ( list === list.next ) list.steiner = true;
  20754. queue.push( getLeftmost( list ) );
  20755. }
  20756. queue.sort( compareX );
  20757. // process holes from left to right
  20758. for ( i = 0; i < queue.length; i ++ ) {
  20759. outerNode = eliminateHole( queue[ i ], outerNode );
  20760. }
  20761. return outerNode;
  20762. }
  20763. function compareX( a, b ) {
  20764. return a.x - b.x;
  20765. }
  20766. // find a bridge between vertices that connects hole with an outer ring and link it
  20767. function eliminateHole( hole, outerNode ) {
  20768. const bridge = findHoleBridge( hole, outerNode );
  20769. if ( ! bridge ) {
  20770. return outerNode;
  20771. }
  20772. const bridgeReverse = splitPolygon( bridge, hole );
  20773. // filter collinear points around the cuts
  20774. filterPoints( bridgeReverse, bridgeReverse.next );
  20775. return filterPoints( bridge, bridge.next );
  20776. }
  20777. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  20778. function findHoleBridge( hole, outerNode ) {
  20779. let p = outerNode,
  20780. qx = - Infinity,
  20781. m;
  20782. const hx = hole.x, hy = hole.y;
  20783. // find a segment intersected by a ray from the hole's leftmost point to the left;
  20784. // segment's endpoint with lesser x will be potential connection point
  20785. do {
  20786. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  20787. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  20788. if ( x <= hx && x > qx ) {
  20789. qx = x;
  20790. m = p.x < p.next.x ? p : p.next;
  20791. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  20792. }
  20793. }
  20794. p = p.next;
  20795. } while ( p !== outerNode );
  20796. if ( ! m ) return null;
  20797. // look for points inside the triangle of hole point, segment intersection and endpoint;
  20798. // if there are no points found, we have a valid connection;
  20799. // otherwise choose the point of the minimum angle with the ray as connection point
  20800. const stop = m,
  20801. mx = m.x,
  20802. my = m.y;
  20803. let tanMin = Infinity, tan;
  20804. p = m;
  20805. do {
  20806. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  20807. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  20808. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  20809. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  20810. m = p;
  20811. tanMin = tan;
  20812. }
  20813. }
  20814. p = p.next;
  20815. } while ( p !== stop );
  20816. return m;
  20817. }
  20818. // whether sector in vertex m contains sector in vertex p in the same coordinates
  20819. function sectorContainsSector( m, p ) {
  20820. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  20821. }
  20822. // interlink polygon nodes in z-order
  20823. function indexCurve( start, minX, minY, invSize ) {
  20824. let p = start;
  20825. do {
  20826. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  20827. p.prevZ = p.prev;
  20828. p.nextZ = p.next;
  20829. p = p.next;
  20830. } while ( p !== start );
  20831. p.prevZ.nextZ = null;
  20832. p.prevZ = null;
  20833. sortLinked( p );
  20834. }
  20835. // Simon Tatham's linked list merge sort algorithm
  20836. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  20837. function sortLinked( list ) {
  20838. let i, p, q, e, tail, numMerges, pSize, qSize,
  20839. inSize = 1;
  20840. do {
  20841. p = list;
  20842. list = null;
  20843. tail = null;
  20844. numMerges = 0;
  20845. while ( p ) {
  20846. numMerges ++;
  20847. q = p;
  20848. pSize = 0;
  20849. for ( i = 0; i < inSize; i ++ ) {
  20850. pSize ++;
  20851. q = q.nextZ;
  20852. if ( ! q ) break;
  20853. }
  20854. qSize = inSize;
  20855. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  20856. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  20857. e = p;
  20858. p = p.nextZ;
  20859. pSize --;
  20860. } else {
  20861. e = q;
  20862. q = q.nextZ;
  20863. qSize --;
  20864. }
  20865. if ( tail ) tail.nextZ = e;
  20866. else list = e;
  20867. e.prevZ = tail;
  20868. tail = e;
  20869. }
  20870. p = q;
  20871. }
  20872. tail.nextZ = null;
  20873. inSize *= 2;
  20874. } while ( numMerges > 1 );
  20875. return list;
  20876. }
  20877. // z-order of a point given coords and inverse of the longer side of data bbox
  20878. function zOrder( x, y, minX, minY, invSize ) {
  20879. // coords are transformed into non-negative 15-bit integer range
  20880. x = ( x - minX ) * invSize | 0;
  20881. y = ( y - minY ) * invSize | 0;
  20882. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  20883. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  20884. x = ( x | ( x << 2 ) ) & 0x33333333;
  20885. x = ( x | ( x << 1 ) ) & 0x55555555;
  20886. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  20887. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  20888. y = ( y | ( y << 2 ) ) & 0x33333333;
  20889. y = ( y | ( y << 1 ) ) & 0x55555555;
  20890. return x | ( y << 1 );
  20891. }
  20892. // find the leftmost node of a polygon ring
  20893. function getLeftmost( start ) {
  20894. let p = start,
  20895. leftmost = start;
  20896. do {
  20897. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  20898. p = p.next;
  20899. } while ( p !== start );
  20900. return leftmost;
  20901. }
  20902. // check if a point lies within a convex triangle
  20903. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  20904. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  20905. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  20906. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  20907. }
  20908. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  20909. function isValidDiagonal( a, b ) {
  20910. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  20911. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  20912. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  20913. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  20914. }
  20915. // signed area of a triangle
  20916. function area( p, q, r ) {
  20917. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  20918. }
  20919. // check if two points are equal
  20920. function equals( p1, p2 ) {
  20921. return p1.x === p2.x && p1.y === p2.y;
  20922. }
  20923. // check if two segments intersect
  20924. function intersects( p1, q1, p2, q2 ) {
  20925. const o1 = sign( area( p1, q1, p2 ) );
  20926. const o2 = sign( area( p1, q1, q2 ) );
  20927. const o3 = sign( area( p2, q2, p1 ) );
  20928. const o4 = sign( area( p2, q2, q1 ) );
  20929. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  20930. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  20931. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  20932. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  20933. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  20934. return false;
  20935. }
  20936. // for collinear points p, q, r, check if point q lies on segment pr
  20937. function onSegment( p, q, r ) {
  20938. 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 );
  20939. }
  20940. function sign( num ) {
  20941. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  20942. }
  20943. // check if a polygon diagonal intersects any polygon segments
  20944. function intersectsPolygon( a, b ) {
  20945. let p = a;
  20946. do {
  20947. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  20948. intersects( p, p.next, a, b ) ) return true;
  20949. p = p.next;
  20950. } while ( p !== a );
  20951. return false;
  20952. }
  20953. // check if a polygon diagonal is locally inside the polygon
  20954. function locallyInside( a, b ) {
  20955. return area( a.prev, a, a.next ) < 0 ?
  20956. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  20957. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  20958. }
  20959. // check if the middle point of a polygon diagonal is inside the polygon
  20960. function middleInside( a, b ) {
  20961. let p = a,
  20962. inside = false;
  20963. const px = ( a.x + b.x ) / 2,
  20964. py = ( a.y + b.y ) / 2;
  20965. do {
  20966. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  20967. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  20968. inside = ! inside;
  20969. p = p.next;
  20970. } while ( p !== a );
  20971. return inside;
  20972. }
  20973. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  20974. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  20975. function splitPolygon( a, b ) {
  20976. const a2 = new Node( a.i, a.x, a.y ),
  20977. b2 = new Node( b.i, b.x, b.y ),
  20978. an = a.next,
  20979. bp = b.prev;
  20980. a.next = b;
  20981. b.prev = a;
  20982. a2.next = an;
  20983. an.prev = a2;
  20984. b2.next = a2;
  20985. a2.prev = b2;
  20986. bp.next = b2;
  20987. b2.prev = bp;
  20988. return b2;
  20989. }
  20990. // create a node and optionally link it with previous one (in a circular doubly linked list)
  20991. function insertNode( i, x, y, last ) {
  20992. const p = new Node( i, x, y );
  20993. if ( ! last ) {
  20994. p.prev = p;
  20995. p.next = p;
  20996. } else {
  20997. p.next = last.next;
  20998. p.prev = last;
  20999. last.next.prev = p;
  21000. last.next = p;
  21001. }
  21002. return p;
  21003. }
  21004. function removeNode( p ) {
  21005. p.next.prev = p.prev;
  21006. p.prev.next = p.next;
  21007. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  21008. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  21009. }
  21010. function Node( i, x, y ) {
  21011. // vertex index in coordinates array
  21012. this.i = i;
  21013. // vertex coordinates
  21014. this.x = x;
  21015. this.y = y;
  21016. // previous and next vertex nodes in a polygon ring
  21017. this.prev = null;
  21018. this.next = null;
  21019. // z-order curve value
  21020. this.z = 0;
  21021. // previous and next nodes in z-order
  21022. this.prevZ = null;
  21023. this.nextZ = null;
  21024. // indicates whether this is a steiner point
  21025. this.steiner = false;
  21026. }
  21027. function signedArea( data, start, end, dim ) {
  21028. let sum = 0;
  21029. for ( let i = start, j = end - dim; i < end; i += dim ) {
  21030. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  21031. j = i;
  21032. }
  21033. return sum;
  21034. }
  21035. class ShapeUtils {
  21036. // calculate area of the contour polygon
  21037. static area( contour ) {
  21038. const n = contour.length;
  21039. let a = 0.0;
  21040. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  21041. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  21042. }
  21043. return a * 0.5;
  21044. }
  21045. static isClockWise( pts ) {
  21046. return ShapeUtils.area( pts ) < 0;
  21047. }
  21048. static triangulateShape( contour, holes ) {
  21049. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  21050. const holeIndices = []; // array of hole indices
  21051. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  21052. removeDupEndPts( contour );
  21053. addContour( vertices, contour );
  21054. //
  21055. let holeIndex = contour.length;
  21056. holes.forEach( removeDupEndPts );
  21057. for ( let i = 0; i < holes.length; i ++ ) {
  21058. holeIndices.push( holeIndex );
  21059. holeIndex += holes[ i ].length;
  21060. addContour( vertices, holes[ i ] );
  21061. }
  21062. //
  21063. const triangles = Earcut.triangulate( vertices, holeIndices );
  21064. //
  21065. for ( let i = 0; i < triangles.length; i += 3 ) {
  21066. faces.push( triangles.slice( i, i + 3 ) );
  21067. }
  21068. return faces;
  21069. }
  21070. }
  21071. function removeDupEndPts( points ) {
  21072. const l = points.length;
  21073. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  21074. points.pop();
  21075. }
  21076. }
  21077. function addContour( vertices, contour ) {
  21078. for ( let i = 0; i < contour.length; i ++ ) {
  21079. vertices.push( contour[ i ].x );
  21080. vertices.push( contour[ i ].y );
  21081. }
  21082. }
  21083. /**
  21084. * Creates extruded geometry from a path shape.
  21085. *
  21086. * parameters = {
  21087. *
  21088. * curveSegments: <int>, // number of points on the curves
  21089. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  21090. * depth: <float>, // Depth to extrude the shape
  21091. *
  21092. * bevelEnabled: <bool>, // turn on bevel
  21093. * bevelThickness: <float>, // how deep into the original shape bevel goes
  21094. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  21095. * bevelOffset: <float>, // how far from shape outline does bevel start
  21096. * bevelSegments: <int>, // number of bevel layers
  21097. *
  21098. * extrudePath: <THREE.Curve> // curve to extrude shape along
  21099. *
  21100. * UVGenerator: <Object> // object that provides UV generator functions
  21101. *
  21102. * }
  21103. */
  21104. class ExtrudeGeometry extends BufferGeometry {
  21105. 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 = {} ) {
  21106. super();
  21107. this.type = 'ExtrudeGeometry';
  21108. this.parameters = {
  21109. shapes: shapes,
  21110. options: options
  21111. };
  21112. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  21113. const scope = this;
  21114. const verticesArray = [];
  21115. const uvArray = [];
  21116. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21117. const shape = shapes[ i ];
  21118. addShape( shape );
  21119. }
  21120. // build geometry
  21121. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  21122. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  21123. this.computeVertexNormals();
  21124. // functions
  21125. function addShape( shape ) {
  21126. const placeholder = [];
  21127. // options
  21128. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  21129. const steps = options.steps !== undefined ? options.steps : 1;
  21130. const depth = options.depth !== undefined ? options.depth : 1;
  21131. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  21132. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  21133. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  21134. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  21135. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  21136. const extrudePath = options.extrudePath;
  21137. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  21138. //
  21139. let extrudePts, extrudeByPath = false;
  21140. let splineTube, binormal, normal, position2;
  21141. if ( extrudePath ) {
  21142. extrudePts = extrudePath.getSpacedPoints( steps );
  21143. extrudeByPath = true;
  21144. bevelEnabled = false; // bevels not supported for path extrusion
  21145. // SETUP TNB variables
  21146. // TODO1 - have a .isClosed in spline?
  21147. splineTube = extrudePath.computeFrenetFrames( steps, false );
  21148. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  21149. binormal = new Vector3();
  21150. normal = new Vector3();
  21151. position2 = new Vector3();
  21152. }
  21153. // Safeguards if bevels are not enabled
  21154. if ( ! bevelEnabled ) {
  21155. bevelSegments = 0;
  21156. bevelThickness = 0;
  21157. bevelSize = 0;
  21158. bevelOffset = 0;
  21159. }
  21160. // Variables initialization
  21161. const shapePoints = shape.extractPoints( curveSegments );
  21162. let vertices = shapePoints.shape;
  21163. const holes = shapePoints.holes;
  21164. const reverse = ! ShapeUtils.isClockWise( vertices );
  21165. if ( reverse ) {
  21166. vertices = vertices.reverse();
  21167. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  21168. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21169. const ahole = holes[ h ];
  21170. if ( ShapeUtils.isClockWise( ahole ) ) {
  21171. holes[ h ] = ahole.reverse();
  21172. }
  21173. }
  21174. }
  21175. const faces = ShapeUtils.triangulateShape( vertices, holes );
  21176. /* Vertices */
  21177. const contour = vertices; // vertices has all points but contour has only points of circumference
  21178. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21179. const ahole = holes[ h ];
  21180. vertices = vertices.concat( ahole );
  21181. }
  21182. function scalePt2( pt, vec, size ) {
  21183. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  21184. return pt.clone().addScaledVector( vec, size );
  21185. }
  21186. const vlen = vertices.length, flen = faces.length;
  21187. // Find directions for point movement
  21188. function getBevelVec( inPt, inPrev, inNext ) {
  21189. // computes for inPt the corresponding point inPt' on a new contour
  21190. // shifted by 1 unit (length of normalized vector) to the left
  21191. // if we walk along contour clockwise, this new contour is outside the old one
  21192. //
  21193. // inPt' is the intersection of the two lines parallel to the two
  21194. // adjacent edges of inPt at a distance of 1 unit on the left side.
  21195. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  21196. // good reading for geometry algorithms (here: line-line intersection)
  21197. // http://geomalgorithms.com/a05-_intersect-1.html
  21198. const v_prev_x = inPt.x - inPrev.x,
  21199. v_prev_y = inPt.y - inPrev.y;
  21200. const v_next_x = inNext.x - inPt.x,
  21201. v_next_y = inNext.y - inPt.y;
  21202. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  21203. // check for collinear edges
  21204. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21205. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  21206. // not collinear
  21207. // length of vectors for normalizing
  21208. const v_prev_len = Math.sqrt( v_prev_lensq );
  21209. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  21210. // shift adjacent points by unit vectors to the left
  21211. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  21212. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  21213. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  21214. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  21215. // scaling factor for v_prev to intersection point
  21216. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  21217. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  21218. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21219. // vector from inPt to intersection point
  21220. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  21221. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  21222. // Don't normalize!, otherwise sharp corners become ugly
  21223. // but prevent crazy spikes
  21224. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  21225. if ( v_trans_lensq <= 2 ) {
  21226. return new Vector2( v_trans_x, v_trans_y );
  21227. } else {
  21228. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  21229. }
  21230. } else {
  21231. // handle special case of collinear edges
  21232. let direction_eq = false; // assumes: opposite
  21233. if ( v_prev_x > Number.EPSILON ) {
  21234. if ( v_next_x > Number.EPSILON ) {
  21235. direction_eq = true;
  21236. }
  21237. } else {
  21238. if ( v_prev_x < - Number.EPSILON ) {
  21239. if ( v_next_x < - Number.EPSILON ) {
  21240. direction_eq = true;
  21241. }
  21242. } else {
  21243. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  21244. direction_eq = true;
  21245. }
  21246. }
  21247. }
  21248. if ( direction_eq ) {
  21249. // console.log("Warning: lines are a straight sequence");
  21250. v_trans_x = - v_prev_y;
  21251. v_trans_y = v_prev_x;
  21252. shrink_by = Math.sqrt( v_prev_lensq );
  21253. } else {
  21254. // console.log("Warning: lines are a straight spike");
  21255. v_trans_x = v_prev_x;
  21256. v_trans_y = v_prev_y;
  21257. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  21258. }
  21259. }
  21260. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  21261. }
  21262. const contourMovements = [];
  21263. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21264. if ( j === il ) j = 0;
  21265. if ( k === il ) k = 0;
  21266. // (j)---(i)---(k)
  21267. // console.log('i,j,k', i, j , k)
  21268. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  21269. }
  21270. const holesMovements = [];
  21271. let oneHoleMovements, verticesMovements = contourMovements.concat();
  21272. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21273. const ahole = holes[ h ];
  21274. oneHoleMovements = [];
  21275. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21276. if ( j === il ) j = 0;
  21277. if ( k === il ) k = 0;
  21278. // (j)---(i)---(k)
  21279. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  21280. }
  21281. holesMovements.push( oneHoleMovements );
  21282. verticesMovements = verticesMovements.concat( oneHoleMovements );
  21283. }
  21284. // Loop bevelSegments, 1 for the front, 1 for the back
  21285. for ( let b = 0; b < bevelSegments; b ++ ) {
  21286. //for ( b = bevelSegments; b > 0; b -- ) {
  21287. const t = b / bevelSegments;
  21288. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21289. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21290. // contract shape
  21291. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21292. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21293. v( vert.x, vert.y, - z );
  21294. }
  21295. // expand holes
  21296. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21297. const ahole = holes[ h ];
  21298. oneHoleMovements = holesMovements[ h ];
  21299. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21300. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21301. v( vert.x, vert.y, - z );
  21302. }
  21303. }
  21304. }
  21305. const bs = bevelSize + bevelOffset;
  21306. // Back facing vertices
  21307. for ( let i = 0; i < vlen; i ++ ) {
  21308. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21309. if ( ! extrudeByPath ) {
  21310. v( vert.x, vert.y, 0 );
  21311. } else {
  21312. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  21313. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  21314. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  21315. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  21316. v( position2.x, position2.y, position2.z );
  21317. }
  21318. }
  21319. // Add stepped vertices...
  21320. // Including front facing vertices
  21321. for ( let s = 1; s <= steps; s ++ ) {
  21322. for ( let i = 0; i < vlen; i ++ ) {
  21323. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21324. if ( ! extrudeByPath ) {
  21325. v( vert.x, vert.y, depth / steps * s );
  21326. } else {
  21327. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  21328. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  21329. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  21330. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  21331. v( position2.x, position2.y, position2.z );
  21332. }
  21333. }
  21334. }
  21335. // Add bevel segments planes
  21336. //for ( b = 1; b <= bevelSegments; b ++ ) {
  21337. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  21338. const t = b / bevelSegments;
  21339. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21340. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21341. // contract shape
  21342. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21343. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21344. v( vert.x, vert.y, depth + z );
  21345. }
  21346. // expand holes
  21347. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21348. const ahole = holes[ h ];
  21349. oneHoleMovements = holesMovements[ h ];
  21350. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21351. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21352. if ( ! extrudeByPath ) {
  21353. v( vert.x, vert.y, depth + z );
  21354. } else {
  21355. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  21356. }
  21357. }
  21358. }
  21359. }
  21360. /* Faces */
  21361. // Top and bottom faces
  21362. buildLidFaces();
  21363. // Sides faces
  21364. buildSideFaces();
  21365. ///// Internal functions
  21366. function buildLidFaces() {
  21367. const start = verticesArray.length / 3;
  21368. if ( bevelEnabled ) {
  21369. let layer = 0; // steps + 1
  21370. let offset = vlen * layer;
  21371. // Bottom faces
  21372. for ( let i = 0; i < flen; i ++ ) {
  21373. const face = faces[ i ];
  21374. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  21375. }
  21376. layer = steps + bevelSegments * 2;
  21377. offset = vlen * layer;
  21378. // Top faces
  21379. for ( let i = 0; i < flen; i ++ ) {
  21380. const face = faces[ i ];
  21381. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  21382. }
  21383. } else {
  21384. // Bottom faces
  21385. for ( let i = 0; i < flen; i ++ ) {
  21386. const face = faces[ i ];
  21387. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  21388. }
  21389. // Top faces
  21390. for ( let i = 0; i < flen; i ++ ) {
  21391. const face = faces[ i ];
  21392. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  21393. }
  21394. }
  21395. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  21396. }
  21397. // Create faces for the z-sides of the shape
  21398. function buildSideFaces() {
  21399. const start = verticesArray.length / 3;
  21400. let layeroffset = 0;
  21401. sidewalls( contour, layeroffset );
  21402. layeroffset += contour.length;
  21403. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21404. const ahole = holes[ h ];
  21405. sidewalls( ahole, layeroffset );
  21406. //, true
  21407. layeroffset += ahole.length;
  21408. }
  21409. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  21410. }
  21411. function sidewalls( contour, layeroffset ) {
  21412. let i = contour.length;
  21413. while ( -- i >= 0 ) {
  21414. const j = i;
  21415. let k = i - 1;
  21416. if ( k < 0 ) k = contour.length - 1;
  21417. //console.log('b', i,j, i-1, k,vertices.length);
  21418. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  21419. const slen1 = vlen * s;
  21420. const slen2 = vlen * ( s + 1 );
  21421. const a = layeroffset + j + slen1,
  21422. b = layeroffset + k + slen1,
  21423. c = layeroffset + k + slen2,
  21424. d = layeroffset + j + slen2;
  21425. f4( a, b, c, d );
  21426. }
  21427. }
  21428. }
  21429. function v( x, y, z ) {
  21430. placeholder.push( x );
  21431. placeholder.push( y );
  21432. placeholder.push( z );
  21433. }
  21434. function f3( a, b, c ) {
  21435. addVertex( a );
  21436. addVertex( b );
  21437. addVertex( c );
  21438. const nextIndex = verticesArray.length / 3;
  21439. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21440. addUV( uvs[ 0 ] );
  21441. addUV( uvs[ 1 ] );
  21442. addUV( uvs[ 2 ] );
  21443. }
  21444. function f4( a, b, c, d ) {
  21445. addVertex( a );
  21446. addVertex( b );
  21447. addVertex( d );
  21448. addVertex( b );
  21449. addVertex( c );
  21450. addVertex( d );
  21451. const nextIndex = verticesArray.length / 3;
  21452. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21453. addUV( uvs[ 0 ] );
  21454. addUV( uvs[ 1 ] );
  21455. addUV( uvs[ 3 ] );
  21456. addUV( uvs[ 1 ] );
  21457. addUV( uvs[ 2 ] );
  21458. addUV( uvs[ 3 ] );
  21459. }
  21460. function addVertex( index ) {
  21461. verticesArray.push( placeholder[ index * 3 + 0 ] );
  21462. verticesArray.push( placeholder[ index * 3 + 1 ] );
  21463. verticesArray.push( placeholder[ index * 3 + 2 ] );
  21464. }
  21465. function addUV( vector2 ) {
  21466. uvArray.push( vector2.x );
  21467. uvArray.push( vector2.y );
  21468. }
  21469. }
  21470. }
  21471. copy( source ) {
  21472. super.copy( source );
  21473. this.parameters = Object.assign( {}, source.parameters );
  21474. return this;
  21475. }
  21476. toJSON() {
  21477. const data = super.toJSON();
  21478. const shapes = this.parameters.shapes;
  21479. const options = this.parameters.options;
  21480. return toJSON$1( shapes, options, data );
  21481. }
  21482. static fromJSON( data, shapes ) {
  21483. const geometryShapes = [];
  21484. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21485. const shape = shapes[ data.shapes[ j ] ];
  21486. geometryShapes.push( shape );
  21487. }
  21488. const extrudePath = data.options.extrudePath;
  21489. if ( extrudePath !== undefined ) {
  21490. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  21491. }
  21492. return new ExtrudeGeometry( geometryShapes, data.options );
  21493. }
  21494. }
  21495. const WorldUVGenerator = {
  21496. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  21497. const a_x = vertices[ indexA * 3 ];
  21498. const a_y = vertices[ indexA * 3 + 1 ];
  21499. const b_x = vertices[ indexB * 3 ];
  21500. const b_y = vertices[ indexB * 3 + 1 ];
  21501. const c_x = vertices[ indexC * 3 ];
  21502. const c_y = vertices[ indexC * 3 + 1 ];
  21503. return [
  21504. new Vector2( a_x, a_y ),
  21505. new Vector2( b_x, b_y ),
  21506. new Vector2( c_x, c_y )
  21507. ];
  21508. },
  21509. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  21510. const a_x = vertices[ indexA * 3 ];
  21511. const a_y = vertices[ indexA * 3 + 1 ];
  21512. const a_z = vertices[ indexA * 3 + 2 ];
  21513. const b_x = vertices[ indexB * 3 ];
  21514. const b_y = vertices[ indexB * 3 + 1 ];
  21515. const b_z = vertices[ indexB * 3 + 2 ];
  21516. const c_x = vertices[ indexC * 3 ];
  21517. const c_y = vertices[ indexC * 3 + 1 ];
  21518. const c_z = vertices[ indexC * 3 + 2 ];
  21519. const d_x = vertices[ indexD * 3 ];
  21520. const d_y = vertices[ indexD * 3 + 1 ];
  21521. const d_z = vertices[ indexD * 3 + 2 ];
  21522. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  21523. return [
  21524. new Vector2( a_x, 1 - a_z ),
  21525. new Vector2( b_x, 1 - b_z ),
  21526. new Vector2( c_x, 1 - c_z ),
  21527. new Vector2( d_x, 1 - d_z )
  21528. ];
  21529. } else {
  21530. return [
  21531. new Vector2( a_y, 1 - a_z ),
  21532. new Vector2( b_y, 1 - b_z ),
  21533. new Vector2( c_y, 1 - c_z ),
  21534. new Vector2( d_y, 1 - d_z )
  21535. ];
  21536. }
  21537. }
  21538. };
  21539. function toJSON$1( shapes, options, data ) {
  21540. data.shapes = [];
  21541. if ( Array.isArray( shapes ) ) {
  21542. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21543. const shape = shapes[ i ];
  21544. data.shapes.push( shape.uuid );
  21545. }
  21546. } else {
  21547. data.shapes.push( shapes.uuid );
  21548. }
  21549. data.options = Object.assign( {}, options );
  21550. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  21551. return data;
  21552. }
  21553. class IcosahedronGeometry extends PolyhedronGeometry {
  21554. constructor( radius = 1, detail = 0 ) {
  21555. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  21556. const vertices = [
  21557. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  21558. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  21559. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  21560. ];
  21561. const indices = [
  21562. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  21563. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  21564. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  21565. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  21566. ];
  21567. super( vertices, indices, radius, detail );
  21568. this.type = 'IcosahedronGeometry';
  21569. this.parameters = {
  21570. radius: radius,
  21571. detail: detail
  21572. };
  21573. }
  21574. static fromJSON( data ) {
  21575. return new IcosahedronGeometry( data.radius, data.detail );
  21576. }
  21577. }
  21578. class OctahedronGeometry extends PolyhedronGeometry {
  21579. constructor( radius = 1, detail = 0 ) {
  21580. const vertices = [
  21581. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  21582. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  21583. ];
  21584. const indices = [
  21585. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  21586. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  21587. 1, 3, 4, 1, 4, 2
  21588. ];
  21589. super( vertices, indices, radius, detail );
  21590. this.type = 'OctahedronGeometry';
  21591. this.parameters = {
  21592. radius: radius,
  21593. detail: detail
  21594. };
  21595. }
  21596. static fromJSON( data ) {
  21597. return new OctahedronGeometry( data.radius, data.detail );
  21598. }
  21599. }
  21600. class RingGeometry extends BufferGeometry {
  21601. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21602. super();
  21603. this.type = 'RingGeometry';
  21604. this.parameters = {
  21605. innerRadius: innerRadius,
  21606. outerRadius: outerRadius,
  21607. thetaSegments: thetaSegments,
  21608. phiSegments: phiSegments,
  21609. thetaStart: thetaStart,
  21610. thetaLength: thetaLength
  21611. };
  21612. thetaSegments = Math.max( 3, thetaSegments );
  21613. phiSegments = Math.max( 1, phiSegments );
  21614. // buffers
  21615. const indices = [];
  21616. const vertices = [];
  21617. const normals = [];
  21618. const uvs = [];
  21619. // some helper variables
  21620. let radius = innerRadius;
  21621. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  21622. const vertex = new Vector3();
  21623. const uv = new Vector2();
  21624. // generate vertices, normals and uvs
  21625. for ( let j = 0; j <= phiSegments; j ++ ) {
  21626. for ( let i = 0; i <= thetaSegments; i ++ ) {
  21627. // values are generate from the inside of the ring to the outside
  21628. const segment = thetaStart + i / thetaSegments * thetaLength;
  21629. // vertex
  21630. vertex.x = radius * Math.cos( segment );
  21631. vertex.y = radius * Math.sin( segment );
  21632. vertices.push( vertex.x, vertex.y, vertex.z );
  21633. // normal
  21634. normals.push( 0, 0, 1 );
  21635. // uv
  21636. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  21637. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  21638. uvs.push( uv.x, uv.y );
  21639. }
  21640. // increase the radius for next row of vertices
  21641. radius += radiusStep;
  21642. }
  21643. // indices
  21644. for ( let j = 0; j < phiSegments; j ++ ) {
  21645. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  21646. for ( let i = 0; i < thetaSegments; i ++ ) {
  21647. const segment = i + thetaSegmentLevel;
  21648. const a = segment;
  21649. const b = segment + thetaSegments + 1;
  21650. const c = segment + thetaSegments + 2;
  21651. const d = segment + 1;
  21652. // faces
  21653. indices.push( a, b, d );
  21654. indices.push( b, c, d );
  21655. }
  21656. }
  21657. // build geometry
  21658. this.setIndex( indices );
  21659. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21660. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21661. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21662. }
  21663. copy( source ) {
  21664. super.copy( source );
  21665. this.parameters = Object.assign( {}, source.parameters );
  21666. return this;
  21667. }
  21668. static fromJSON( data ) {
  21669. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  21670. }
  21671. }
  21672. class ShapeGeometry extends BufferGeometry {
  21673. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  21674. super();
  21675. this.type = 'ShapeGeometry';
  21676. this.parameters = {
  21677. shapes: shapes,
  21678. curveSegments: curveSegments
  21679. };
  21680. // buffers
  21681. const indices = [];
  21682. const vertices = [];
  21683. const normals = [];
  21684. const uvs = [];
  21685. // helper variables
  21686. let groupStart = 0;
  21687. let groupCount = 0;
  21688. // allow single and array values for "shapes" parameter
  21689. if ( Array.isArray( shapes ) === false ) {
  21690. addShape( shapes );
  21691. } else {
  21692. for ( let i = 0; i < shapes.length; i ++ ) {
  21693. addShape( shapes[ i ] );
  21694. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  21695. groupStart += groupCount;
  21696. groupCount = 0;
  21697. }
  21698. }
  21699. // build geometry
  21700. this.setIndex( indices );
  21701. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21702. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21703. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21704. // helper functions
  21705. function addShape( shape ) {
  21706. const indexOffset = vertices.length / 3;
  21707. const points = shape.extractPoints( curveSegments );
  21708. let shapeVertices = points.shape;
  21709. const shapeHoles = points.holes;
  21710. // check direction of vertices
  21711. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  21712. shapeVertices = shapeVertices.reverse();
  21713. }
  21714. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21715. const shapeHole = shapeHoles[ i ];
  21716. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  21717. shapeHoles[ i ] = shapeHole.reverse();
  21718. }
  21719. }
  21720. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  21721. // join vertices of inner and outer paths to a single array
  21722. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21723. const shapeHole = shapeHoles[ i ];
  21724. shapeVertices = shapeVertices.concat( shapeHole );
  21725. }
  21726. // vertices, normals, uvs
  21727. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  21728. const vertex = shapeVertices[ i ];
  21729. vertices.push( vertex.x, vertex.y, 0 );
  21730. normals.push( 0, 0, 1 );
  21731. uvs.push( vertex.x, vertex.y ); // world uvs
  21732. }
  21733. // indices
  21734. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  21735. const face = faces[ i ];
  21736. const a = face[ 0 ] + indexOffset;
  21737. const b = face[ 1 ] + indexOffset;
  21738. const c = face[ 2 ] + indexOffset;
  21739. indices.push( a, b, c );
  21740. groupCount += 3;
  21741. }
  21742. }
  21743. }
  21744. copy( source ) {
  21745. super.copy( source );
  21746. this.parameters = Object.assign( {}, source.parameters );
  21747. return this;
  21748. }
  21749. toJSON() {
  21750. const data = super.toJSON();
  21751. const shapes = this.parameters.shapes;
  21752. return toJSON( shapes, data );
  21753. }
  21754. static fromJSON( data, shapes ) {
  21755. const geometryShapes = [];
  21756. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21757. const shape = shapes[ data.shapes[ j ] ];
  21758. geometryShapes.push( shape );
  21759. }
  21760. return new ShapeGeometry( geometryShapes, data.curveSegments );
  21761. }
  21762. }
  21763. function toJSON( shapes, data ) {
  21764. data.shapes = [];
  21765. if ( Array.isArray( shapes ) ) {
  21766. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21767. const shape = shapes[ i ];
  21768. data.shapes.push( shape.uuid );
  21769. }
  21770. } else {
  21771. data.shapes.push( shapes.uuid );
  21772. }
  21773. return data;
  21774. }
  21775. class SphereGeometry extends BufferGeometry {
  21776. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  21777. super();
  21778. this.type = 'SphereGeometry';
  21779. this.parameters = {
  21780. radius: radius,
  21781. widthSegments: widthSegments,
  21782. heightSegments: heightSegments,
  21783. phiStart: phiStart,
  21784. phiLength: phiLength,
  21785. thetaStart: thetaStart,
  21786. thetaLength: thetaLength
  21787. };
  21788. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  21789. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  21790. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  21791. let index = 0;
  21792. const grid = [];
  21793. const vertex = new Vector3();
  21794. const normal = new Vector3();
  21795. // buffers
  21796. const indices = [];
  21797. const vertices = [];
  21798. const normals = [];
  21799. const uvs = [];
  21800. // generate vertices, normals and uvs
  21801. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  21802. const verticesRow = [];
  21803. const v = iy / heightSegments;
  21804. // special case for the poles
  21805. let uOffset = 0;
  21806. if ( iy == 0 && thetaStart == 0 ) {
  21807. uOffset = 0.5 / widthSegments;
  21808. } else if ( iy == heightSegments && thetaEnd == Math.PI ) {
  21809. uOffset = - 0.5 / widthSegments;
  21810. }
  21811. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  21812. const u = ix / widthSegments;
  21813. // vertex
  21814. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21815. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  21816. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21817. vertices.push( vertex.x, vertex.y, vertex.z );
  21818. // normal
  21819. normal.copy( vertex ).normalize();
  21820. normals.push( normal.x, normal.y, normal.z );
  21821. // uv
  21822. uvs.push( u + uOffset, 1 - v );
  21823. verticesRow.push( index ++ );
  21824. }
  21825. grid.push( verticesRow );
  21826. }
  21827. // indices
  21828. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  21829. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  21830. const a = grid[ iy ][ ix + 1 ];
  21831. const b = grid[ iy ][ ix ];
  21832. const c = grid[ iy + 1 ][ ix ];
  21833. const d = grid[ iy + 1 ][ ix + 1 ];
  21834. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  21835. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  21836. }
  21837. }
  21838. // build geometry
  21839. this.setIndex( indices );
  21840. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21841. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21842. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21843. }
  21844. copy( source ) {
  21845. super.copy( source );
  21846. this.parameters = Object.assign( {}, source.parameters );
  21847. return this;
  21848. }
  21849. static fromJSON( data ) {
  21850. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  21851. }
  21852. }
  21853. class TetrahedronGeometry extends PolyhedronGeometry {
  21854. constructor( radius = 1, detail = 0 ) {
  21855. const vertices = [
  21856. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  21857. ];
  21858. const indices = [
  21859. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  21860. ];
  21861. super( vertices, indices, radius, detail );
  21862. this.type = 'TetrahedronGeometry';
  21863. this.parameters = {
  21864. radius: radius,
  21865. detail: detail
  21866. };
  21867. }
  21868. static fromJSON( data ) {
  21869. return new TetrahedronGeometry( data.radius, data.detail );
  21870. }
  21871. }
  21872. class TorusGeometry extends BufferGeometry {
  21873. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  21874. super();
  21875. this.type = 'TorusGeometry';
  21876. this.parameters = {
  21877. radius: radius,
  21878. tube: tube,
  21879. radialSegments: radialSegments,
  21880. tubularSegments: tubularSegments,
  21881. arc: arc
  21882. };
  21883. radialSegments = Math.floor( radialSegments );
  21884. tubularSegments = Math.floor( tubularSegments );
  21885. // buffers
  21886. const indices = [];
  21887. const vertices = [];
  21888. const normals = [];
  21889. const uvs = [];
  21890. // helper variables
  21891. const center = new Vector3();
  21892. const vertex = new Vector3();
  21893. const normal = new Vector3();
  21894. // generate vertices, normals and uvs
  21895. for ( let j = 0; j <= radialSegments; j ++ ) {
  21896. for ( let i = 0; i <= tubularSegments; i ++ ) {
  21897. const u = i / tubularSegments * arc;
  21898. const v = j / radialSegments * Math.PI * 2;
  21899. // vertex
  21900. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  21901. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  21902. vertex.z = tube * Math.sin( v );
  21903. vertices.push( vertex.x, vertex.y, vertex.z );
  21904. // normal
  21905. center.x = radius * Math.cos( u );
  21906. center.y = radius * Math.sin( u );
  21907. normal.subVectors( vertex, center ).normalize();
  21908. normals.push( normal.x, normal.y, normal.z );
  21909. // uv
  21910. uvs.push( i / tubularSegments );
  21911. uvs.push( j / radialSegments );
  21912. }
  21913. }
  21914. // generate indices
  21915. for ( let j = 1; j <= radialSegments; j ++ ) {
  21916. for ( let i = 1; i <= tubularSegments; i ++ ) {
  21917. // indices
  21918. const a = ( tubularSegments + 1 ) * j + i - 1;
  21919. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  21920. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  21921. const d = ( tubularSegments + 1 ) * j + i;
  21922. // faces
  21923. indices.push( a, b, d );
  21924. indices.push( b, c, d );
  21925. }
  21926. }
  21927. // build geometry
  21928. this.setIndex( indices );
  21929. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21930. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21931. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21932. }
  21933. copy( source ) {
  21934. super.copy( source );
  21935. this.parameters = Object.assign( {}, source.parameters );
  21936. return this;
  21937. }
  21938. static fromJSON( data ) {
  21939. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  21940. }
  21941. }
  21942. class TorusKnotGeometry extends BufferGeometry {
  21943. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  21944. super();
  21945. this.type = 'TorusKnotGeometry';
  21946. this.parameters = {
  21947. radius: radius,
  21948. tube: tube,
  21949. tubularSegments: tubularSegments,
  21950. radialSegments: radialSegments,
  21951. p: p,
  21952. q: q
  21953. };
  21954. tubularSegments = Math.floor( tubularSegments );
  21955. radialSegments = Math.floor( radialSegments );
  21956. // buffers
  21957. const indices = [];
  21958. const vertices = [];
  21959. const normals = [];
  21960. const uvs = [];
  21961. // helper variables
  21962. const vertex = new Vector3();
  21963. const normal = new Vector3();
  21964. const P1 = new Vector3();
  21965. const P2 = new Vector3();
  21966. const B = new Vector3();
  21967. const T = new Vector3();
  21968. const N = new Vector3();
  21969. // generate vertices, normals and uvs
  21970. for ( let i = 0; i <= tubularSegments; ++ i ) {
  21971. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  21972. const u = i / tubularSegments * p * Math.PI * 2;
  21973. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  21974. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  21975. calculatePositionOnCurve( u, p, q, radius, P1 );
  21976. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  21977. // calculate orthonormal basis
  21978. T.subVectors( P2, P1 );
  21979. N.addVectors( P2, P1 );
  21980. B.crossVectors( T, N );
  21981. N.crossVectors( B, T );
  21982. // normalize B, N. T can be ignored, we don't use it
  21983. B.normalize();
  21984. N.normalize();
  21985. for ( let j = 0; j <= radialSegments; ++ j ) {
  21986. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  21987. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  21988. const v = j / radialSegments * Math.PI * 2;
  21989. const cx = - tube * Math.cos( v );
  21990. const cy = tube * Math.sin( v );
  21991. // now calculate the final vertex position.
  21992. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  21993. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  21994. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  21995. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  21996. vertices.push( vertex.x, vertex.y, vertex.z );
  21997. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  21998. normal.subVectors( vertex, P1 ).normalize();
  21999. normals.push( normal.x, normal.y, normal.z );
  22000. // uv
  22001. uvs.push( i / tubularSegments );
  22002. uvs.push( j / radialSegments );
  22003. }
  22004. }
  22005. // generate indices
  22006. for ( let j = 1; j <= tubularSegments; j ++ ) {
  22007. for ( let i = 1; i <= radialSegments; i ++ ) {
  22008. // indices
  22009. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  22010. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  22011. const c = ( radialSegments + 1 ) * j + i;
  22012. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  22013. // faces
  22014. indices.push( a, b, d );
  22015. indices.push( b, c, d );
  22016. }
  22017. }
  22018. // build geometry
  22019. this.setIndex( indices );
  22020. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22021. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22022. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22023. // this function calculates the current position on the torus curve
  22024. function calculatePositionOnCurve( u, p, q, radius, position ) {
  22025. const cu = Math.cos( u );
  22026. const su = Math.sin( u );
  22027. const quOverP = q / p * u;
  22028. const cs = Math.cos( quOverP );
  22029. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  22030. position.y = radius * ( 2 + cs ) * su * 0.5;
  22031. position.z = radius * Math.sin( quOverP ) * 0.5;
  22032. }
  22033. }
  22034. copy( source ) {
  22035. super.copy( source );
  22036. this.parameters = Object.assign( {}, source.parameters );
  22037. return this;
  22038. }
  22039. static fromJSON( data ) {
  22040. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  22041. }
  22042. }
  22043. class TubeGeometry extends BufferGeometry {
  22044. 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 ) {
  22045. super();
  22046. this.type = 'TubeGeometry';
  22047. this.parameters = {
  22048. path: path,
  22049. tubularSegments: tubularSegments,
  22050. radius: radius,
  22051. radialSegments: radialSegments,
  22052. closed: closed
  22053. };
  22054. const frames = path.computeFrenetFrames( tubularSegments, closed );
  22055. // expose internals
  22056. this.tangents = frames.tangents;
  22057. this.normals = frames.normals;
  22058. this.binormals = frames.binormals;
  22059. // helper variables
  22060. const vertex = new Vector3();
  22061. const normal = new Vector3();
  22062. const uv = new Vector2();
  22063. let P = new Vector3();
  22064. // buffer
  22065. const vertices = [];
  22066. const normals = [];
  22067. const uvs = [];
  22068. const indices = [];
  22069. // create buffer data
  22070. generateBufferData();
  22071. // build geometry
  22072. this.setIndex( indices );
  22073. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22074. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22075. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22076. // functions
  22077. function generateBufferData() {
  22078. for ( let i = 0; i < tubularSegments; i ++ ) {
  22079. generateSegment( i );
  22080. }
  22081. // if the geometry is not closed, generate the last row of vertices and normals
  22082. // at the regular position on the given path
  22083. //
  22084. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  22085. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  22086. // uvs are generated in a separate function.
  22087. // this makes it easy compute correct values for closed geometries
  22088. generateUVs();
  22089. // finally create faces
  22090. generateIndices();
  22091. }
  22092. function generateSegment( i ) {
  22093. // we use getPointAt to sample evenly distributed points from the given path
  22094. P = path.getPointAt( i / tubularSegments, P );
  22095. // retrieve corresponding normal and binormal
  22096. const N = frames.normals[ i ];
  22097. const B = frames.binormals[ i ];
  22098. // generate normals and vertices for the current segment
  22099. for ( let j = 0; j <= radialSegments; j ++ ) {
  22100. const v = j / radialSegments * Math.PI * 2;
  22101. const sin = Math.sin( v );
  22102. const cos = - Math.cos( v );
  22103. // normal
  22104. normal.x = ( cos * N.x + sin * B.x );
  22105. normal.y = ( cos * N.y + sin * B.y );
  22106. normal.z = ( cos * N.z + sin * B.z );
  22107. normal.normalize();
  22108. normals.push( normal.x, normal.y, normal.z );
  22109. // vertex
  22110. vertex.x = P.x + radius * normal.x;
  22111. vertex.y = P.y + radius * normal.y;
  22112. vertex.z = P.z + radius * normal.z;
  22113. vertices.push( vertex.x, vertex.y, vertex.z );
  22114. }
  22115. }
  22116. function generateIndices() {
  22117. for ( let j = 1; j <= tubularSegments; j ++ ) {
  22118. for ( let i = 1; i <= radialSegments; i ++ ) {
  22119. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  22120. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  22121. const c = ( radialSegments + 1 ) * j + i;
  22122. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  22123. // faces
  22124. indices.push( a, b, d );
  22125. indices.push( b, c, d );
  22126. }
  22127. }
  22128. }
  22129. function generateUVs() {
  22130. for ( let i = 0; i <= tubularSegments; i ++ ) {
  22131. for ( let j = 0; j <= radialSegments; j ++ ) {
  22132. uv.x = i / tubularSegments;
  22133. uv.y = j / radialSegments;
  22134. uvs.push( uv.x, uv.y );
  22135. }
  22136. }
  22137. }
  22138. }
  22139. copy( source ) {
  22140. super.copy( source );
  22141. this.parameters = Object.assign( {}, source.parameters );
  22142. return this;
  22143. }
  22144. toJSON() {
  22145. const data = super.toJSON();
  22146. data.path = this.parameters.path.toJSON();
  22147. return data;
  22148. }
  22149. static fromJSON( data ) {
  22150. // This only works for built-in curves (e.g. CatmullRomCurve3).
  22151. // User defined curves or instances of CurvePath will not be deserialized.
  22152. return new TubeGeometry(
  22153. new Curves[ data.path.type ]().fromJSON( data.path ),
  22154. data.tubularSegments,
  22155. data.radius,
  22156. data.radialSegments,
  22157. data.closed
  22158. );
  22159. }
  22160. }
  22161. class WireframeGeometry extends BufferGeometry {
  22162. constructor( geometry = null ) {
  22163. super();
  22164. this.type = 'WireframeGeometry';
  22165. this.parameters = {
  22166. geometry: geometry
  22167. };
  22168. if ( geometry !== null ) {
  22169. // buffer
  22170. const vertices = [];
  22171. const edges = new Set();
  22172. // helper variables
  22173. const start = new Vector3();
  22174. const end = new Vector3();
  22175. if ( geometry.index !== null ) {
  22176. // indexed BufferGeometry
  22177. const position = geometry.attributes.position;
  22178. const indices = geometry.index;
  22179. let groups = geometry.groups;
  22180. if ( groups.length === 0 ) {
  22181. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  22182. }
  22183. // create a data structure that contains all edges without duplicates
  22184. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  22185. const group = groups[ o ];
  22186. const groupStart = group.start;
  22187. const groupCount = group.count;
  22188. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  22189. for ( let j = 0; j < 3; j ++ ) {
  22190. const index1 = indices.getX( i + j );
  22191. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  22192. start.fromBufferAttribute( position, index1 );
  22193. end.fromBufferAttribute( position, index2 );
  22194. if ( isUniqueEdge( start, end, edges ) === true ) {
  22195. vertices.push( start.x, start.y, start.z );
  22196. vertices.push( end.x, end.y, end.z );
  22197. }
  22198. }
  22199. }
  22200. }
  22201. } else {
  22202. // non-indexed BufferGeometry
  22203. const position = geometry.attributes.position;
  22204. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  22205. for ( let j = 0; j < 3; j ++ ) {
  22206. // three edges per triangle, an edge is represented as (index1, index2)
  22207. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  22208. const index1 = 3 * i + j;
  22209. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  22210. start.fromBufferAttribute( position, index1 );
  22211. end.fromBufferAttribute( position, index2 );
  22212. if ( isUniqueEdge( start, end, edges ) === true ) {
  22213. vertices.push( start.x, start.y, start.z );
  22214. vertices.push( end.x, end.y, end.z );
  22215. }
  22216. }
  22217. }
  22218. }
  22219. // build geometry
  22220. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22221. }
  22222. }
  22223. copy( source ) {
  22224. super.copy( source );
  22225. this.parameters = Object.assign( {}, source.parameters );
  22226. return this;
  22227. }
  22228. }
  22229. function isUniqueEdge( start, end, edges ) {
  22230. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  22231. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  22232. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  22233. return false;
  22234. } else {
  22235. edges.add( hash1 );
  22236. edges.add( hash2 );
  22237. return true;
  22238. }
  22239. }
  22240. var Geometries = /*#__PURE__*/Object.freeze({
  22241. __proto__: null,
  22242. BoxGeometry: BoxGeometry,
  22243. CapsuleGeometry: CapsuleGeometry,
  22244. CircleGeometry: CircleGeometry,
  22245. ConeGeometry: ConeGeometry,
  22246. CylinderGeometry: CylinderGeometry,
  22247. DodecahedronGeometry: DodecahedronGeometry,
  22248. EdgesGeometry: EdgesGeometry,
  22249. ExtrudeGeometry: ExtrudeGeometry,
  22250. IcosahedronGeometry: IcosahedronGeometry,
  22251. LatheGeometry: LatheGeometry,
  22252. OctahedronGeometry: OctahedronGeometry,
  22253. PlaneGeometry: PlaneGeometry,
  22254. PolyhedronGeometry: PolyhedronGeometry,
  22255. RingGeometry: RingGeometry,
  22256. ShapeGeometry: ShapeGeometry,
  22257. SphereGeometry: SphereGeometry,
  22258. TetrahedronGeometry: TetrahedronGeometry,
  22259. TorusGeometry: TorusGeometry,
  22260. TorusKnotGeometry: TorusKnotGeometry,
  22261. TubeGeometry: TubeGeometry,
  22262. WireframeGeometry: WireframeGeometry
  22263. });
  22264. class ShadowMaterial extends Material {
  22265. constructor( parameters ) {
  22266. super();
  22267. this.isShadowMaterial = true;
  22268. this.type = 'ShadowMaterial';
  22269. this.color = new Color( 0x000000 );
  22270. this.transparent = true;
  22271. this.fog = true;
  22272. this.setValues( parameters );
  22273. }
  22274. copy( source ) {
  22275. super.copy( source );
  22276. this.color.copy( source.color );
  22277. this.fog = source.fog;
  22278. return this;
  22279. }
  22280. }
  22281. class RawShaderMaterial extends ShaderMaterial {
  22282. constructor( parameters ) {
  22283. super( parameters );
  22284. this.isRawShaderMaterial = true;
  22285. this.type = 'RawShaderMaterial';
  22286. }
  22287. }
  22288. class MeshStandardMaterial extends Material {
  22289. constructor( parameters ) {
  22290. super();
  22291. this.isMeshStandardMaterial = true;
  22292. this.defines = { 'STANDARD': '' };
  22293. this.type = 'MeshStandardMaterial';
  22294. this.color = new Color( 0xffffff ); // diffuse
  22295. this.roughness = 1.0;
  22296. this.metalness = 0.0;
  22297. this.map = null;
  22298. this.lightMap = null;
  22299. this.lightMapIntensity = 1.0;
  22300. this.aoMap = null;
  22301. this.aoMapIntensity = 1.0;
  22302. this.emissive = new Color( 0x000000 );
  22303. this.emissiveIntensity = 1.0;
  22304. this.emissiveMap = null;
  22305. this.bumpMap = null;
  22306. this.bumpScale = 1;
  22307. this.normalMap = null;
  22308. this.normalMapType = TangentSpaceNormalMap;
  22309. this.normalScale = new Vector2( 1, 1 );
  22310. this.displacementMap = null;
  22311. this.displacementScale = 1;
  22312. this.displacementBias = 0;
  22313. this.roughnessMap = null;
  22314. this.metalnessMap = null;
  22315. this.alphaMap = null;
  22316. this.envMap = null;
  22317. this.envMapIntensity = 1.0;
  22318. this.wireframe = false;
  22319. this.wireframeLinewidth = 1;
  22320. this.wireframeLinecap = 'round';
  22321. this.wireframeLinejoin = 'round';
  22322. this.flatShading = false;
  22323. this.fog = true;
  22324. this.setValues( parameters );
  22325. }
  22326. copy( source ) {
  22327. super.copy( source );
  22328. this.defines = { 'STANDARD': '' };
  22329. this.color.copy( source.color );
  22330. this.roughness = source.roughness;
  22331. this.metalness = source.metalness;
  22332. this.map = source.map;
  22333. this.lightMap = source.lightMap;
  22334. this.lightMapIntensity = source.lightMapIntensity;
  22335. this.aoMap = source.aoMap;
  22336. this.aoMapIntensity = source.aoMapIntensity;
  22337. this.emissive.copy( source.emissive );
  22338. this.emissiveMap = source.emissiveMap;
  22339. this.emissiveIntensity = source.emissiveIntensity;
  22340. this.bumpMap = source.bumpMap;
  22341. this.bumpScale = source.bumpScale;
  22342. this.normalMap = source.normalMap;
  22343. this.normalMapType = source.normalMapType;
  22344. this.normalScale.copy( source.normalScale );
  22345. this.displacementMap = source.displacementMap;
  22346. this.displacementScale = source.displacementScale;
  22347. this.displacementBias = source.displacementBias;
  22348. this.roughnessMap = source.roughnessMap;
  22349. this.metalnessMap = source.metalnessMap;
  22350. this.alphaMap = source.alphaMap;
  22351. this.envMap = source.envMap;
  22352. this.envMapIntensity = source.envMapIntensity;
  22353. this.wireframe = source.wireframe;
  22354. this.wireframeLinewidth = source.wireframeLinewidth;
  22355. this.wireframeLinecap = source.wireframeLinecap;
  22356. this.wireframeLinejoin = source.wireframeLinejoin;
  22357. this.flatShading = source.flatShading;
  22358. this.fog = source.fog;
  22359. return this;
  22360. }
  22361. }
  22362. class MeshPhysicalMaterial extends MeshStandardMaterial {
  22363. constructor( parameters ) {
  22364. super();
  22365. this.isMeshPhysicalMaterial = true;
  22366. this.defines = {
  22367. 'STANDARD': '',
  22368. 'PHYSICAL': ''
  22369. };
  22370. this.type = 'MeshPhysicalMaterial';
  22371. this.clearcoatMap = null;
  22372. this.clearcoatRoughness = 0.0;
  22373. this.clearcoatRoughnessMap = null;
  22374. this.clearcoatNormalScale = new Vector2( 1, 1 );
  22375. this.clearcoatNormalMap = null;
  22376. this.ior = 1.5;
  22377. Object.defineProperty( this, 'reflectivity', {
  22378. get: function () {
  22379. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  22380. },
  22381. set: function ( reflectivity ) {
  22382. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  22383. }
  22384. } );
  22385. this.iridescenceMap = null;
  22386. this.iridescenceIOR = 1.3;
  22387. this.iridescenceThicknessRange = [ 100, 400 ];
  22388. this.iridescenceThicknessMap = null;
  22389. this.sheenColor = new Color( 0x000000 );
  22390. this.sheenColorMap = null;
  22391. this.sheenRoughness = 1.0;
  22392. this.sheenRoughnessMap = null;
  22393. this.transmissionMap = null;
  22394. this.thickness = 0;
  22395. this.thicknessMap = null;
  22396. this.attenuationDistance = Infinity;
  22397. this.attenuationColor = new Color( 1, 1, 1 );
  22398. this.specularIntensity = 1.0;
  22399. this.specularIntensityMap = null;
  22400. this.specularColor = new Color( 1, 1, 1 );
  22401. this.specularColorMap = null;
  22402. this._sheen = 0.0;
  22403. this._clearcoat = 0;
  22404. this._iridescence = 0;
  22405. this._transmission = 0;
  22406. this.setValues( parameters );
  22407. }
  22408. get sheen() {
  22409. return this._sheen;
  22410. }
  22411. set sheen( value ) {
  22412. if ( this._sheen > 0 !== value > 0 ) {
  22413. this.version ++;
  22414. }
  22415. this._sheen = value;
  22416. }
  22417. get clearcoat() {
  22418. return this._clearcoat;
  22419. }
  22420. set clearcoat( value ) {
  22421. if ( this._clearcoat > 0 !== value > 0 ) {
  22422. this.version ++;
  22423. }
  22424. this._clearcoat = value;
  22425. }
  22426. get iridescence() {
  22427. return this._iridescence;
  22428. }
  22429. set iridescence( value ) {
  22430. if ( this._iridescence > 0 !== value > 0 ) {
  22431. this.version ++;
  22432. }
  22433. this._iridescence = value;
  22434. }
  22435. get transmission() {
  22436. return this._transmission;
  22437. }
  22438. set transmission( value ) {
  22439. if ( this._transmission > 0 !== value > 0 ) {
  22440. this.version ++;
  22441. }
  22442. this._transmission = value;
  22443. }
  22444. copy( source ) {
  22445. super.copy( source );
  22446. this.defines = {
  22447. 'STANDARD': '',
  22448. 'PHYSICAL': ''
  22449. };
  22450. this.clearcoat = source.clearcoat;
  22451. this.clearcoatMap = source.clearcoatMap;
  22452. this.clearcoatRoughness = source.clearcoatRoughness;
  22453. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  22454. this.clearcoatNormalMap = source.clearcoatNormalMap;
  22455. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  22456. this.ior = source.ior;
  22457. this.iridescence = source.iridescence;
  22458. this.iridescenceMap = source.iridescenceMap;
  22459. this.iridescenceIOR = source.iridescenceIOR;
  22460. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  22461. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  22462. this.sheen = source.sheen;
  22463. this.sheenColor.copy( source.sheenColor );
  22464. this.sheenColorMap = source.sheenColorMap;
  22465. this.sheenRoughness = source.sheenRoughness;
  22466. this.sheenRoughnessMap = source.sheenRoughnessMap;
  22467. this.transmission = source.transmission;
  22468. this.transmissionMap = source.transmissionMap;
  22469. this.thickness = source.thickness;
  22470. this.thicknessMap = source.thicknessMap;
  22471. this.attenuationDistance = source.attenuationDistance;
  22472. this.attenuationColor.copy( source.attenuationColor );
  22473. this.specularIntensity = source.specularIntensity;
  22474. this.specularIntensityMap = source.specularIntensityMap;
  22475. this.specularColor.copy( source.specularColor );
  22476. this.specularColorMap = source.specularColorMap;
  22477. return this;
  22478. }
  22479. }
  22480. class MeshPhongMaterial extends Material {
  22481. constructor( parameters ) {
  22482. super();
  22483. this.isMeshPhongMaterial = true;
  22484. this.type = 'MeshPhongMaterial';
  22485. this.color = new Color( 0xffffff ); // diffuse
  22486. this.specular = new Color( 0x111111 );
  22487. this.shininess = 30;
  22488. this.map = null;
  22489. this.lightMap = null;
  22490. this.lightMapIntensity = 1.0;
  22491. this.aoMap = null;
  22492. this.aoMapIntensity = 1.0;
  22493. this.emissive = new Color( 0x000000 );
  22494. this.emissiveIntensity = 1.0;
  22495. this.emissiveMap = null;
  22496. this.bumpMap = null;
  22497. this.bumpScale = 1;
  22498. this.normalMap = null;
  22499. this.normalMapType = TangentSpaceNormalMap;
  22500. this.normalScale = new Vector2( 1, 1 );
  22501. this.displacementMap = null;
  22502. this.displacementScale = 1;
  22503. this.displacementBias = 0;
  22504. this.specularMap = null;
  22505. this.alphaMap = null;
  22506. this.envMap = null;
  22507. this.combine = MultiplyOperation;
  22508. this.reflectivity = 1;
  22509. this.refractionRatio = 0.98;
  22510. this.wireframe = false;
  22511. this.wireframeLinewidth = 1;
  22512. this.wireframeLinecap = 'round';
  22513. this.wireframeLinejoin = 'round';
  22514. this.flatShading = false;
  22515. this.fog = true;
  22516. this.setValues( parameters );
  22517. }
  22518. copy( source ) {
  22519. super.copy( source );
  22520. this.color.copy( source.color );
  22521. this.specular.copy( source.specular );
  22522. this.shininess = source.shininess;
  22523. this.map = source.map;
  22524. this.lightMap = source.lightMap;
  22525. this.lightMapIntensity = source.lightMapIntensity;
  22526. this.aoMap = source.aoMap;
  22527. this.aoMapIntensity = source.aoMapIntensity;
  22528. this.emissive.copy( source.emissive );
  22529. this.emissiveMap = source.emissiveMap;
  22530. this.emissiveIntensity = source.emissiveIntensity;
  22531. this.bumpMap = source.bumpMap;
  22532. this.bumpScale = source.bumpScale;
  22533. this.normalMap = source.normalMap;
  22534. this.normalMapType = source.normalMapType;
  22535. this.normalScale.copy( source.normalScale );
  22536. this.displacementMap = source.displacementMap;
  22537. this.displacementScale = source.displacementScale;
  22538. this.displacementBias = source.displacementBias;
  22539. this.specularMap = source.specularMap;
  22540. this.alphaMap = source.alphaMap;
  22541. this.envMap = source.envMap;
  22542. this.combine = source.combine;
  22543. this.reflectivity = source.reflectivity;
  22544. this.refractionRatio = source.refractionRatio;
  22545. this.wireframe = source.wireframe;
  22546. this.wireframeLinewidth = source.wireframeLinewidth;
  22547. this.wireframeLinecap = source.wireframeLinecap;
  22548. this.wireframeLinejoin = source.wireframeLinejoin;
  22549. this.flatShading = source.flatShading;
  22550. this.fog = source.fog;
  22551. return this;
  22552. }
  22553. }
  22554. class MeshToonMaterial extends Material {
  22555. constructor( parameters ) {
  22556. super();
  22557. this.isMeshToonMaterial = true;
  22558. this.defines = { 'TOON': '' };
  22559. this.type = 'MeshToonMaterial';
  22560. this.color = new Color( 0xffffff );
  22561. this.map = null;
  22562. this.gradientMap = null;
  22563. this.lightMap = null;
  22564. this.lightMapIntensity = 1.0;
  22565. this.aoMap = null;
  22566. this.aoMapIntensity = 1.0;
  22567. this.emissive = new Color( 0x000000 );
  22568. this.emissiveIntensity = 1.0;
  22569. this.emissiveMap = null;
  22570. this.bumpMap = null;
  22571. this.bumpScale = 1;
  22572. this.normalMap = null;
  22573. this.normalMapType = TangentSpaceNormalMap;
  22574. this.normalScale = new Vector2( 1, 1 );
  22575. this.displacementMap = null;
  22576. this.displacementScale = 1;
  22577. this.displacementBias = 0;
  22578. this.alphaMap = null;
  22579. this.wireframe = false;
  22580. this.wireframeLinewidth = 1;
  22581. this.wireframeLinecap = 'round';
  22582. this.wireframeLinejoin = 'round';
  22583. this.fog = true;
  22584. this.setValues( parameters );
  22585. }
  22586. copy( source ) {
  22587. super.copy( source );
  22588. this.color.copy( source.color );
  22589. this.map = source.map;
  22590. this.gradientMap = source.gradientMap;
  22591. this.lightMap = source.lightMap;
  22592. this.lightMapIntensity = source.lightMapIntensity;
  22593. this.aoMap = source.aoMap;
  22594. this.aoMapIntensity = source.aoMapIntensity;
  22595. this.emissive.copy( source.emissive );
  22596. this.emissiveMap = source.emissiveMap;
  22597. this.emissiveIntensity = source.emissiveIntensity;
  22598. this.bumpMap = source.bumpMap;
  22599. this.bumpScale = source.bumpScale;
  22600. this.normalMap = source.normalMap;
  22601. this.normalMapType = source.normalMapType;
  22602. this.normalScale.copy( source.normalScale );
  22603. this.displacementMap = source.displacementMap;
  22604. this.displacementScale = source.displacementScale;
  22605. this.displacementBias = source.displacementBias;
  22606. this.alphaMap = source.alphaMap;
  22607. this.wireframe = source.wireframe;
  22608. this.wireframeLinewidth = source.wireframeLinewidth;
  22609. this.wireframeLinecap = source.wireframeLinecap;
  22610. this.wireframeLinejoin = source.wireframeLinejoin;
  22611. this.fog = source.fog;
  22612. return this;
  22613. }
  22614. }
  22615. class MeshNormalMaterial extends Material {
  22616. constructor( parameters ) {
  22617. super();
  22618. this.isMeshNormalMaterial = true;
  22619. this.type = 'MeshNormalMaterial';
  22620. this.bumpMap = null;
  22621. this.bumpScale = 1;
  22622. this.normalMap = null;
  22623. this.normalMapType = TangentSpaceNormalMap;
  22624. this.normalScale = new Vector2( 1, 1 );
  22625. this.displacementMap = null;
  22626. this.displacementScale = 1;
  22627. this.displacementBias = 0;
  22628. this.wireframe = false;
  22629. this.wireframeLinewidth = 1;
  22630. this.flatShading = false;
  22631. this.setValues( parameters );
  22632. }
  22633. copy( source ) {
  22634. super.copy( source );
  22635. this.bumpMap = source.bumpMap;
  22636. this.bumpScale = source.bumpScale;
  22637. this.normalMap = source.normalMap;
  22638. this.normalMapType = source.normalMapType;
  22639. this.normalScale.copy( source.normalScale );
  22640. this.displacementMap = source.displacementMap;
  22641. this.displacementScale = source.displacementScale;
  22642. this.displacementBias = source.displacementBias;
  22643. this.wireframe = source.wireframe;
  22644. this.wireframeLinewidth = source.wireframeLinewidth;
  22645. this.flatShading = source.flatShading;
  22646. return this;
  22647. }
  22648. }
  22649. class MeshLambertMaterial extends Material {
  22650. constructor( parameters ) {
  22651. super();
  22652. this.isMeshLambertMaterial = true;
  22653. this.type = 'MeshLambertMaterial';
  22654. this.color = new Color( 0xffffff ); // diffuse
  22655. this.map = null;
  22656. this.lightMap = null;
  22657. this.lightMapIntensity = 1.0;
  22658. this.aoMap = null;
  22659. this.aoMapIntensity = 1.0;
  22660. this.emissive = new Color( 0x000000 );
  22661. this.emissiveIntensity = 1.0;
  22662. this.emissiveMap = null;
  22663. this.bumpMap = null;
  22664. this.bumpScale = 1;
  22665. this.normalMap = null;
  22666. this.normalMapType = TangentSpaceNormalMap;
  22667. this.normalScale = new Vector2( 1, 1 );
  22668. this.displacementMap = null;
  22669. this.displacementScale = 1;
  22670. this.displacementBias = 0;
  22671. this.specularMap = null;
  22672. this.alphaMap = null;
  22673. this.envMap = null;
  22674. this.combine = MultiplyOperation;
  22675. this.reflectivity = 1;
  22676. this.refractionRatio = 0.98;
  22677. this.wireframe = false;
  22678. this.wireframeLinewidth = 1;
  22679. this.wireframeLinecap = 'round';
  22680. this.wireframeLinejoin = 'round';
  22681. this.flatShading = false;
  22682. this.fog = true;
  22683. this.setValues( parameters );
  22684. }
  22685. copy( source ) {
  22686. super.copy( source );
  22687. this.color.copy( source.color );
  22688. this.map = source.map;
  22689. this.lightMap = source.lightMap;
  22690. this.lightMapIntensity = source.lightMapIntensity;
  22691. this.aoMap = source.aoMap;
  22692. this.aoMapIntensity = source.aoMapIntensity;
  22693. this.emissive.copy( source.emissive );
  22694. this.emissiveMap = source.emissiveMap;
  22695. this.emissiveIntensity = source.emissiveIntensity;
  22696. this.bumpMap = source.bumpMap;
  22697. this.bumpScale = source.bumpScale;
  22698. this.normalMap = source.normalMap;
  22699. this.normalMapType = source.normalMapType;
  22700. this.normalScale.copy( source.normalScale );
  22701. this.displacementMap = source.displacementMap;
  22702. this.displacementScale = source.displacementScale;
  22703. this.displacementBias = source.displacementBias;
  22704. this.specularMap = source.specularMap;
  22705. this.alphaMap = source.alphaMap;
  22706. this.envMap = source.envMap;
  22707. this.combine = source.combine;
  22708. this.reflectivity = source.reflectivity;
  22709. this.refractionRatio = source.refractionRatio;
  22710. this.wireframe = source.wireframe;
  22711. this.wireframeLinewidth = source.wireframeLinewidth;
  22712. this.wireframeLinecap = source.wireframeLinecap;
  22713. this.wireframeLinejoin = source.wireframeLinejoin;
  22714. this.flatShading = source.flatShading;
  22715. this.fog = source.fog;
  22716. return this;
  22717. }
  22718. }
  22719. class MeshMatcapMaterial extends Material {
  22720. constructor( parameters ) {
  22721. super();
  22722. this.isMeshMatcapMaterial = true;
  22723. this.defines = { 'MATCAP': '' };
  22724. this.type = 'MeshMatcapMaterial';
  22725. this.color = new Color( 0xffffff ); // diffuse
  22726. this.matcap = null;
  22727. this.map = null;
  22728. this.bumpMap = null;
  22729. this.bumpScale = 1;
  22730. this.normalMap = null;
  22731. this.normalMapType = TangentSpaceNormalMap;
  22732. this.normalScale = new Vector2( 1, 1 );
  22733. this.displacementMap = null;
  22734. this.displacementScale = 1;
  22735. this.displacementBias = 0;
  22736. this.alphaMap = null;
  22737. this.flatShading = false;
  22738. this.fog = true;
  22739. this.setValues( parameters );
  22740. }
  22741. copy( source ) {
  22742. super.copy( source );
  22743. this.defines = { 'MATCAP': '' };
  22744. this.color.copy( source.color );
  22745. this.matcap = source.matcap;
  22746. this.map = source.map;
  22747. this.bumpMap = source.bumpMap;
  22748. this.bumpScale = source.bumpScale;
  22749. this.normalMap = source.normalMap;
  22750. this.normalMapType = source.normalMapType;
  22751. this.normalScale.copy( source.normalScale );
  22752. this.displacementMap = source.displacementMap;
  22753. this.displacementScale = source.displacementScale;
  22754. this.displacementBias = source.displacementBias;
  22755. this.alphaMap = source.alphaMap;
  22756. this.flatShading = source.flatShading;
  22757. this.fog = source.fog;
  22758. return this;
  22759. }
  22760. }
  22761. class LineDashedMaterial extends LineBasicMaterial {
  22762. constructor( parameters ) {
  22763. super();
  22764. this.isLineDashedMaterial = true;
  22765. this.type = 'LineDashedMaterial';
  22766. this.scale = 1;
  22767. this.dashSize = 3;
  22768. this.gapSize = 1;
  22769. this.setValues( parameters );
  22770. }
  22771. copy( source ) {
  22772. super.copy( source );
  22773. this.scale = source.scale;
  22774. this.dashSize = source.dashSize;
  22775. this.gapSize = source.gapSize;
  22776. return this;
  22777. }
  22778. }
  22779. // same as Array.prototype.slice, but also works on typed arrays
  22780. function arraySlice( array, from, to ) {
  22781. if ( isTypedArray( array ) ) {
  22782. // in ios9 array.subarray(from, undefined) will return empty array
  22783. // but array.subarray(from) or array.subarray(from, len) is correct
  22784. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  22785. }
  22786. return array.slice( from, to );
  22787. }
  22788. // converts an array to a specific type
  22789. function convertArray( array, type, forceClone ) {
  22790. if ( ! array || // let 'undefined' and 'null' pass
  22791. ! forceClone && array.constructor === type ) return array;
  22792. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  22793. return new type( array ); // create typed array
  22794. }
  22795. return Array.prototype.slice.call( array ); // create Array
  22796. }
  22797. function isTypedArray( object ) {
  22798. return ArrayBuffer.isView( object ) &&
  22799. ! ( object instanceof DataView );
  22800. }
  22801. // returns an array by which times and values can be sorted
  22802. function getKeyframeOrder( times ) {
  22803. function compareTime( i, j ) {
  22804. return times[ i ] - times[ j ];
  22805. }
  22806. const n = times.length;
  22807. const result = new Array( n );
  22808. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  22809. result.sort( compareTime );
  22810. return result;
  22811. }
  22812. // uses the array previously returned by 'getKeyframeOrder' to sort data
  22813. function sortedArray( values, stride, order ) {
  22814. const nValues = values.length;
  22815. const result = new values.constructor( nValues );
  22816. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  22817. const srcOffset = order[ i ] * stride;
  22818. for ( let j = 0; j !== stride; ++ j ) {
  22819. result[ dstOffset ++ ] = values[ srcOffset + j ];
  22820. }
  22821. }
  22822. return result;
  22823. }
  22824. // function for parsing AOS keyframe formats
  22825. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  22826. let i = 1, key = jsonKeys[ 0 ];
  22827. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  22828. key = jsonKeys[ i ++ ];
  22829. }
  22830. if ( key === undefined ) return; // no data
  22831. let value = key[ valuePropertyName ];
  22832. if ( value === undefined ) return; // no data
  22833. if ( Array.isArray( value ) ) {
  22834. do {
  22835. value = key[ valuePropertyName ];
  22836. if ( value !== undefined ) {
  22837. times.push( key.time );
  22838. values.push.apply( values, value ); // push all elements
  22839. }
  22840. key = jsonKeys[ i ++ ];
  22841. } while ( key !== undefined );
  22842. } else if ( value.toArray !== undefined ) {
  22843. // ...assume THREE.Math-ish
  22844. do {
  22845. value = key[ valuePropertyName ];
  22846. if ( value !== undefined ) {
  22847. times.push( key.time );
  22848. value.toArray( values, values.length );
  22849. }
  22850. key = jsonKeys[ i ++ ];
  22851. } while ( key !== undefined );
  22852. } else {
  22853. // otherwise push as-is
  22854. do {
  22855. value = key[ valuePropertyName ];
  22856. if ( value !== undefined ) {
  22857. times.push( key.time );
  22858. values.push( value );
  22859. }
  22860. key = jsonKeys[ i ++ ];
  22861. } while ( key !== undefined );
  22862. }
  22863. }
  22864. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  22865. const clip = sourceClip.clone();
  22866. clip.name = name;
  22867. const tracks = [];
  22868. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22869. const track = clip.tracks[ i ];
  22870. const valueSize = track.getValueSize();
  22871. const times = [];
  22872. const values = [];
  22873. for ( let j = 0; j < track.times.length; ++ j ) {
  22874. const frame = track.times[ j ] * fps;
  22875. if ( frame < startFrame || frame >= endFrame ) continue;
  22876. times.push( track.times[ j ] );
  22877. for ( let k = 0; k < valueSize; ++ k ) {
  22878. values.push( track.values[ j * valueSize + k ] );
  22879. }
  22880. }
  22881. if ( times.length === 0 ) continue;
  22882. track.times = convertArray( times, track.times.constructor );
  22883. track.values = convertArray( values, track.values.constructor );
  22884. tracks.push( track );
  22885. }
  22886. clip.tracks = tracks;
  22887. // find minimum .times value across all tracks in the trimmed clip
  22888. let minStartTime = Infinity;
  22889. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22890. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  22891. minStartTime = clip.tracks[ i ].times[ 0 ];
  22892. }
  22893. }
  22894. // shift all tracks such that clip begins at t=0
  22895. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22896. clip.tracks[ i ].shift( - 1 * minStartTime );
  22897. }
  22898. clip.resetDuration();
  22899. return clip;
  22900. }
  22901. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  22902. if ( fps <= 0 ) fps = 30;
  22903. const numTracks = referenceClip.tracks.length;
  22904. const referenceTime = referenceFrame / fps;
  22905. // Make each track's values relative to the values at the reference frame
  22906. for ( let i = 0; i < numTracks; ++ i ) {
  22907. const referenceTrack = referenceClip.tracks[ i ];
  22908. const referenceTrackType = referenceTrack.ValueTypeName;
  22909. // Skip this track if it's non-numeric
  22910. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  22911. // Find the track in the target clip whose name and type matches the reference track
  22912. const targetTrack = targetClip.tracks.find( function ( track ) {
  22913. return track.name === referenceTrack.name
  22914. && track.ValueTypeName === referenceTrackType;
  22915. } );
  22916. if ( targetTrack === undefined ) continue;
  22917. let referenceOffset = 0;
  22918. const referenceValueSize = referenceTrack.getValueSize();
  22919. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  22920. referenceOffset = referenceValueSize / 3;
  22921. }
  22922. let targetOffset = 0;
  22923. const targetValueSize = targetTrack.getValueSize();
  22924. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  22925. targetOffset = targetValueSize / 3;
  22926. }
  22927. const lastIndex = referenceTrack.times.length - 1;
  22928. let referenceValue;
  22929. // Find the value to subtract out of the track
  22930. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  22931. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  22932. const startIndex = referenceOffset;
  22933. const endIndex = referenceValueSize - referenceOffset;
  22934. referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );
  22935. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  22936. // Reference frame is after the last keyframe, so just use the last keyframe
  22937. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  22938. const endIndex = startIndex + referenceValueSize - referenceOffset;
  22939. referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );
  22940. } else {
  22941. // Interpolate to the reference value
  22942. const interpolant = referenceTrack.createInterpolant();
  22943. const startIndex = referenceOffset;
  22944. const endIndex = referenceValueSize - referenceOffset;
  22945. interpolant.evaluate( referenceTime );
  22946. referenceValue = arraySlice( interpolant.resultBuffer, startIndex, endIndex );
  22947. }
  22948. // Conjugate the quaternion
  22949. if ( referenceTrackType === 'quaternion' ) {
  22950. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  22951. referenceQuat.toArray( referenceValue );
  22952. }
  22953. // Subtract the reference value from all of the track values
  22954. const numTimes = targetTrack.times.length;
  22955. for ( let j = 0; j < numTimes; ++ j ) {
  22956. const valueStart = j * targetValueSize + targetOffset;
  22957. if ( referenceTrackType === 'quaternion' ) {
  22958. // Multiply the conjugate for quaternion track types
  22959. Quaternion.multiplyQuaternionsFlat(
  22960. targetTrack.values,
  22961. valueStart,
  22962. referenceValue,
  22963. 0,
  22964. targetTrack.values,
  22965. valueStart
  22966. );
  22967. } else {
  22968. const valueEnd = targetValueSize - targetOffset * 2;
  22969. // Subtract each value for all other numeric track types
  22970. for ( let k = 0; k < valueEnd; ++ k ) {
  22971. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  22972. }
  22973. }
  22974. }
  22975. }
  22976. targetClip.blendMode = AdditiveAnimationBlendMode;
  22977. return targetClip;
  22978. }
  22979. const AnimationUtils = {
  22980. arraySlice: arraySlice,
  22981. convertArray: convertArray,
  22982. isTypedArray: isTypedArray,
  22983. getKeyframeOrder: getKeyframeOrder,
  22984. sortedArray: sortedArray,
  22985. flattenJSON: flattenJSON,
  22986. subclip: subclip,
  22987. makeClipAdditive: makeClipAdditive
  22988. };
  22989. /**
  22990. * Abstract base class of interpolants over parametric samples.
  22991. *
  22992. * The parameter domain is one dimensional, typically the time or a path
  22993. * along a curve defined by the data.
  22994. *
  22995. * The sample values can have any dimensionality and derived classes may
  22996. * apply special interpretations to the data.
  22997. *
  22998. * This class provides the interval seek in a Template Method, deferring
  22999. * the actual interpolation to derived classes.
  23000. *
  23001. * Time complexity is O(1) for linear access crossing at most two points
  23002. * and O(log N) for random access, where N is the number of positions.
  23003. *
  23004. * References:
  23005. *
  23006. * http://www.oodesign.com/template-method-pattern.html
  23007. *
  23008. */
  23009. class Interpolant {
  23010. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23011. this.parameterPositions = parameterPositions;
  23012. this._cachedIndex = 0;
  23013. this.resultBuffer = resultBuffer !== undefined ?
  23014. resultBuffer : new sampleValues.constructor( sampleSize );
  23015. this.sampleValues = sampleValues;
  23016. this.valueSize = sampleSize;
  23017. this.settings = null;
  23018. this.DefaultSettings_ = {};
  23019. }
  23020. evaluate( t ) {
  23021. const pp = this.parameterPositions;
  23022. let i1 = this._cachedIndex,
  23023. t1 = pp[ i1 ],
  23024. t0 = pp[ i1 - 1 ];
  23025. validate_interval: {
  23026. seek: {
  23027. let right;
  23028. linear_scan: {
  23029. //- See http://jsperf.com/comparison-to-undefined/3
  23030. //- slower code:
  23031. //-
  23032. //- if ( t >= t1 || t1 === undefined ) {
  23033. forward_scan: if ( ! ( t < t1 ) ) {
  23034. for ( let giveUpAt = i1 + 2; ; ) {
  23035. if ( t1 === undefined ) {
  23036. if ( t < t0 ) break forward_scan;
  23037. // after end
  23038. i1 = pp.length;
  23039. this._cachedIndex = i1;
  23040. return this.copySampleValue_( i1 - 1 );
  23041. }
  23042. if ( i1 === giveUpAt ) break; // this loop
  23043. t0 = t1;
  23044. t1 = pp[ ++ i1 ];
  23045. if ( t < t1 ) {
  23046. // we have arrived at the sought interval
  23047. break seek;
  23048. }
  23049. }
  23050. // prepare binary search on the right side of the index
  23051. right = pp.length;
  23052. break linear_scan;
  23053. }
  23054. //- slower code:
  23055. //- if ( t < t0 || t0 === undefined ) {
  23056. if ( ! ( t >= t0 ) ) {
  23057. // looping?
  23058. const t1global = pp[ 1 ];
  23059. if ( t < t1global ) {
  23060. i1 = 2; // + 1, using the scan for the details
  23061. t0 = t1global;
  23062. }
  23063. // linear reverse scan
  23064. for ( let giveUpAt = i1 - 2; ; ) {
  23065. if ( t0 === undefined ) {
  23066. // before start
  23067. this._cachedIndex = 0;
  23068. return this.copySampleValue_( 0 );
  23069. }
  23070. if ( i1 === giveUpAt ) break; // this loop
  23071. t1 = t0;
  23072. t0 = pp[ -- i1 - 1 ];
  23073. if ( t >= t0 ) {
  23074. // we have arrived at the sought interval
  23075. break seek;
  23076. }
  23077. }
  23078. // prepare binary search on the left side of the index
  23079. right = i1;
  23080. i1 = 0;
  23081. break linear_scan;
  23082. }
  23083. // the interval is valid
  23084. break validate_interval;
  23085. } // linear scan
  23086. // binary search
  23087. while ( i1 < right ) {
  23088. const mid = ( i1 + right ) >>> 1;
  23089. if ( t < pp[ mid ] ) {
  23090. right = mid;
  23091. } else {
  23092. i1 = mid + 1;
  23093. }
  23094. }
  23095. t1 = pp[ i1 ];
  23096. t0 = pp[ i1 - 1 ];
  23097. // check boundary cases, again
  23098. if ( t0 === undefined ) {
  23099. this._cachedIndex = 0;
  23100. return this.copySampleValue_( 0 );
  23101. }
  23102. if ( t1 === undefined ) {
  23103. i1 = pp.length;
  23104. this._cachedIndex = i1;
  23105. return this.copySampleValue_( i1 - 1 );
  23106. }
  23107. } // seek
  23108. this._cachedIndex = i1;
  23109. this.intervalChanged_( i1, t0, t1 );
  23110. } // validate_interval
  23111. return this.interpolate_( i1, t0, t, t1 );
  23112. }
  23113. getSettings_() {
  23114. return this.settings || this.DefaultSettings_;
  23115. }
  23116. copySampleValue_( index ) {
  23117. // copies a sample value to the result buffer
  23118. const result = this.resultBuffer,
  23119. values = this.sampleValues,
  23120. stride = this.valueSize,
  23121. offset = index * stride;
  23122. for ( let i = 0; i !== stride; ++ i ) {
  23123. result[ i ] = values[ offset + i ];
  23124. }
  23125. return result;
  23126. }
  23127. // Template methods for derived classes:
  23128. interpolate_( /* i1, t0, t, t1 */ ) {
  23129. throw new Error( 'call to abstract method' );
  23130. // implementations shall return this.resultBuffer
  23131. }
  23132. intervalChanged_( /* i1, t0, t1 */ ) {
  23133. // empty
  23134. }
  23135. }
  23136. /**
  23137. * Fast and simple cubic spline interpolant.
  23138. *
  23139. * It was derived from a Hermitian construction setting the first derivative
  23140. * at each sample position to the linear slope between neighboring positions
  23141. * over their parameter interval.
  23142. */
  23143. class CubicInterpolant extends Interpolant {
  23144. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23145. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23146. this._weightPrev = - 0;
  23147. this._offsetPrev = - 0;
  23148. this._weightNext = - 0;
  23149. this._offsetNext = - 0;
  23150. this.DefaultSettings_ = {
  23151. endingStart: ZeroCurvatureEnding,
  23152. endingEnd: ZeroCurvatureEnding
  23153. };
  23154. }
  23155. intervalChanged_( i1, t0, t1 ) {
  23156. const pp = this.parameterPositions;
  23157. let iPrev = i1 - 2,
  23158. iNext = i1 + 1,
  23159. tPrev = pp[ iPrev ],
  23160. tNext = pp[ iNext ];
  23161. if ( tPrev === undefined ) {
  23162. switch ( this.getSettings_().endingStart ) {
  23163. case ZeroSlopeEnding:
  23164. // f'(t0) = 0
  23165. iPrev = i1;
  23166. tPrev = 2 * t0 - t1;
  23167. break;
  23168. case WrapAroundEnding:
  23169. // use the other end of the curve
  23170. iPrev = pp.length - 2;
  23171. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  23172. break;
  23173. default: // ZeroCurvatureEnding
  23174. // f''(t0) = 0 a.k.a. Natural Spline
  23175. iPrev = i1;
  23176. tPrev = t1;
  23177. }
  23178. }
  23179. if ( tNext === undefined ) {
  23180. switch ( this.getSettings_().endingEnd ) {
  23181. case ZeroSlopeEnding:
  23182. // f'(tN) = 0
  23183. iNext = i1;
  23184. tNext = 2 * t1 - t0;
  23185. break;
  23186. case WrapAroundEnding:
  23187. // use the other end of the curve
  23188. iNext = 1;
  23189. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  23190. break;
  23191. default: // ZeroCurvatureEnding
  23192. // f''(tN) = 0, a.k.a. Natural Spline
  23193. iNext = i1 - 1;
  23194. tNext = t0;
  23195. }
  23196. }
  23197. const halfDt = ( t1 - t0 ) * 0.5,
  23198. stride = this.valueSize;
  23199. this._weightPrev = halfDt / ( t0 - tPrev );
  23200. this._weightNext = halfDt / ( tNext - t1 );
  23201. this._offsetPrev = iPrev * stride;
  23202. this._offsetNext = iNext * stride;
  23203. }
  23204. interpolate_( i1, t0, t, t1 ) {
  23205. const result = this.resultBuffer,
  23206. values = this.sampleValues,
  23207. stride = this.valueSize,
  23208. o1 = i1 * stride, o0 = o1 - stride,
  23209. oP = this._offsetPrev, oN = this._offsetNext,
  23210. wP = this._weightPrev, wN = this._weightNext,
  23211. p = ( t - t0 ) / ( t1 - t0 ),
  23212. pp = p * p,
  23213. ppp = pp * p;
  23214. // evaluate polynomials
  23215. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  23216. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  23217. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  23218. const sN = wN * ppp - wN * pp;
  23219. // combine data linearly
  23220. for ( let i = 0; i !== stride; ++ i ) {
  23221. result[ i ] =
  23222. sP * values[ oP + i ] +
  23223. s0 * values[ o0 + i ] +
  23224. s1 * values[ o1 + i ] +
  23225. sN * values[ oN + i ];
  23226. }
  23227. return result;
  23228. }
  23229. }
  23230. class LinearInterpolant extends Interpolant {
  23231. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23232. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23233. }
  23234. interpolate_( i1, t0, t, t1 ) {
  23235. const result = this.resultBuffer,
  23236. values = this.sampleValues,
  23237. stride = this.valueSize,
  23238. offset1 = i1 * stride,
  23239. offset0 = offset1 - stride,
  23240. weight1 = ( t - t0 ) / ( t1 - t0 ),
  23241. weight0 = 1 - weight1;
  23242. for ( let i = 0; i !== stride; ++ i ) {
  23243. result[ i ] =
  23244. values[ offset0 + i ] * weight0 +
  23245. values[ offset1 + i ] * weight1;
  23246. }
  23247. return result;
  23248. }
  23249. }
  23250. /**
  23251. *
  23252. * Interpolant that evaluates to the sample value at the position preceding
  23253. * the parameter.
  23254. */
  23255. class DiscreteInterpolant extends Interpolant {
  23256. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23257. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23258. }
  23259. interpolate_( i1 /*, t0, t, t1 */ ) {
  23260. return this.copySampleValue_( i1 - 1 );
  23261. }
  23262. }
  23263. class KeyframeTrack {
  23264. constructor( name, times, values, interpolation ) {
  23265. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  23266. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  23267. this.name = name;
  23268. this.times = convertArray( times, this.TimeBufferType );
  23269. this.values = convertArray( values, this.ValueBufferType );
  23270. this.setInterpolation( interpolation || this.DefaultInterpolation );
  23271. }
  23272. // Serialization (in static context, because of constructor invocation
  23273. // and automatic invocation of .toJSON):
  23274. static toJSON( track ) {
  23275. const trackType = track.constructor;
  23276. let json;
  23277. // derived classes can define a static toJSON method
  23278. if ( trackType.toJSON !== this.toJSON ) {
  23279. json = trackType.toJSON( track );
  23280. } else {
  23281. // by default, we assume the data can be serialized as-is
  23282. json = {
  23283. 'name': track.name,
  23284. 'times': convertArray( track.times, Array ),
  23285. 'values': convertArray( track.values, Array )
  23286. };
  23287. const interpolation = track.getInterpolation();
  23288. if ( interpolation !== track.DefaultInterpolation ) {
  23289. json.interpolation = interpolation;
  23290. }
  23291. }
  23292. json.type = track.ValueTypeName; // mandatory
  23293. return json;
  23294. }
  23295. InterpolantFactoryMethodDiscrete( result ) {
  23296. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  23297. }
  23298. InterpolantFactoryMethodLinear( result ) {
  23299. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23300. }
  23301. InterpolantFactoryMethodSmooth( result ) {
  23302. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  23303. }
  23304. setInterpolation( interpolation ) {
  23305. let factoryMethod;
  23306. switch ( interpolation ) {
  23307. case InterpolateDiscrete:
  23308. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  23309. break;
  23310. case InterpolateLinear:
  23311. factoryMethod = this.InterpolantFactoryMethodLinear;
  23312. break;
  23313. case InterpolateSmooth:
  23314. factoryMethod = this.InterpolantFactoryMethodSmooth;
  23315. break;
  23316. }
  23317. if ( factoryMethod === undefined ) {
  23318. const message = 'unsupported interpolation for ' +
  23319. this.ValueTypeName + ' keyframe track named ' + this.name;
  23320. if ( this.createInterpolant === undefined ) {
  23321. // fall back to default, unless the default itself is messed up
  23322. if ( interpolation !== this.DefaultInterpolation ) {
  23323. this.setInterpolation( this.DefaultInterpolation );
  23324. } else {
  23325. throw new Error( message ); // fatal, in this case
  23326. }
  23327. }
  23328. console.warn( 'THREE.KeyframeTrack:', message );
  23329. return this;
  23330. }
  23331. this.createInterpolant = factoryMethod;
  23332. return this;
  23333. }
  23334. getInterpolation() {
  23335. switch ( this.createInterpolant ) {
  23336. case this.InterpolantFactoryMethodDiscrete:
  23337. return InterpolateDiscrete;
  23338. case this.InterpolantFactoryMethodLinear:
  23339. return InterpolateLinear;
  23340. case this.InterpolantFactoryMethodSmooth:
  23341. return InterpolateSmooth;
  23342. }
  23343. }
  23344. getValueSize() {
  23345. return this.values.length / this.times.length;
  23346. }
  23347. // move all keyframes either forwards or backwards in time
  23348. shift( timeOffset ) {
  23349. if ( timeOffset !== 0.0 ) {
  23350. const times = this.times;
  23351. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  23352. times[ i ] += timeOffset;
  23353. }
  23354. }
  23355. return this;
  23356. }
  23357. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  23358. scale( timeScale ) {
  23359. if ( timeScale !== 1.0 ) {
  23360. const times = this.times;
  23361. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  23362. times[ i ] *= timeScale;
  23363. }
  23364. }
  23365. return this;
  23366. }
  23367. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  23368. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  23369. trim( startTime, endTime ) {
  23370. const times = this.times,
  23371. nKeys = times.length;
  23372. let from = 0,
  23373. to = nKeys - 1;
  23374. while ( from !== nKeys && times[ from ] < startTime ) {
  23375. ++ from;
  23376. }
  23377. while ( to !== - 1 && times[ to ] > endTime ) {
  23378. -- to;
  23379. }
  23380. ++ to; // inclusive -> exclusive bound
  23381. if ( from !== 0 || to !== nKeys ) {
  23382. // empty tracks are forbidden, so keep at least one keyframe
  23383. if ( from >= to ) {
  23384. to = Math.max( to, 1 );
  23385. from = to - 1;
  23386. }
  23387. const stride = this.getValueSize();
  23388. this.times = arraySlice( times, from, to );
  23389. this.values = arraySlice( this.values, from * stride, to * stride );
  23390. }
  23391. return this;
  23392. }
  23393. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  23394. validate() {
  23395. let valid = true;
  23396. const valueSize = this.getValueSize();
  23397. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  23398. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  23399. valid = false;
  23400. }
  23401. const times = this.times,
  23402. values = this.values,
  23403. nKeys = times.length;
  23404. if ( nKeys === 0 ) {
  23405. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  23406. valid = false;
  23407. }
  23408. let prevTime = null;
  23409. for ( let i = 0; i !== nKeys; i ++ ) {
  23410. const currTime = times[ i ];
  23411. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  23412. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  23413. valid = false;
  23414. break;
  23415. }
  23416. if ( prevTime !== null && prevTime > currTime ) {
  23417. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  23418. valid = false;
  23419. break;
  23420. }
  23421. prevTime = currTime;
  23422. }
  23423. if ( values !== undefined ) {
  23424. if ( isTypedArray( values ) ) {
  23425. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  23426. const value = values[ i ];
  23427. if ( isNaN( value ) ) {
  23428. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  23429. valid = false;
  23430. break;
  23431. }
  23432. }
  23433. }
  23434. }
  23435. return valid;
  23436. }
  23437. // removes equivalent sequential keys as common in morph target sequences
  23438. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  23439. optimize() {
  23440. // times or values may be shared with other tracks, so overwriting is unsafe
  23441. const times = arraySlice( this.times ),
  23442. values = arraySlice( this.values ),
  23443. stride = this.getValueSize(),
  23444. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  23445. lastIndex = times.length - 1;
  23446. let writeIndex = 1;
  23447. for ( let i = 1; i < lastIndex; ++ i ) {
  23448. let keep = false;
  23449. const time = times[ i ];
  23450. const timeNext = times[ i + 1 ];
  23451. // remove adjacent keyframes scheduled at the same time
  23452. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  23453. if ( ! smoothInterpolation ) {
  23454. // remove unnecessary keyframes same as their neighbors
  23455. const offset = i * stride,
  23456. offsetP = offset - stride,
  23457. offsetN = offset + stride;
  23458. for ( let j = 0; j !== stride; ++ j ) {
  23459. const value = values[ offset + j ];
  23460. if ( value !== values[ offsetP + j ] ||
  23461. value !== values[ offsetN + j ] ) {
  23462. keep = true;
  23463. break;
  23464. }
  23465. }
  23466. } else {
  23467. keep = true;
  23468. }
  23469. }
  23470. // in-place compaction
  23471. if ( keep ) {
  23472. if ( i !== writeIndex ) {
  23473. times[ writeIndex ] = times[ i ];
  23474. const readOffset = i * stride,
  23475. writeOffset = writeIndex * stride;
  23476. for ( let j = 0; j !== stride; ++ j ) {
  23477. values[ writeOffset + j ] = values[ readOffset + j ];
  23478. }
  23479. }
  23480. ++ writeIndex;
  23481. }
  23482. }
  23483. // flush last keyframe (compaction looks ahead)
  23484. if ( lastIndex > 0 ) {
  23485. times[ writeIndex ] = times[ lastIndex ];
  23486. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  23487. values[ writeOffset + j ] = values[ readOffset + j ];
  23488. }
  23489. ++ writeIndex;
  23490. }
  23491. if ( writeIndex !== times.length ) {
  23492. this.times = arraySlice( times, 0, writeIndex );
  23493. this.values = arraySlice( values, 0, writeIndex * stride );
  23494. } else {
  23495. this.times = times;
  23496. this.values = values;
  23497. }
  23498. return this;
  23499. }
  23500. clone() {
  23501. const times = arraySlice( this.times, 0 );
  23502. const values = arraySlice( this.values, 0 );
  23503. const TypedKeyframeTrack = this.constructor;
  23504. const track = new TypedKeyframeTrack( this.name, times, values );
  23505. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  23506. track.createInterpolant = this.createInterpolant;
  23507. return track;
  23508. }
  23509. }
  23510. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  23511. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  23512. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23513. /**
  23514. * A Track of Boolean keyframe values.
  23515. */
  23516. class BooleanKeyframeTrack extends KeyframeTrack {}
  23517. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  23518. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  23519. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23520. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23521. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23522. /**
  23523. * A Track of keyframe values that represent color.
  23524. */
  23525. class ColorKeyframeTrack extends KeyframeTrack {}
  23526. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  23527. /**
  23528. * A Track of numeric keyframe values.
  23529. */
  23530. class NumberKeyframeTrack extends KeyframeTrack {}
  23531. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  23532. /**
  23533. * Spherical linear unit quaternion interpolant.
  23534. */
  23535. class QuaternionLinearInterpolant extends Interpolant {
  23536. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23537. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23538. }
  23539. interpolate_( i1, t0, t, t1 ) {
  23540. const result = this.resultBuffer,
  23541. values = this.sampleValues,
  23542. stride = this.valueSize,
  23543. alpha = ( t - t0 ) / ( t1 - t0 );
  23544. let offset = i1 * stride;
  23545. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  23546. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  23547. }
  23548. return result;
  23549. }
  23550. }
  23551. /**
  23552. * A Track of quaternion keyframe values.
  23553. */
  23554. class QuaternionKeyframeTrack extends KeyframeTrack {
  23555. InterpolantFactoryMethodLinear( result ) {
  23556. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23557. }
  23558. }
  23559. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  23560. // ValueBufferType is inherited
  23561. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23562. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23563. /**
  23564. * A Track that interpolates Strings
  23565. */
  23566. class StringKeyframeTrack extends KeyframeTrack {}
  23567. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  23568. StringKeyframeTrack.prototype.ValueBufferType = Array;
  23569. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23570. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23571. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23572. /**
  23573. * A Track of vectored keyframe values.
  23574. */
  23575. class VectorKeyframeTrack extends KeyframeTrack {}
  23576. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  23577. class AnimationClip {
  23578. constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  23579. this.name = name;
  23580. this.tracks = tracks;
  23581. this.duration = duration;
  23582. this.blendMode = blendMode;
  23583. this.uuid = generateUUID();
  23584. // this means it should figure out its duration by scanning the tracks
  23585. if ( this.duration < 0 ) {
  23586. this.resetDuration();
  23587. }
  23588. }
  23589. static parse( json ) {
  23590. const tracks = [],
  23591. jsonTracks = json.tracks,
  23592. frameTime = 1.0 / ( json.fps || 1.0 );
  23593. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  23594. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  23595. }
  23596. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  23597. clip.uuid = json.uuid;
  23598. return clip;
  23599. }
  23600. static toJSON( clip ) {
  23601. const tracks = [],
  23602. clipTracks = clip.tracks;
  23603. const json = {
  23604. 'name': clip.name,
  23605. 'duration': clip.duration,
  23606. 'tracks': tracks,
  23607. 'uuid': clip.uuid,
  23608. 'blendMode': clip.blendMode
  23609. };
  23610. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  23611. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  23612. }
  23613. return json;
  23614. }
  23615. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  23616. const numMorphTargets = morphTargetSequence.length;
  23617. const tracks = [];
  23618. for ( let i = 0; i < numMorphTargets; i ++ ) {
  23619. let times = [];
  23620. let values = [];
  23621. times.push(
  23622. ( i + numMorphTargets - 1 ) % numMorphTargets,
  23623. i,
  23624. ( i + 1 ) % numMorphTargets );
  23625. values.push( 0, 1, 0 );
  23626. const order = getKeyframeOrder( times );
  23627. times = sortedArray( times, 1, order );
  23628. values = sortedArray( values, 1, order );
  23629. // if there is a key at the first frame, duplicate it as the
  23630. // last frame as well for perfect loop.
  23631. if ( ! noLoop && times[ 0 ] === 0 ) {
  23632. times.push( numMorphTargets );
  23633. values.push( values[ 0 ] );
  23634. }
  23635. tracks.push(
  23636. new NumberKeyframeTrack(
  23637. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  23638. times, values
  23639. ).scale( 1.0 / fps ) );
  23640. }
  23641. return new this( name, - 1, tracks );
  23642. }
  23643. static findByName( objectOrClipArray, name ) {
  23644. let clipArray = objectOrClipArray;
  23645. if ( ! Array.isArray( objectOrClipArray ) ) {
  23646. const o = objectOrClipArray;
  23647. clipArray = o.geometry && o.geometry.animations || o.animations;
  23648. }
  23649. for ( let i = 0; i < clipArray.length; i ++ ) {
  23650. if ( clipArray[ i ].name === name ) {
  23651. return clipArray[ i ];
  23652. }
  23653. }
  23654. return null;
  23655. }
  23656. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  23657. const animationToMorphTargets = {};
  23658. // tested with https://regex101.com/ on trick sequences
  23659. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  23660. const pattern = /^([\w-]*?)([\d]+)$/;
  23661. // sort morph target names into animation groups based
  23662. // patterns like Walk_001, Walk_002, Run_001, Run_002
  23663. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  23664. const morphTarget = morphTargets[ i ];
  23665. const parts = morphTarget.name.match( pattern );
  23666. if ( parts && parts.length > 1 ) {
  23667. const name = parts[ 1 ];
  23668. let animationMorphTargets = animationToMorphTargets[ name ];
  23669. if ( ! animationMorphTargets ) {
  23670. animationToMorphTargets[ name ] = animationMorphTargets = [];
  23671. }
  23672. animationMorphTargets.push( morphTarget );
  23673. }
  23674. }
  23675. const clips = [];
  23676. for ( const name in animationToMorphTargets ) {
  23677. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  23678. }
  23679. return clips;
  23680. }
  23681. // parse the animation.hierarchy format
  23682. static parseAnimation( animation, bones ) {
  23683. if ( ! animation ) {
  23684. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  23685. return null;
  23686. }
  23687. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  23688. // only return track if there are actually keys.
  23689. if ( animationKeys.length !== 0 ) {
  23690. const times = [];
  23691. const values = [];
  23692. flattenJSON( animationKeys, times, values, propertyName );
  23693. // empty keys are filtered out, so check again
  23694. if ( times.length !== 0 ) {
  23695. destTracks.push( new trackType( trackName, times, values ) );
  23696. }
  23697. }
  23698. };
  23699. const tracks = [];
  23700. const clipName = animation.name || 'default';
  23701. const fps = animation.fps || 30;
  23702. const blendMode = animation.blendMode;
  23703. // automatic length determination in AnimationClip.
  23704. let duration = animation.length || - 1;
  23705. const hierarchyTracks = animation.hierarchy || [];
  23706. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  23707. const animationKeys = hierarchyTracks[ h ].keys;
  23708. // skip empty tracks
  23709. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  23710. // process morph targets
  23711. if ( animationKeys[ 0 ].morphTargets ) {
  23712. // figure out all morph targets used in this track
  23713. const morphTargetNames = {};
  23714. let k;
  23715. for ( k = 0; k < animationKeys.length; k ++ ) {
  23716. if ( animationKeys[ k ].morphTargets ) {
  23717. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  23718. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  23719. }
  23720. }
  23721. }
  23722. // create a track for each morph target with all zero
  23723. // morphTargetInfluences except for the keys in which
  23724. // the morphTarget is named.
  23725. for ( const morphTargetName in morphTargetNames ) {
  23726. const times = [];
  23727. const values = [];
  23728. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  23729. const animationKey = animationKeys[ k ];
  23730. times.push( animationKey.time );
  23731. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  23732. }
  23733. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  23734. }
  23735. duration = morphTargetNames.length * fps;
  23736. } else {
  23737. // ...assume skeletal animation
  23738. const boneName = '.bones[' + bones[ h ].name + ']';
  23739. addNonemptyTrack(
  23740. VectorKeyframeTrack, boneName + '.position',
  23741. animationKeys, 'pos', tracks );
  23742. addNonemptyTrack(
  23743. QuaternionKeyframeTrack, boneName + '.quaternion',
  23744. animationKeys, 'rot', tracks );
  23745. addNonemptyTrack(
  23746. VectorKeyframeTrack, boneName + '.scale',
  23747. animationKeys, 'scl', tracks );
  23748. }
  23749. }
  23750. if ( tracks.length === 0 ) {
  23751. return null;
  23752. }
  23753. const clip = new this( clipName, duration, tracks, blendMode );
  23754. return clip;
  23755. }
  23756. resetDuration() {
  23757. const tracks = this.tracks;
  23758. let duration = 0;
  23759. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  23760. const track = this.tracks[ i ];
  23761. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  23762. }
  23763. this.duration = duration;
  23764. return this;
  23765. }
  23766. trim() {
  23767. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23768. this.tracks[ i ].trim( 0, this.duration );
  23769. }
  23770. return this;
  23771. }
  23772. validate() {
  23773. let valid = true;
  23774. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23775. valid = valid && this.tracks[ i ].validate();
  23776. }
  23777. return valid;
  23778. }
  23779. optimize() {
  23780. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23781. this.tracks[ i ].optimize();
  23782. }
  23783. return this;
  23784. }
  23785. clone() {
  23786. const tracks = [];
  23787. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23788. tracks.push( this.tracks[ i ].clone() );
  23789. }
  23790. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  23791. }
  23792. toJSON() {
  23793. return this.constructor.toJSON( this );
  23794. }
  23795. }
  23796. function getTrackTypeForValueTypeName( typeName ) {
  23797. switch ( typeName.toLowerCase() ) {
  23798. case 'scalar':
  23799. case 'double':
  23800. case 'float':
  23801. case 'number':
  23802. case 'integer':
  23803. return NumberKeyframeTrack;
  23804. case 'vector':
  23805. case 'vector2':
  23806. case 'vector3':
  23807. case 'vector4':
  23808. return VectorKeyframeTrack;
  23809. case 'color':
  23810. return ColorKeyframeTrack;
  23811. case 'quaternion':
  23812. return QuaternionKeyframeTrack;
  23813. case 'bool':
  23814. case 'boolean':
  23815. return BooleanKeyframeTrack;
  23816. case 'string':
  23817. return StringKeyframeTrack;
  23818. }
  23819. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  23820. }
  23821. function parseKeyframeTrack( json ) {
  23822. if ( json.type === undefined ) {
  23823. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  23824. }
  23825. const trackType = getTrackTypeForValueTypeName( json.type );
  23826. if ( json.times === undefined ) {
  23827. const times = [], values = [];
  23828. flattenJSON( json.keys, times, values, 'value' );
  23829. json.times = times;
  23830. json.values = values;
  23831. }
  23832. // derived classes can define a static parse method
  23833. if ( trackType.parse !== undefined ) {
  23834. return trackType.parse( json );
  23835. } else {
  23836. // by default, we assume a constructor compatible with the base
  23837. return new trackType( json.name, json.times, json.values, json.interpolation );
  23838. }
  23839. }
  23840. const Cache = {
  23841. enabled: false,
  23842. files: {},
  23843. add: function ( key, file ) {
  23844. if ( this.enabled === false ) return;
  23845. // console.log( 'THREE.Cache', 'Adding key:', key );
  23846. this.files[ key ] = file;
  23847. },
  23848. get: function ( key ) {
  23849. if ( this.enabled === false ) return;
  23850. // console.log( 'THREE.Cache', 'Checking key:', key );
  23851. return this.files[ key ];
  23852. },
  23853. remove: function ( key ) {
  23854. delete this.files[ key ];
  23855. },
  23856. clear: function () {
  23857. this.files = {};
  23858. }
  23859. };
  23860. class LoadingManager {
  23861. constructor( onLoad, onProgress, onError ) {
  23862. const scope = this;
  23863. let isLoading = false;
  23864. let itemsLoaded = 0;
  23865. let itemsTotal = 0;
  23866. let urlModifier = undefined;
  23867. const handlers = [];
  23868. // Refer to #5689 for the reason why we don't set .onStart
  23869. // in the constructor
  23870. this.onStart = undefined;
  23871. this.onLoad = onLoad;
  23872. this.onProgress = onProgress;
  23873. this.onError = onError;
  23874. this.itemStart = function ( url ) {
  23875. itemsTotal ++;
  23876. if ( isLoading === false ) {
  23877. if ( scope.onStart !== undefined ) {
  23878. scope.onStart( url, itemsLoaded, itemsTotal );
  23879. }
  23880. }
  23881. isLoading = true;
  23882. };
  23883. this.itemEnd = function ( url ) {
  23884. itemsLoaded ++;
  23885. if ( scope.onProgress !== undefined ) {
  23886. scope.onProgress( url, itemsLoaded, itemsTotal );
  23887. }
  23888. if ( itemsLoaded === itemsTotal ) {
  23889. isLoading = false;
  23890. if ( scope.onLoad !== undefined ) {
  23891. scope.onLoad();
  23892. }
  23893. }
  23894. };
  23895. this.itemError = function ( url ) {
  23896. if ( scope.onError !== undefined ) {
  23897. scope.onError( url );
  23898. }
  23899. };
  23900. this.resolveURL = function ( url ) {
  23901. if ( urlModifier ) {
  23902. return urlModifier( url );
  23903. }
  23904. return url;
  23905. };
  23906. this.setURLModifier = function ( transform ) {
  23907. urlModifier = transform;
  23908. return this;
  23909. };
  23910. this.addHandler = function ( regex, loader ) {
  23911. handlers.push( regex, loader );
  23912. return this;
  23913. };
  23914. this.removeHandler = function ( regex ) {
  23915. const index = handlers.indexOf( regex );
  23916. if ( index !== - 1 ) {
  23917. handlers.splice( index, 2 );
  23918. }
  23919. return this;
  23920. };
  23921. this.getHandler = function ( file ) {
  23922. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  23923. const regex = handlers[ i ];
  23924. const loader = handlers[ i + 1 ];
  23925. if ( regex.global ) regex.lastIndex = 0; // see #17920
  23926. if ( regex.test( file ) ) {
  23927. return loader;
  23928. }
  23929. }
  23930. return null;
  23931. };
  23932. }
  23933. }
  23934. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  23935. class Loader {
  23936. constructor( manager ) {
  23937. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23938. this.crossOrigin = 'anonymous';
  23939. this.withCredentials = false;
  23940. this.path = '';
  23941. this.resourcePath = '';
  23942. this.requestHeader = {};
  23943. }
  23944. load( /* url, onLoad, onProgress, onError */ ) {}
  23945. loadAsync( url, onProgress ) {
  23946. const scope = this;
  23947. return new Promise( function ( resolve, reject ) {
  23948. scope.load( url, resolve, onProgress, reject );
  23949. } );
  23950. }
  23951. parse( /* data */ ) {}
  23952. setCrossOrigin( crossOrigin ) {
  23953. this.crossOrigin = crossOrigin;
  23954. return this;
  23955. }
  23956. setWithCredentials( value ) {
  23957. this.withCredentials = value;
  23958. return this;
  23959. }
  23960. setPath( path ) {
  23961. this.path = path;
  23962. return this;
  23963. }
  23964. setResourcePath( resourcePath ) {
  23965. this.resourcePath = resourcePath;
  23966. return this;
  23967. }
  23968. setRequestHeader( requestHeader ) {
  23969. this.requestHeader = requestHeader;
  23970. return this;
  23971. }
  23972. }
  23973. const loading = {};
  23974. class HttpError extends Error {
  23975. constructor( message, response ) {
  23976. super( message );
  23977. this.response = response;
  23978. }
  23979. }
  23980. class FileLoader extends Loader {
  23981. constructor( manager ) {
  23982. super( manager );
  23983. }
  23984. load( url, onLoad, onProgress, onError ) {
  23985. if ( url === undefined ) url = '';
  23986. if ( this.path !== undefined ) url = this.path + url;
  23987. url = this.manager.resolveURL( url );
  23988. const cached = Cache.get( url );
  23989. if ( cached !== undefined ) {
  23990. this.manager.itemStart( url );
  23991. setTimeout( () => {
  23992. if ( onLoad ) onLoad( cached );
  23993. this.manager.itemEnd( url );
  23994. }, 0 );
  23995. return cached;
  23996. }
  23997. // Check if request is duplicate
  23998. if ( loading[ url ] !== undefined ) {
  23999. loading[ url ].push( {
  24000. onLoad: onLoad,
  24001. onProgress: onProgress,
  24002. onError: onError
  24003. } );
  24004. return;
  24005. }
  24006. // Initialise array for duplicate requests
  24007. loading[ url ] = [];
  24008. loading[ url ].push( {
  24009. onLoad: onLoad,
  24010. onProgress: onProgress,
  24011. onError: onError,
  24012. } );
  24013. // create request
  24014. const req = new Request( url, {
  24015. headers: new Headers( this.requestHeader ),
  24016. credentials: this.withCredentials ? 'include' : 'same-origin',
  24017. // An abort controller could be added within a future PR
  24018. } );
  24019. // record states ( avoid data race )
  24020. const mimeType = this.mimeType;
  24021. const responseType = this.responseType;
  24022. // start the fetch
  24023. fetch( req )
  24024. .then( response => {
  24025. if ( response.status === 200 || response.status === 0 ) {
  24026. // Some browsers return HTTP Status 0 when using non-http protocol
  24027. // e.g. 'file://' or 'data://'. Handle as success.
  24028. if ( response.status === 0 ) {
  24029. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  24030. }
  24031. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  24032. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  24033. return response;
  24034. }
  24035. const callbacks = loading[ url ];
  24036. const reader = response.body.getReader();
  24037. // Nginx needs X-File-Size check
  24038. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  24039. const contentLength = response.headers.get( 'Content-Length' ) || response.headers.get( 'X-File-Size' );
  24040. const total = contentLength ? parseInt( contentLength ) : 0;
  24041. const lengthComputable = total !== 0;
  24042. let loaded = 0;
  24043. // periodically read data into the new stream tracking while download progress
  24044. const stream = new ReadableStream( {
  24045. start( controller ) {
  24046. readData();
  24047. function readData() {
  24048. reader.read().then( ( { done, value } ) => {
  24049. if ( done ) {
  24050. controller.close();
  24051. } else {
  24052. loaded += value.byteLength;
  24053. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  24054. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24055. const callback = callbacks[ i ];
  24056. if ( callback.onProgress ) callback.onProgress( event );
  24057. }
  24058. controller.enqueue( value );
  24059. readData();
  24060. }
  24061. } );
  24062. }
  24063. }
  24064. } );
  24065. return new Response( stream );
  24066. } else {
  24067. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  24068. }
  24069. } )
  24070. .then( response => {
  24071. switch ( responseType ) {
  24072. case 'arraybuffer':
  24073. return response.arrayBuffer();
  24074. case 'blob':
  24075. return response.blob();
  24076. case 'document':
  24077. return response.text()
  24078. .then( text => {
  24079. const parser = new DOMParser();
  24080. return parser.parseFromString( text, mimeType );
  24081. } );
  24082. case 'json':
  24083. return response.json();
  24084. default:
  24085. if ( mimeType === undefined ) {
  24086. return response.text();
  24087. } else {
  24088. // sniff encoding
  24089. const re = /charset="?([^;"\s]*)"?/i;
  24090. const exec = re.exec( mimeType );
  24091. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  24092. const decoder = new TextDecoder( label );
  24093. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  24094. }
  24095. }
  24096. } )
  24097. .then( data => {
  24098. // Add to cache only on HTTP success, so that we do not cache
  24099. // error response bodies as proper responses to requests.
  24100. Cache.add( url, data );
  24101. const callbacks = loading[ url ];
  24102. delete loading[ url ];
  24103. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24104. const callback = callbacks[ i ];
  24105. if ( callback.onLoad ) callback.onLoad( data );
  24106. }
  24107. } )
  24108. .catch( err => {
  24109. // Abort errors and other errors are handled the same
  24110. const callbacks = loading[ url ];
  24111. if ( callbacks === undefined ) {
  24112. // When onLoad was called and url was deleted in `loading`
  24113. this.manager.itemError( url );
  24114. throw err;
  24115. }
  24116. delete loading[ url ];
  24117. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24118. const callback = callbacks[ i ];
  24119. if ( callback.onError ) callback.onError( err );
  24120. }
  24121. this.manager.itemError( url );
  24122. } )
  24123. .finally( () => {
  24124. this.manager.itemEnd( url );
  24125. } );
  24126. this.manager.itemStart( url );
  24127. }
  24128. setResponseType( value ) {
  24129. this.responseType = value;
  24130. return this;
  24131. }
  24132. setMimeType( value ) {
  24133. this.mimeType = value;
  24134. return this;
  24135. }
  24136. }
  24137. class AnimationLoader extends Loader {
  24138. constructor( manager ) {
  24139. super( manager );
  24140. }
  24141. load( url, onLoad, onProgress, onError ) {
  24142. const scope = this;
  24143. const loader = new FileLoader( this.manager );
  24144. loader.setPath( this.path );
  24145. loader.setRequestHeader( this.requestHeader );
  24146. loader.setWithCredentials( this.withCredentials );
  24147. loader.load( url, function ( text ) {
  24148. try {
  24149. onLoad( scope.parse( JSON.parse( text ) ) );
  24150. } catch ( e ) {
  24151. if ( onError ) {
  24152. onError( e );
  24153. } else {
  24154. console.error( e );
  24155. }
  24156. scope.manager.itemError( url );
  24157. }
  24158. }, onProgress, onError );
  24159. }
  24160. parse( json ) {
  24161. const animations = [];
  24162. for ( let i = 0; i < json.length; i ++ ) {
  24163. const clip = AnimationClip.parse( json[ i ] );
  24164. animations.push( clip );
  24165. }
  24166. return animations;
  24167. }
  24168. }
  24169. /**
  24170. * Abstract Base class to block based textures loader (dds, pvr, ...)
  24171. *
  24172. * Sub classes have to implement the parse() method which will be used in load().
  24173. */
  24174. class CompressedTextureLoader extends Loader {
  24175. constructor( manager ) {
  24176. super( manager );
  24177. }
  24178. load( url, onLoad, onProgress, onError ) {
  24179. const scope = this;
  24180. const images = [];
  24181. const texture = new CompressedTexture();
  24182. const loader = new FileLoader( this.manager );
  24183. loader.setPath( this.path );
  24184. loader.setResponseType( 'arraybuffer' );
  24185. loader.setRequestHeader( this.requestHeader );
  24186. loader.setWithCredentials( scope.withCredentials );
  24187. let loaded = 0;
  24188. function loadTexture( i ) {
  24189. loader.load( url[ i ], function ( buffer ) {
  24190. const texDatas = scope.parse( buffer, true );
  24191. images[ i ] = {
  24192. width: texDatas.width,
  24193. height: texDatas.height,
  24194. format: texDatas.format,
  24195. mipmaps: texDatas.mipmaps
  24196. };
  24197. loaded += 1;
  24198. if ( loaded === 6 ) {
  24199. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  24200. texture.image = images;
  24201. texture.format = texDatas.format;
  24202. texture.needsUpdate = true;
  24203. if ( onLoad ) onLoad( texture );
  24204. }
  24205. }, onProgress, onError );
  24206. }
  24207. if ( Array.isArray( url ) ) {
  24208. for ( let i = 0, il = url.length; i < il; ++ i ) {
  24209. loadTexture( i );
  24210. }
  24211. } else {
  24212. // compressed cubemap texture stored in a single DDS file
  24213. loader.load( url, function ( buffer ) {
  24214. const texDatas = scope.parse( buffer, true );
  24215. if ( texDatas.isCubemap ) {
  24216. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  24217. for ( let f = 0; f < faces; f ++ ) {
  24218. images[ f ] = { mipmaps: [] };
  24219. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  24220. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  24221. images[ f ].format = texDatas.format;
  24222. images[ f ].width = texDatas.width;
  24223. images[ f ].height = texDatas.height;
  24224. }
  24225. }
  24226. texture.image = images;
  24227. } else {
  24228. texture.image.width = texDatas.width;
  24229. texture.image.height = texDatas.height;
  24230. texture.mipmaps = texDatas.mipmaps;
  24231. }
  24232. if ( texDatas.mipmapCount === 1 ) {
  24233. texture.minFilter = LinearFilter;
  24234. }
  24235. texture.format = texDatas.format;
  24236. texture.needsUpdate = true;
  24237. if ( onLoad ) onLoad( texture );
  24238. }, onProgress, onError );
  24239. }
  24240. return texture;
  24241. }
  24242. }
  24243. class ImageLoader extends Loader {
  24244. constructor( manager ) {
  24245. super( manager );
  24246. }
  24247. load( url, onLoad, onProgress, onError ) {
  24248. if ( this.path !== undefined ) url = this.path + url;
  24249. url = this.manager.resolveURL( url );
  24250. const scope = this;
  24251. const cached = Cache.get( url );
  24252. if ( cached !== undefined ) {
  24253. scope.manager.itemStart( url );
  24254. setTimeout( function () {
  24255. if ( onLoad ) onLoad( cached );
  24256. scope.manager.itemEnd( url );
  24257. }, 0 );
  24258. return cached;
  24259. }
  24260. const image = createElementNS( 'img' );
  24261. function onImageLoad() {
  24262. removeEventListeners();
  24263. Cache.add( url, this );
  24264. if ( onLoad ) onLoad( this );
  24265. scope.manager.itemEnd( url );
  24266. }
  24267. function onImageError( event ) {
  24268. removeEventListeners();
  24269. if ( onError ) onError( event );
  24270. scope.manager.itemError( url );
  24271. scope.manager.itemEnd( url );
  24272. }
  24273. function removeEventListeners() {
  24274. image.removeEventListener( 'load', onImageLoad, false );
  24275. image.removeEventListener( 'error', onImageError, false );
  24276. }
  24277. image.addEventListener( 'load', onImageLoad, false );
  24278. image.addEventListener( 'error', onImageError, false );
  24279. if ( url.slice( 0, 5 ) !== 'data:' ) {
  24280. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  24281. }
  24282. scope.manager.itemStart( url );
  24283. image.src = url;
  24284. return image;
  24285. }
  24286. }
  24287. class CubeTextureLoader extends Loader {
  24288. constructor( manager ) {
  24289. super( manager );
  24290. }
  24291. load( urls, onLoad, onProgress, onError ) {
  24292. const texture = new CubeTexture();
  24293. const loader = new ImageLoader( this.manager );
  24294. loader.setCrossOrigin( this.crossOrigin );
  24295. loader.setPath( this.path );
  24296. let loaded = 0;
  24297. function loadTexture( i ) {
  24298. loader.load( urls[ i ], function ( image ) {
  24299. texture.images[ i ] = image;
  24300. loaded ++;
  24301. if ( loaded === 6 ) {
  24302. texture.needsUpdate = true;
  24303. if ( onLoad ) onLoad( texture );
  24304. }
  24305. }, undefined, onError );
  24306. }
  24307. for ( let i = 0; i < urls.length; ++ i ) {
  24308. loadTexture( i );
  24309. }
  24310. return texture;
  24311. }
  24312. }
  24313. /**
  24314. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  24315. *
  24316. * Sub classes have to implement the parse() method which will be used in load().
  24317. */
  24318. class DataTextureLoader extends Loader {
  24319. constructor( manager ) {
  24320. super( manager );
  24321. }
  24322. load( url, onLoad, onProgress, onError ) {
  24323. const scope = this;
  24324. const texture = new DataTexture();
  24325. const loader = new FileLoader( this.manager );
  24326. loader.setResponseType( 'arraybuffer' );
  24327. loader.setRequestHeader( this.requestHeader );
  24328. loader.setPath( this.path );
  24329. loader.setWithCredentials( scope.withCredentials );
  24330. loader.load( url, function ( buffer ) {
  24331. const texData = scope.parse( buffer );
  24332. if ( ! texData ) return;
  24333. if ( texData.image !== undefined ) {
  24334. texture.image = texData.image;
  24335. } else if ( texData.data !== undefined ) {
  24336. texture.image.width = texData.width;
  24337. texture.image.height = texData.height;
  24338. texture.image.data = texData.data;
  24339. }
  24340. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  24341. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  24342. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  24343. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  24344. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  24345. if ( texData.encoding !== undefined ) {
  24346. texture.encoding = texData.encoding;
  24347. }
  24348. if ( texData.flipY !== undefined ) {
  24349. texture.flipY = texData.flipY;
  24350. }
  24351. if ( texData.format !== undefined ) {
  24352. texture.format = texData.format;
  24353. }
  24354. if ( texData.type !== undefined ) {
  24355. texture.type = texData.type;
  24356. }
  24357. if ( texData.mipmaps !== undefined ) {
  24358. texture.mipmaps = texData.mipmaps;
  24359. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  24360. }
  24361. if ( texData.mipmapCount === 1 ) {
  24362. texture.minFilter = LinearFilter;
  24363. }
  24364. if ( texData.generateMipmaps !== undefined ) {
  24365. texture.generateMipmaps = texData.generateMipmaps;
  24366. }
  24367. texture.needsUpdate = true;
  24368. if ( onLoad ) onLoad( texture, texData );
  24369. }, onProgress, onError );
  24370. return texture;
  24371. }
  24372. }
  24373. class TextureLoader extends Loader {
  24374. constructor( manager ) {
  24375. super( manager );
  24376. }
  24377. load( url, onLoad, onProgress, onError ) {
  24378. const texture = new Texture();
  24379. const loader = new ImageLoader( this.manager );
  24380. loader.setCrossOrigin( this.crossOrigin );
  24381. loader.setPath( this.path );
  24382. loader.load( url, function ( image ) {
  24383. texture.image = image;
  24384. texture.needsUpdate = true;
  24385. if ( onLoad !== undefined ) {
  24386. onLoad( texture );
  24387. }
  24388. }, onProgress, onError );
  24389. return texture;
  24390. }
  24391. }
  24392. class Light extends Object3D {
  24393. constructor( color, intensity = 1 ) {
  24394. super();
  24395. this.isLight = true;
  24396. this.type = 'Light';
  24397. this.color = new Color( color );
  24398. this.intensity = intensity;
  24399. }
  24400. dispose() {
  24401. // Empty here in base class; some subclasses override.
  24402. }
  24403. copy( source, recursive ) {
  24404. super.copy( source, recursive );
  24405. this.color.copy( source.color );
  24406. this.intensity = source.intensity;
  24407. return this;
  24408. }
  24409. toJSON( meta ) {
  24410. const data = super.toJSON( meta );
  24411. data.object.color = this.color.getHex();
  24412. data.object.intensity = this.intensity;
  24413. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  24414. if ( this.distance !== undefined ) data.object.distance = this.distance;
  24415. if ( this.angle !== undefined ) data.object.angle = this.angle;
  24416. if ( this.decay !== undefined ) data.object.decay = this.decay;
  24417. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  24418. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  24419. return data;
  24420. }
  24421. }
  24422. class HemisphereLight extends Light {
  24423. constructor( skyColor, groundColor, intensity ) {
  24424. super( skyColor, intensity );
  24425. this.isHemisphereLight = true;
  24426. this.type = 'HemisphereLight';
  24427. this.position.copy( Object3D.DEFAULT_UP );
  24428. this.updateMatrix();
  24429. this.groundColor = new Color( groundColor );
  24430. }
  24431. copy( source, recursive ) {
  24432. super.copy( source, recursive );
  24433. this.groundColor.copy( source.groundColor );
  24434. return this;
  24435. }
  24436. }
  24437. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  24438. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  24439. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  24440. class LightShadow {
  24441. constructor( camera ) {
  24442. this.camera = camera;
  24443. this.bias = 0;
  24444. this.normalBias = 0;
  24445. this.radius = 1;
  24446. this.blurSamples = 8;
  24447. this.mapSize = new Vector2( 512, 512 );
  24448. this.map = null;
  24449. this.mapPass = null;
  24450. this.matrix = new Matrix4();
  24451. this.autoUpdate = true;
  24452. this.needsUpdate = false;
  24453. this._frustum = new Frustum();
  24454. this._frameExtents = new Vector2( 1, 1 );
  24455. this._viewportCount = 1;
  24456. this._viewports = [
  24457. new Vector4( 0, 0, 1, 1 )
  24458. ];
  24459. }
  24460. getViewportCount() {
  24461. return this._viewportCount;
  24462. }
  24463. getFrustum() {
  24464. return this._frustum;
  24465. }
  24466. updateMatrices( light ) {
  24467. const shadowCamera = this.camera;
  24468. const shadowMatrix = this.matrix;
  24469. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  24470. shadowCamera.position.copy( _lightPositionWorld$1 );
  24471. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  24472. shadowCamera.lookAt( _lookTarget$1 );
  24473. shadowCamera.updateMatrixWorld();
  24474. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  24475. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  24476. shadowMatrix.set(
  24477. 0.5, 0.0, 0.0, 0.5,
  24478. 0.0, 0.5, 0.0, 0.5,
  24479. 0.0, 0.0, 0.5, 0.5,
  24480. 0.0, 0.0, 0.0, 1.0
  24481. );
  24482. shadowMatrix.multiply( _projScreenMatrix$1 );
  24483. }
  24484. getViewport( viewportIndex ) {
  24485. return this._viewports[ viewportIndex ];
  24486. }
  24487. getFrameExtents() {
  24488. return this._frameExtents;
  24489. }
  24490. dispose() {
  24491. if ( this.map ) {
  24492. this.map.dispose();
  24493. }
  24494. if ( this.mapPass ) {
  24495. this.mapPass.dispose();
  24496. }
  24497. }
  24498. copy( source ) {
  24499. this.camera = source.camera.clone();
  24500. this.bias = source.bias;
  24501. this.radius = source.radius;
  24502. this.mapSize.copy( source.mapSize );
  24503. return this;
  24504. }
  24505. clone() {
  24506. return new this.constructor().copy( this );
  24507. }
  24508. toJSON() {
  24509. const object = {};
  24510. if ( this.bias !== 0 ) object.bias = this.bias;
  24511. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  24512. if ( this.radius !== 1 ) object.radius = this.radius;
  24513. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  24514. object.camera = this.camera.toJSON( false ).object;
  24515. delete object.camera.matrix;
  24516. return object;
  24517. }
  24518. }
  24519. class SpotLightShadow extends LightShadow {
  24520. constructor() {
  24521. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  24522. this.isSpotLightShadow = true;
  24523. this.focus = 1;
  24524. }
  24525. updateMatrices( light ) {
  24526. const camera = this.camera;
  24527. const fov = RAD2DEG * 2 * light.angle * this.focus;
  24528. const aspect = this.mapSize.width / this.mapSize.height;
  24529. const far = light.distance || camera.far;
  24530. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  24531. camera.fov = fov;
  24532. camera.aspect = aspect;
  24533. camera.far = far;
  24534. camera.updateProjectionMatrix();
  24535. }
  24536. super.updateMatrices( light );
  24537. }
  24538. copy( source ) {
  24539. super.copy( source );
  24540. this.focus = source.focus;
  24541. return this;
  24542. }
  24543. }
  24544. class SpotLight extends Light {
  24545. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  24546. super( color, intensity );
  24547. this.isSpotLight = true;
  24548. this.type = 'SpotLight';
  24549. this.position.copy( Object3D.DEFAULT_UP );
  24550. this.updateMatrix();
  24551. this.target = new Object3D();
  24552. this.distance = distance;
  24553. this.angle = angle;
  24554. this.penumbra = penumbra;
  24555. this.decay = decay;
  24556. this.map = null;
  24557. this.shadow = new SpotLightShadow();
  24558. }
  24559. get power() {
  24560. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24561. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  24562. return this.intensity * Math.PI;
  24563. }
  24564. set power( power ) {
  24565. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24566. this.intensity = power / Math.PI;
  24567. }
  24568. dispose() {
  24569. this.shadow.dispose();
  24570. }
  24571. copy( source, recursive ) {
  24572. super.copy( source, recursive );
  24573. this.distance = source.distance;
  24574. this.angle = source.angle;
  24575. this.penumbra = source.penumbra;
  24576. this.decay = source.decay;
  24577. this.target = source.target.clone();
  24578. this.shadow = source.shadow.clone();
  24579. return this;
  24580. }
  24581. }
  24582. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  24583. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  24584. const _lookTarget = /*@__PURE__*/ new Vector3();
  24585. class PointLightShadow extends LightShadow {
  24586. constructor() {
  24587. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  24588. this.isPointLightShadow = true;
  24589. this._frameExtents = new Vector2( 4, 2 );
  24590. this._viewportCount = 6;
  24591. this._viewports = [
  24592. // These viewports map a cube-map onto a 2D texture with the
  24593. // following orientation:
  24594. //
  24595. // xzXZ
  24596. // y Y
  24597. //
  24598. // X - Positive x direction
  24599. // x - Negative x direction
  24600. // Y - Positive y direction
  24601. // y - Negative y direction
  24602. // Z - Positive z direction
  24603. // z - Negative z direction
  24604. // positive X
  24605. new Vector4( 2, 1, 1, 1 ),
  24606. // negative X
  24607. new Vector4( 0, 1, 1, 1 ),
  24608. // positive Z
  24609. new Vector4( 3, 1, 1, 1 ),
  24610. // negative Z
  24611. new Vector4( 1, 1, 1, 1 ),
  24612. // positive Y
  24613. new Vector4( 3, 0, 1, 1 ),
  24614. // negative Y
  24615. new Vector4( 1, 0, 1, 1 )
  24616. ];
  24617. this._cubeDirections = [
  24618. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  24619. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  24620. ];
  24621. this._cubeUps = [
  24622. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  24623. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  24624. ];
  24625. }
  24626. updateMatrices( light, viewportIndex = 0 ) {
  24627. const camera = this.camera;
  24628. const shadowMatrix = this.matrix;
  24629. const far = light.distance || camera.far;
  24630. if ( far !== camera.far ) {
  24631. camera.far = far;
  24632. camera.updateProjectionMatrix();
  24633. }
  24634. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  24635. camera.position.copy( _lightPositionWorld );
  24636. _lookTarget.copy( camera.position );
  24637. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  24638. camera.up.copy( this._cubeUps[ viewportIndex ] );
  24639. camera.lookAt( _lookTarget );
  24640. camera.updateMatrixWorld();
  24641. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  24642. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  24643. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  24644. }
  24645. }
  24646. class PointLight extends Light {
  24647. constructor( color, intensity, distance = 0, decay = 2 ) {
  24648. super( color, intensity );
  24649. this.isPointLight = true;
  24650. this.type = 'PointLight';
  24651. this.distance = distance;
  24652. this.decay = decay;
  24653. this.shadow = new PointLightShadow();
  24654. }
  24655. get power() {
  24656. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24657. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  24658. return this.intensity * 4 * Math.PI;
  24659. }
  24660. set power( power ) {
  24661. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24662. this.intensity = power / ( 4 * Math.PI );
  24663. }
  24664. dispose() {
  24665. this.shadow.dispose();
  24666. }
  24667. copy( source, recursive ) {
  24668. super.copy( source, recursive );
  24669. this.distance = source.distance;
  24670. this.decay = source.decay;
  24671. this.shadow = source.shadow.clone();
  24672. return this;
  24673. }
  24674. }
  24675. class DirectionalLightShadow extends LightShadow {
  24676. constructor() {
  24677. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  24678. this.isDirectionalLightShadow = true;
  24679. }
  24680. }
  24681. class DirectionalLight extends Light {
  24682. constructor( color, intensity ) {
  24683. super( color, intensity );
  24684. this.isDirectionalLight = true;
  24685. this.type = 'DirectionalLight';
  24686. this.position.copy( Object3D.DEFAULT_UP );
  24687. this.updateMatrix();
  24688. this.target = new Object3D();
  24689. this.shadow = new DirectionalLightShadow();
  24690. }
  24691. dispose() {
  24692. this.shadow.dispose();
  24693. }
  24694. copy( source ) {
  24695. super.copy( source );
  24696. this.target = source.target.clone();
  24697. this.shadow = source.shadow.clone();
  24698. return this;
  24699. }
  24700. }
  24701. class AmbientLight extends Light {
  24702. constructor( color, intensity ) {
  24703. super( color, intensity );
  24704. this.isAmbientLight = true;
  24705. this.type = 'AmbientLight';
  24706. }
  24707. }
  24708. class RectAreaLight extends Light {
  24709. constructor( color, intensity, width = 10, height = 10 ) {
  24710. super( color, intensity );
  24711. this.isRectAreaLight = true;
  24712. this.type = 'RectAreaLight';
  24713. this.width = width;
  24714. this.height = height;
  24715. }
  24716. get power() {
  24717. // compute the light's luminous power (in lumens) from its intensity (in nits)
  24718. return this.intensity * this.width * this.height * Math.PI;
  24719. }
  24720. set power( power ) {
  24721. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  24722. this.intensity = power / ( this.width * this.height * Math.PI );
  24723. }
  24724. copy( source ) {
  24725. super.copy( source );
  24726. this.width = source.width;
  24727. this.height = source.height;
  24728. return this;
  24729. }
  24730. toJSON( meta ) {
  24731. const data = super.toJSON( meta );
  24732. data.object.width = this.width;
  24733. data.object.height = this.height;
  24734. return data;
  24735. }
  24736. }
  24737. /**
  24738. * Primary reference:
  24739. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24740. *
  24741. * Secondary reference:
  24742. * https://www.ppsloan.org/publications/StupidSH36.pdf
  24743. */
  24744. // 3-band SH defined by 9 coefficients
  24745. class SphericalHarmonics3 {
  24746. constructor() {
  24747. this.isSphericalHarmonics3 = true;
  24748. this.coefficients = [];
  24749. for ( let i = 0; i < 9; i ++ ) {
  24750. this.coefficients.push( new Vector3() );
  24751. }
  24752. }
  24753. set( coefficients ) {
  24754. for ( let i = 0; i < 9; i ++ ) {
  24755. this.coefficients[ i ].copy( coefficients[ i ] );
  24756. }
  24757. return this;
  24758. }
  24759. zero() {
  24760. for ( let i = 0; i < 9; i ++ ) {
  24761. this.coefficients[ i ].set( 0, 0, 0 );
  24762. }
  24763. return this;
  24764. }
  24765. // get the radiance in the direction of the normal
  24766. // target is a Vector3
  24767. getAt( normal, target ) {
  24768. // normal is assumed to be unit length
  24769. const x = normal.x, y = normal.y, z = normal.z;
  24770. const coeff = this.coefficients;
  24771. // band 0
  24772. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  24773. // band 1
  24774. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  24775. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  24776. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  24777. // band 2
  24778. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  24779. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  24780. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  24781. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  24782. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  24783. return target;
  24784. }
  24785. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  24786. // target is a Vector3
  24787. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24788. getIrradianceAt( normal, target ) {
  24789. // normal is assumed to be unit length
  24790. const x = normal.x, y = normal.y, z = normal.z;
  24791. const coeff = this.coefficients;
  24792. // band 0
  24793. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  24794. // band 1
  24795. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  24796. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  24797. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  24798. // band 2
  24799. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  24800. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  24801. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  24802. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  24803. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  24804. return target;
  24805. }
  24806. add( sh ) {
  24807. for ( let i = 0; i < 9; i ++ ) {
  24808. this.coefficients[ i ].add( sh.coefficients[ i ] );
  24809. }
  24810. return this;
  24811. }
  24812. addScaledSH( sh, s ) {
  24813. for ( let i = 0; i < 9; i ++ ) {
  24814. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  24815. }
  24816. return this;
  24817. }
  24818. scale( s ) {
  24819. for ( let i = 0; i < 9; i ++ ) {
  24820. this.coefficients[ i ].multiplyScalar( s );
  24821. }
  24822. return this;
  24823. }
  24824. lerp( sh, alpha ) {
  24825. for ( let i = 0; i < 9; i ++ ) {
  24826. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  24827. }
  24828. return this;
  24829. }
  24830. equals( sh ) {
  24831. for ( let i = 0; i < 9; i ++ ) {
  24832. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  24833. return false;
  24834. }
  24835. }
  24836. return true;
  24837. }
  24838. copy( sh ) {
  24839. return this.set( sh.coefficients );
  24840. }
  24841. clone() {
  24842. return new this.constructor().copy( this );
  24843. }
  24844. fromArray( array, offset = 0 ) {
  24845. const coefficients = this.coefficients;
  24846. for ( let i = 0; i < 9; i ++ ) {
  24847. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  24848. }
  24849. return this;
  24850. }
  24851. toArray( array = [], offset = 0 ) {
  24852. const coefficients = this.coefficients;
  24853. for ( let i = 0; i < 9; i ++ ) {
  24854. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  24855. }
  24856. return array;
  24857. }
  24858. // evaluate the basis functions
  24859. // shBasis is an Array[ 9 ]
  24860. static getBasisAt( normal, shBasis ) {
  24861. // normal is assumed to be unit length
  24862. const x = normal.x, y = normal.y, z = normal.z;
  24863. // band 0
  24864. shBasis[ 0 ] = 0.282095;
  24865. // band 1
  24866. shBasis[ 1 ] = 0.488603 * y;
  24867. shBasis[ 2 ] = 0.488603 * z;
  24868. shBasis[ 3 ] = 0.488603 * x;
  24869. // band 2
  24870. shBasis[ 4 ] = 1.092548 * x * y;
  24871. shBasis[ 5 ] = 1.092548 * y * z;
  24872. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  24873. shBasis[ 7 ] = 1.092548 * x * z;
  24874. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  24875. }
  24876. }
  24877. class LightProbe extends Light {
  24878. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  24879. super( undefined, intensity );
  24880. this.isLightProbe = true;
  24881. this.sh = sh;
  24882. }
  24883. copy( source ) {
  24884. super.copy( source );
  24885. this.sh.copy( source.sh );
  24886. return this;
  24887. }
  24888. fromJSON( json ) {
  24889. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  24890. this.sh.fromArray( json.sh );
  24891. return this;
  24892. }
  24893. toJSON( meta ) {
  24894. const data = super.toJSON( meta );
  24895. data.object.sh = this.sh.toArray();
  24896. return data;
  24897. }
  24898. }
  24899. class MaterialLoader extends Loader {
  24900. constructor( manager ) {
  24901. super( manager );
  24902. this.textures = {};
  24903. }
  24904. load( url, onLoad, onProgress, onError ) {
  24905. const scope = this;
  24906. const loader = new FileLoader( scope.manager );
  24907. loader.setPath( scope.path );
  24908. loader.setRequestHeader( scope.requestHeader );
  24909. loader.setWithCredentials( scope.withCredentials );
  24910. loader.load( url, function ( text ) {
  24911. try {
  24912. onLoad( scope.parse( JSON.parse( text ) ) );
  24913. } catch ( e ) {
  24914. if ( onError ) {
  24915. onError( e );
  24916. } else {
  24917. console.error( e );
  24918. }
  24919. scope.manager.itemError( url );
  24920. }
  24921. }, onProgress, onError );
  24922. }
  24923. parse( json ) {
  24924. const textures = this.textures;
  24925. function getTexture( name ) {
  24926. if ( textures[ name ] === undefined ) {
  24927. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  24928. }
  24929. return textures[ name ];
  24930. }
  24931. const material = MaterialLoader.createMaterialFromType( json.type );
  24932. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  24933. if ( json.name !== undefined ) material.name = json.name;
  24934. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  24935. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  24936. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  24937. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  24938. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  24939. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  24940. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  24941. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  24942. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  24943. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  24944. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  24945. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  24946. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  24947. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  24948. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  24949. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  24950. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  24951. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  24952. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  24953. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  24954. if ( json.fog !== undefined ) material.fog = json.fog;
  24955. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  24956. if ( json.blending !== undefined ) material.blending = json.blending;
  24957. if ( json.combine !== undefined ) material.combine = json.combine;
  24958. if ( json.side !== undefined ) material.side = json.side;
  24959. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  24960. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  24961. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  24962. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  24963. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  24964. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  24965. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  24966. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  24967. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  24968. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  24969. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  24970. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  24971. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  24972. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  24973. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  24974. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  24975. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  24976. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  24977. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  24978. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  24979. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  24980. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  24981. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  24982. if ( json.scale !== undefined ) material.scale = json.scale;
  24983. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  24984. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  24985. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  24986. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  24987. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  24988. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  24989. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  24990. if ( json.visible !== undefined ) material.visible = json.visible;
  24991. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  24992. if ( json.userData !== undefined ) material.userData = json.userData;
  24993. if ( json.vertexColors !== undefined ) {
  24994. if ( typeof json.vertexColors === 'number' ) {
  24995. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  24996. } else {
  24997. material.vertexColors = json.vertexColors;
  24998. }
  24999. }
  25000. // Shader Material
  25001. if ( json.uniforms !== undefined ) {
  25002. for ( const name in json.uniforms ) {
  25003. const uniform = json.uniforms[ name ];
  25004. material.uniforms[ name ] = {};
  25005. switch ( uniform.type ) {
  25006. case 't':
  25007. material.uniforms[ name ].value = getTexture( uniform.value );
  25008. break;
  25009. case 'c':
  25010. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  25011. break;
  25012. case 'v2':
  25013. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  25014. break;
  25015. case 'v3':
  25016. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  25017. break;
  25018. case 'v4':
  25019. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  25020. break;
  25021. case 'm3':
  25022. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  25023. break;
  25024. case 'm4':
  25025. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  25026. break;
  25027. default:
  25028. material.uniforms[ name ].value = uniform.value;
  25029. }
  25030. }
  25031. }
  25032. if ( json.defines !== undefined ) material.defines = json.defines;
  25033. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  25034. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  25035. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  25036. if ( json.extensions !== undefined ) {
  25037. for ( const key in json.extensions ) {
  25038. material.extensions[ key ] = json.extensions[ key ];
  25039. }
  25040. }
  25041. // for PointsMaterial
  25042. if ( json.size !== undefined ) material.size = json.size;
  25043. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  25044. // maps
  25045. if ( json.map !== undefined ) material.map = getTexture( json.map );
  25046. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  25047. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  25048. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  25049. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  25050. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  25051. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  25052. if ( json.normalScale !== undefined ) {
  25053. let normalScale = json.normalScale;
  25054. if ( Array.isArray( normalScale ) === false ) {
  25055. // Blender exporter used to export a scalar. See #7459
  25056. normalScale = [ normalScale, normalScale ];
  25057. }
  25058. material.normalScale = new Vector2().fromArray( normalScale );
  25059. }
  25060. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  25061. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  25062. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  25063. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  25064. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  25065. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  25066. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  25067. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  25068. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  25069. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  25070. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  25071. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  25072. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  25073. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  25074. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  25075. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  25076. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  25077. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  25078. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  25079. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  25080. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  25081. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  25082. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  25083. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  25084. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  25085. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  25086. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  25087. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  25088. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  25089. return material;
  25090. }
  25091. setTextures( value ) {
  25092. this.textures = value;
  25093. return this;
  25094. }
  25095. static createMaterialFromType( type ) {
  25096. const materialLib = {
  25097. ShadowMaterial,
  25098. SpriteMaterial,
  25099. RawShaderMaterial,
  25100. ShaderMaterial,
  25101. PointsMaterial,
  25102. MeshPhysicalMaterial,
  25103. MeshStandardMaterial,
  25104. MeshPhongMaterial,
  25105. MeshToonMaterial,
  25106. MeshNormalMaterial,
  25107. MeshLambertMaterial,
  25108. MeshDepthMaterial,
  25109. MeshDistanceMaterial,
  25110. MeshBasicMaterial,
  25111. MeshMatcapMaterial,
  25112. LineDashedMaterial,
  25113. LineBasicMaterial,
  25114. Material
  25115. };
  25116. return new materialLib[ type ]();
  25117. }
  25118. }
  25119. class LoaderUtils {
  25120. static decodeText( array ) {
  25121. if ( typeof TextDecoder !== 'undefined' ) {
  25122. return new TextDecoder().decode( array );
  25123. }
  25124. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  25125. // throws a "maximum call stack size exceeded" error for large arrays.
  25126. let s = '';
  25127. for ( let i = 0, il = array.length; i < il; i ++ ) {
  25128. // Implicitly assumes little-endian.
  25129. s += String.fromCharCode( array[ i ] );
  25130. }
  25131. try {
  25132. // merges multi-byte utf-8 characters.
  25133. return decodeURIComponent( escape( s ) );
  25134. } catch ( e ) { // see #16358
  25135. return s;
  25136. }
  25137. }
  25138. static extractUrlBase( url ) {
  25139. const index = url.lastIndexOf( '/' );
  25140. if ( index === - 1 ) return './';
  25141. return url.slice( 0, index + 1 );
  25142. }
  25143. static resolveURL( url, path ) {
  25144. // Invalid URL
  25145. if ( typeof url !== 'string' || url === '' ) return '';
  25146. // Host Relative URL
  25147. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  25148. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  25149. }
  25150. // Absolute URL http://,https://,//
  25151. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  25152. // Data URI
  25153. if ( /^data:.*,.*$/i.test( url ) ) return url;
  25154. // Blob URL
  25155. if ( /^blob:.*$/i.test( url ) ) return url;
  25156. // Relative URL
  25157. return path + url;
  25158. }
  25159. }
  25160. class InstancedBufferGeometry extends BufferGeometry {
  25161. constructor() {
  25162. super();
  25163. this.isInstancedBufferGeometry = true;
  25164. this.type = 'InstancedBufferGeometry';
  25165. this.instanceCount = Infinity;
  25166. }
  25167. copy( source ) {
  25168. super.copy( source );
  25169. this.instanceCount = source.instanceCount;
  25170. return this;
  25171. }
  25172. toJSON() {
  25173. const data = super.toJSON();
  25174. data.instanceCount = this.instanceCount;
  25175. data.isInstancedBufferGeometry = true;
  25176. return data;
  25177. }
  25178. }
  25179. class BufferGeometryLoader extends Loader {
  25180. constructor( manager ) {
  25181. super( manager );
  25182. }
  25183. load( url, onLoad, onProgress, onError ) {
  25184. const scope = this;
  25185. const loader = new FileLoader( scope.manager );
  25186. loader.setPath( scope.path );
  25187. loader.setRequestHeader( scope.requestHeader );
  25188. loader.setWithCredentials( scope.withCredentials );
  25189. loader.load( url, function ( text ) {
  25190. try {
  25191. onLoad( scope.parse( JSON.parse( text ) ) );
  25192. } catch ( e ) {
  25193. if ( onError ) {
  25194. onError( e );
  25195. } else {
  25196. console.error( e );
  25197. }
  25198. scope.manager.itemError( url );
  25199. }
  25200. }, onProgress, onError );
  25201. }
  25202. parse( json ) {
  25203. const interleavedBufferMap = {};
  25204. const arrayBufferMap = {};
  25205. function getInterleavedBuffer( json, uuid ) {
  25206. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  25207. const interleavedBuffers = json.interleavedBuffers;
  25208. const interleavedBuffer = interleavedBuffers[ uuid ];
  25209. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  25210. const array = getTypedArray( interleavedBuffer.type, buffer );
  25211. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  25212. ib.uuid = interleavedBuffer.uuid;
  25213. interleavedBufferMap[ uuid ] = ib;
  25214. return ib;
  25215. }
  25216. function getArrayBuffer( json, uuid ) {
  25217. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  25218. const arrayBuffers = json.arrayBuffers;
  25219. const arrayBuffer = arrayBuffers[ uuid ];
  25220. const ab = new Uint32Array( arrayBuffer ).buffer;
  25221. arrayBufferMap[ uuid ] = ab;
  25222. return ab;
  25223. }
  25224. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  25225. const index = json.data.index;
  25226. if ( index !== undefined ) {
  25227. const typedArray = getTypedArray( index.type, index.array );
  25228. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  25229. }
  25230. const attributes = json.data.attributes;
  25231. for ( const key in attributes ) {
  25232. const attribute = attributes[ key ];
  25233. let bufferAttribute;
  25234. if ( attribute.isInterleavedBufferAttribute ) {
  25235. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25236. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25237. } else {
  25238. const typedArray = getTypedArray( attribute.type, attribute.array );
  25239. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  25240. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  25241. }
  25242. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25243. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  25244. if ( attribute.updateRange !== undefined ) {
  25245. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  25246. bufferAttribute.updateRange.count = attribute.updateRange.count;
  25247. }
  25248. geometry.setAttribute( key, bufferAttribute );
  25249. }
  25250. const morphAttributes = json.data.morphAttributes;
  25251. if ( morphAttributes ) {
  25252. for ( const key in morphAttributes ) {
  25253. const attributeArray = morphAttributes[ key ];
  25254. const array = [];
  25255. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  25256. const attribute = attributeArray[ i ];
  25257. let bufferAttribute;
  25258. if ( attribute.isInterleavedBufferAttribute ) {
  25259. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25260. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25261. } else {
  25262. const typedArray = getTypedArray( attribute.type, attribute.array );
  25263. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  25264. }
  25265. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25266. array.push( bufferAttribute );
  25267. }
  25268. geometry.morphAttributes[ key ] = array;
  25269. }
  25270. }
  25271. const morphTargetsRelative = json.data.morphTargetsRelative;
  25272. if ( morphTargetsRelative ) {
  25273. geometry.morphTargetsRelative = true;
  25274. }
  25275. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  25276. if ( groups !== undefined ) {
  25277. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  25278. const group = groups[ i ];
  25279. geometry.addGroup( group.start, group.count, group.materialIndex );
  25280. }
  25281. }
  25282. const boundingSphere = json.data.boundingSphere;
  25283. if ( boundingSphere !== undefined ) {
  25284. const center = new Vector3();
  25285. if ( boundingSphere.center !== undefined ) {
  25286. center.fromArray( boundingSphere.center );
  25287. }
  25288. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  25289. }
  25290. if ( json.name ) geometry.name = json.name;
  25291. if ( json.userData ) geometry.userData = json.userData;
  25292. return geometry;
  25293. }
  25294. }
  25295. class ObjectLoader extends Loader {
  25296. constructor( manager ) {
  25297. super( manager );
  25298. }
  25299. load( url, onLoad, onProgress, onError ) {
  25300. const scope = this;
  25301. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  25302. this.resourcePath = this.resourcePath || path;
  25303. const loader = new FileLoader( this.manager );
  25304. loader.setPath( this.path );
  25305. loader.setRequestHeader( this.requestHeader );
  25306. loader.setWithCredentials( this.withCredentials );
  25307. loader.load( url, function ( text ) {
  25308. let json = null;
  25309. try {
  25310. json = JSON.parse( text );
  25311. } catch ( error ) {
  25312. if ( onError !== undefined ) onError( error );
  25313. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  25314. return;
  25315. }
  25316. const metadata = json.metadata;
  25317. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  25318. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  25319. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  25320. return;
  25321. }
  25322. scope.parse( json, onLoad );
  25323. }, onProgress, onError );
  25324. }
  25325. async loadAsync( url, onProgress ) {
  25326. const scope = this;
  25327. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  25328. this.resourcePath = this.resourcePath || path;
  25329. const loader = new FileLoader( this.manager );
  25330. loader.setPath( this.path );
  25331. loader.setRequestHeader( this.requestHeader );
  25332. loader.setWithCredentials( this.withCredentials );
  25333. const text = await loader.loadAsync( url, onProgress );
  25334. const json = JSON.parse( text );
  25335. const metadata = json.metadata;
  25336. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  25337. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  25338. }
  25339. return await scope.parseAsync( json );
  25340. }
  25341. parse( json, onLoad ) {
  25342. const animations = this.parseAnimations( json.animations );
  25343. const shapes = this.parseShapes( json.shapes );
  25344. const geometries = this.parseGeometries( json.geometries, shapes );
  25345. const images = this.parseImages( json.images, function () {
  25346. if ( onLoad !== undefined ) onLoad( object );
  25347. } );
  25348. const textures = this.parseTextures( json.textures, images );
  25349. const materials = this.parseMaterials( json.materials, textures );
  25350. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  25351. const skeletons = this.parseSkeletons( json.skeletons, object );
  25352. this.bindSkeletons( object, skeletons );
  25353. //
  25354. if ( onLoad !== undefined ) {
  25355. let hasImages = false;
  25356. for ( const uuid in images ) {
  25357. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  25358. hasImages = true;
  25359. break;
  25360. }
  25361. }
  25362. if ( hasImages === false ) onLoad( object );
  25363. }
  25364. return object;
  25365. }
  25366. async parseAsync( json ) {
  25367. const animations = this.parseAnimations( json.animations );
  25368. const shapes = this.parseShapes( json.shapes );
  25369. const geometries = this.parseGeometries( json.geometries, shapes );
  25370. const images = await this.parseImagesAsync( json.images );
  25371. const textures = this.parseTextures( json.textures, images );
  25372. const materials = this.parseMaterials( json.materials, textures );
  25373. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  25374. const skeletons = this.parseSkeletons( json.skeletons, object );
  25375. this.bindSkeletons( object, skeletons );
  25376. return object;
  25377. }
  25378. parseShapes( json ) {
  25379. const shapes = {};
  25380. if ( json !== undefined ) {
  25381. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25382. const shape = new Shape().fromJSON( json[ i ] );
  25383. shapes[ shape.uuid ] = shape;
  25384. }
  25385. }
  25386. return shapes;
  25387. }
  25388. parseSkeletons( json, object ) {
  25389. const skeletons = {};
  25390. const bones = {};
  25391. // generate bone lookup table
  25392. object.traverse( function ( child ) {
  25393. if ( child.isBone ) bones[ child.uuid ] = child;
  25394. } );
  25395. // create skeletons
  25396. if ( json !== undefined ) {
  25397. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25398. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  25399. skeletons[ skeleton.uuid ] = skeleton;
  25400. }
  25401. }
  25402. return skeletons;
  25403. }
  25404. parseGeometries( json, shapes ) {
  25405. const geometries = {};
  25406. if ( json !== undefined ) {
  25407. const bufferGeometryLoader = new BufferGeometryLoader();
  25408. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25409. let geometry;
  25410. const data = json[ i ];
  25411. switch ( data.type ) {
  25412. case 'BufferGeometry':
  25413. case 'InstancedBufferGeometry':
  25414. geometry = bufferGeometryLoader.parse( data );
  25415. break;
  25416. default:
  25417. if ( data.type in Geometries ) {
  25418. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  25419. } else {
  25420. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  25421. }
  25422. }
  25423. geometry.uuid = data.uuid;
  25424. if ( data.name !== undefined ) geometry.name = data.name;
  25425. if ( data.userData !== undefined ) geometry.userData = data.userData;
  25426. geometries[ data.uuid ] = geometry;
  25427. }
  25428. }
  25429. return geometries;
  25430. }
  25431. parseMaterials( json, textures ) {
  25432. const cache = {}; // MultiMaterial
  25433. const materials = {};
  25434. if ( json !== undefined ) {
  25435. const loader = new MaterialLoader();
  25436. loader.setTextures( textures );
  25437. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25438. const data = json[ i ];
  25439. if ( cache[ data.uuid ] === undefined ) {
  25440. cache[ data.uuid ] = loader.parse( data );
  25441. }
  25442. materials[ data.uuid ] = cache[ data.uuid ];
  25443. }
  25444. }
  25445. return materials;
  25446. }
  25447. parseAnimations( json ) {
  25448. const animations = {};
  25449. if ( json !== undefined ) {
  25450. for ( let i = 0; i < json.length; i ++ ) {
  25451. const data = json[ i ];
  25452. const clip = AnimationClip.parse( data );
  25453. animations[ clip.uuid ] = clip;
  25454. }
  25455. }
  25456. return animations;
  25457. }
  25458. parseImages( json, onLoad ) {
  25459. const scope = this;
  25460. const images = {};
  25461. let loader;
  25462. function loadImage( url ) {
  25463. scope.manager.itemStart( url );
  25464. return loader.load( url, function () {
  25465. scope.manager.itemEnd( url );
  25466. }, undefined, function () {
  25467. scope.manager.itemError( url );
  25468. scope.manager.itemEnd( url );
  25469. } );
  25470. }
  25471. function deserializeImage( image ) {
  25472. if ( typeof image === 'string' ) {
  25473. const url = image;
  25474. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25475. return loadImage( path );
  25476. } else {
  25477. if ( image.data ) {
  25478. return {
  25479. data: getTypedArray( image.type, image.data ),
  25480. width: image.width,
  25481. height: image.height
  25482. };
  25483. } else {
  25484. return null;
  25485. }
  25486. }
  25487. }
  25488. if ( json !== undefined && json.length > 0 ) {
  25489. const manager = new LoadingManager( onLoad );
  25490. loader = new ImageLoader( manager );
  25491. loader.setCrossOrigin( this.crossOrigin );
  25492. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25493. const image = json[ i ];
  25494. const url = image.url;
  25495. if ( Array.isArray( url ) ) {
  25496. // load array of images e.g CubeTexture
  25497. const imageArray = [];
  25498. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25499. const currentUrl = url[ j ];
  25500. const deserializedImage = deserializeImage( currentUrl );
  25501. if ( deserializedImage !== null ) {
  25502. if ( deserializedImage instanceof HTMLImageElement ) {
  25503. imageArray.push( deserializedImage );
  25504. } else {
  25505. // special case: handle array of data textures for cube textures
  25506. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25507. }
  25508. }
  25509. }
  25510. images[ image.uuid ] = new Source( imageArray );
  25511. } else {
  25512. // load single image
  25513. const deserializedImage = deserializeImage( image.url );
  25514. images[ image.uuid ] = new Source( deserializedImage );
  25515. }
  25516. }
  25517. }
  25518. return images;
  25519. }
  25520. async parseImagesAsync( json ) {
  25521. const scope = this;
  25522. const images = {};
  25523. let loader;
  25524. async function deserializeImage( image ) {
  25525. if ( typeof image === 'string' ) {
  25526. const url = image;
  25527. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25528. return await loader.loadAsync( path );
  25529. } else {
  25530. if ( image.data ) {
  25531. return {
  25532. data: getTypedArray( image.type, image.data ),
  25533. width: image.width,
  25534. height: image.height
  25535. };
  25536. } else {
  25537. return null;
  25538. }
  25539. }
  25540. }
  25541. if ( json !== undefined && json.length > 0 ) {
  25542. loader = new ImageLoader( this.manager );
  25543. loader.setCrossOrigin( this.crossOrigin );
  25544. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25545. const image = json[ i ];
  25546. const url = image.url;
  25547. if ( Array.isArray( url ) ) {
  25548. // load array of images e.g CubeTexture
  25549. const imageArray = [];
  25550. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25551. const currentUrl = url[ j ];
  25552. const deserializedImage = await deserializeImage( currentUrl );
  25553. if ( deserializedImage !== null ) {
  25554. if ( deserializedImage instanceof HTMLImageElement ) {
  25555. imageArray.push( deserializedImage );
  25556. } else {
  25557. // special case: handle array of data textures for cube textures
  25558. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25559. }
  25560. }
  25561. }
  25562. images[ image.uuid ] = new Source( imageArray );
  25563. } else {
  25564. // load single image
  25565. const deserializedImage = await deserializeImage( image.url );
  25566. images[ image.uuid ] = new Source( deserializedImage );
  25567. }
  25568. }
  25569. }
  25570. return images;
  25571. }
  25572. parseTextures( json, images ) {
  25573. function parseConstant( value, type ) {
  25574. if ( typeof value === 'number' ) return value;
  25575. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  25576. return type[ value ];
  25577. }
  25578. const textures = {};
  25579. if ( json !== undefined ) {
  25580. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25581. const data = json[ i ];
  25582. if ( data.image === undefined ) {
  25583. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  25584. }
  25585. if ( images[ data.image ] === undefined ) {
  25586. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  25587. }
  25588. const source = images[ data.image ];
  25589. const image = source.data;
  25590. let texture;
  25591. if ( Array.isArray( image ) ) {
  25592. texture = new CubeTexture();
  25593. if ( image.length === 6 ) texture.needsUpdate = true;
  25594. } else {
  25595. if ( image && image.data ) {
  25596. texture = new DataTexture();
  25597. } else {
  25598. texture = new Texture();
  25599. }
  25600. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  25601. }
  25602. texture.source = source;
  25603. texture.uuid = data.uuid;
  25604. if ( data.name !== undefined ) texture.name = data.name;
  25605. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  25606. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  25607. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  25608. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  25609. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  25610. if ( data.wrap !== undefined ) {
  25611. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  25612. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  25613. }
  25614. if ( data.format !== undefined ) texture.format = data.format;
  25615. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  25616. if ( data.type !== undefined ) texture.type = data.type;
  25617. if ( data.encoding !== undefined ) texture.encoding = data.encoding;
  25618. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  25619. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  25620. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  25621. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  25622. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  25623. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  25624. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  25625. if ( data.userData !== undefined ) texture.userData = data.userData;
  25626. textures[ data.uuid ] = texture;
  25627. }
  25628. }
  25629. return textures;
  25630. }
  25631. parseObject( data, geometries, materials, textures, animations ) {
  25632. let object;
  25633. function getGeometry( name ) {
  25634. if ( geometries[ name ] === undefined ) {
  25635. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  25636. }
  25637. return geometries[ name ];
  25638. }
  25639. function getMaterial( name ) {
  25640. if ( name === undefined ) return undefined;
  25641. if ( Array.isArray( name ) ) {
  25642. const array = [];
  25643. for ( let i = 0, l = name.length; i < l; i ++ ) {
  25644. const uuid = name[ i ];
  25645. if ( materials[ uuid ] === undefined ) {
  25646. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  25647. }
  25648. array.push( materials[ uuid ] );
  25649. }
  25650. return array;
  25651. }
  25652. if ( materials[ name ] === undefined ) {
  25653. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  25654. }
  25655. return materials[ name ];
  25656. }
  25657. function getTexture( uuid ) {
  25658. if ( textures[ uuid ] === undefined ) {
  25659. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  25660. }
  25661. return textures[ uuid ];
  25662. }
  25663. let geometry, material;
  25664. switch ( data.type ) {
  25665. case 'Scene':
  25666. object = new Scene();
  25667. if ( data.background !== undefined ) {
  25668. if ( Number.isInteger( data.background ) ) {
  25669. object.background = new Color( data.background );
  25670. } else {
  25671. object.background = getTexture( data.background );
  25672. }
  25673. }
  25674. if ( data.environment !== undefined ) {
  25675. object.environment = getTexture( data.environment );
  25676. }
  25677. if ( data.fog !== undefined ) {
  25678. if ( data.fog.type === 'Fog' ) {
  25679. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  25680. } else if ( data.fog.type === 'FogExp2' ) {
  25681. object.fog = new FogExp2( data.fog.color, data.fog.density );
  25682. }
  25683. }
  25684. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  25685. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  25686. break;
  25687. case 'PerspectiveCamera':
  25688. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  25689. if ( data.focus !== undefined ) object.focus = data.focus;
  25690. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25691. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  25692. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  25693. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25694. break;
  25695. case 'OrthographicCamera':
  25696. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  25697. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25698. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25699. break;
  25700. case 'AmbientLight':
  25701. object = new AmbientLight( data.color, data.intensity );
  25702. break;
  25703. case 'DirectionalLight':
  25704. object = new DirectionalLight( data.color, data.intensity );
  25705. break;
  25706. case 'PointLight':
  25707. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  25708. break;
  25709. case 'RectAreaLight':
  25710. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  25711. break;
  25712. case 'SpotLight':
  25713. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  25714. break;
  25715. case 'HemisphereLight':
  25716. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  25717. break;
  25718. case 'LightProbe':
  25719. object = new LightProbe().fromJSON( data );
  25720. break;
  25721. case 'SkinnedMesh':
  25722. geometry = getGeometry( data.geometry );
  25723. material = getMaterial( data.material );
  25724. object = new SkinnedMesh( geometry, material );
  25725. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  25726. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  25727. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  25728. break;
  25729. case 'Mesh':
  25730. geometry = getGeometry( data.geometry );
  25731. material = getMaterial( data.material );
  25732. object = new Mesh( geometry, material );
  25733. break;
  25734. case 'InstancedMesh':
  25735. geometry = getGeometry( data.geometry );
  25736. material = getMaterial( data.material );
  25737. const count = data.count;
  25738. const instanceMatrix = data.instanceMatrix;
  25739. const instanceColor = data.instanceColor;
  25740. object = new InstancedMesh( geometry, material, count );
  25741. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  25742. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  25743. break;
  25744. case 'LOD':
  25745. object = new LOD();
  25746. break;
  25747. case 'Line':
  25748. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  25749. break;
  25750. case 'LineLoop':
  25751. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  25752. break;
  25753. case 'LineSegments':
  25754. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  25755. break;
  25756. case 'PointCloud':
  25757. case 'Points':
  25758. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  25759. break;
  25760. case 'Sprite':
  25761. object = new Sprite( getMaterial( data.material ) );
  25762. break;
  25763. case 'Group':
  25764. object = new Group();
  25765. break;
  25766. case 'Bone':
  25767. object = new Bone();
  25768. break;
  25769. default:
  25770. object = new Object3D();
  25771. }
  25772. object.uuid = data.uuid;
  25773. if ( data.name !== undefined ) object.name = data.name;
  25774. if ( data.matrix !== undefined ) {
  25775. object.matrix.fromArray( data.matrix );
  25776. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  25777. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  25778. } else {
  25779. if ( data.position !== undefined ) object.position.fromArray( data.position );
  25780. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  25781. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  25782. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  25783. }
  25784. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  25785. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  25786. if ( data.shadow ) {
  25787. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  25788. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  25789. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  25790. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  25791. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  25792. }
  25793. if ( data.visible !== undefined ) object.visible = data.visible;
  25794. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  25795. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  25796. if ( data.userData !== undefined ) object.userData = data.userData;
  25797. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  25798. if ( data.children !== undefined ) {
  25799. const children = data.children;
  25800. for ( let i = 0; i < children.length; i ++ ) {
  25801. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  25802. }
  25803. }
  25804. if ( data.animations !== undefined ) {
  25805. const objectAnimations = data.animations;
  25806. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  25807. const uuid = objectAnimations[ i ];
  25808. object.animations.push( animations[ uuid ] );
  25809. }
  25810. }
  25811. if ( data.type === 'LOD' ) {
  25812. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  25813. const levels = data.levels;
  25814. for ( let l = 0; l < levels.length; l ++ ) {
  25815. const level = levels[ l ];
  25816. const child = object.getObjectByProperty( 'uuid', level.object );
  25817. if ( child !== undefined ) {
  25818. object.addLevel( child, level.distance, level.hysteresis );
  25819. }
  25820. }
  25821. }
  25822. return object;
  25823. }
  25824. bindSkeletons( object, skeletons ) {
  25825. if ( Object.keys( skeletons ).length === 0 ) return;
  25826. object.traverse( function ( child ) {
  25827. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  25828. const skeleton = skeletons[ child.skeleton ];
  25829. if ( skeleton === undefined ) {
  25830. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  25831. } else {
  25832. child.bind( skeleton, child.bindMatrix );
  25833. }
  25834. }
  25835. } );
  25836. }
  25837. }
  25838. const TEXTURE_MAPPING = {
  25839. UVMapping: UVMapping,
  25840. CubeReflectionMapping: CubeReflectionMapping,
  25841. CubeRefractionMapping: CubeRefractionMapping,
  25842. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  25843. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  25844. CubeUVReflectionMapping: CubeUVReflectionMapping
  25845. };
  25846. const TEXTURE_WRAPPING = {
  25847. RepeatWrapping: RepeatWrapping,
  25848. ClampToEdgeWrapping: ClampToEdgeWrapping,
  25849. MirroredRepeatWrapping: MirroredRepeatWrapping
  25850. };
  25851. const TEXTURE_FILTER = {
  25852. NearestFilter: NearestFilter,
  25853. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  25854. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  25855. LinearFilter: LinearFilter,
  25856. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  25857. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  25858. };
  25859. class ImageBitmapLoader extends Loader {
  25860. constructor( manager ) {
  25861. super( manager );
  25862. this.isImageBitmapLoader = true;
  25863. if ( typeof createImageBitmap === 'undefined' ) {
  25864. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  25865. }
  25866. if ( typeof fetch === 'undefined' ) {
  25867. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  25868. }
  25869. this.options = { premultiplyAlpha: 'none' };
  25870. }
  25871. setOptions( options ) {
  25872. this.options = options;
  25873. return this;
  25874. }
  25875. load( url, onLoad, onProgress, onError ) {
  25876. if ( url === undefined ) url = '';
  25877. if ( this.path !== undefined ) url = this.path + url;
  25878. url = this.manager.resolveURL( url );
  25879. const scope = this;
  25880. const cached = Cache.get( url );
  25881. if ( cached !== undefined ) {
  25882. scope.manager.itemStart( url );
  25883. setTimeout( function () {
  25884. if ( onLoad ) onLoad( cached );
  25885. scope.manager.itemEnd( url );
  25886. }, 0 );
  25887. return cached;
  25888. }
  25889. const fetchOptions = {};
  25890. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  25891. fetchOptions.headers = this.requestHeader;
  25892. fetch( url, fetchOptions ).then( function ( res ) {
  25893. return res.blob();
  25894. } ).then( function ( blob ) {
  25895. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  25896. } ).then( function ( imageBitmap ) {
  25897. Cache.add( url, imageBitmap );
  25898. if ( onLoad ) onLoad( imageBitmap );
  25899. scope.manager.itemEnd( url );
  25900. } ).catch( function ( e ) {
  25901. if ( onError ) onError( e );
  25902. scope.manager.itemError( url );
  25903. scope.manager.itemEnd( url );
  25904. } );
  25905. scope.manager.itemStart( url );
  25906. }
  25907. }
  25908. let _context;
  25909. class AudioContext {
  25910. static getContext() {
  25911. if ( _context === undefined ) {
  25912. _context = new ( window.AudioContext || window.webkitAudioContext )();
  25913. }
  25914. return _context;
  25915. }
  25916. static setContext( value ) {
  25917. _context = value;
  25918. }
  25919. }
  25920. class AudioLoader extends Loader {
  25921. constructor( manager ) {
  25922. super( manager );
  25923. }
  25924. load( url, onLoad, onProgress, onError ) {
  25925. const scope = this;
  25926. const loader = new FileLoader( this.manager );
  25927. loader.setResponseType( 'arraybuffer' );
  25928. loader.setPath( this.path );
  25929. loader.setRequestHeader( this.requestHeader );
  25930. loader.setWithCredentials( this.withCredentials );
  25931. loader.load( url, function ( buffer ) {
  25932. try {
  25933. // Create a copy of the buffer. The `decodeAudioData` method
  25934. // detaches the buffer when complete, preventing reuse.
  25935. const bufferCopy = buffer.slice( 0 );
  25936. const context = AudioContext.getContext();
  25937. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  25938. onLoad( audioBuffer );
  25939. } );
  25940. } catch ( e ) {
  25941. if ( onError ) {
  25942. onError( e );
  25943. } else {
  25944. console.error( e );
  25945. }
  25946. scope.manager.itemError( url );
  25947. }
  25948. }, onProgress, onError );
  25949. }
  25950. }
  25951. class HemisphereLightProbe extends LightProbe {
  25952. constructor( skyColor, groundColor, intensity = 1 ) {
  25953. super( undefined, intensity );
  25954. this.isHemisphereLightProbe = true;
  25955. const color1 = new Color().set( skyColor );
  25956. const color2 = new Color().set( groundColor );
  25957. const sky = new Vector3( color1.r, color1.g, color1.b );
  25958. const ground = new Vector3( color2.r, color2.g, color2.b );
  25959. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  25960. const c0 = Math.sqrt( Math.PI );
  25961. const c1 = c0 * Math.sqrt( 0.75 );
  25962. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  25963. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  25964. }
  25965. }
  25966. class AmbientLightProbe extends LightProbe {
  25967. constructor( color, intensity = 1 ) {
  25968. super( undefined, intensity );
  25969. this.isAmbientLightProbe = true;
  25970. const color1 = new Color().set( color );
  25971. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  25972. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  25973. }
  25974. }
  25975. const _eyeRight = /*@__PURE__*/ new Matrix4();
  25976. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  25977. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  25978. class StereoCamera {
  25979. constructor() {
  25980. this.type = 'StereoCamera';
  25981. this.aspect = 1;
  25982. this.eyeSep = 0.064;
  25983. this.cameraL = new PerspectiveCamera();
  25984. this.cameraL.layers.enable( 1 );
  25985. this.cameraL.matrixAutoUpdate = false;
  25986. this.cameraR = new PerspectiveCamera();
  25987. this.cameraR.layers.enable( 2 );
  25988. this.cameraR.matrixAutoUpdate = false;
  25989. this._cache = {
  25990. focus: null,
  25991. fov: null,
  25992. aspect: null,
  25993. near: null,
  25994. far: null,
  25995. zoom: null,
  25996. eyeSep: null
  25997. };
  25998. }
  25999. update( camera ) {
  26000. const cache = this._cache;
  26001. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  26002. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  26003. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  26004. if ( needsUpdate ) {
  26005. cache.focus = camera.focus;
  26006. cache.fov = camera.fov;
  26007. cache.aspect = camera.aspect * this.aspect;
  26008. cache.near = camera.near;
  26009. cache.far = camera.far;
  26010. cache.zoom = camera.zoom;
  26011. cache.eyeSep = this.eyeSep;
  26012. // Off-axis stereoscopic effect based on
  26013. // http://paulbourke.net/stereographics/stereorender/
  26014. _projectionMatrix.copy( camera.projectionMatrix );
  26015. const eyeSepHalf = cache.eyeSep / 2;
  26016. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  26017. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  26018. let xmin, xmax;
  26019. // translate xOffset
  26020. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  26021. _eyeRight.elements[ 12 ] = eyeSepHalf;
  26022. // for left eye
  26023. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  26024. xmax = ymax * cache.aspect + eyeSepOnProjection;
  26025. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  26026. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26027. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  26028. // for right eye
  26029. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  26030. xmax = ymax * cache.aspect - eyeSepOnProjection;
  26031. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  26032. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26033. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  26034. }
  26035. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  26036. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  26037. }
  26038. }
  26039. class Clock {
  26040. constructor( autoStart = true ) {
  26041. this.autoStart = autoStart;
  26042. this.startTime = 0;
  26043. this.oldTime = 0;
  26044. this.elapsedTime = 0;
  26045. this.running = false;
  26046. }
  26047. start() {
  26048. this.startTime = now();
  26049. this.oldTime = this.startTime;
  26050. this.elapsedTime = 0;
  26051. this.running = true;
  26052. }
  26053. stop() {
  26054. this.getElapsedTime();
  26055. this.running = false;
  26056. this.autoStart = false;
  26057. }
  26058. getElapsedTime() {
  26059. this.getDelta();
  26060. return this.elapsedTime;
  26061. }
  26062. getDelta() {
  26063. let diff = 0;
  26064. if ( this.autoStart && ! this.running ) {
  26065. this.start();
  26066. return 0;
  26067. }
  26068. if ( this.running ) {
  26069. const newTime = now();
  26070. diff = ( newTime - this.oldTime ) / 1000;
  26071. this.oldTime = newTime;
  26072. this.elapsedTime += diff;
  26073. }
  26074. return diff;
  26075. }
  26076. }
  26077. function now() {
  26078. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  26079. }
  26080. const _position$1 = /*@__PURE__*/ new Vector3();
  26081. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  26082. const _scale$1 = /*@__PURE__*/ new Vector3();
  26083. const _orientation$1 = /*@__PURE__*/ new Vector3();
  26084. class AudioListener extends Object3D {
  26085. constructor() {
  26086. super();
  26087. this.type = 'AudioListener';
  26088. this.context = AudioContext.getContext();
  26089. this.gain = this.context.createGain();
  26090. this.gain.connect( this.context.destination );
  26091. this.filter = null;
  26092. this.timeDelta = 0;
  26093. // private
  26094. this._clock = new Clock();
  26095. }
  26096. getInput() {
  26097. return this.gain;
  26098. }
  26099. removeFilter() {
  26100. if ( this.filter !== null ) {
  26101. this.gain.disconnect( this.filter );
  26102. this.filter.disconnect( this.context.destination );
  26103. this.gain.connect( this.context.destination );
  26104. this.filter = null;
  26105. }
  26106. return this;
  26107. }
  26108. getFilter() {
  26109. return this.filter;
  26110. }
  26111. setFilter( value ) {
  26112. if ( this.filter !== null ) {
  26113. this.gain.disconnect( this.filter );
  26114. this.filter.disconnect( this.context.destination );
  26115. } else {
  26116. this.gain.disconnect( this.context.destination );
  26117. }
  26118. this.filter = value;
  26119. this.gain.connect( this.filter );
  26120. this.filter.connect( this.context.destination );
  26121. return this;
  26122. }
  26123. getMasterVolume() {
  26124. return this.gain.gain.value;
  26125. }
  26126. setMasterVolume( value ) {
  26127. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26128. return this;
  26129. }
  26130. updateMatrixWorld( force ) {
  26131. super.updateMatrixWorld( force );
  26132. const listener = this.context.listener;
  26133. const up = this.up;
  26134. this.timeDelta = this._clock.getDelta();
  26135. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  26136. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  26137. if ( listener.positionX ) {
  26138. // code path for Chrome (see #14393)
  26139. const endTime = this.context.currentTime + this.timeDelta;
  26140. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  26141. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  26142. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  26143. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  26144. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  26145. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  26146. listener.upX.linearRampToValueAtTime( up.x, endTime );
  26147. listener.upY.linearRampToValueAtTime( up.y, endTime );
  26148. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  26149. } else {
  26150. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  26151. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  26152. }
  26153. }
  26154. }
  26155. class Audio extends Object3D {
  26156. constructor( listener ) {
  26157. super();
  26158. this.type = 'Audio';
  26159. this.listener = listener;
  26160. this.context = listener.context;
  26161. this.gain = this.context.createGain();
  26162. this.gain.connect( listener.getInput() );
  26163. this.autoplay = false;
  26164. this.buffer = null;
  26165. this.detune = 0;
  26166. this.loop = false;
  26167. this.loopStart = 0;
  26168. this.loopEnd = 0;
  26169. this.offset = 0;
  26170. this.duration = undefined;
  26171. this.playbackRate = 1;
  26172. this.isPlaying = false;
  26173. this.hasPlaybackControl = true;
  26174. this.source = null;
  26175. this.sourceType = 'empty';
  26176. this._startedAt = 0;
  26177. this._progress = 0;
  26178. this._connected = false;
  26179. this.filters = [];
  26180. }
  26181. getOutput() {
  26182. return this.gain;
  26183. }
  26184. setNodeSource( audioNode ) {
  26185. this.hasPlaybackControl = false;
  26186. this.sourceType = 'audioNode';
  26187. this.source = audioNode;
  26188. this.connect();
  26189. return this;
  26190. }
  26191. setMediaElementSource( mediaElement ) {
  26192. this.hasPlaybackControl = false;
  26193. this.sourceType = 'mediaNode';
  26194. this.source = this.context.createMediaElementSource( mediaElement );
  26195. this.connect();
  26196. return this;
  26197. }
  26198. setMediaStreamSource( mediaStream ) {
  26199. this.hasPlaybackControl = false;
  26200. this.sourceType = 'mediaStreamNode';
  26201. this.source = this.context.createMediaStreamSource( mediaStream );
  26202. this.connect();
  26203. return this;
  26204. }
  26205. setBuffer( audioBuffer ) {
  26206. this.buffer = audioBuffer;
  26207. this.sourceType = 'buffer';
  26208. if ( this.autoplay ) this.play();
  26209. return this;
  26210. }
  26211. play( delay = 0 ) {
  26212. if ( this.isPlaying === true ) {
  26213. console.warn( 'THREE.Audio: Audio is already playing.' );
  26214. return;
  26215. }
  26216. if ( this.hasPlaybackControl === false ) {
  26217. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26218. return;
  26219. }
  26220. this._startedAt = this.context.currentTime + delay;
  26221. const source = this.context.createBufferSource();
  26222. source.buffer = this.buffer;
  26223. source.loop = this.loop;
  26224. source.loopStart = this.loopStart;
  26225. source.loopEnd = this.loopEnd;
  26226. source.onended = this.onEnded.bind( this );
  26227. source.start( this._startedAt, this._progress + this.offset, this.duration );
  26228. this.isPlaying = true;
  26229. this.source = source;
  26230. this.setDetune( this.detune );
  26231. this.setPlaybackRate( this.playbackRate );
  26232. return this.connect();
  26233. }
  26234. pause() {
  26235. if ( this.hasPlaybackControl === false ) {
  26236. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26237. return;
  26238. }
  26239. if ( this.isPlaying === true ) {
  26240. // update current progress
  26241. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  26242. if ( this.loop === true ) {
  26243. // ensure _progress does not exceed duration with looped audios
  26244. this._progress = this._progress % ( this.duration || this.buffer.duration );
  26245. }
  26246. this.source.stop();
  26247. this.source.onended = null;
  26248. this.isPlaying = false;
  26249. }
  26250. return this;
  26251. }
  26252. stop() {
  26253. if ( this.hasPlaybackControl === false ) {
  26254. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26255. return;
  26256. }
  26257. this._progress = 0;
  26258. if ( this.source !== null ) {
  26259. this.source.stop();
  26260. this.source.onended = null;
  26261. }
  26262. this.isPlaying = false;
  26263. return this;
  26264. }
  26265. connect() {
  26266. if ( this.filters.length > 0 ) {
  26267. this.source.connect( this.filters[ 0 ] );
  26268. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26269. this.filters[ i - 1 ].connect( this.filters[ i ] );
  26270. }
  26271. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  26272. } else {
  26273. this.source.connect( this.getOutput() );
  26274. }
  26275. this._connected = true;
  26276. return this;
  26277. }
  26278. disconnect() {
  26279. if ( this.filters.length > 0 ) {
  26280. this.source.disconnect( this.filters[ 0 ] );
  26281. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26282. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  26283. }
  26284. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  26285. } else {
  26286. this.source.disconnect( this.getOutput() );
  26287. }
  26288. this._connected = false;
  26289. return this;
  26290. }
  26291. getFilters() {
  26292. return this.filters;
  26293. }
  26294. setFilters( value ) {
  26295. if ( ! value ) value = [];
  26296. if ( this._connected === true ) {
  26297. this.disconnect();
  26298. this.filters = value.slice();
  26299. this.connect();
  26300. } else {
  26301. this.filters = value.slice();
  26302. }
  26303. return this;
  26304. }
  26305. setDetune( value ) {
  26306. this.detune = value;
  26307. if ( this.source.detune === undefined ) return; // only set detune when available
  26308. if ( this.isPlaying === true ) {
  26309. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  26310. }
  26311. return this;
  26312. }
  26313. getDetune() {
  26314. return this.detune;
  26315. }
  26316. getFilter() {
  26317. return this.getFilters()[ 0 ];
  26318. }
  26319. setFilter( filter ) {
  26320. return this.setFilters( filter ? [ filter ] : [] );
  26321. }
  26322. setPlaybackRate( value ) {
  26323. if ( this.hasPlaybackControl === false ) {
  26324. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26325. return;
  26326. }
  26327. this.playbackRate = value;
  26328. if ( this.isPlaying === true ) {
  26329. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  26330. }
  26331. return this;
  26332. }
  26333. getPlaybackRate() {
  26334. return this.playbackRate;
  26335. }
  26336. onEnded() {
  26337. this.isPlaying = false;
  26338. }
  26339. getLoop() {
  26340. if ( this.hasPlaybackControl === false ) {
  26341. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26342. return false;
  26343. }
  26344. return this.loop;
  26345. }
  26346. setLoop( value ) {
  26347. if ( this.hasPlaybackControl === false ) {
  26348. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26349. return;
  26350. }
  26351. this.loop = value;
  26352. if ( this.isPlaying === true ) {
  26353. this.source.loop = this.loop;
  26354. }
  26355. return this;
  26356. }
  26357. setLoopStart( value ) {
  26358. this.loopStart = value;
  26359. return this;
  26360. }
  26361. setLoopEnd( value ) {
  26362. this.loopEnd = value;
  26363. return this;
  26364. }
  26365. getVolume() {
  26366. return this.gain.gain.value;
  26367. }
  26368. setVolume( value ) {
  26369. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26370. return this;
  26371. }
  26372. }
  26373. const _position = /*@__PURE__*/ new Vector3();
  26374. const _quaternion = /*@__PURE__*/ new Quaternion();
  26375. const _scale = /*@__PURE__*/ new Vector3();
  26376. const _orientation = /*@__PURE__*/ new Vector3();
  26377. class PositionalAudio extends Audio {
  26378. constructor( listener ) {
  26379. super( listener );
  26380. this.panner = this.context.createPanner();
  26381. this.panner.panningModel = 'HRTF';
  26382. this.panner.connect( this.gain );
  26383. }
  26384. disconnect() {
  26385. super.disconnect();
  26386. this.panner.disconnect( this.gain );
  26387. }
  26388. getOutput() {
  26389. return this.panner;
  26390. }
  26391. getRefDistance() {
  26392. return this.panner.refDistance;
  26393. }
  26394. setRefDistance( value ) {
  26395. this.panner.refDistance = value;
  26396. return this;
  26397. }
  26398. getRolloffFactor() {
  26399. return this.panner.rolloffFactor;
  26400. }
  26401. setRolloffFactor( value ) {
  26402. this.panner.rolloffFactor = value;
  26403. return this;
  26404. }
  26405. getDistanceModel() {
  26406. return this.panner.distanceModel;
  26407. }
  26408. setDistanceModel( value ) {
  26409. this.panner.distanceModel = value;
  26410. return this;
  26411. }
  26412. getMaxDistance() {
  26413. return this.panner.maxDistance;
  26414. }
  26415. setMaxDistance( value ) {
  26416. this.panner.maxDistance = value;
  26417. return this;
  26418. }
  26419. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  26420. this.panner.coneInnerAngle = coneInnerAngle;
  26421. this.panner.coneOuterAngle = coneOuterAngle;
  26422. this.panner.coneOuterGain = coneOuterGain;
  26423. return this;
  26424. }
  26425. updateMatrixWorld( force ) {
  26426. super.updateMatrixWorld( force );
  26427. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  26428. this.matrixWorld.decompose( _position, _quaternion, _scale );
  26429. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  26430. const panner = this.panner;
  26431. if ( panner.positionX ) {
  26432. // code path for Chrome and Firefox (see #14393)
  26433. const endTime = this.context.currentTime + this.listener.timeDelta;
  26434. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  26435. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  26436. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  26437. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  26438. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  26439. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  26440. } else {
  26441. panner.setPosition( _position.x, _position.y, _position.z );
  26442. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  26443. }
  26444. }
  26445. }
  26446. class AudioAnalyser {
  26447. constructor( audio, fftSize = 2048 ) {
  26448. this.analyser = audio.context.createAnalyser();
  26449. this.analyser.fftSize = fftSize;
  26450. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  26451. audio.getOutput().connect( this.analyser );
  26452. }
  26453. getFrequencyData() {
  26454. this.analyser.getByteFrequencyData( this.data );
  26455. return this.data;
  26456. }
  26457. getAverageFrequency() {
  26458. let value = 0;
  26459. const data = this.getFrequencyData();
  26460. for ( let i = 0; i < data.length; i ++ ) {
  26461. value += data[ i ];
  26462. }
  26463. return value / data.length;
  26464. }
  26465. }
  26466. class PropertyMixer {
  26467. constructor( binding, typeName, valueSize ) {
  26468. this.binding = binding;
  26469. this.valueSize = valueSize;
  26470. let mixFunction,
  26471. mixFunctionAdditive,
  26472. setIdentity;
  26473. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  26474. //
  26475. // interpolators can use .buffer as their .result
  26476. // the data then goes to 'incoming'
  26477. //
  26478. // 'accu0' and 'accu1' are used frame-interleaved for
  26479. // the cumulative result and are compared to detect
  26480. // changes
  26481. //
  26482. // 'orig' stores the original state of the property
  26483. //
  26484. // 'add' is used for additive cumulative results
  26485. //
  26486. // 'work' is optional and is only present for quaternion types. It is used
  26487. // to store intermediate quaternion multiplication results
  26488. switch ( typeName ) {
  26489. case 'quaternion':
  26490. mixFunction = this._slerp;
  26491. mixFunctionAdditive = this._slerpAdditive;
  26492. setIdentity = this._setAdditiveIdentityQuaternion;
  26493. this.buffer = new Float64Array( valueSize * 6 );
  26494. this._workIndex = 5;
  26495. break;
  26496. case 'string':
  26497. case 'bool':
  26498. mixFunction = this._select;
  26499. // Use the regular mix function and for additive on these types,
  26500. // additive is not relevant for non-numeric types
  26501. mixFunctionAdditive = this._select;
  26502. setIdentity = this._setAdditiveIdentityOther;
  26503. this.buffer = new Array( valueSize * 5 );
  26504. break;
  26505. default:
  26506. mixFunction = this._lerp;
  26507. mixFunctionAdditive = this._lerpAdditive;
  26508. setIdentity = this._setAdditiveIdentityNumeric;
  26509. this.buffer = new Float64Array( valueSize * 5 );
  26510. }
  26511. this._mixBufferRegion = mixFunction;
  26512. this._mixBufferRegionAdditive = mixFunctionAdditive;
  26513. this._setIdentity = setIdentity;
  26514. this._origIndex = 3;
  26515. this._addIndex = 4;
  26516. this.cumulativeWeight = 0;
  26517. this.cumulativeWeightAdditive = 0;
  26518. this.useCount = 0;
  26519. this.referenceCount = 0;
  26520. }
  26521. // accumulate data in the 'incoming' region into 'accu<i>'
  26522. accumulate( accuIndex, weight ) {
  26523. // note: happily accumulating nothing when weight = 0, the caller knows
  26524. // the weight and shouldn't have made the call in the first place
  26525. const buffer = this.buffer,
  26526. stride = this.valueSize,
  26527. offset = accuIndex * stride + stride;
  26528. let currentWeight = this.cumulativeWeight;
  26529. if ( currentWeight === 0 ) {
  26530. // accuN := incoming * weight
  26531. for ( let i = 0; i !== stride; ++ i ) {
  26532. buffer[ offset + i ] = buffer[ i ];
  26533. }
  26534. currentWeight = weight;
  26535. } else {
  26536. // accuN := accuN + incoming * weight
  26537. currentWeight += weight;
  26538. const mix = weight / currentWeight;
  26539. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  26540. }
  26541. this.cumulativeWeight = currentWeight;
  26542. }
  26543. // accumulate data in the 'incoming' region into 'add'
  26544. accumulateAdditive( weight ) {
  26545. const buffer = this.buffer,
  26546. stride = this.valueSize,
  26547. offset = stride * this._addIndex;
  26548. if ( this.cumulativeWeightAdditive === 0 ) {
  26549. // add = identity
  26550. this._setIdentity();
  26551. }
  26552. // add := add + incoming * weight
  26553. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  26554. this.cumulativeWeightAdditive += weight;
  26555. }
  26556. // apply the state of 'accu<i>' to the binding when accus differ
  26557. apply( accuIndex ) {
  26558. const stride = this.valueSize,
  26559. buffer = this.buffer,
  26560. offset = accuIndex * stride + stride,
  26561. weight = this.cumulativeWeight,
  26562. weightAdditive = this.cumulativeWeightAdditive,
  26563. binding = this.binding;
  26564. this.cumulativeWeight = 0;
  26565. this.cumulativeWeightAdditive = 0;
  26566. if ( weight < 1 ) {
  26567. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26568. const originalValueOffset = stride * this._origIndex;
  26569. this._mixBufferRegion(
  26570. buffer, offset, originalValueOffset, 1 - weight, stride );
  26571. }
  26572. if ( weightAdditive > 0 ) {
  26573. // accuN := accuN + additive accuN
  26574. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  26575. }
  26576. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  26577. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  26578. // value has changed -> update scene graph
  26579. binding.setValue( buffer, offset );
  26580. break;
  26581. }
  26582. }
  26583. }
  26584. // remember the state of the bound property and copy it to both accus
  26585. saveOriginalState() {
  26586. const binding = this.binding;
  26587. const buffer = this.buffer,
  26588. stride = this.valueSize,
  26589. originalValueOffset = stride * this._origIndex;
  26590. binding.getValue( buffer, originalValueOffset );
  26591. // accu[0..1] := orig -- initially detect changes against the original
  26592. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  26593. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  26594. }
  26595. // Add to identity for additive
  26596. this._setIdentity();
  26597. this.cumulativeWeight = 0;
  26598. this.cumulativeWeightAdditive = 0;
  26599. }
  26600. // apply the state previously taken via 'saveOriginalState' to the binding
  26601. restoreOriginalState() {
  26602. const originalValueOffset = this.valueSize * 3;
  26603. this.binding.setValue( this.buffer, originalValueOffset );
  26604. }
  26605. _setAdditiveIdentityNumeric() {
  26606. const startIndex = this._addIndex * this.valueSize;
  26607. const endIndex = startIndex + this.valueSize;
  26608. for ( let i = startIndex; i < endIndex; i ++ ) {
  26609. this.buffer[ i ] = 0;
  26610. }
  26611. }
  26612. _setAdditiveIdentityQuaternion() {
  26613. this._setAdditiveIdentityNumeric();
  26614. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  26615. }
  26616. _setAdditiveIdentityOther() {
  26617. const startIndex = this._origIndex * this.valueSize;
  26618. const targetIndex = this._addIndex * this.valueSize;
  26619. for ( let i = 0; i < this.valueSize; i ++ ) {
  26620. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  26621. }
  26622. }
  26623. // mix functions
  26624. _select( buffer, dstOffset, srcOffset, t, stride ) {
  26625. if ( t >= 0.5 ) {
  26626. for ( let i = 0; i !== stride; ++ i ) {
  26627. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  26628. }
  26629. }
  26630. }
  26631. _slerp( buffer, dstOffset, srcOffset, t ) {
  26632. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  26633. }
  26634. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  26635. const workOffset = this._workIndex * stride;
  26636. // Store result in intermediate buffer offset
  26637. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  26638. // Slerp to the intermediate result
  26639. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  26640. }
  26641. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  26642. const s = 1 - t;
  26643. for ( let i = 0; i !== stride; ++ i ) {
  26644. const j = dstOffset + i;
  26645. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  26646. }
  26647. }
  26648. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  26649. for ( let i = 0; i !== stride; ++ i ) {
  26650. const j = dstOffset + i;
  26651. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  26652. }
  26653. }
  26654. }
  26655. // Characters [].:/ are reserved for track binding syntax.
  26656. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  26657. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  26658. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  26659. // only latin characters, and the unicode \p{L} is not yet supported. So
  26660. // instead, we exclude reserved characters and match everything else.
  26661. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  26662. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  26663. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  26664. // be matched to parse the rest of the track name.
  26665. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  26666. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  26667. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  26668. // Object on target node, and accessor. May not contain reserved
  26669. // characters. Accessor may contain any character except closing bracket.
  26670. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  26671. // Property and accessor. May not contain reserved characters. Accessor may
  26672. // contain any non-bracket characters.
  26673. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  26674. const _trackRe = new RegExp( ''
  26675. + '^'
  26676. + _directoryRe
  26677. + _nodeRe
  26678. + _objectRe
  26679. + _propertyRe
  26680. + '$'
  26681. );
  26682. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  26683. class Composite {
  26684. constructor( targetGroup, path, optionalParsedPath ) {
  26685. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  26686. this._targetGroup = targetGroup;
  26687. this._bindings = targetGroup.subscribe_( path, parsedPath );
  26688. }
  26689. getValue( array, offset ) {
  26690. this.bind(); // bind all binding
  26691. const firstValidIndex = this._targetGroup.nCachedObjects_,
  26692. binding = this._bindings[ firstValidIndex ];
  26693. // and only call .getValue on the first
  26694. if ( binding !== undefined ) binding.getValue( array, offset );
  26695. }
  26696. setValue( array, offset ) {
  26697. const bindings = this._bindings;
  26698. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26699. bindings[ i ].setValue( array, offset );
  26700. }
  26701. }
  26702. bind() {
  26703. const bindings = this._bindings;
  26704. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26705. bindings[ i ].bind();
  26706. }
  26707. }
  26708. unbind() {
  26709. const bindings = this._bindings;
  26710. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26711. bindings[ i ].unbind();
  26712. }
  26713. }
  26714. }
  26715. // Note: This class uses a State pattern on a per-method basis:
  26716. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  26717. // prototype version of these methods with one that represents
  26718. // the bound state. When the property is not found, the methods
  26719. // become no-ops.
  26720. class PropertyBinding {
  26721. constructor( rootNode, path, parsedPath ) {
  26722. this.path = path;
  26723. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  26724. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  26725. this.rootNode = rootNode;
  26726. // initial state of these methods that calls 'bind'
  26727. this.getValue = this._getValue_unbound;
  26728. this.setValue = this._setValue_unbound;
  26729. }
  26730. static create( root, path, parsedPath ) {
  26731. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  26732. return new PropertyBinding( root, path, parsedPath );
  26733. } else {
  26734. return new PropertyBinding.Composite( root, path, parsedPath );
  26735. }
  26736. }
  26737. /**
  26738. * Replaces spaces with underscores and removes unsupported characters from
  26739. * node names, to ensure compatibility with parseTrackName().
  26740. *
  26741. * @param {string} name Node name to be sanitized.
  26742. * @return {string}
  26743. */
  26744. static sanitizeNodeName( name ) {
  26745. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  26746. }
  26747. static parseTrackName( trackName ) {
  26748. const matches = _trackRe.exec( trackName );
  26749. if ( matches === null ) {
  26750. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  26751. }
  26752. const results = {
  26753. // directoryName: matches[ 1 ], // (tschw) currently unused
  26754. nodeName: matches[ 2 ],
  26755. objectName: matches[ 3 ],
  26756. objectIndex: matches[ 4 ],
  26757. propertyName: matches[ 5 ], // required
  26758. propertyIndex: matches[ 6 ]
  26759. };
  26760. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  26761. if ( lastDot !== undefined && lastDot !== - 1 ) {
  26762. const objectName = results.nodeName.substring( lastDot + 1 );
  26763. // Object names must be checked against an allowlist. Otherwise, there
  26764. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  26765. // 'bar' could be the objectName, or part of a nodeName (which can
  26766. // include '.' characters).
  26767. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  26768. results.nodeName = results.nodeName.substring( 0, lastDot );
  26769. results.objectName = objectName;
  26770. }
  26771. }
  26772. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  26773. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  26774. }
  26775. return results;
  26776. }
  26777. static findNode( root, nodeName ) {
  26778. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  26779. return root;
  26780. }
  26781. // search into skeleton bones.
  26782. if ( root.skeleton ) {
  26783. const bone = root.skeleton.getBoneByName( nodeName );
  26784. if ( bone !== undefined ) {
  26785. return bone;
  26786. }
  26787. }
  26788. // search into node subtree.
  26789. if ( root.children ) {
  26790. const searchNodeSubtree = function ( children ) {
  26791. for ( let i = 0; i < children.length; i ++ ) {
  26792. const childNode = children[ i ];
  26793. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  26794. return childNode;
  26795. }
  26796. const result = searchNodeSubtree( childNode.children );
  26797. if ( result ) return result;
  26798. }
  26799. return null;
  26800. };
  26801. const subTreeNode = searchNodeSubtree( root.children );
  26802. if ( subTreeNode ) {
  26803. return subTreeNode;
  26804. }
  26805. }
  26806. return null;
  26807. }
  26808. // these are used to "bind" a nonexistent property
  26809. _getValue_unavailable() {}
  26810. _setValue_unavailable() {}
  26811. // Getters
  26812. _getValue_direct( buffer, offset ) {
  26813. buffer[ offset ] = this.targetObject[ this.propertyName ];
  26814. }
  26815. _getValue_array( buffer, offset ) {
  26816. const source = this.resolvedProperty;
  26817. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  26818. buffer[ offset ++ ] = source[ i ];
  26819. }
  26820. }
  26821. _getValue_arrayElement( buffer, offset ) {
  26822. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  26823. }
  26824. _getValue_toArray( buffer, offset ) {
  26825. this.resolvedProperty.toArray( buffer, offset );
  26826. }
  26827. // Direct
  26828. _setValue_direct( buffer, offset ) {
  26829. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26830. }
  26831. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  26832. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26833. this.targetObject.needsUpdate = true;
  26834. }
  26835. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26836. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26837. this.targetObject.matrixWorldNeedsUpdate = true;
  26838. }
  26839. // EntireArray
  26840. _setValue_array( buffer, offset ) {
  26841. const dest = this.resolvedProperty;
  26842. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26843. dest[ i ] = buffer[ offset ++ ];
  26844. }
  26845. }
  26846. _setValue_array_setNeedsUpdate( buffer, offset ) {
  26847. const dest = this.resolvedProperty;
  26848. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26849. dest[ i ] = buffer[ offset ++ ];
  26850. }
  26851. this.targetObject.needsUpdate = true;
  26852. }
  26853. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26854. const dest = this.resolvedProperty;
  26855. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26856. dest[ i ] = buffer[ offset ++ ];
  26857. }
  26858. this.targetObject.matrixWorldNeedsUpdate = true;
  26859. }
  26860. // ArrayElement
  26861. _setValue_arrayElement( buffer, offset ) {
  26862. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26863. }
  26864. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  26865. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26866. this.targetObject.needsUpdate = true;
  26867. }
  26868. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26869. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26870. this.targetObject.matrixWorldNeedsUpdate = true;
  26871. }
  26872. // HasToFromArray
  26873. _setValue_fromArray( buffer, offset ) {
  26874. this.resolvedProperty.fromArray( buffer, offset );
  26875. }
  26876. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  26877. this.resolvedProperty.fromArray( buffer, offset );
  26878. this.targetObject.needsUpdate = true;
  26879. }
  26880. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26881. this.resolvedProperty.fromArray( buffer, offset );
  26882. this.targetObject.matrixWorldNeedsUpdate = true;
  26883. }
  26884. _getValue_unbound( targetArray, offset ) {
  26885. this.bind();
  26886. this.getValue( targetArray, offset );
  26887. }
  26888. _setValue_unbound( sourceArray, offset ) {
  26889. this.bind();
  26890. this.setValue( sourceArray, offset );
  26891. }
  26892. // create getter / setter pair for a property in the scene graph
  26893. bind() {
  26894. let targetObject = this.node;
  26895. const parsedPath = this.parsedPath;
  26896. const objectName = parsedPath.objectName;
  26897. const propertyName = parsedPath.propertyName;
  26898. let propertyIndex = parsedPath.propertyIndex;
  26899. if ( ! targetObject ) {
  26900. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  26901. this.node = targetObject;
  26902. }
  26903. // set fail state so we can just 'return' on error
  26904. this.getValue = this._getValue_unavailable;
  26905. this.setValue = this._setValue_unavailable;
  26906. // ensure there is a value node
  26907. if ( ! targetObject ) {
  26908. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  26909. return;
  26910. }
  26911. if ( objectName ) {
  26912. let objectIndex = parsedPath.objectIndex;
  26913. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  26914. switch ( objectName ) {
  26915. case 'materials':
  26916. if ( ! targetObject.material ) {
  26917. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  26918. return;
  26919. }
  26920. if ( ! targetObject.material.materials ) {
  26921. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  26922. return;
  26923. }
  26924. targetObject = targetObject.material.materials;
  26925. break;
  26926. case 'bones':
  26927. if ( ! targetObject.skeleton ) {
  26928. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  26929. return;
  26930. }
  26931. // potential future optimization: skip this if propertyIndex is already an integer
  26932. // and convert the integer string to a true integer.
  26933. targetObject = targetObject.skeleton.bones;
  26934. // support resolving morphTarget names into indices.
  26935. for ( let i = 0; i < targetObject.length; i ++ ) {
  26936. if ( targetObject[ i ].name === objectIndex ) {
  26937. objectIndex = i;
  26938. break;
  26939. }
  26940. }
  26941. break;
  26942. case 'map':
  26943. if ( 'map' in targetObject ) {
  26944. targetObject = targetObject.map;
  26945. break;
  26946. }
  26947. if ( ! targetObject.material ) {
  26948. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  26949. return;
  26950. }
  26951. if ( ! targetObject.material.map ) {
  26952. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  26953. return;
  26954. }
  26955. targetObject = targetObject.material.map;
  26956. break;
  26957. default:
  26958. if ( targetObject[ objectName ] === undefined ) {
  26959. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  26960. return;
  26961. }
  26962. targetObject = targetObject[ objectName ];
  26963. }
  26964. if ( objectIndex !== undefined ) {
  26965. if ( targetObject[ objectIndex ] === undefined ) {
  26966. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  26967. return;
  26968. }
  26969. targetObject = targetObject[ objectIndex ];
  26970. }
  26971. }
  26972. // resolve property
  26973. const nodeProperty = targetObject[ propertyName ];
  26974. if ( nodeProperty === undefined ) {
  26975. const nodeName = parsedPath.nodeName;
  26976. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  26977. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  26978. return;
  26979. }
  26980. // determine versioning scheme
  26981. let versioning = this.Versioning.None;
  26982. this.targetObject = targetObject;
  26983. if ( targetObject.needsUpdate !== undefined ) { // material
  26984. versioning = this.Versioning.NeedsUpdate;
  26985. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  26986. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  26987. }
  26988. // determine how the property gets bound
  26989. let bindingType = this.BindingType.Direct;
  26990. if ( propertyIndex !== undefined ) {
  26991. // access a sub element of the property array (only primitives are supported right now)
  26992. if ( propertyName === 'morphTargetInfluences' ) {
  26993. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  26994. // support resolving morphTarget names into indices.
  26995. if ( ! targetObject.geometry ) {
  26996. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  26997. return;
  26998. }
  26999. if ( ! targetObject.geometry.morphAttributes ) {
  27000. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  27001. return;
  27002. }
  27003. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  27004. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  27005. }
  27006. }
  27007. bindingType = this.BindingType.ArrayElement;
  27008. this.resolvedProperty = nodeProperty;
  27009. this.propertyIndex = propertyIndex;
  27010. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  27011. // must use copy for Object3D.Euler/Quaternion
  27012. bindingType = this.BindingType.HasFromToArray;
  27013. this.resolvedProperty = nodeProperty;
  27014. } else if ( Array.isArray( nodeProperty ) ) {
  27015. bindingType = this.BindingType.EntireArray;
  27016. this.resolvedProperty = nodeProperty;
  27017. } else {
  27018. this.propertyName = propertyName;
  27019. }
  27020. // select getter / setter
  27021. this.getValue = this.GetterByBindingType[ bindingType ];
  27022. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  27023. }
  27024. unbind() {
  27025. this.node = null;
  27026. // back to the prototype version of getValue / setValue
  27027. // note: avoiding to mutate the shape of 'this' via 'delete'
  27028. this.getValue = this._getValue_unbound;
  27029. this.setValue = this._setValue_unbound;
  27030. }
  27031. }
  27032. PropertyBinding.Composite = Composite;
  27033. PropertyBinding.prototype.BindingType = {
  27034. Direct: 0,
  27035. EntireArray: 1,
  27036. ArrayElement: 2,
  27037. HasFromToArray: 3
  27038. };
  27039. PropertyBinding.prototype.Versioning = {
  27040. None: 0,
  27041. NeedsUpdate: 1,
  27042. MatrixWorldNeedsUpdate: 2
  27043. };
  27044. PropertyBinding.prototype.GetterByBindingType = [
  27045. PropertyBinding.prototype._getValue_direct,
  27046. PropertyBinding.prototype._getValue_array,
  27047. PropertyBinding.prototype._getValue_arrayElement,
  27048. PropertyBinding.prototype._getValue_toArray,
  27049. ];
  27050. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  27051. [
  27052. // Direct
  27053. PropertyBinding.prototype._setValue_direct,
  27054. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  27055. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  27056. ], [
  27057. // EntireArray
  27058. PropertyBinding.prototype._setValue_array,
  27059. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  27060. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  27061. ], [
  27062. // ArrayElement
  27063. PropertyBinding.prototype._setValue_arrayElement,
  27064. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  27065. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  27066. ], [
  27067. // HasToFromArray
  27068. PropertyBinding.prototype._setValue_fromArray,
  27069. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  27070. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  27071. ]
  27072. ];
  27073. /**
  27074. *
  27075. * A group of objects that receives a shared animation state.
  27076. *
  27077. * Usage:
  27078. *
  27079. * - Add objects you would otherwise pass as 'root' to the
  27080. * constructor or the .clipAction method of AnimationMixer.
  27081. *
  27082. * - Instead pass this object as 'root'.
  27083. *
  27084. * - You can also add and remove objects later when the mixer
  27085. * is running.
  27086. *
  27087. * Note:
  27088. *
  27089. * Objects of this class appear as one object to the mixer,
  27090. * so cache control of the individual objects must be done
  27091. * on the group.
  27092. *
  27093. * Limitation:
  27094. *
  27095. * - The animated properties must be compatible among the
  27096. * all objects in the group.
  27097. *
  27098. * - A single property can either be controlled through a
  27099. * target group or directly, but not both.
  27100. */
  27101. class AnimationObjectGroup {
  27102. constructor() {
  27103. this.isAnimationObjectGroup = true;
  27104. this.uuid = generateUUID();
  27105. // cached objects followed by the active ones
  27106. this._objects = Array.prototype.slice.call( arguments );
  27107. this.nCachedObjects_ = 0; // threshold
  27108. // note: read by PropertyBinding.Composite
  27109. const indices = {};
  27110. this._indicesByUUID = indices; // for bookkeeping
  27111. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27112. indices[ arguments[ i ].uuid ] = i;
  27113. }
  27114. this._paths = []; // inside: string
  27115. this._parsedPaths = []; // inside: { we don't care, here }
  27116. this._bindings = []; // inside: Array< PropertyBinding >
  27117. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  27118. const scope = this;
  27119. this.stats = {
  27120. objects: {
  27121. get total() {
  27122. return scope._objects.length;
  27123. },
  27124. get inUse() {
  27125. return this.total - scope.nCachedObjects_;
  27126. }
  27127. },
  27128. get bindingsPerObject() {
  27129. return scope._bindings.length;
  27130. }
  27131. };
  27132. }
  27133. add() {
  27134. const objects = this._objects,
  27135. indicesByUUID = this._indicesByUUID,
  27136. paths = this._paths,
  27137. parsedPaths = this._parsedPaths,
  27138. bindings = this._bindings,
  27139. nBindings = bindings.length;
  27140. let knownObject = undefined,
  27141. nObjects = objects.length,
  27142. nCachedObjects = this.nCachedObjects_;
  27143. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27144. const object = arguments[ i ],
  27145. uuid = object.uuid;
  27146. let index = indicesByUUID[ uuid ];
  27147. if ( index === undefined ) {
  27148. // unknown object -> add it to the ACTIVE region
  27149. index = nObjects ++;
  27150. indicesByUUID[ uuid ] = index;
  27151. objects.push( object );
  27152. // accounting is done, now do the same for all bindings
  27153. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27154. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  27155. }
  27156. } else if ( index < nCachedObjects ) {
  27157. knownObject = objects[ index ];
  27158. // move existing object to the ACTIVE region
  27159. const firstActiveIndex = -- nCachedObjects,
  27160. lastCachedObject = objects[ firstActiveIndex ];
  27161. indicesByUUID[ lastCachedObject.uuid ] = index;
  27162. objects[ index ] = lastCachedObject;
  27163. indicesByUUID[ uuid ] = firstActiveIndex;
  27164. objects[ firstActiveIndex ] = object;
  27165. // accounting is done, now do the same for all bindings
  27166. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27167. const bindingsForPath = bindings[ j ],
  27168. lastCached = bindingsForPath[ firstActiveIndex ];
  27169. let binding = bindingsForPath[ index ];
  27170. bindingsForPath[ index ] = lastCached;
  27171. if ( binding === undefined ) {
  27172. // since we do not bother to create new bindings
  27173. // for objects that are cached, the binding may
  27174. // or may not exist
  27175. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  27176. }
  27177. bindingsForPath[ firstActiveIndex ] = binding;
  27178. }
  27179. } else if ( objects[ index ] !== knownObject ) {
  27180. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  27181. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  27182. } // else the object is already where we want it to be
  27183. } // for arguments
  27184. this.nCachedObjects_ = nCachedObjects;
  27185. }
  27186. remove() {
  27187. const objects = this._objects,
  27188. indicesByUUID = this._indicesByUUID,
  27189. bindings = this._bindings,
  27190. nBindings = bindings.length;
  27191. let nCachedObjects = this.nCachedObjects_;
  27192. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27193. const object = arguments[ i ],
  27194. uuid = object.uuid,
  27195. index = indicesByUUID[ uuid ];
  27196. if ( index !== undefined && index >= nCachedObjects ) {
  27197. // move existing object into the CACHED region
  27198. const lastCachedIndex = nCachedObjects ++,
  27199. firstActiveObject = objects[ lastCachedIndex ];
  27200. indicesByUUID[ firstActiveObject.uuid ] = index;
  27201. objects[ index ] = firstActiveObject;
  27202. indicesByUUID[ uuid ] = lastCachedIndex;
  27203. objects[ lastCachedIndex ] = object;
  27204. // accounting is done, now do the same for all bindings
  27205. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27206. const bindingsForPath = bindings[ j ],
  27207. firstActive = bindingsForPath[ lastCachedIndex ],
  27208. binding = bindingsForPath[ index ];
  27209. bindingsForPath[ index ] = firstActive;
  27210. bindingsForPath[ lastCachedIndex ] = binding;
  27211. }
  27212. }
  27213. } // for arguments
  27214. this.nCachedObjects_ = nCachedObjects;
  27215. }
  27216. // remove & forget
  27217. uncache() {
  27218. const objects = this._objects,
  27219. indicesByUUID = this._indicesByUUID,
  27220. bindings = this._bindings,
  27221. nBindings = bindings.length;
  27222. let nCachedObjects = this.nCachedObjects_,
  27223. nObjects = objects.length;
  27224. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27225. const object = arguments[ i ],
  27226. uuid = object.uuid,
  27227. index = indicesByUUID[ uuid ];
  27228. if ( index !== undefined ) {
  27229. delete indicesByUUID[ uuid ];
  27230. if ( index < nCachedObjects ) {
  27231. // object is cached, shrink the CACHED region
  27232. const firstActiveIndex = -- nCachedObjects,
  27233. lastCachedObject = objects[ firstActiveIndex ],
  27234. lastIndex = -- nObjects,
  27235. lastObject = objects[ lastIndex ];
  27236. // last cached object takes this object's place
  27237. indicesByUUID[ lastCachedObject.uuid ] = index;
  27238. objects[ index ] = lastCachedObject;
  27239. // last object goes to the activated slot and pop
  27240. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  27241. objects[ firstActiveIndex ] = lastObject;
  27242. objects.pop();
  27243. // accounting is done, now do the same for all bindings
  27244. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27245. const bindingsForPath = bindings[ j ],
  27246. lastCached = bindingsForPath[ firstActiveIndex ],
  27247. last = bindingsForPath[ lastIndex ];
  27248. bindingsForPath[ index ] = lastCached;
  27249. bindingsForPath[ firstActiveIndex ] = last;
  27250. bindingsForPath.pop();
  27251. }
  27252. } else {
  27253. // object is active, just swap with the last and pop
  27254. const lastIndex = -- nObjects,
  27255. lastObject = objects[ lastIndex ];
  27256. if ( lastIndex > 0 ) {
  27257. indicesByUUID[ lastObject.uuid ] = index;
  27258. }
  27259. objects[ index ] = lastObject;
  27260. objects.pop();
  27261. // accounting is done, now do the same for all bindings
  27262. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27263. const bindingsForPath = bindings[ j ];
  27264. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  27265. bindingsForPath.pop();
  27266. }
  27267. } // cached or active
  27268. } // if object is known
  27269. } // for arguments
  27270. this.nCachedObjects_ = nCachedObjects;
  27271. }
  27272. // Internal interface used by befriended PropertyBinding.Composite:
  27273. subscribe_( path, parsedPath ) {
  27274. // returns an array of bindings for the given path that is changed
  27275. // according to the contained objects in the group
  27276. const indicesByPath = this._bindingsIndicesByPath;
  27277. let index = indicesByPath[ path ];
  27278. const bindings = this._bindings;
  27279. if ( index !== undefined ) return bindings[ index ];
  27280. const paths = this._paths,
  27281. parsedPaths = this._parsedPaths,
  27282. objects = this._objects,
  27283. nObjects = objects.length,
  27284. nCachedObjects = this.nCachedObjects_,
  27285. bindingsForPath = new Array( nObjects );
  27286. index = bindings.length;
  27287. indicesByPath[ path ] = index;
  27288. paths.push( path );
  27289. parsedPaths.push( parsedPath );
  27290. bindings.push( bindingsForPath );
  27291. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  27292. const object = objects[ i ];
  27293. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  27294. }
  27295. return bindingsForPath;
  27296. }
  27297. unsubscribe_( path ) {
  27298. // tells the group to forget about a property path and no longer
  27299. // update the array previously obtained with 'subscribe_'
  27300. const indicesByPath = this._bindingsIndicesByPath,
  27301. index = indicesByPath[ path ];
  27302. if ( index !== undefined ) {
  27303. const paths = this._paths,
  27304. parsedPaths = this._parsedPaths,
  27305. bindings = this._bindings,
  27306. lastBindingsIndex = bindings.length - 1,
  27307. lastBindings = bindings[ lastBindingsIndex ],
  27308. lastBindingsPath = path[ lastBindingsIndex ];
  27309. indicesByPath[ lastBindingsPath ] = index;
  27310. bindings[ index ] = lastBindings;
  27311. bindings.pop();
  27312. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  27313. parsedPaths.pop();
  27314. paths[ index ] = paths[ lastBindingsIndex ];
  27315. paths.pop();
  27316. }
  27317. }
  27318. }
  27319. class AnimationAction {
  27320. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  27321. this._mixer = mixer;
  27322. this._clip = clip;
  27323. this._localRoot = localRoot;
  27324. this.blendMode = blendMode;
  27325. const tracks = clip.tracks,
  27326. nTracks = tracks.length,
  27327. interpolants = new Array( nTracks );
  27328. const interpolantSettings = {
  27329. endingStart: ZeroCurvatureEnding,
  27330. endingEnd: ZeroCurvatureEnding
  27331. };
  27332. for ( let i = 0; i !== nTracks; ++ i ) {
  27333. const interpolant = tracks[ i ].createInterpolant( null );
  27334. interpolants[ i ] = interpolant;
  27335. interpolant.settings = interpolantSettings;
  27336. }
  27337. this._interpolantSettings = interpolantSettings;
  27338. this._interpolants = interpolants; // bound by the mixer
  27339. // inside: PropertyMixer (managed by the mixer)
  27340. this._propertyBindings = new Array( nTracks );
  27341. this._cacheIndex = null; // for the memory manager
  27342. this._byClipCacheIndex = null; // for the memory manager
  27343. this._timeScaleInterpolant = null;
  27344. this._weightInterpolant = null;
  27345. this.loop = LoopRepeat;
  27346. this._loopCount = - 1;
  27347. // global mixer time when the action is to be started
  27348. // it's set back to 'null' upon start of the action
  27349. this._startTime = null;
  27350. // scaled local time of the action
  27351. // gets clamped or wrapped to 0..clip.duration according to loop
  27352. this.time = 0;
  27353. this.timeScale = 1;
  27354. this._effectiveTimeScale = 1;
  27355. this.weight = 1;
  27356. this._effectiveWeight = 1;
  27357. this.repetitions = Infinity; // no. of repetitions when looping
  27358. this.paused = false; // true -> zero effective time scale
  27359. this.enabled = true; // false -> zero effective weight
  27360. this.clampWhenFinished = false;// keep feeding the last frame?
  27361. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  27362. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  27363. }
  27364. // State & Scheduling
  27365. play() {
  27366. this._mixer._activateAction( this );
  27367. return this;
  27368. }
  27369. stop() {
  27370. this._mixer._deactivateAction( this );
  27371. return this.reset();
  27372. }
  27373. reset() {
  27374. this.paused = false;
  27375. this.enabled = true;
  27376. this.time = 0; // restart clip
  27377. this._loopCount = - 1;// forget previous loops
  27378. this._startTime = null;// forget scheduling
  27379. return this.stopFading().stopWarping();
  27380. }
  27381. isRunning() {
  27382. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  27383. this._startTime === null && this._mixer._isActiveAction( this );
  27384. }
  27385. // return true when play has been called
  27386. isScheduled() {
  27387. return this._mixer._isActiveAction( this );
  27388. }
  27389. startAt( time ) {
  27390. this._startTime = time;
  27391. return this;
  27392. }
  27393. setLoop( mode, repetitions ) {
  27394. this.loop = mode;
  27395. this.repetitions = repetitions;
  27396. return this;
  27397. }
  27398. // Weight
  27399. // set the weight stopping any scheduled fading
  27400. // although .enabled = false yields an effective weight of zero, this
  27401. // method does *not* change .enabled, because it would be confusing
  27402. setEffectiveWeight( weight ) {
  27403. this.weight = weight;
  27404. // note: same logic as when updated at runtime
  27405. this._effectiveWeight = this.enabled ? weight : 0;
  27406. return this.stopFading();
  27407. }
  27408. // return the weight considering fading and .enabled
  27409. getEffectiveWeight() {
  27410. return this._effectiveWeight;
  27411. }
  27412. fadeIn( duration ) {
  27413. return this._scheduleFading( duration, 0, 1 );
  27414. }
  27415. fadeOut( duration ) {
  27416. return this._scheduleFading( duration, 1, 0 );
  27417. }
  27418. crossFadeFrom( fadeOutAction, duration, warp ) {
  27419. fadeOutAction.fadeOut( duration );
  27420. this.fadeIn( duration );
  27421. if ( warp ) {
  27422. const fadeInDuration = this._clip.duration,
  27423. fadeOutDuration = fadeOutAction._clip.duration,
  27424. startEndRatio = fadeOutDuration / fadeInDuration,
  27425. endStartRatio = fadeInDuration / fadeOutDuration;
  27426. fadeOutAction.warp( 1.0, startEndRatio, duration );
  27427. this.warp( endStartRatio, 1.0, duration );
  27428. }
  27429. return this;
  27430. }
  27431. crossFadeTo( fadeInAction, duration, warp ) {
  27432. return fadeInAction.crossFadeFrom( this, duration, warp );
  27433. }
  27434. stopFading() {
  27435. const weightInterpolant = this._weightInterpolant;
  27436. if ( weightInterpolant !== null ) {
  27437. this._weightInterpolant = null;
  27438. this._mixer._takeBackControlInterpolant( weightInterpolant );
  27439. }
  27440. return this;
  27441. }
  27442. // Time Scale Control
  27443. // set the time scale stopping any scheduled warping
  27444. // although .paused = true yields an effective time scale of zero, this
  27445. // method does *not* change .paused, because it would be confusing
  27446. setEffectiveTimeScale( timeScale ) {
  27447. this.timeScale = timeScale;
  27448. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  27449. return this.stopWarping();
  27450. }
  27451. // return the time scale considering warping and .paused
  27452. getEffectiveTimeScale() {
  27453. return this._effectiveTimeScale;
  27454. }
  27455. setDuration( duration ) {
  27456. this.timeScale = this._clip.duration / duration;
  27457. return this.stopWarping();
  27458. }
  27459. syncWith( action ) {
  27460. this.time = action.time;
  27461. this.timeScale = action.timeScale;
  27462. return this.stopWarping();
  27463. }
  27464. halt( duration ) {
  27465. return this.warp( this._effectiveTimeScale, 0, duration );
  27466. }
  27467. warp( startTimeScale, endTimeScale, duration ) {
  27468. const mixer = this._mixer,
  27469. now = mixer.time,
  27470. timeScale = this.timeScale;
  27471. let interpolant = this._timeScaleInterpolant;
  27472. if ( interpolant === null ) {
  27473. interpolant = mixer._lendControlInterpolant();
  27474. this._timeScaleInterpolant = interpolant;
  27475. }
  27476. const times = interpolant.parameterPositions,
  27477. values = interpolant.sampleValues;
  27478. times[ 0 ] = now;
  27479. times[ 1 ] = now + duration;
  27480. values[ 0 ] = startTimeScale / timeScale;
  27481. values[ 1 ] = endTimeScale / timeScale;
  27482. return this;
  27483. }
  27484. stopWarping() {
  27485. const timeScaleInterpolant = this._timeScaleInterpolant;
  27486. if ( timeScaleInterpolant !== null ) {
  27487. this._timeScaleInterpolant = null;
  27488. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  27489. }
  27490. return this;
  27491. }
  27492. // Object Accessors
  27493. getMixer() {
  27494. return this._mixer;
  27495. }
  27496. getClip() {
  27497. return this._clip;
  27498. }
  27499. getRoot() {
  27500. return this._localRoot || this._mixer._root;
  27501. }
  27502. // Interna
  27503. _update( time, deltaTime, timeDirection, accuIndex ) {
  27504. // called by the mixer
  27505. if ( ! this.enabled ) {
  27506. // call ._updateWeight() to update ._effectiveWeight
  27507. this._updateWeight( time );
  27508. return;
  27509. }
  27510. const startTime = this._startTime;
  27511. if ( startTime !== null ) {
  27512. // check for scheduled start of action
  27513. const timeRunning = ( time - startTime ) * timeDirection;
  27514. if ( timeRunning < 0 || timeDirection === 0 ) {
  27515. deltaTime = 0;
  27516. } else {
  27517. this._startTime = null; // unschedule
  27518. deltaTime = timeDirection * timeRunning;
  27519. }
  27520. }
  27521. // apply time scale and advance time
  27522. deltaTime *= this._updateTimeScale( time );
  27523. const clipTime = this._updateTime( deltaTime );
  27524. // note: _updateTime may disable the action resulting in
  27525. // an effective weight of 0
  27526. const weight = this._updateWeight( time );
  27527. if ( weight > 0 ) {
  27528. const interpolants = this._interpolants;
  27529. const propertyMixers = this._propertyBindings;
  27530. switch ( this.blendMode ) {
  27531. case AdditiveAnimationBlendMode:
  27532. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27533. interpolants[ j ].evaluate( clipTime );
  27534. propertyMixers[ j ].accumulateAdditive( weight );
  27535. }
  27536. break;
  27537. case NormalAnimationBlendMode:
  27538. default:
  27539. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27540. interpolants[ j ].evaluate( clipTime );
  27541. propertyMixers[ j ].accumulate( accuIndex, weight );
  27542. }
  27543. }
  27544. }
  27545. }
  27546. _updateWeight( time ) {
  27547. let weight = 0;
  27548. if ( this.enabled ) {
  27549. weight = this.weight;
  27550. const interpolant = this._weightInterpolant;
  27551. if ( interpolant !== null ) {
  27552. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27553. weight *= interpolantValue;
  27554. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27555. this.stopFading();
  27556. if ( interpolantValue === 0 ) {
  27557. // faded out, disable
  27558. this.enabled = false;
  27559. }
  27560. }
  27561. }
  27562. }
  27563. this._effectiveWeight = weight;
  27564. return weight;
  27565. }
  27566. _updateTimeScale( time ) {
  27567. let timeScale = 0;
  27568. if ( ! this.paused ) {
  27569. timeScale = this.timeScale;
  27570. const interpolant = this._timeScaleInterpolant;
  27571. if ( interpolant !== null ) {
  27572. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27573. timeScale *= interpolantValue;
  27574. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27575. this.stopWarping();
  27576. if ( timeScale === 0 ) {
  27577. // motion has halted, pause
  27578. this.paused = true;
  27579. } else {
  27580. // warp done - apply final time scale
  27581. this.timeScale = timeScale;
  27582. }
  27583. }
  27584. }
  27585. }
  27586. this._effectiveTimeScale = timeScale;
  27587. return timeScale;
  27588. }
  27589. _updateTime( deltaTime ) {
  27590. const duration = this._clip.duration;
  27591. const loop = this.loop;
  27592. let time = this.time + deltaTime;
  27593. let loopCount = this._loopCount;
  27594. const pingPong = ( loop === LoopPingPong );
  27595. if ( deltaTime === 0 ) {
  27596. if ( loopCount === - 1 ) return time;
  27597. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  27598. }
  27599. if ( loop === LoopOnce ) {
  27600. if ( loopCount === - 1 ) {
  27601. // just started
  27602. this._loopCount = 0;
  27603. this._setEndings( true, true, false );
  27604. }
  27605. handle_stop: {
  27606. if ( time >= duration ) {
  27607. time = duration;
  27608. } else if ( time < 0 ) {
  27609. time = 0;
  27610. } else {
  27611. this.time = time;
  27612. break handle_stop;
  27613. }
  27614. if ( this.clampWhenFinished ) this.paused = true;
  27615. else this.enabled = false;
  27616. this.time = time;
  27617. this._mixer.dispatchEvent( {
  27618. type: 'finished', action: this,
  27619. direction: deltaTime < 0 ? - 1 : 1
  27620. } );
  27621. }
  27622. } else { // repetitive Repeat or PingPong
  27623. if ( loopCount === - 1 ) {
  27624. // just started
  27625. if ( deltaTime >= 0 ) {
  27626. loopCount = 0;
  27627. this._setEndings( true, this.repetitions === 0, pingPong );
  27628. } else {
  27629. // when looping in reverse direction, the initial
  27630. // transition through zero counts as a repetition,
  27631. // so leave loopCount at -1
  27632. this._setEndings( this.repetitions === 0, true, pingPong );
  27633. }
  27634. }
  27635. if ( time >= duration || time < 0 ) {
  27636. // wrap around
  27637. const loopDelta = Math.floor( time / duration ); // signed
  27638. time -= duration * loopDelta;
  27639. loopCount += Math.abs( loopDelta );
  27640. const pending = this.repetitions - loopCount;
  27641. if ( pending <= 0 ) {
  27642. // have to stop (switch state, clamp time, fire event)
  27643. if ( this.clampWhenFinished ) this.paused = true;
  27644. else this.enabled = false;
  27645. time = deltaTime > 0 ? duration : 0;
  27646. this.time = time;
  27647. this._mixer.dispatchEvent( {
  27648. type: 'finished', action: this,
  27649. direction: deltaTime > 0 ? 1 : - 1
  27650. } );
  27651. } else {
  27652. // keep running
  27653. if ( pending === 1 ) {
  27654. // entering the last round
  27655. const atStart = deltaTime < 0;
  27656. this._setEndings( atStart, ! atStart, pingPong );
  27657. } else {
  27658. this._setEndings( false, false, pingPong );
  27659. }
  27660. this._loopCount = loopCount;
  27661. this.time = time;
  27662. this._mixer.dispatchEvent( {
  27663. type: 'loop', action: this, loopDelta: loopDelta
  27664. } );
  27665. }
  27666. } else {
  27667. this.time = time;
  27668. }
  27669. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  27670. // invert time for the "pong round"
  27671. return duration - time;
  27672. }
  27673. }
  27674. return time;
  27675. }
  27676. _setEndings( atStart, atEnd, pingPong ) {
  27677. const settings = this._interpolantSettings;
  27678. if ( pingPong ) {
  27679. settings.endingStart = ZeroSlopeEnding;
  27680. settings.endingEnd = ZeroSlopeEnding;
  27681. } else {
  27682. // assuming for LoopOnce atStart == atEnd == true
  27683. if ( atStart ) {
  27684. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27685. } else {
  27686. settings.endingStart = WrapAroundEnding;
  27687. }
  27688. if ( atEnd ) {
  27689. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27690. } else {
  27691. settings.endingEnd = WrapAroundEnding;
  27692. }
  27693. }
  27694. }
  27695. _scheduleFading( duration, weightNow, weightThen ) {
  27696. const mixer = this._mixer, now = mixer.time;
  27697. let interpolant = this._weightInterpolant;
  27698. if ( interpolant === null ) {
  27699. interpolant = mixer._lendControlInterpolant();
  27700. this._weightInterpolant = interpolant;
  27701. }
  27702. const times = interpolant.parameterPositions,
  27703. values = interpolant.sampleValues;
  27704. times[ 0 ] = now;
  27705. values[ 0 ] = weightNow;
  27706. times[ 1 ] = now + duration;
  27707. values[ 1 ] = weightThen;
  27708. return this;
  27709. }
  27710. }
  27711. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  27712. class AnimationMixer extends EventDispatcher {
  27713. constructor( root ) {
  27714. super();
  27715. this._root = root;
  27716. this._initMemoryManager();
  27717. this._accuIndex = 0;
  27718. this.time = 0;
  27719. this.timeScale = 1.0;
  27720. }
  27721. _bindAction( action, prototypeAction ) {
  27722. const root = action._localRoot || this._root,
  27723. tracks = action._clip.tracks,
  27724. nTracks = tracks.length,
  27725. bindings = action._propertyBindings,
  27726. interpolants = action._interpolants,
  27727. rootUuid = root.uuid,
  27728. bindingsByRoot = this._bindingsByRootAndName;
  27729. let bindingsByName = bindingsByRoot[ rootUuid ];
  27730. if ( bindingsByName === undefined ) {
  27731. bindingsByName = {};
  27732. bindingsByRoot[ rootUuid ] = bindingsByName;
  27733. }
  27734. for ( let i = 0; i !== nTracks; ++ i ) {
  27735. const track = tracks[ i ],
  27736. trackName = track.name;
  27737. let binding = bindingsByName[ trackName ];
  27738. if ( binding !== undefined ) {
  27739. ++ binding.referenceCount;
  27740. bindings[ i ] = binding;
  27741. } else {
  27742. binding = bindings[ i ];
  27743. if ( binding !== undefined ) {
  27744. // existing binding, make sure the cache knows
  27745. if ( binding._cacheIndex === null ) {
  27746. ++ binding.referenceCount;
  27747. this._addInactiveBinding( binding, rootUuid, trackName );
  27748. }
  27749. continue;
  27750. }
  27751. const path = prototypeAction && prototypeAction.
  27752. _propertyBindings[ i ].binding.parsedPath;
  27753. binding = new PropertyMixer(
  27754. PropertyBinding.create( root, trackName, path ),
  27755. track.ValueTypeName, track.getValueSize() );
  27756. ++ binding.referenceCount;
  27757. this._addInactiveBinding( binding, rootUuid, trackName );
  27758. bindings[ i ] = binding;
  27759. }
  27760. interpolants[ i ].resultBuffer = binding.buffer;
  27761. }
  27762. }
  27763. _activateAction( action ) {
  27764. if ( ! this._isActiveAction( action ) ) {
  27765. if ( action._cacheIndex === null ) {
  27766. // this action has been forgotten by the cache, but the user
  27767. // appears to be still using it -> rebind
  27768. const rootUuid = ( action._localRoot || this._root ).uuid,
  27769. clipUuid = action._clip.uuid,
  27770. actionsForClip = this._actionsByClip[ clipUuid ];
  27771. this._bindAction( action,
  27772. actionsForClip && actionsForClip.knownActions[ 0 ] );
  27773. this._addInactiveAction( action, clipUuid, rootUuid );
  27774. }
  27775. const bindings = action._propertyBindings;
  27776. // increment reference counts / sort out state
  27777. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27778. const binding = bindings[ i ];
  27779. if ( binding.useCount ++ === 0 ) {
  27780. this._lendBinding( binding );
  27781. binding.saveOriginalState();
  27782. }
  27783. }
  27784. this._lendAction( action );
  27785. }
  27786. }
  27787. _deactivateAction( action ) {
  27788. if ( this._isActiveAction( action ) ) {
  27789. const bindings = action._propertyBindings;
  27790. // decrement reference counts / sort out state
  27791. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27792. const binding = bindings[ i ];
  27793. if ( -- binding.useCount === 0 ) {
  27794. binding.restoreOriginalState();
  27795. this._takeBackBinding( binding );
  27796. }
  27797. }
  27798. this._takeBackAction( action );
  27799. }
  27800. }
  27801. // Memory manager
  27802. _initMemoryManager() {
  27803. this._actions = []; // 'nActiveActions' followed by inactive ones
  27804. this._nActiveActions = 0;
  27805. this._actionsByClip = {};
  27806. // inside:
  27807. // {
  27808. // knownActions: Array< AnimationAction > - used as prototypes
  27809. // actionByRoot: AnimationAction - lookup
  27810. // }
  27811. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27812. this._nActiveBindings = 0;
  27813. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27814. this._controlInterpolants = []; // same game as above
  27815. this._nActiveControlInterpolants = 0;
  27816. const scope = this;
  27817. this.stats = {
  27818. actions: {
  27819. get total() {
  27820. return scope._actions.length;
  27821. },
  27822. get inUse() {
  27823. return scope._nActiveActions;
  27824. }
  27825. },
  27826. bindings: {
  27827. get total() {
  27828. return scope._bindings.length;
  27829. },
  27830. get inUse() {
  27831. return scope._nActiveBindings;
  27832. }
  27833. },
  27834. controlInterpolants: {
  27835. get total() {
  27836. return scope._controlInterpolants.length;
  27837. },
  27838. get inUse() {
  27839. return scope._nActiveControlInterpolants;
  27840. }
  27841. }
  27842. };
  27843. }
  27844. // Memory management for AnimationAction objects
  27845. _isActiveAction( action ) {
  27846. const index = action._cacheIndex;
  27847. return index !== null && index < this._nActiveActions;
  27848. }
  27849. _addInactiveAction( action, clipUuid, rootUuid ) {
  27850. const actions = this._actions,
  27851. actionsByClip = this._actionsByClip;
  27852. let actionsForClip = actionsByClip[ clipUuid ];
  27853. if ( actionsForClip === undefined ) {
  27854. actionsForClip = {
  27855. knownActions: [ action ],
  27856. actionByRoot: {}
  27857. };
  27858. action._byClipCacheIndex = 0;
  27859. actionsByClip[ clipUuid ] = actionsForClip;
  27860. } else {
  27861. const knownActions = actionsForClip.knownActions;
  27862. action._byClipCacheIndex = knownActions.length;
  27863. knownActions.push( action );
  27864. }
  27865. action._cacheIndex = actions.length;
  27866. actions.push( action );
  27867. actionsForClip.actionByRoot[ rootUuid ] = action;
  27868. }
  27869. _removeInactiveAction( action ) {
  27870. const actions = this._actions,
  27871. lastInactiveAction = actions[ actions.length - 1 ],
  27872. cacheIndex = action._cacheIndex;
  27873. lastInactiveAction._cacheIndex = cacheIndex;
  27874. actions[ cacheIndex ] = lastInactiveAction;
  27875. actions.pop();
  27876. action._cacheIndex = null;
  27877. const clipUuid = action._clip.uuid,
  27878. actionsByClip = this._actionsByClip,
  27879. actionsForClip = actionsByClip[ clipUuid ],
  27880. knownActionsForClip = actionsForClip.knownActions,
  27881. lastKnownAction =
  27882. knownActionsForClip[ knownActionsForClip.length - 1 ],
  27883. byClipCacheIndex = action._byClipCacheIndex;
  27884. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27885. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  27886. knownActionsForClip.pop();
  27887. action._byClipCacheIndex = null;
  27888. const actionByRoot = actionsForClip.actionByRoot,
  27889. rootUuid = ( action._localRoot || this._root ).uuid;
  27890. delete actionByRoot[ rootUuid ];
  27891. if ( knownActionsForClip.length === 0 ) {
  27892. delete actionsByClip[ clipUuid ];
  27893. }
  27894. this._removeInactiveBindingsForAction( action );
  27895. }
  27896. _removeInactiveBindingsForAction( action ) {
  27897. const bindings = action._propertyBindings;
  27898. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27899. const binding = bindings[ i ];
  27900. if ( -- binding.referenceCount === 0 ) {
  27901. this._removeInactiveBinding( binding );
  27902. }
  27903. }
  27904. }
  27905. _lendAction( action ) {
  27906. // [ active actions | inactive actions ]
  27907. // [ active actions >| inactive actions ]
  27908. // s a
  27909. // <-swap->
  27910. // a s
  27911. const actions = this._actions,
  27912. prevIndex = action._cacheIndex,
  27913. lastActiveIndex = this._nActiveActions ++,
  27914. firstInactiveAction = actions[ lastActiveIndex ];
  27915. action._cacheIndex = lastActiveIndex;
  27916. actions[ lastActiveIndex ] = action;
  27917. firstInactiveAction._cacheIndex = prevIndex;
  27918. actions[ prevIndex ] = firstInactiveAction;
  27919. }
  27920. _takeBackAction( action ) {
  27921. // [ active actions | inactive actions ]
  27922. // [ active actions |< inactive actions ]
  27923. // a s
  27924. // <-swap->
  27925. // s a
  27926. const actions = this._actions,
  27927. prevIndex = action._cacheIndex,
  27928. firstInactiveIndex = -- this._nActiveActions,
  27929. lastActiveAction = actions[ firstInactiveIndex ];
  27930. action._cacheIndex = firstInactiveIndex;
  27931. actions[ firstInactiveIndex ] = action;
  27932. lastActiveAction._cacheIndex = prevIndex;
  27933. actions[ prevIndex ] = lastActiveAction;
  27934. }
  27935. // Memory management for PropertyMixer objects
  27936. _addInactiveBinding( binding, rootUuid, trackName ) {
  27937. const bindingsByRoot = this._bindingsByRootAndName,
  27938. bindings = this._bindings;
  27939. let bindingByName = bindingsByRoot[ rootUuid ];
  27940. if ( bindingByName === undefined ) {
  27941. bindingByName = {};
  27942. bindingsByRoot[ rootUuid ] = bindingByName;
  27943. }
  27944. bindingByName[ trackName ] = binding;
  27945. binding._cacheIndex = bindings.length;
  27946. bindings.push( binding );
  27947. }
  27948. _removeInactiveBinding( binding ) {
  27949. const bindings = this._bindings,
  27950. propBinding = binding.binding,
  27951. rootUuid = propBinding.rootNode.uuid,
  27952. trackName = propBinding.path,
  27953. bindingsByRoot = this._bindingsByRootAndName,
  27954. bindingByName = bindingsByRoot[ rootUuid ],
  27955. lastInactiveBinding = bindings[ bindings.length - 1 ],
  27956. cacheIndex = binding._cacheIndex;
  27957. lastInactiveBinding._cacheIndex = cacheIndex;
  27958. bindings[ cacheIndex ] = lastInactiveBinding;
  27959. bindings.pop();
  27960. delete bindingByName[ trackName ];
  27961. if ( Object.keys( bindingByName ).length === 0 ) {
  27962. delete bindingsByRoot[ rootUuid ];
  27963. }
  27964. }
  27965. _lendBinding( binding ) {
  27966. const bindings = this._bindings,
  27967. prevIndex = binding._cacheIndex,
  27968. lastActiveIndex = this._nActiveBindings ++,
  27969. firstInactiveBinding = bindings[ lastActiveIndex ];
  27970. binding._cacheIndex = lastActiveIndex;
  27971. bindings[ lastActiveIndex ] = binding;
  27972. firstInactiveBinding._cacheIndex = prevIndex;
  27973. bindings[ prevIndex ] = firstInactiveBinding;
  27974. }
  27975. _takeBackBinding( binding ) {
  27976. const bindings = this._bindings,
  27977. prevIndex = binding._cacheIndex,
  27978. firstInactiveIndex = -- this._nActiveBindings,
  27979. lastActiveBinding = bindings[ firstInactiveIndex ];
  27980. binding._cacheIndex = firstInactiveIndex;
  27981. bindings[ firstInactiveIndex ] = binding;
  27982. lastActiveBinding._cacheIndex = prevIndex;
  27983. bindings[ prevIndex ] = lastActiveBinding;
  27984. }
  27985. // Memory management of Interpolants for weight and time scale
  27986. _lendControlInterpolant() {
  27987. const interpolants = this._controlInterpolants,
  27988. lastActiveIndex = this._nActiveControlInterpolants ++;
  27989. let interpolant = interpolants[ lastActiveIndex ];
  27990. if ( interpolant === undefined ) {
  27991. interpolant = new LinearInterpolant(
  27992. new Float32Array( 2 ), new Float32Array( 2 ),
  27993. 1, _controlInterpolantsResultBuffer );
  27994. interpolant.__cacheIndex = lastActiveIndex;
  27995. interpolants[ lastActiveIndex ] = interpolant;
  27996. }
  27997. return interpolant;
  27998. }
  27999. _takeBackControlInterpolant( interpolant ) {
  28000. const interpolants = this._controlInterpolants,
  28001. prevIndex = interpolant.__cacheIndex,
  28002. firstInactiveIndex = -- this._nActiveControlInterpolants,
  28003. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  28004. interpolant.__cacheIndex = firstInactiveIndex;
  28005. interpolants[ firstInactiveIndex ] = interpolant;
  28006. lastActiveInterpolant.__cacheIndex = prevIndex;
  28007. interpolants[ prevIndex ] = lastActiveInterpolant;
  28008. }
  28009. // return an action for a clip optionally using a custom root target
  28010. // object (this method allocates a lot of dynamic memory in case a
  28011. // previously unknown clip/root combination is specified)
  28012. clipAction( clip, optionalRoot, blendMode ) {
  28013. const root = optionalRoot || this._root,
  28014. rootUuid = root.uuid;
  28015. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  28016. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  28017. const actionsForClip = this._actionsByClip[ clipUuid ];
  28018. let prototypeAction = null;
  28019. if ( blendMode === undefined ) {
  28020. if ( clipObject !== null ) {
  28021. blendMode = clipObject.blendMode;
  28022. } else {
  28023. blendMode = NormalAnimationBlendMode;
  28024. }
  28025. }
  28026. if ( actionsForClip !== undefined ) {
  28027. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  28028. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  28029. return existingAction;
  28030. }
  28031. // we know the clip, so we don't have to parse all
  28032. // the bindings again but can just copy
  28033. prototypeAction = actionsForClip.knownActions[ 0 ];
  28034. // also, take the clip from the prototype action
  28035. if ( clipObject === null )
  28036. clipObject = prototypeAction._clip;
  28037. }
  28038. // clip must be known when specified via string
  28039. if ( clipObject === null ) return null;
  28040. // allocate all resources required to run it
  28041. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  28042. this._bindAction( newAction, prototypeAction );
  28043. // and make the action known to the memory manager
  28044. this._addInactiveAction( newAction, clipUuid, rootUuid );
  28045. return newAction;
  28046. }
  28047. // get an existing action
  28048. existingAction( clip, optionalRoot ) {
  28049. const root = optionalRoot || this._root,
  28050. rootUuid = root.uuid,
  28051. clipObject = typeof clip === 'string' ?
  28052. AnimationClip.findByName( root, clip ) : clip,
  28053. clipUuid = clipObject ? clipObject.uuid : clip,
  28054. actionsForClip = this._actionsByClip[ clipUuid ];
  28055. if ( actionsForClip !== undefined ) {
  28056. return actionsForClip.actionByRoot[ rootUuid ] || null;
  28057. }
  28058. return null;
  28059. }
  28060. // deactivates all previously scheduled actions
  28061. stopAllAction() {
  28062. const actions = this._actions,
  28063. nActions = this._nActiveActions;
  28064. for ( let i = nActions - 1; i >= 0; -- i ) {
  28065. actions[ i ].stop();
  28066. }
  28067. return this;
  28068. }
  28069. // advance the time and update apply the animation
  28070. update( deltaTime ) {
  28071. deltaTime *= this.timeScale;
  28072. const actions = this._actions,
  28073. nActions = this._nActiveActions,
  28074. time = this.time += deltaTime,
  28075. timeDirection = Math.sign( deltaTime ),
  28076. accuIndex = this._accuIndex ^= 1;
  28077. // run active actions
  28078. for ( let i = 0; i !== nActions; ++ i ) {
  28079. const action = actions[ i ];
  28080. action._update( time, deltaTime, timeDirection, accuIndex );
  28081. }
  28082. // update scene graph
  28083. const bindings = this._bindings,
  28084. nBindings = this._nActiveBindings;
  28085. for ( let i = 0; i !== nBindings; ++ i ) {
  28086. bindings[ i ].apply( accuIndex );
  28087. }
  28088. return this;
  28089. }
  28090. // Allows you to seek to a specific time in an animation.
  28091. setTime( timeInSeconds ) {
  28092. this.time = 0; // Zero out time attribute for AnimationMixer object;
  28093. for ( let i = 0; i < this._actions.length; i ++ ) {
  28094. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  28095. }
  28096. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  28097. }
  28098. // return this mixer's root target object
  28099. getRoot() {
  28100. return this._root;
  28101. }
  28102. // free all resources specific to a particular clip
  28103. uncacheClip( clip ) {
  28104. const actions = this._actions,
  28105. clipUuid = clip.uuid,
  28106. actionsByClip = this._actionsByClip,
  28107. actionsForClip = actionsByClip[ clipUuid ];
  28108. if ( actionsForClip !== undefined ) {
  28109. // note: just calling _removeInactiveAction would mess up the
  28110. // iteration state and also require updating the state we can
  28111. // just throw away
  28112. const actionsToRemove = actionsForClip.knownActions;
  28113. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  28114. const action = actionsToRemove[ i ];
  28115. this._deactivateAction( action );
  28116. const cacheIndex = action._cacheIndex,
  28117. lastInactiveAction = actions[ actions.length - 1 ];
  28118. action._cacheIndex = null;
  28119. action._byClipCacheIndex = null;
  28120. lastInactiveAction._cacheIndex = cacheIndex;
  28121. actions[ cacheIndex ] = lastInactiveAction;
  28122. actions.pop();
  28123. this._removeInactiveBindingsForAction( action );
  28124. }
  28125. delete actionsByClip[ clipUuid ];
  28126. }
  28127. }
  28128. // free all resources specific to a particular root target object
  28129. uncacheRoot( root ) {
  28130. const rootUuid = root.uuid,
  28131. actionsByClip = this._actionsByClip;
  28132. for ( const clipUuid in actionsByClip ) {
  28133. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  28134. action = actionByRoot[ rootUuid ];
  28135. if ( action !== undefined ) {
  28136. this._deactivateAction( action );
  28137. this._removeInactiveAction( action );
  28138. }
  28139. }
  28140. const bindingsByRoot = this._bindingsByRootAndName,
  28141. bindingByName = bindingsByRoot[ rootUuid ];
  28142. if ( bindingByName !== undefined ) {
  28143. for ( const trackName in bindingByName ) {
  28144. const binding = bindingByName[ trackName ];
  28145. binding.restoreOriginalState();
  28146. this._removeInactiveBinding( binding );
  28147. }
  28148. }
  28149. }
  28150. // remove a targeted clip from the cache
  28151. uncacheAction( clip, optionalRoot ) {
  28152. const action = this.existingAction( clip, optionalRoot );
  28153. if ( action !== null ) {
  28154. this._deactivateAction( action );
  28155. this._removeInactiveAction( action );
  28156. }
  28157. }
  28158. }
  28159. class Uniform {
  28160. constructor( value ) {
  28161. this.value = value;
  28162. }
  28163. clone() {
  28164. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  28165. }
  28166. }
  28167. let id = 0;
  28168. class UniformsGroup extends EventDispatcher {
  28169. constructor() {
  28170. super();
  28171. this.isUniformsGroup = true;
  28172. Object.defineProperty( this, 'id', { value: id ++ } );
  28173. this.name = '';
  28174. this.usage = StaticDrawUsage;
  28175. this.uniforms = [];
  28176. }
  28177. add( uniform ) {
  28178. this.uniforms.push( uniform );
  28179. return this;
  28180. }
  28181. remove( uniform ) {
  28182. const index = this.uniforms.indexOf( uniform );
  28183. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  28184. return this;
  28185. }
  28186. setName( name ) {
  28187. this.name = name;
  28188. return this;
  28189. }
  28190. setUsage( value ) {
  28191. this.usage = value;
  28192. return this;
  28193. }
  28194. dispose() {
  28195. this.dispatchEvent( { type: 'dispose' } );
  28196. return this;
  28197. }
  28198. copy( source ) {
  28199. this.name = source.name;
  28200. this.usage = source.usage;
  28201. const uniformsSource = source.uniforms;
  28202. this.uniforms.length = 0;
  28203. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  28204. this.uniforms.push( uniformsSource[ i ].clone() );
  28205. }
  28206. return this;
  28207. }
  28208. clone() {
  28209. return new this.constructor().copy( this );
  28210. }
  28211. }
  28212. class InstancedInterleavedBuffer extends InterleavedBuffer {
  28213. constructor( array, stride, meshPerAttribute = 1 ) {
  28214. super( array, stride );
  28215. this.isInstancedInterleavedBuffer = true;
  28216. this.meshPerAttribute = meshPerAttribute;
  28217. }
  28218. copy( source ) {
  28219. super.copy( source );
  28220. this.meshPerAttribute = source.meshPerAttribute;
  28221. return this;
  28222. }
  28223. clone( data ) {
  28224. const ib = super.clone( data );
  28225. ib.meshPerAttribute = this.meshPerAttribute;
  28226. return ib;
  28227. }
  28228. toJSON( data ) {
  28229. const json = super.toJSON( data );
  28230. json.isInstancedInterleavedBuffer = true;
  28231. json.meshPerAttribute = this.meshPerAttribute;
  28232. return json;
  28233. }
  28234. }
  28235. class GLBufferAttribute {
  28236. constructor( buffer, type, itemSize, elementSize, count ) {
  28237. this.isGLBufferAttribute = true;
  28238. this.name = '';
  28239. this.buffer = buffer;
  28240. this.type = type;
  28241. this.itemSize = itemSize;
  28242. this.elementSize = elementSize;
  28243. this.count = count;
  28244. this.version = 0;
  28245. }
  28246. set needsUpdate( value ) {
  28247. if ( value === true ) this.version ++;
  28248. }
  28249. setBuffer( buffer ) {
  28250. this.buffer = buffer;
  28251. return this;
  28252. }
  28253. setType( type, elementSize ) {
  28254. this.type = type;
  28255. this.elementSize = elementSize;
  28256. return this;
  28257. }
  28258. setItemSize( itemSize ) {
  28259. this.itemSize = itemSize;
  28260. return this;
  28261. }
  28262. setCount( count ) {
  28263. this.count = count;
  28264. return this;
  28265. }
  28266. }
  28267. class Raycaster {
  28268. constructor( origin, direction, near = 0, far = Infinity ) {
  28269. this.ray = new Ray( origin, direction );
  28270. // direction is assumed to be normalized (for accurate distance calculations)
  28271. this.near = near;
  28272. this.far = far;
  28273. this.camera = null;
  28274. this.layers = new Layers();
  28275. this.params = {
  28276. Mesh: {},
  28277. Line: { threshold: 1 },
  28278. LOD: {},
  28279. Points: { threshold: 1 },
  28280. Sprite: {}
  28281. };
  28282. }
  28283. set( origin, direction ) {
  28284. // direction is assumed to be normalized (for accurate distance calculations)
  28285. this.ray.set( origin, direction );
  28286. }
  28287. setFromCamera( coords, camera ) {
  28288. if ( camera.isPerspectiveCamera ) {
  28289. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  28290. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  28291. this.camera = camera;
  28292. } else if ( camera.isOrthographicCamera ) {
  28293. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  28294. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  28295. this.camera = camera;
  28296. } else {
  28297. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  28298. }
  28299. }
  28300. intersectObject( object, recursive = true, intersects = [] ) {
  28301. intersectObject( object, this, intersects, recursive );
  28302. intersects.sort( ascSort );
  28303. return intersects;
  28304. }
  28305. intersectObjects( objects, recursive = true, intersects = [] ) {
  28306. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  28307. intersectObject( objects[ i ], this, intersects, recursive );
  28308. }
  28309. intersects.sort( ascSort );
  28310. return intersects;
  28311. }
  28312. }
  28313. function ascSort( a, b ) {
  28314. return a.distance - b.distance;
  28315. }
  28316. function intersectObject( object, raycaster, intersects, recursive ) {
  28317. if ( object.layers.test( raycaster.layers ) ) {
  28318. object.raycast( raycaster, intersects );
  28319. }
  28320. if ( recursive === true ) {
  28321. const children = object.children;
  28322. for ( let i = 0, l = children.length; i < l; i ++ ) {
  28323. intersectObject( children[ i ], raycaster, intersects, true );
  28324. }
  28325. }
  28326. }
  28327. /**
  28328. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  28329. *
  28330. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  28331. * The azimuthal angle (theta) is measured from the positive z-axis.
  28332. */
  28333. class Spherical {
  28334. constructor( radius = 1, phi = 0, theta = 0 ) {
  28335. this.radius = radius;
  28336. this.phi = phi; // polar angle
  28337. this.theta = theta; // azimuthal angle
  28338. return this;
  28339. }
  28340. set( radius, phi, theta ) {
  28341. this.radius = radius;
  28342. this.phi = phi;
  28343. this.theta = theta;
  28344. return this;
  28345. }
  28346. copy( other ) {
  28347. this.radius = other.radius;
  28348. this.phi = other.phi;
  28349. this.theta = other.theta;
  28350. return this;
  28351. }
  28352. // restrict phi to be between EPS and PI-EPS
  28353. makeSafe() {
  28354. const EPS = 0.000001;
  28355. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  28356. return this;
  28357. }
  28358. setFromVector3( v ) {
  28359. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28360. }
  28361. setFromCartesianCoords( x, y, z ) {
  28362. this.radius = Math.sqrt( x * x + y * y + z * z );
  28363. if ( this.radius === 0 ) {
  28364. this.theta = 0;
  28365. this.phi = 0;
  28366. } else {
  28367. this.theta = Math.atan2( x, z );
  28368. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  28369. }
  28370. return this;
  28371. }
  28372. clone() {
  28373. return new this.constructor().copy( this );
  28374. }
  28375. }
  28376. /**
  28377. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  28378. */
  28379. class Cylindrical {
  28380. constructor( radius = 1, theta = 0, y = 0 ) {
  28381. this.radius = radius; // distance from the origin to a point in the x-z plane
  28382. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  28383. this.y = y; // height above the x-z plane
  28384. return this;
  28385. }
  28386. set( radius, theta, y ) {
  28387. this.radius = radius;
  28388. this.theta = theta;
  28389. this.y = y;
  28390. return this;
  28391. }
  28392. copy( other ) {
  28393. this.radius = other.radius;
  28394. this.theta = other.theta;
  28395. this.y = other.y;
  28396. return this;
  28397. }
  28398. setFromVector3( v ) {
  28399. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28400. }
  28401. setFromCartesianCoords( x, y, z ) {
  28402. this.radius = Math.sqrt( x * x + z * z );
  28403. this.theta = Math.atan2( x, z );
  28404. this.y = y;
  28405. return this;
  28406. }
  28407. clone() {
  28408. return new this.constructor().copy( this );
  28409. }
  28410. }
  28411. const _vector$4 = /*@__PURE__*/ new Vector2();
  28412. class Box2 {
  28413. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  28414. this.isBox2 = true;
  28415. this.min = min;
  28416. this.max = max;
  28417. }
  28418. set( min, max ) {
  28419. this.min.copy( min );
  28420. this.max.copy( max );
  28421. return this;
  28422. }
  28423. setFromPoints( points ) {
  28424. this.makeEmpty();
  28425. for ( let i = 0, il = points.length; i < il; i ++ ) {
  28426. this.expandByPoint( points[ i ] );
  28427. }
  28428. return this;
  28429. }
  28430. setFromCenterAndSize( center, size ) {
  28431. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  28432. this.min.copy( center ).sub( halfSize );
  28433. this.max.copy( center ).add( halfSize );
  28434. return this;
  28435. }
  28436. clone() {
  28437. return new this.constructor().copy( this );
  28438. }
  28439. copy( box ) {
  28440. this.min.copy( box.min );
  28441. this.max.copy( box.max );
  28442. return this;
  28443. }
  28444. makeEmpty() {
  28445. this.min.x = this.min.y = + Infinity;
  28446. this.max.x = this.max.y = - Infinity;
  28447. return this;
  28448. }
  28449. isEmpty() {
  28450. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  28451. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  28452. }
  28453. getCenter( target ) {
  28454. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  28455. }
  28456. getSize( target ) {
  28457. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  28458. }
  28459. expandByPoint( point ) {
  28460. this.min.min( point );
  28461. this.max.max( point );
  28462. return this;
  28463. }
  28464. expandByVector( vector ) {
  28465. this.min.sub( vector );
  28466. this.max.add( vector );
  28467. return this;
  28468. }
  28469. expandByScalar( scalar ) {
  28470. this.min.addScalar( - scalar );
  28471. this.max.addScalar( scalar );
  28472. return this;
  28473. }
  28474. containsPoint( point ) {
  28475. return point.x < this.min.x || point.x > this.max.x ||
  28476. point.y < this.min.y || point.y > this.max.y ? false : true;
  28477. }
  28478. containsBox( box ) {
  28479. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  28480. this.min.y <= box.min.y && box.max.y <= this.max.y;
  28481. }
  28482. getParameter( point, target ) {
  28483. // This can potentially have a divide by zero if the box
  28484. // has a size dimension of 0.
  28485. return target.set(
  28486. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  28487. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  28488. );
  28489. }
  28490. intersectsBox( box ) {
  28491. // using 4 splitting planes to rule out intersections
  28492. return box.max.x < this.min.x || box.min.x > this.max.x ||
  28493. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  28494. }
  28495. clampPoint( point, target ) {
  28496. return target.copy( point ).clamp( this.min, this.max );
  28497. }
  28498. distanceToPoint( point ) {
  28499. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  28500. }
  28501. intersect( box ) {
  28502. this.min.max( box.min );
  28503. this.max.min( box.max );
  28504. if ( this.isEmpty() ) this.makeEmpty();
  28505. return this;
  28506. }
  28507. union( box ) {
  28508. this.min.min( box.min );
  28509. this.max.max( box.max );
  28510. return this;
  28511. }
  28512. translate( offset ) {
  28513. this.min.add( offset );
  28514. this.max.add( offset );
  28515. return this;
  28516. }
  28517. equals( box ) {
  28518. return box.min.equals( this.min ) && box.max.equals( this.max );
  28519. }
  28520. }
  28521. const _startP = /*@__PURE__*/ new Vector3();
  28522. const _startEnd = /*@__PURE__*/ new Vector3();
  28523. class Line3 {
  28524. constructor( start = new Vector3(), end = new Vector3() ) {
  28525. this.start = start;
  28526. this.end = end;
  28527. }
  28528. set( start, end ) {
  28529. this.start.copy( start );
  28530. this.end.copy( end );
  28531. return this;
  28532. }
  28533. copy( line ) {
  28534. this.start.copy( line.start );
  28535. this.end.copy( line.end );
  28536. return this;
  28537. }
  28538. getCenter( target ) {
  28539. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  28540. }
  28541. delta( target ) {
  28542. return target.subVectors( this.end, this.start );
  28543. }
  28544. distanceSq() {
  28545. return this.start.distanceToSquared( this.end );
  28546. }
  28547. distance() {
  28548. return this.start.distanceTo( this.end );
  28549. }
  28550. at( t, target ) {
  28551. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28552. }
  28553. closestPointToPointParameter( point, clampToLine ) {
  28554. _startP.subVectors( point, this.start );
  28555. _startEnd.subVectors( this.end, this.start );
  28556. const startEnd2 = _startEnd.dot( _startEnd );
  28557. const startEnd_startP = _startEnd.dot( _startP );
  28558. let t = startEnd_startP / startEnd2;
  28559. if ( clampToLine ) {
  28560. t = clamp( t, 0, 1 );
  28561. }
  28562. return t;
  28563. }
  28564. closestPointToPoint( point, clampToLine, target ) {
  28565. const t = this.closestPointToPointParameter( point, clampToLine );
  28566. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28567. }
  28568. applyMatrix4( matrix ) {
  28569. this.start.applyMatrix4( matrix );
  28570. this.end.applyMatrix4( matrix );
  28571. return this;
  28572. }
  28573. equals( line ) {
  28574. return line.start.equals( this.start ) && line.end.equals( this.end );
  28575. }
  28576. clone() {
  28577. return new this.constructor().copy( this );
  28578. }
  28579. }
  28580. const _vector$3 = /*@__PURE__*/ new Vector3();
  28581. class SpotLightHelper extends Object3D {
  28582. constructor( light, color ) {
  28583. super();
  28584. this.light = light;
  28585. this.matrix = light.matrixWorld;
  28586. this.matrixAutoUpdate = false;
  28587. this.color = color;
  28588. this.type = 'SpotLightHelper';
  28589. const geometry = new BufferGeometry();
  28590. const positions = [
  28591. 0, 0, 0, 0, 0, 1,
  28592. 0, 0, 0, 1, 0, 1,
  28593. 0, 0, 0, - 1, 0, 1,
  28594. 0, 0, 0, 0, 1, 1,
  28595. 0, 0, 0, 0, - 1, 1
  28596. ];
  28597. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  28598. const p1 = ( i / l ) * Math.PI * 2;
  28599. const p2 = ( j / l ) * Math.PI * 2;
  28600. positions.push(
  28601. Math.cos( p1 ), Math.sin( p1 ), 1,
  28602. Math.cos( p2 ), Math.sin( p2 ), 1
  28603. );
  28604. }
  28605. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28606. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28607. this.cone = new LineSegments( geometry, material );
  28608. this.add( this.cone );
  28609. this.update();
  28610. }
  28611. dispose() {
  28612. this.cone.geometry.dispose();
  28613. this.cone.material.dispose();
  28614. }
  28615. update() {
  28616. this.light.updateWorldMatrix( true, false );
  28617. this.light.target.updateWorldMatrix( true, false );
  28618. const coneLength = this.light.distance ? this.light.distance : 1000;
  28619. const coneWidth = coneLength * Math.tan( this.light.angle );
  28620. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  28621. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  28622. this.cone.lookAt( _vector$3 );
  28623. if ( this.color !== undefined ) {
  28624. this.cone.material.color.set( this.color );
  28625. } else {
  28626. this.cone.material.color.copy( this.light.color );
  28627. }
  28628. }
  28629. }
  28630. const _vector$2 = /*@__PURE__*/ new Vector3();
  28631. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  28632. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  28633. class SkeletonHelper extends LineSegments {
  28634. constructor( object ) {
  28635. const bones = getBoneList( object );
  28636. const geometry = new BufferGeometry();
  28637. const vertices = [];
  28638. const colors = [];
  28639. const color1 = new Color( 0, 0, 1 );
  28640. const color2 = new Color( 0, 1, 0 );
  28641. for ( let i = 0; i < bones.length; i ++ ) {
  28642. const bone = bones[ i ];
  28643. if ( bone.parent && bone.parent.isBone ) {
  28644. vertices.push( 0, 0, 0 );
  28645. vertices.push( 0, 0, 0 );
  28646. colors.push( color1.r, color1.g, color1.b );
  28647. colors.push( color2.r, color2.g, color2.b );
  28648. }
  28649. }
  28650. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28651. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28652. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  28653. super( geometry, material );
  28654. this.isSkeletonHelper = true;
  28655. this.type = 'SkeletonHelper';
  28656. this.root = object;
  28657. this.bones = bones;
  28658. this.matrix = object.matrixWorld;
  28659. this.matrixAutoUpdate = false;
  28660. }
  28661. updateMatrixWorld( force ) {
  28662. const bones = this.bones;
  28663. const geometry = this.geometry;
  28664. const position = geometry.getAttribute( 'position' );
  28665. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  28666. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  28667. const bone = bones[ i ];
  28668. if ( bone.parent && bone.parent.isBone ) {
  28669. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  28670. _vector$2.setFromMatrixPosition( _boneMatrix );
  28671. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  28672. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  28673. _vector$2.setFromMatrixPosition( _boneMatrix );
  28674. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  28675. j += 2;
  28676. }
  28677. }
  28678. geometry.getAttribute( 'position' ).needsUpdate = true;
  28679. super.updateMatrixWorld( force );
  28680. }
  28681. dispose() {
  28682. this.geometry.dispose();
  28683. this.material.dispose();
  28684. }
  28685. }
  28686. function getBoneList( object ) {
  28687. const boneList = [];
  28688. if ( object.isBone === true ) {
  28689. boneList.push( object );
  28690. }
  28691. for ( let i = 0; i < object.children.length; i ++ ) {
  28692. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  28693. }
  28694. return boneList;
  28695. }
  28696. class PointLightHelper extends Mesh {
  28697. constructor( light, sphereSize, color ) {
  28698. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  28699. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28700. super( geometry, material );
  28701. this.light = light;
  28702. this.color = color;
  28703. this.type = 'PointLightHelper';
  28704. this.matrix = this.light.matrixWorld;
  28705. this.matrixAutoUpdate = false;
  28706. this.update();
  28707. /*
  28708. // TODO: delete this comment?
  28709. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  28710. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28711. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28712. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28713. const d = light.distance;
  28714. if ( d === 0.0 ) {
  28715. this.lightDistance.visible = false;
  28716. } else {
  28717. this.lightDistance.scale.set( d, d, d );
  28718. }
  28719. this.add( this.lightDistance );
  28720. */
  28721. }
  28722. dispose() {
  28723. this.geometry.dispose();
  28724. this.material.dispose();
  28725. }
  28726. update() {
  28727. this.light.updateWorldMatrix( true, false );
  28728. if ( this.color !== undefined ) {
  28729. this.material.color.set( this.color );
  28730. } else {
  28731. this.material.color.copy( this.light.color );
  28732. }
  28733. /*
  28734. const d = this.light.distance;
  28735. if ( d === 0.0 ) {
  28736. this.lightDistance.visible = false;
  28737. } else {
  28738. this.lightDistance.visible = true;
  28739. this.lightDistance.scale.set( d, d, d );
  28740. }
  28741. */
  28742. }
  28743. }
  28744. const _vector$1 = /*@__PURE__*/ new Vector3();
  28745. const _color1 = /*@__PURE__*/ new Color();
  28746. const _color2 = /*@__PURE__*/ new Color();
  28747. class HemisphereLightHelper extends Object3D {
  28748. constructor( light, size, color ) {
  28749. super();
  28750. this.light = light;
  28751. this.matrix = light.matrixWorld;
  28752. this.matrixAutoUpdate = false;
  28753. this.color = color;
  28754. this.type = 'HemisphereLightHelper';
  28755. const geometry = new OctahedronGeometry( size );
  28756. geometry.rotateY( Math.PI * 0.5 );
  28757. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28758. if ( this.color === undefined ) this.material.vertexColors = true;
  28759. const position = geometry.getAttribute( 'position' );
  28760. const colors = new Float32Array( position.count * 3 );
  28761. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  28762. this.add( new Mesh( geometry, this.material ) );
  28763. this.update();
  28764. }
  28765. dispose() {
  28766. this.children[ 0 ].geometry.dispose();
  28767. this.children[ 0 ].material.dispose();
  28768. }
  28769. update() {
  28770. const mesh = this.children[ 0 ];
  28771. if ( this.color !== undefined ) {
  28772. this.material.color.set( this.color );
  28773. } else {
  28774. const colors = mesh.geometry.getAttribute( 'color' );
  28775. _color1.copy( this.light.color );
  28776. _color2.copy( this.light.groundColor );
  28777. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  28778. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  28779. colors.setXYZ( i, color.r, color.g, color.b );
  28780. }
  28781. colors.needsUpdate = true;
  28782. }
  28783. this.light.updateWorldMatrix( true, false );
  28784. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  28785. }
  28786. }
  28787. class GridHelper extends LineSegments {
  28788. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  28789. color1 = new Color( color1 );
  28790. color2 = new Color( color2 );
  28791. const center = divisions / 2;
  28792. const step = size / divisions;
  28793. const halfSize = size / 2;
  28794. const vertices = [], colors = [];
  28795. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  28796. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  28797. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  28798. const color = i === center ? color1 : color2;
  28799. color.toArray( colors, j ); j += 3;
  28800. color.toArray( colors, j ); j += 3;
  28801. color.toArray( colors, j ); j += 3;
  28802. color.toArray( colors, j ); j += 3;
  28803. }
  28804. const geometry = new BufferGeometry();
  28805. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28806. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28807. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28808. super( geometry, material );
  28809. this.type = 'GridHelper';
  28810. }
  28811. dispose() {
  28812. this.geometry.dispose();
  28813. this.material.dispose();
  28814. }
  28815. }
  28816. class PolarGridHelper extends LineSegments {
  28817. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  28818. color1 = new Color( color1 );
  28819. color2 = new Color( color2 );
  28820. const vertices = [];
  28821. const colors = [];
  28822. // create the sectors
  28823. if ( sectors > 1 ) {
  28824. for ( let i = 0; i < sectors; i ++ ) {
  28825. const v = ( i / sectors ) * ( Math.PI * 2 );
  28826. const x = Math.sin( v ) * radius;
  28827. const z = Math.cos( v ) * radius;
  28828. vertices.push( 0, 0, 0 );
  28829. vertices.push( x, 0, z );
  28830. const color = ( i & 1 ) ? color1 : color2;
  28831. colors.push( color.r, color.g, color.b );
  28832. colors.push( color.r, color.g, color.b );
  28833. }
  28834. }
  28835. // create the rings
  28836. for ( let i = 0; i < rings; i ++ ) {
  28837. const color = ( i & 1 ) ? color1 : color2;
  28838. const r = radius - ( radius / rings * i );
  28839. for ( let j = 0; j < divisions; j ++ ) {
  28840. // first vertex
  28841. let v = ( j / divisions ) * ( Math.PI * 2 );
  28842. let x = Math.sin( v ) * r;
  28843. let z = Math.cos( v ) * r;
  28844. vertices.push( x, 0, z );
  28845. colors.push( color.r, color.g, color.b );
  28846. // second vertex
  28847. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  28848. x = Math.sin( v ) * r;
  28849. z = Math.cos( v ) * r;
  28850. vertices.push( x, 0, z );
  28851. colors.push( color.r, color.g, color.b );
  28852. }
  28853. }
  28854. const geometry = new BufferGeometry();
  28855. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28856. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28857. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28858. super( geometry, material );
  28859. this.type = 'PolarGridHelper';
  28860. }
  28861. dispose() {
  28862. this.geometry.dispose();
  28863. this.material.dispose();
  28864. }
  28865. }
  28866. const _v1 = /*@__PURE__*/ new Vector3();
  28867. const _v2 = /*@__PURE__*/ new Vector3();
  28868. const _v3 = /*@__PURE__*/ new Vector3();
  28869. class DirectionalLightHelper extends Object3D {
  28870. constructor( light, size, color ) {
  28871. super();
  28872. this.light = light;
  28873. this.matrix = light.matrixWorld;
  28874. this.matrixAutoUpdate = false;
  28875. this.color = color;
  28876. this.type = 'DirectionalLightHelper';
  28877. if ( size === undefined ) size = 1;
  28878. let geometry = new BufferGeometry();
  28879. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  28880. - size, size, 0,
  28881. size, size, 0,
  28882. size, - size, 0,
  28883. - size, - size, 0,
  28884. - size, size, 0
  28885. ], 3 ) );
  28886. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28887. this.lightPlane = new Line( geometry, material );
  28888. this.add( this.lightPlane );
  28889. geometry = new BufferGeometry();
  28890. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  28891. this.targetLine = new Line( geometry, material );
  28892. this.add( this.targetLine );
  28893. this.update();
  28894. }
  28895. dispose() {
  28896. this.lightPlane.geometry.dispose();
  28897. this.lightPlane.material.dispose();
  28898. this.targetLine.geometry.dispose();
  28899. this.targetLine.material.dispose();
  28900. }
  28901. update() {
  28902. this.light.updateWorldMatrix( true, false );
  28903. this.light.target.updateWorldMatrix( true, false );
  28904. _v1.setFromMatrixPosition( this.light.matrixWorld );
  28905. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  28906. _v3.subVectors( _v2, _v1 );
  28907. this.lightPlane.lookAt( _v2 );
  28908. if ( this.color !== undefined ) {
  28909. this.lightPlane.material.color.set( this.color );
  28910. this.targetLine.material.color.set( this.color );
  28911. } else {
  28912. this.lightPlane.material.color.copy( this.light.color );
  28913. this.targetLine.material.color.copy( this.light.color );
  28914. }
  28915. this.targetLine.lookAt( _v2 );
  28916. this.targetLine.scale.z = _v3.length();
  28917. }
  28918. }
  28919. const _vector = /*@__PURE__*/ new Vector3();
  28920. const _camera = /*@__PURE__*/ new Camera();
  28921. /**
  28922. * - shows frustum, line of sight and up of the camera
  28923. * - suitable for fast updates
  28924. * - based on frustum visualization in lightgl.js shadowmap example
  28925. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  28926. */
  28927. class CameraHelper extends LineSegments {
  28928. constructor( camera ) {
  28929. const geometry = new BufferGeometry();
  28930. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  28931. const vertices = [];
  28932. const colors = [];
  28933. const pointMap = {};
  28934. // near
  28935. addLine( 'n1', 'n2' );
  28936. addLine( 'n2', 'n4' );
  28937. addLine( 'n4', 'n3' );
  28938. addLine( 'n3', 'n1' );
  28939. // far
  28940. addLine( 'f1', 'f2' );
  28941. addLine( 'f2', 'f4' );
  28942. addLine( 'f4', 'f3' );
  28943. addLine( 'f3', 'f1' );
  28944. // sides
  28945. addLine( 'n1', 'f1' );
  28946. addLine( 'n2', 'f2' );
  28947. addLine( 'n3', 'f3' );
  28948. addLine( 'n4', 'f4' );
  28949. // cone
  28950. addLine( 'p', 'n1' );
  28951. addLine( 'p', 'n2' );
  28952. addLine( 'p', 'n3' );
  28953. addLine( 'p', 'n4' );
  28954. // up
  28955. addLine( 'u1', 'u2' );
  28956. addLine( 'u2', 'u3' );
  28957. addLine( 'u3', 'u1' );
  28958. // target
  28959. addLine( 'c', 't' );
  28960. addLine( 'p', 'c' );
  28961. // cross
  28962. addLine( 'cn1', 'cn2' );
  28963. addLine( 'cn3', 'cn4' );
  28964. addLine( 'cf1', 'cf2' );
  28965. addLine( 'cf3', 'cf4' );
  28966. function addLine( a, b ) {
  28967. addPoint( a );
  28968. addPoint( b );
  28969. }
  28970. function addPoint( id ) {
  28971. vertices.push( 0, 0, 0 );
  28972. colors.push( 0, 0, 0 );
  28973. if ( pointMap[ id ] === undefined ) {
  28974. pointMap[ id ] = [];
  28975. }
  28976. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  28977. }
  28978. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28979. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28980. super( geometry, material );
  28981. this.type = 'CameraHelper';
  28982. this.camera = camera;
  28983. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  28984. this.matrix = camera.matrixWorld;
  28985. this.matrixAutoUpdate = false;
  28986. this.pointMap = pointMap;
  28987. this.update();
  28988. // colors
  28989. const colorFrustum = new Color( 0xffaa00 );
  28990. const colorCone = new Color( 0xff0000 );
  28991. const colorUp = new Color( 0x00aaff );
  28992. const colorTarget = new Color( 0xffffff );
  28993. const colorCross = new Color( 0x333333 );
  28994. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  28995. }
  28996. setColors( frustum, cone, up, target, cross ) {
  28997. const geometry = this.geometry;
  28998. const colorAttribute = geometry.getAttribute( 'color' );
  28999. // near
  29000. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  29001. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  29002. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  29003. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  29004. // far
  29005. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  29006. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  29007. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  29008. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  29009. // sides
  29010. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  29011. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  29012. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  29013. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  29014. // cone
  29015. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  29016. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  29017. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  29018. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  29019. // up
  29020. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  29021. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  29022. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  29023. // target
  29024. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  29025. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  29026. // cross
  29027. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  29028. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  29029. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  29030. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  29031. colorAttribute.needsUpdate = true;
  29032. }
  29033. update() {
  29034. const geometry = this.geometry;
  29035. const pointMap = this.pointMap;
  29036. const w = 1, h = 1;
  29037. // we need just camera projection matrix inverse
  29038. // world matrix must be identity
  29039. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  29040. // center / target
  29041. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  29042. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  29043. // near
  29044. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  29045. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  29046. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  29047. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  29048. // far
  29049. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  29050. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  29051. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  29052. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  29053. // up
  29054. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  29055. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  29056. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  29057. // cross
  29058. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  29059. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  29060. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  29061. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  29062. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  29063. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  29064. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  29065. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  29066. geometry.getAttribute( 'position' ).needsUpdate = true;
  29067. }
  29068. dispose() {
  29069. this.geometry.dispose();
  29070. this.material.dispose();
  29071. }
  29072. }
  29073. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  29074. _vector.set( x, y, z ).unproject( camera );
  29075. const points = pointMap[ point ];
  29076. if ( points !== undefined ) {
  29077. const position = geometry.getAttribute( 'position' );
  29078. for ( let i = 0, l = points.length; i < l; i ++ ) {
  29079. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  29080. }
  29081. }
  29082. }
  29083. const _box = /*@__PURE__*/ new Box3();
  29084. class BoxHelper extends LineSegments {
  29085. constructor( object, color = 0xffff00 ) {
  29086. 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 ] );
  29087. const positions = new Float32Array( 8 * 3 );
  29088. const geometry = new BufferGeometry();
  29089. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29090. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  29091. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29092. this.object = object;
  29093. this.type = 'BoxHelper';
  29094. this.matrixAutoUpdate = false;
  29095. this.update();
  29096. }
  29097. update( object ) {
  29098. if ( object !== undefined ) {
  29099. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  29100. }
  29101. if ( this.object !== undefined ) {
  29102. _box.setFromObject( this.object );
  29103. }
  29104. if ( _box.isEmpty() ) return;
  29105. const min = _box.min;
  29106. const max = _box.max;
  29107. /*
  29108. 5____4
  29109. 1/___0/|
  29110. | 6__|_7
  29111. 2/___3/
  29112. 0: max.x, max.y, max.z
  29113. 1: min.x, max.y, max.z
  29114. 2: min.x, min.y, max.z
  29115. 3: max.x, min.y, max.z
  29116. 4: max.x, max.y, min.z
  29117. 5: min.x, max.y, min.z
  29118. 6: min.x, min.y, min.z
  29119. 7: max.x, min.y, min.z
  29120. */
  29121. const position = this.geometry.attributes.position;
  29122. const array = position.array;
  29123. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  29124. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  29125. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  29126. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  29127. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  29128. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  29129. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  29130. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  29131. position.needsUpdate = true;
  29132. this.geometry.computeBoundingSphere();
  29133. }
  29134. setFromObject( object ) {
  29135. this.object = object;
  29136. this.update();
  29137. return this;
  29138. }
  29139. copy( source, recursive ) {
  29140. super.copy( source, recursive );
  29141. this.object = source.object;
  29142. return this;
  29143. }
  29144. dispose() {
  29145. this.geometry.dispose();
  29146. this.material.dispose();
  29147. }
  29148. }
  29149. class Box3Helper extends LineSegments {
  29150. constructor( box, color = 0xffff00 ) {
  29151. 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 ] );
  29152. 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 ];
  29153. const geometry = new BufferGeometry();
  29154. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29155. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29156. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29157. this.box = box;
  29158. this.type = 'Box3Helper';
  29159. this.geometry.computeBoundingSphere();
  29160. }
  29161. updateMatrixWorld( force ) {
  29162. const box = this.box;
  29163. if ( box.isEmpty() ) return;
  29164. box.getCenter( this.position );
  29165. box.getSize( this.scale );
  29166. this.scale.multiplyScalar( 0.5 );
  29167. super.updateMatrixWorld( force );
  29168. }
  29169. dispose() {
  29170. this.geometry.dispose();
  29171. this.material.dispose();
  29172. }
  29173. }
  29174. class PlaneHelper extends Line {
  29175. constructor( plane, size = 1, hex = 0xffff00 ) {
  29176. const color = hex;
  29177. 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 ];
  29178. const geometry = new BufferGeometry();
  29179. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29180. geometry.computeBoundingSphere();
  29181. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29182. this.type = 'PlaneHelper';
  29183. this.plane = plane;
  29184. this.size = size;
  29185. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  29186. const geometry2 = new BufferGeometry();
  29187. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  29188. geometry2.computeBoundingSphere();
  29189. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  29190. }
  29191. updateMatrixWorld( force ) {
  29192. this.position.set( 0, 0, 0 );
  29193. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  29194. this.lookAt( this.plane.normal );
  29195. this.translateZ( - this.plane.constant );
  29196. super.updateMatrixWorld( force );
  29197. }
  29198. dispose() {
  29199. this.geometry.dispose();
  29200. this.material.dispose();
  29201. this.children[ 0 ].geometry.dispose();
  29202. this.children[ 0 ].material.dispose();
  29203. }
  29204. }
  29205. const _axis = /*@__PURE__*/ new Vector3();
  29206. let _lineGeometry, _coneGeometry;
  29207. class ArrowHelper extends Object3D {
  29208. // dir is assumed to be normalized
  29209. 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 ) {
  29210. super();
  29211. this.type = 'ArrowHelper';
  29212. if ( _lineGeometry === undefined ) {
  29213. _lineGeometry = new BufferGeometry();
  29214. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  29215. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  29216. _coneGeometry.translate( 0, - 0.5, 0 );
  29217. }
  29218. this.position.copy( origin );
  29219. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29220. this.line.matrixAutoUpdate = false;
  29221. this.add( this.line );
  29222. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  29223. this.cone.matrixAutoUpdate = false;
  29224. this.add( this.cone );
  29225. this.setDirection( dir );
  29226. this.setLength( length, headLength, headWidth );
  29227. }
  29228. setDirection( dir ) {
  29229. // dir is assumed to be normalized
  29230. if ( dir.y > 0.99999 ) {
  29231. this.quaternion.set( 0, 0, 0, 1 );
  29232. } else if ( dir.y < - 0.99999 ) {
  29233. this.quaternion.set( 1, 0, 0, 0 );
  29234. } else {
  29235. _axis.set( dir.z, 0, - dir.x ).normalize();
  29236. const radians = Math.acos( dir.y );
  29237. this.quaternion.setFromAxisAngle( _axis, radians );
  29238. }
  29239. }
  29240. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  29241. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  29242. this.line.updateMatrix();
  29243. this.cone.scale.set( headWidth, headLength, headWidth );
  29244. this.cone.position.y = length;
  29245. this.cone.updateMatrix();
  29246. }
  29247. setColor( color ) {
  29248. this.line.material.color.set( color );
  29249. this.cone.material.color.set( color );
  29250. }
  29251. copy( source ) {
  29252. super.copy( source, false );
  29253. this.line.copy( source.line );
  29254. this.cone.copy( source.cone );
  29255. return this;
  29256. }
  29257. dispose() {
  29258. this.line.geometry.dispose();
  29259. this.line.material.dispose();
  29260. this.cone.geometry.dispose();
  29261. this.cone.material.dispose();
  29262. }
  29263. }
  29264. class AxesHelper extends LineSegments {
  29265. constructor( size = 1 ) {
  29266. const vertices = [
  29267. 0, 0, 0, size, 0, 0,
  29268. 0, 0, 0, 0, size, 0,
  29269. 0, 0, 0, 0, 0, size
  29270. ];
  29271. const colors = [
  29272. 1, 0, 0, 1, 0.6, 0,
  29273. 0, 1, 0, 0.6, 1, 0,
  29274. 0, 0, 1, 0, 0.6, 1
  29275. ];
  29276. const geometry = new BufferGeometry();
  29277. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29278. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29279. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29280. super( geometry, material );
  29281. this.type = 'AxesHelper';
  29282. }
  29283. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  29284. const color = new Color();
  29285. const array = this.geometry.attributes.color.array;
  29286. color.set( xAxisColor );
  29287. color.toArray( array, 0 );
  29288. color.toArray( array, 3 );
  29289. color.set( yAxisColor );
  29290. color.toArray( array, 6 );
  29291. color.toArray( array, 9 );
  29292. color.set( zAxisColor );
  29293. color.toArray( array, 12 );
  29294. color.toArray( array, 15 );
  29295. this.geometry.attributes.color.needsUpdate = true;
  29296. return this;
  29297. }
  29298. dispose() {
  29299. this.geometry.dispose();
  29300. this.material.dispose();
  29301. }
  29302. }
  29303. class ShapePath {
  29304. constructor() {
  29305. this.type = 'ShapePath';
  29306. this.color = new Color();
  29307. this.subPaths = [];
  29308. this.currentPath = null;
  29309. }
  29310. moveTo( x, y ) {
  29311. this.currentPath = new Path();
  29312. this.subPaths.push( this.currentPath );
  29313. this.currentPath.moveTo( x, y );
  29314. return this;
  29315. }
  29316. lineTo( x, y ) {
  29317. this.currentPath.lineTo( x, y );
  29318. return this;
  29319. }
  29320. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  29321. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  29322. return this;
  29323. }
  29324. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  29325. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  29326. return this;
  29327. }
  29328. splineThru( pts ) {
  29329. this.currentPath.splineThru( pts );
  29330. return this;
  29331. }
  29332. toShapes( isCCW ) {
  29333. function toShapesNoHoles( inSubpaths ) {
  29334. const shapes = [];
  29335. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  29336. const tmpPath = inSubpaths[ i ];
  29337. const tmpShape = new Shape();
  29338. tmpShape.curves = tmpPath.curves;
  29339. shapes.push( tmpShape );
  29340. }
  29341. return shapes;
  29342. }
  29343. function isPointInsidePolygon( inPt, inPolygon ) {
  29344. const polyLen = inPolygon.length;
  29345. // inPt on polygon contour => immediate success or
  29346. // toggling of inside/outside at every single! intersection point of an edge
  29347. // with the horizontal line through inPt, left of inPt
  29348. // not counting lowerY endpoints of edges and whole edges on that line
  29349. let inside = false;
  29350. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  29351. let edgeLowPt = inPolygon[ p ];
  29352. let edgeHighPt = inPolygon[ q ];
  29353. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  29354. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  29355. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  29356. // not parallel
  29357. if ( edgeDy < 0 ) {
  29358. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  29359. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  29360. }
  29361. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  29362. if ( inPt.y === edgeLowPt.y ) {
  29363. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  29364. // continue; // no intersection or edgeLowPt => doesn't count !!!
  29365. } else {
  29366. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  29367. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  29368. if ( perpEdge < 0 ) continue;
  29369. inside = ! inside; // true intersection left of inPt
  29370. }
  29371. } else {
  29372. // parallel or collinear
  29373. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  29374. // edge lies on the same horizontal line as inPt
  29375. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  29376. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  29377. // continue;
  29378. }
  29379. }
  29380. return inside;
  29381. }
  29382. const isClockWise = ShapeUtils.isClockWise;
  29383. const subPaths = this.subPaths;
  29384. if ( subPaths.length === 0 ) return [];
  29385. let solid, tmpPath, tmpShape;
  29386. const shapes = [];
  29387. if ( subPaths.length === 1 ) {
  29388. tmpPath = subPaths[ 0 ];
  29389. tmpShape = new Shape();
  29390. tmpShape.curves = tmpPath.curves;
  29391. shapes.push( tmpShape );
  29392. return shapes;
  29393. }
  29394. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  29395. holesFirst = isCCW ? ! holesFirst : holesFirst;
  29396. // console.log("Holes first", holesFirst);
  29397. const betterShapeHoles = [];
  29398. const newShapes = [];
  29399. let newShapeHoles = [];
  29400. let mainIdx = 0;
  29401. let tmpPoints;
  29402. newShapes[ mainIdx ] = undefined;
  29403. newShapeHoles[ mainIdx ] = [];
  29404. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  29405. tmpPath = subPaths[ i ];
  29406. tmpPoints = tmpPath.getPoints();
  29407. solid = isClockWise( tmpPoints );
  29408. solid = isCCW ? ! solid : solid;
  29409. if ( solid ) {
  29410. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  29411. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  29412. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  29413. if ( holesFirst ) mainIdx ++;
  29414. newShapeHoles[ mainIdx ] = [];
  29415. //console.log('cw', i);
  29416. } else {
  29417. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  29418. //console.log('ccw', i);
  29419. }
  29420. }
  29421. // only Holes? -> probably all Shapes with wrong orientation
  29422. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  29423. if ( newShapes.length > 1 ) {
  29424. let ambiguous = false;
  29425. let toChange = 0;
  29426. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  29427. betterShapeHoles[ sIdx ] = [];
  29428. }
  29429. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  29430. const sho = newShapeHoles[ sIdx ];
  29431. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  29432. const ho = sho[ hIdx ];
  29433. let hole_unassigned = true;
  29434. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  29435. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  29436. if ( sIdx !== s2Idx ) toChange ++;
  29437. if ( hole_unassigned ) {
  29438. hole_unassigned = false;
  29439. betterShapeHoles[ s2Idx ].push( ho );
  29440. } else {
  29441. ambiguous = true;
  29442. }
  29443. }
  29444. }
  29445. if ( hole_unassigned ) {
  29446. betterShapeHoles[ sIdx ].push( ho );
  29447. }
  29448. }
  29449. }
  29450. if ( toChange > 0 && ambiguous === false ) {
  29451. newShapeHoles = betterShapeHoles;
  29452. }
  29453. }
  29454. let tmpHoles;
  29455. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  29456. tmpShape = newShapes[ i ].s;
  29457. shapes.push( tmpShape );
  29458. tmpHoles = newShapeHoles[ i ];
  29459. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  29460. tmpShape.holes.push( tmpHoles[ j ].h );
  29461. }
  29462. }
  29463. //console.log("shape", shapes);
  29464. return shapes;
  29465. }
  29466. }
  29467. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  29468. const _tables = /*@__PURE__*/ _generateTables();
  29469. function _generateTables() {
  29470. // float32 to float16 helpers
  29471. const buffer = new ArrayBuffer( 4 );
  29472. const floatView = new Float32Array( buffer );
  29473. const uint32View = new Uint32Array( buffer );
  29474. const baseTable = new Uint32Array( 512 );
  29475. const shiftTable = new Uint32Array( 512 );
  29476. for ( let i = 0; i < 256; ++ i ) {
  29477. const e = i - 127;
  29478. // very small number (0, -0)
  29479. if ( e < - 27 ) {
  29480. baseTable[ i ] = 0x0000;
  29481. baseTable[ i | 0x100 ] = 0x8000;
  29482. shiftTable[ i ] = 24;
  29483. shiftTable[ i | 0x100 ] = 24;
  29484. // small number (denorm)
  29485. } else if ( e < - 14 ) {
  29486. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  29487. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  29488. shiftTable[ i ] = - e - 1;
  29489. shiftTable[ i | 0x100 ] = - e - 1;
  29490. // normal number
  29491. } else if ( e <= 15 ) {
  29492. baseTable[ i ] = ( e + 15 ) << 10;
  29493. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  29494. shiftTable[ i ] = 13;
  29495. shiftTable[ i | 0x100 ] = 13;
  29496. // large number (Infinity, -Infinity)
  29497. } else if ( e < 128 ) {
  29498. baseTable[ i ] = 0x7c00;
  29499. baseTable[ i | 0x100 ] = 0xfc00;
  29500. shiftTable[ i ] = 24;
  29501. shiftTable[ i | 0x100 ] = 24;
  29502. // stay (NaN, Infinity, -Infinity)
  29503. } else {
  29504. baseTable[ i ] = 0x7c00;
  29505. baseTable[ i | 0x100 ] = 0xfc00;
  29506. shiftTable[ i ] = 13;
  29507. shiftTable[ i | 0x100 ] = 13;
  29508. }
  29509. }
  29510. // float16 to float32 helpers
  29511. const mantissaTable = new Uint32Array( 2048 );
  29512. const exponentTable = new Uint32Array( 64 );
  29513. const offsetTable = new Uint32Array( 64 );
  29514. for ( let i = 1; i < 1024; ++ i ) {
  29515. let m = i << 13; // zero pad mantissa bits
  29516. let e = 0; // zero exponent
  29517. // normalized
  29518. while ( ( m & 0x00800000 ) === 0 ) {
  29519. m <<= 1;
  29520. e -= 0x00800000; // decrement exponent
  29521. }
  29522. m &= ~ 0x00800000; // clear leading 1 bit
  29523. e += 0x38800000; // adjust bias
  29524. mantissaTable[ i ] = m | e;
  29525. }
  29526. for ( let i = 1024; i < 2048; ++ i ) {
  29527. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  29528. }
  29529. for ( let i = 1; i < 31; ++ i ) {
  29530. exponentTable[ i ] = i << 23;
  29531. }
  29532. exponentTable[ 31 ] = 0x47800000;
  29533. exponentTable[ 32 ] = 0x80000000;
  29534. for ( let i = 33; i < 63; ++ i ) {
  29535. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  29536. }
  29537. exponentTable[ 63 ] = 0xc7800000;
  29538. for ( let i = 1; i < 64; ++ i ) {
  29539. if ( i !== 32 ) {
  29540. offsetTable[ i ] = 1024;
  29541. }
  29542. }
  29543. return {
  29544. floatView: floatView,
  29545. uint32View: uint32View,
  29546. baseTable: baseTable,
  29547. shiftTable: shiftTable,
  29548. mantissaTable: mantissaTable,
  29549. exponentTable: exponentTable,
  29550. offsetTable: offsetTable
  29551. };
  29552. }
  29553. // float32 to float16
  29554. function toHalfFloat( val ) {
  29555. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  29556. val = clamp( val, - 65504, 65504 );
  29557. _tables.floatView[ 0 ] = val;
  29558. const f = _tables.uint32View[ 0 ];
  29559. const e = ( f >> 23 ) & 0x1ff;
  29560. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  29561. }
  29562. // float16 to float32
  29563. function fromHalfFloat( val ) {
  29564. const m = val >> 10;
  29565. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  29566. return _tables.floatView[ 0 ];
  29567. }
  29568. const DataUtils = {
  29569. toHalfFloat: toHalfFloat,
  29570. fromHalfFloat: fromHalfFloat,
  29571. };
  29572. // r144
  29573. class BoxBufferGeometry extends BoxGeometry {
  29574. constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  29575. console.warn( 'THREE.BoxBufferGeometry has been renamed to THREE.BoxGeometry.' );
  29576. super( width, height, depth, widthSegments, heightSegments, depthSegments );
  29577. }
  29578. }
  29579. // r144
  29580. class CapsuleBufferGeometry extends CapsuleGeometry {
  29581. constructor( radius, length, capSegments, radialSegments ) {
  29582. console.warn( 'THREE.CapsuleBufferGeometry has been renamed to THREE.CapsuleGeometry.' );
  29583. super( radius, length, capSegments, radialSegments );
  29584. }
  29585. }
  29586. // r144
  29587. class CircleBufferGeometry extends CircleGeometry {
  29588. constructor( radius, segments, thetaStart, thetaLength ) {
  29589. console.warn( 'THREE.CircleBufferGeometry has been renamed to THREE.CircleGeometry.' );
  29590. super( radius, segments, thetaStart, thetaLength );
  29591. }
  29592. }
  29593. // r144
  29594. class ConeBufferGeometry extends ConeGeometry {
  29595. constructor( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  29596. console.warn( 'THREE.ConeBufferGeometry has been renamed to THREE.ConeGeometry.' );
  29597. super( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  29598. }
  29599. }
  29600. // r144
  29601. class CylinderBufferGeometry extends CylinderGeometry {
  29602. constructor( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  29603. console.warn( 'THREE.CylinderBufferGeometry has been renamed to THREE.CylinderGeometry.' );
  29604. super( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  29605. }
  29606. }
  29607. // r144
  29608. class DodecahedronBufferGeometry extends DodecahedronGeometry {
  29609. constructor( radius, detail ) {
  29610. console.warn( 'THREE.DodecahedronBufferGeometry has been renamed to THREE.DodecahedronGeometry.' );
  29611. super( radius, detail );
  29612. }
  29613. }
  29614. // r144
  29615. class ExtrudeBufferGeometry extends ExtrudeGeometry {
  29616. constructor( shapes, options ) {
  29617. console.warn( 'THREE.ExtrudeBufferGeometry has been renamed to THREE.ExtrudeGeometry.' );
  29618. super( shapes, options );
  29619. }
  29620. }
  29621. // r144
  29622. class IcosahedronBufferGeometry extends IcosahedronGeometry {
  29623. constructor( radius, detail ) {
  29624. console.warn( 'THREE.IcosahedronBufferGeometry has been renamed to THREE.IcosahedronGeometry.' );
  29625. super( radius, detail );
  29626. }
  29627. }
  29628. // r144
  29629. class LatheBufferGeometry extends LatheGeometry {
  29630. constructor( points, segments, phiStart, phiLength ) {
  29631. console.warn( 'THREE.LatheBufferGeometry has been renamed to THREE.LatheGeometry.' );
  29632. super( points, segments, phiStart, phiLength );
  29633. }
  29634. }
  29635. // r144
  29636. class OctahedronBufferGeometry extends OctahedronGeometry {
  29637. constructor( radius, detail ) {
  29638. console.warn( 'THREE.OctahedronBufferGeometry has been renamed to THREE.OctahedronGeometry.' );
  29639. super( radius, detail );
  29640. }
  29641. }
  29642. // r144
  29643. class PlaneBufferGeometry extends PlaneGeometry {
  29644. constructor( width, height, widthSegments, heightSegments ) {
  29645. console.warn( 'THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry.' );
  29646. super( width, height, widthSegments, heightSegments );
  29647. }
  29648. }
  29649. // r144
  29650. class PolyhedronBufferGeometry extends PolyhedronGeometry {
  29651. constructor( vertices, indices, radius, detail ) {
  29652. console.warn( 'THREE.PolyhedronBufferGeometry has been renamed to THREE.PolyhedronGeometry.' );
  29653. super( vertices, indices, radius, detail );
  29654. }
  29655. }
  29656. // r144
  29657. class RingBufferGeometry extends RingGeometry {
  29658. constructor( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  29659. console.warn( 'THREE.RingBufferGeometry has been renamed to THREE.RingGeometry.' );
  29660. super( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength );
  29661. }
  29662. }
  29663. // r144
  29664. class ShapeBufferGeometry extends ShapeGeometry {
  29665. constructor( shapes, curveSegments ) {
  29666. console.warn( 'THREE.ShapeBufferGeometry has been renamed to THREE.ShapeGeometry.' );
  29667. super( shapes, curveSegments );
  29668. }
  29669. }
  29670. // r144
  29671. class SphereBufferGeometry extends SphereGeometry {
  29672. constructor( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  29673. console.warn( 'THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry.' );
  29674. super( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength );
  29675. }
  29676. }
  29677. // r144
  29678. class TetrahedronBufferGeometry extends TetrahedronGeometry {
  29679. constructor( radius, detail ) {
  29680. console.warn( 'THREE.TetrahedronBufferGeometry has been renamed to THREE.TetrahedronGeometry.' );
  29681. super( radius, detail );
  29682. }
  29683. }
  29684. // r144
  29685. class TorusBufferGeometry extends TorusGeometry {
  29686. constructor( radius, tube, radialSegments, tubularSegments, arc ) {
  29687. console.warn( 'THREE.TorusBufferGeometry has been renamed to THREE.TorusGeometry.' );
  29688. super( radius, tube, radialSegments, tubularSegments, arc );
  29689. }
  29690. }
  29691. // r144
  29692. class TorusKnotBufferGeometry extends TorusKnotGeometry {
  29693. constructor( radius, tube, tubularSegments, radialSegments, p, q ) {
  29694. console.warn( 'THREE.TorusKnotBufferGeometry has been renamed to THREE.TorusKnotGeometry.' );
  29695. super( radius, tube, tubularSegments, radialSegments, p, q );
  29696. }
  29697. }
  29698. // r144
  29699. class TubeBufferGeometry extends TubeGeometry {
  29700. constructor( path, tubularSegments, radius, radialSegments, closed ) {
  29701. console.warn( 'THREE.TubeBufferGeometry has been renamed to THREE.TubeGeometry.' );
  29702. super( path, tubularSegments, radius, radialSegments, closed );
  29703. }
  29704. }
  29705. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  29706. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  29707. revision: REVISION,
  29708. } } ) );
  29709. }
  29710. if ( typeof window !== 'undefined' ) {
  29711. if ( window.__THREE__ ) {
  29712. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  29713. } else {
  29714. window.__THREE__ = REVISION;
  29715. }
  29716. }
  29717. export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AlphaFormat, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightProbe, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BackSide, BasicDepthPacking, BasicShadowMap, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxBufferGeometry, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasTexture, CapsuleBufferGeometry, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleBufferGeometry, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, ColorManagement, CompressedArrayTexture, CompressedTexture, CompressedTextureLoader, ConeBufferGeometry, ConeGeometry, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderBufferGeometry, CylinderGeometry, Cylindrical, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DisplayP3ColorSpace, DodecahedronBufferGeometry, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExtrudeBufferGeometry, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Float32BufferAttribute, Float64BufferAttribute, FloatType, Fog, FogExp2, FramebufferTexture, FrontSide, Frustum, GLBufferAttribute, GLSL1, GLSL3, GreaterDepth, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightProbe, IcosahedronBufferGeometry, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, KeepStencilOp, KeyframeTrack, LOD, LatheBufferGeometry, LatheGeometry, Layers, LessDepth, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LineSegments, LinearEncoding, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, Loader, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, Material, MaterialLoader, MathUtils, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronBufferGeometry, OctahedronGeometry, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColo