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.

55849 rivejä
1.3 MiB

  1. /******/ (() => { // webpackBootstrap
  2. /******/ var __webpack_modules__ = ({
  3. /***/ "./node_modules/three-orbitcontrols/OrbitControls.js":
  4. /*!***********************************************************!*\
  5. !*** ./node_modules/three-orbitcontrols/OrbitControls.js ***!
  6. \***********************************************************/
  7. /***/ ((module, exports, __webpack_require__) => {
  8. /* three-orbitcontrols addendum */ var THREE = __webpack_require__(/*! three */ "./node_modules/three/build/three.module.js");
  9. /**
  10. * @author qiao / https://github.com/qiao
  11. * @author mrdoob / http://mrdoob.com
  12. * @author alteredq / http://alteredqualia.com/
  13. * @author WestLangley / http://github.com/WestLangley
  14. * @author erich666 / http://erichaines.com
  15. * @author ScieCode / http://github.com/sciecode
  16. */
  17. // This set of controls performs orbiting, dollying (zooming), and panning.
  18. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  19. //
  20. // Orbit - left mouse / touch: one-finger move
  21. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  22. // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
  23. THREE.OrbitControls = function ( object, domElement ) {
  24. if ( domElement === undefined ) console.warn( 'THREE.OrbitControls: The second parameter "domElement" is now mandatory.' );
  25. if ( domElement === document ) console.error( 'THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.' );
  26. this.object = object;
  27. this.domElement = domElement;
  28. // Set to false to disable this control
  29. this.enabled = true;
  30. // "target" sets the location of focus, where the object orbits around
  31. this.target = new THREE.Vector3();
  32. // How far you can dolly in and out ( PerspectiveCamera only )
  33. this.minDistance = 0;
  34. this.maxDistance = Infinity;
  35. // How far you can zoom in and out ( OrthographicCamera only )
  36. this.minZoom = 0;
  37. this.maxZoom = Infinity;
  38. // How far you can orbit vertically, upper and lower limits.
  39. // Range is 0 to Math.PI radians.
  40. this.minPolarAngle = 0; // radians
  41. this.maxPolarAngle = Math.PI; // radians
  42. // How far you can orbit horizontally, upper and lower limits.
  43. // If set, must be a sub-interval of the interval [ - Math.PI, Math.PI ].
  44. this.minAzimuthAngle = - Infinity; // radians
  45. this.maxAzimuthAngle = Infinity; // radians
  46. // Set to true to enable damping (inertia)
  47. // If damping is enabled, you must call controls.update() in your animation loop
  48. this.enableDamping = false;
  49. this.dampingFactor = 0.05;
  50. // This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
  51. // Set to false to disable zooming
  52. this.enableZoom = true;
  53. this.zoomSpeed = 1.0;
  54. // Set to false to disable rotating
  55. this.enableRotate = true;
  56. this.rotateSpeed = 1.0;
  57. // Set to false to disable panning
  58. this.enablePan = true;
  59. this.panSpeed = 1.0;
  60. this.screenSpacePanning = false; // if true, pan in screen-space
  61. this.keyPanSpeed = 7.0; // pixels moved per arrow key push
  62. // Set to true to automatically rotate around the target
  63. // If auto-rotate is enabled, you must call controls.update() in your animation loop
  64. this.autoRotate = false;
  65. this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60
  66. // Set to false to disable use of the keys
  67. this.enableKeys = true;
  68. // The four arrow keys
  69. this.keys = { LEFT: 37, UP: 38, RIGHT: 39, BOTTOM: 40 };
  70. // Mouse buttons
  71. this.mouseButtons = { LEFT: THREE.MOUSE.ROTATE, MIDDLE: THREE.MOUSE.DOLLY, RIGHT: THREE.MOUSE.PAN };
  72. // Touch fingers
  73. this.touches = { ONE: THREE.TOUCH.ROTATE, TWO: THREE.TOUCH.DOLLY_PAN };
  74. // for reset
  75. this.target0 = this.target.clone();
  76. this.position0 = this.object.position.clone();
  77. this.zoom0 = this.object.zoom;
  78. //
  79. // public methods
  80. //
  81. this.getPolarAngle = function () {
  82. return spherical.phi;
  83. };
  84. this.getAzimuthalAngle = function () {
  85. return spherical.theta;
  86. };
  87. this.saveState = function () {
  88. scope.target0.copy( scope.target );
  89. scope.position0.copy( scope.object.position );
  90. scope.zoom0 = scope.object.zoom;
  91. };
  92. this.reset = function () {
  93. scope.target.copy( scope.target0 );
  94. scope.object.position.copy( scope.position0 );
  95. scope.object.zoom = scope.zoom0;
  96. scope.object.updateProjectionMatrix();
  97. scope.dispatchEvent( changeEvent );
  98. scope.update();
  99. state = STATE.NONE;
  100. };
  101. // this method is exposed, but perhaps it would be better if we can make it private...
  102. this.update = function () {
  103. var offset = new THREE.Vector3();
  104. // so camera.up is the orbit axis
  105. var quat = new THREE.Quaternion().setFromUnitVectors( object.up, new THREE.Vector3( 0, 1, 0 ) );
  106. var quatInverse = quat.clone().inverse();
  107. var lastPosition = new THREE.Vector3();
  108. var lastQuaternion = new THREE.Quaternion();
  109. return function update() {
  110. var position = scope.object.position;
  111. offset.copy( position ).sub( scope.target );
  112. // rotate offset to "y-axis-is-up" space
  113. offset.applyQuaternion( quat );
  114. // angle from z-axis around y-axis
  115. spherical.setFromVector3( offset );
  116. if ( scope.autoRotate && state === STATE.NONE ) {
  117. rotateLeft( getAutoRotationAngle() );
  118. }
  119. if ( scope.enableDamping ) {
  120. spherical.theta += sphericalDelta.theta * scope.dampingFactor;
  121. spherical.phi += sphericalDelta.phi * scope.dampingFactor;
  122. } else {
  123. spherical.theta += sphericalDelta.theta;
  124. spherical.phi += sphericalDelta.phi;
  125. }
  126. // restrict theta to be between desired limits
  127. spherical.theta = Math.max( scope.minAzimuthAngle, Math.min( scope.maxAzimuthAngle, spherical.theta ) );
  128. // restrict phi to be between desired limits
  129. spherical.phi = Math.max( scope.minPolarAngle, Math.min( scope.maxPolarAngle, spherical.phi ) );
  130. spherical.makeSafe();
  131. spherical.radius *= scale;
  132. // restrict radius to be between desired limits
  133. spherical.radius = Math.max( scope.minDistance, Math.min( scope.maxDistance, spherical.radius ) );
  134. // move target to panned location
  135. if ( scope.enableDamping === true ) {
  136. scope.target.addScaledVector( panOffset, scope.dampingFactor );
  137. } else {
  138. scope.target.add( panOffset );
  139. }
  140. offset.setFromSpherical( spherical );
  141. // rotate offset back to "camera-up-vector-is-up" space
  142. offset.applyQuaternion( quatInverse );
  143. position.copy( scope.target ).add( offset );
  144. scope.object.lookAt( scope.target );
  145. if ( scope.enableDamping === true ) {
  146. sphericalDelta.theta *= ( 1 - scope.dampingFactor );
  147. sphericalDelta.phi *= ( 1 - scope.dampingFactor );
  148. panOffset.multiplyScalar( 1 - scope.dampingFactor );
  149. } else {
  150. sphericalDelta.set( 0, 0, 0 );
  151. panOffset.set( 0, 0, 0 );
  152. }
  153. scale = 1;
  154. // update condition is:
  155. // min(camera displacement, camera rotation in radians)^2 > EPS
  156. // using small-angle approximation cos(x/2) = 1 - x^2 / 8
  157. if ( zoomChanged ||
  158. lastPosition.distanceToSquared( scope.object.position ) > EPS ||
  159. 8 * ( 1 - lastQuaternion.dot( scope.object.quaternion ) ) > EPS ) {
  160. scope.dispatchEvent( changeEvent );
  161. lastPosition.copy( scope.object.position );
  162. lastQuaternion.copy( scope.object.quaternion );
  163. zoomChanged = false;
  164. return true;
  165. }
  166. return false;
  167. };
  168. }();
  169. this.dispose = function () {
  170. scope.domElement.removeEventListener( 'contextmenu', onContextMenu, false );
  171. scope.domElement.removeEventListener( 'mousedown', onMouseDown, false );
  172. scope.domElement.removeEventListener( 'wheel', onMouseWheel, false );
  173. scope.domElement.removeEventListener( 'touchstart', onTouchStart, false );
  174. scope.domElement.removeEventListener( 'touchend', onTouchEnd, false );
  175. scope.domElement.removeEventListener( 'touchmove', onTouchMove, false );
  176. document.removeEventListener( 'mousemove', onMouseMove, false );
  177. document.removeEventListener( 'mouseup', onMouseUp, false );
  178. scope.domElement.removeEventListener( 'keydown', onKeyDown, false );
  179. //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?
  180. };
  181. //
  182. // internals
  183. //
  184. var scope = this;
  185. var changeEvent = { type: 'change' };
  186. var startEvent = { type: 'start' };
  187. var endEvent = { type: 'end' };
  188. var STATE = {
  189. NONE: - 1,
  190. ROTATE: 0,
  191. DOLLY: 1,
  192. PAN: 2,
  193. TOUCH_ROTATE: 3,
  194. TOUCH_PAN: 4,
  195. TOUCH_DOLLY_PAN: 5,
  196. TOUCH_DOLLY_ROTATE: 6
  197. };
  198. var state = STATE.NONE;
  199. var EPS = 0.000001;
  200. // current position in spherical coordinates
  201. var spherical = new THREE.Spherical();
  202. var sphericalDelta = new THREE.Spherical();
  203. var scale = 1;
  204. var panOffset = new THREE.Vector3();
  205. var zoomChanged = false;
  206. var rotateStart = new THREE.Vector2();
  207. var rotateEnd = new THREE.Vector2();
  208. var rotateDelta = new THREE.Vector2();
  209. var panStart = new THREE.Vector2();
  210. var panEnd = new THREE.Vector2();
  211. var panDelta = new THREE.Vector2();
  212. var dollyStart = new THREE.Vector2();
  213. var dollyEnd = new THREE.Vector2();
  214. var dollyDelta = new THREE.Vector2();
  215. function getAutoRotationAngle() {
  216. return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
  217. }
  218. function getZoomScale() {
  219. return Math.pow( 0.95, scope.zoomSpeed );
  220. }
  221. function rotateLeft( angle ) {
  222. sphericalDelta.theta -= angle;
  223. }
  224. function rotateUp( angle ) {
  225. sphericalDelta.phi -= angle;
  226. }
  227. var panLeft = function () {
  228. var v = new THREE.Vector3();
  229. return function panLeft( distance, objectMatrix ) {
  230. v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix
  231. v.multiplyScalar( - distance );
  232. panOffset.add( v );
  233. };
  234. }();
  235. var panUp = function () {
  236. var v = new THREE.Vector3();
  237. return function panUp( distance, objectMatrix ) {
  238. if ( scope.screenSpacePanning === true ) {
  239. v.setFromMatrixColumn( objectMatrix, 1 );
  240. } else {
  241. v.setFromMatrixColumn( objectMatrix, 0 );
  242. v.crossVectors( scope.object.up, v );
  243. }
  244. v.multiplyScalar( distance );
  245. panOffset.add( v );
  246. };
  247. }();
  248. // deltaX and deltaY are in pixels; right and down are positive
  249. var pan = function () {
  250. var offset = new THREE.Vector3();
  251. return function pan( deltaX, deltaY ) {
  252. var element = scope.domElement;
  253. if ( scope.object.isPerspectiveCamera ) {
  254. // perspective
  255. var position = scope.object.position;
  256. offset.copy( position ).sub( scope.target );
  257. var targetDistance = offset.length();
  258. // half of the fov is center to top of screen
  259. targetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 );
  260. // we use only clientHeight here so aspect ratio does not distort speed
  261. panLeft( 2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix );
  262. panUp( 2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix );
  263. } else if ( scope.object.isOrthographicCamera ) {
  264. // orthographic
  265. panLeft( deltaX * ( scope.object.right - scope.object.left ) / scope.object.zoom / element.clientWidth, scope.object.matrix );
  266. panUp( deltaY * ( scope.object.top - scope.object.bottom ) / scope.object.zoom / element.clientHeight, scope.object.matrix );
  267. } else {
  268. // camera neither orthographic nor perspective
  269. console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' );
  270. scope.enablePan = false;
  271. }
  272. };
  273. }();
  274. function dollyIn( dollyScale ) {
  275. if ( scope.object.isPerspectiveCamera ) {
  276. scale /= dollyScale;
  277. } else if ( scope.object.isOrthographicCamera ) {
  278. scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom * dollyScale ) );
  279. scope.object.updateProjectionMatrix();
  280. zoomChanged = true;
  281. } else {
  282. console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
  283. scope.enableZoom = false;
  284. }
  285. }
  286. function dollyOut( dollyScale ) {
  287. if ( scope.object.isPerspectiveCamera ) {
  288. scale *= dollyScale;
  289. } else if ( scope.object.isOrthographicCamera ) {
  290. scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / dollyScale ) );
  291. scope.object.updateProjectionMatrix();
  292. zoomChanged = true;
  293. } else {
  294. console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
  295. scope.enableZoom = false;
  296. }
  297. }
  298. //
  299. // event callbacks - update the object state
  300. //
  301. function handleMouseDownRotate( event ) {
  302. rotateStart.set( event.clientX, event.clientY );
  303. }
  304. function handleMouseDownDolly( event ) {
  305. dollyStart.set( event.clientX, event.clientY );
  306. }
  307. function handleMouseDownPan( event ) {
  308. panStart.set( event.clientX, event.clientY );
  309. }
  310. function handleMouseMoveRotate( event ) {
  311. rotateEnd.set( event.clientX, event.clientY );
  312. rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed );
  313. var element = scope.domElement;
  314. rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height
  315. rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight );
  316. rotateStart.copy( rotateEnd );
  317. scope.update();
  318. }
  319. function handleMouseMoveDolly( event ) {
  320. dollyEnd.set( event.clientX, event.clientY );
  321. dollyDelta.subVectors( dollyEnd, dollyStart );
  322. if ( dollyDelta.y > 0 ) {
  323. dollyIn( getZoomScale() );
  324. } else if ( dollyDelta.y < 0 ) {
  325. dollyOut( getZoomScale() );
  326. }
  327. dollyStart.copy( dollyEnd );
  328. scope.update();
  329. }
  330. function handleMouseMovePan( event ) {
  331. panEnd.set( event.clientX, event.clientY );
  332. panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed );
  333. pan( panDelta.x, panDelta.y );
  334. panStart.copy( panEnd );
  335. scope.update();
  336. }
  337. function handleMouseUp( /*event*/ ) {
  338. // no-op
  339. }
  340. function handleMouseWheel( event ) {
  341. if ( event.deltaY < 0 ) {
  342. dollyOut( getZoomScale() );
  343. } else if ( event.deltaY > 0 ) {
  344. dollyIn( getZoomScale() );
  345. }
  346. scope.update();
  347. }
  348. function handleKeyDown( event ) {
  349. var needsUpdate = false;
  350. switch ( event.keyCode ) {
  351. case scope.keys.UP:
  352. pan( 0, scope.keyPanSpeed );
  353. needsUpdate = true;
  354. break;
  355. case scope.keys.BOTTOM:
  356. pan( 0, - scope.keyPanSpeed );
  357. needsUpdate = true;
  358. break;
  359. case scope.keys.LEFT:
  360. pan( scope.keyPanSpeed, 0 );
  361. needsUpdate = true;
  362. break;
  363. case scope.keys.RIGHT:
  364. pan( - scope.keyPanSpeed, 0 );
  365. needsUpdate = true;
  366. break;
  367. }
  368. if ( needsUpdate ) {
  369. // prevent the browser from scrolling on cursor keys
  370. event.preventDefault();
  371. scope.update();
  372. }
  373. }
  374. function handleTouchStartRotate( event ) {
  375. if ( event.touches.length == 1 ) {
  376. rotateStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
  377. } else {
  378. var x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX );
  379. var y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY );
  380. rotateStart.set( x, y );
  381. }
  382. }
  383. function handleTouchStartPan( event ) {
  384. if ( event.touches.length == 1 ) {
  385. panStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
  386. } else {
  387. var x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX );
  388. var y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY );
  389. panStart.set( x, y );
  390. }
  391. }
  392. function handleTouchStartDolly( event ) {
  393. var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX;
  394. var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY;
  395. var distance = Math.sqrt( dx * dx + dy * dy );
  396. dollyStart.set( 0, distance );
  397. }
  398. function handleTouchStartDollyPan( event ) {
  399. if ( scope.enableZoom ) handleTouchStartDolly( event );
  400. if ( scope.enablePan ) handleTouchStartPan( event );
  401. }
  402. function handleTouchStartDollyRotate( event ) {
  403. if ( scope.enableZoom ) handleTouchStartDolly( event );
  404. if ( scope.enableRotate ) handleTouchStartRotate( event );
  405. }
  406. function handleTouchMoveRotate( event ) {
  407. if ( event.touches.length == 1 ) {
  408. rotateEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
  409. } else {
  410. var x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX );
  411. var y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY );
  412. rotateEnd.set( x, y );
  413. }
  414. rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed );
  415. var element = scope.domElement;
  416. rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height
  417. rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight );
  418. rotateStart.copy( rotateEnd );
  419. }
  420. function handleTouchMovePan( event ) {
  421. if ( event.touches.length == 1 ) {
  422. panEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
  423. } else {
  424. var x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX );
  425. var y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY );
  426. panEnd.set( x, y );
  427. }
  428. panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed );
  429. pan( panDelta.x, panDelta.y );
  430. panStart.copy( panEnd );
  431. }
  432. function handleTouchMoveDolly( event ) {
  433. var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX;
  434. var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY;
  435. var distance = Math.sqrt( dx * dx + dy * dy );
  436. dollyEnd.set( 0, distance );
  437. dollyDelta.set( 0, Math.pow( dollyEnd.y / dollyStart.y, scope.zoomSpeed ) );
  438. dollyIn( dollyDelta.y );
  439. dollyStart.copy( dollyEnd );
  440. }
  441. function handleTouchMoveDollyPan( event ) {
  442. if ( scope.enableZoom ) handleTouchMoveDolly( event );
  443. if ( scope.enablePan ) handleTouchMovePan( event );
  444. }
  445. function handleTouchMoveDollyRotate( event ) {
  446. if ( scope.enableZoom ) handleTouchMoveDolly( event );
  447. if ( scope.enableRotate ) handleTouchMoveRotate( event );
  448. }
  449. function handleTouchEnd( /*event*/ ) {
  450. // no-op
  451. }
  452. //
  453. // event handlers - FSM: listen for events and reset state
  454. //
  455. function onMouseDown( event ) {
  456. if ( scope.enabled === false ) return;
  457. // Prevent the browser from scrolling.
  458. event.preventDefault();
  459. // Manually set the focus since calling preventDefault above
  460. // prevents the browser from setting it automatically.
  461. scope.domElement.focus ? scope.domElement.focus() : window.focus();
  462. switch ( event.button ) {
  463. case 0:
  464. switch ( scope.mouseButtons.LEFT ) {
  465. case THREE.MOUSE.ROTATE:
  466. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  467. if ( scope.enablePan === false ) return;
  468. handleMouseDownPan( event );
  469. state = STATE.PAN;
  470. } else {
  471. if ( scope.enableRotate === false ) return;
  472. handleMouseDownRotate( event );
  473. state = STATE.ROTATE;
  474. }
  475. break;
  476. case THREE.MOUSE.PAN:
  477. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  478. if ( scope.enableRotate === false ) return;
  479. handleMouseDownRotate( event );
  480. state = STATE.ROTATE;
  481. } else {
  482. if ( scope.enablePan === false ) return;
  483. handleMouseDownPan( event );
  484. state = STATE.PAN;
  485. }
  486. break;
  487. default:
  488. state = STATE.NONE;
  489. }
  490. break;
  491. case 1:
  492. switch ( scope.mouseButtons.MIDDLE ) {
  493. case THREE.MOUSE.DOLLY:
  494. if ( scope.enableZoom === false ) return;
  495. handleMouseDownDolly( event );
  496. state = STATE.DOLLY;
  497. break;
  498. default:
  499. state = STATE.NONE;
  500. }
  501. break;
  502. case 2:
  503. switch ( scope.mouseButtons.RIGHT ) {
  504. case THREE.MOUSE.ROTATE:
  505. if ( scope.enableRotate === false ) return;
  506. handleMouseDownRotate( event );
  507. state = STATE.ROTATE;
  508. break;
  509. case THREE.MOUSE.PAN:
  510. if ( scope.enablePan === false ) return;
  511. handleMouseDownPan( event );
  512. state = STATE.PAN;
  513. break;
  514. default:
  515. state = STATE.NONE;
  516. }
  517. break;
  518. }
  519. if ( state !== STATE.NONE ) {
  520. document.addEventListener( 'mousemove', onMouseMove, false );
  521. document.addEventListener( 'mouseup', onMouseUp, false );
  522. scope.dispatchEvent( startEvent );
  523. }
  524. }
  525. function onMouseMove( event ) {
  526. if ( scope.enabled === false ) return;
  527. event.preventDefault();
  528. switch ( state ) {
  529. case STATE.ROTATE:
  530. if ( scope.enableRotate === false ) return;
  531. handleMouseMoveRotate( event );
  532. break;
  533. case STATE.DOLLY:
  534. if ( scope.enableZoom === false ) return;
  535. handleMouseMoveDolly( event );
  536. break;
  537. case STATE.PAN:
  538. if ( scope.enablePan === false ) return;
  539. handleMouseMovePan( event );
  540. break;
  541. }
  542. }
  543. function onMouseUp( event ) {
  544. if ( scope.enabled === false ) return;
  545. handleMouseUp( event );
  546. document.removeEventListener( 'mousemove', onMouseMove, false );
  547. document.removeEventListener( 'mouseup', onMouseUp, false );
  548. scope.dispatchEvent( endEvent );
  549. state = STATE.NONE;
  550. }
  551. function onMouseWheel( event ) {
  552. if ( scope.enabled === false || scope.enableZoom === false || ( state !== STATE.NONE && state !== STATE.ROTATE ) ) return;
  553. event.preventDefault();
  554. event.stopPropagation();
  555. scope.dispatchEvent( startEvent );
  556. handleMouseWheel( event );
  557. scope.dispatchEvent( endEvent );
  558. }
  559. function onKeyDown( event ) {
  560. if ( scope.enabled === false || scope.enableKeys === false || scope.enablePan === false ) return;
  561. handleKeyDown( event );
  562. }
  563. function onTouchStart( event ) {
  564. if ( scope.enabled === false ) return;
  565. event.preventDefault();
  566. switch ( event.touches.length ) {
  567. case 1:
  568. switch ( scope.touches.ONE ) {
  569. case THREE.TOUCH.ROTATE:
  570. if ( scope.enableRotate === false ) return;
  571. handleTouchStartRotate( event );
  572. state = STATE.TOUCH_ROTATE;
  573. break;
  574. case THREE.TOUCH.PAN:
  575. if ( scope.enablePan === false ) return;
  576. handleTouchStartPan( event );
  577. state = STATE.TOUCH_PAN;
  578. break;
  579. default:
  580. state = STATE.NONE;
  581. }
  582. break;
  583. case 2:
  584. switch ( scope.touches.TWO ) {
  585. case THREE.TOUCH.DOLLY_PAN:
  586. if ( scope.enableZoom === false && scope.enablePan === false ) return;
  587. handleTouchStartDollyPan( event );
  588. state = STATE.TOUCH_DOLLY_PAN;
  589. break;
  590. case THREE.TOUCH.DOLLY_ROTATE:
  591. if ( scope.enableZoom === false && scope.enableRotate === false ) return;
  592. handleTouchStartDollyRotate( event );
  593. state = STATE.TOUCH_DOLLY_ROTATE;
  594. break;
  595. default:
  596. state = STATE.NONE;
  597. }
  598. break;
  599. default:
  600. state = STATE.NONE;
  601. }
  602. if ( state !== STATE.NONE ) {
  603. scope.dispatchEvent( startEvent );
  604. }
  605. }
  606. function onTouchMove( event ) {
  607. if ( scope.enabled === false ) return;
  608. event.preventDefault();
  609. event.stopPropagation();
  610. switch ( state ) {
  611. case STATE.TOUCH_ROTATE:
  612. if ( scope.enableRotate === false ) return;
  613. handleTouchMoveRotate( event );
  614. scope.update();
  615. break;
  616. case STATE.TOUCH_PAN:
  617. if ( scope.enablePan === false ) return;
  618. handleTouchMovePan( event );
  619. scope.update();
  620. break;
  621. case STATE.TOUCH_DOLLY_PAN:
  622. if ( scope.enableZoom === false && scope.enablePan === false ) return;
  623. handleTouchMoveDollyPan( event );
  624. scope.update();
  625. break;
  626. case STATE.TOUCH_DOLLY_ROTATE:
  627. if ( scope.enableZoom === false && scope.enableRotate === false ) return;
  628. handleTouchMoveDollyRotate( event );
  629. scope.update();
  630. break;
  631. default:
  632. state = STATE.NONE;
  633. }
  634. }
  635. function onTouchEnd( event ) {
  636. if ( scope.enabled === false ) return;
  637. handleTouchEnd( event );
  638. scope.dispatchEvent( endEvent );
  639. state = STATE.NONE;
  640. }
  641. function onContextMenu( event ) {
  642. if ( scope.enabled === false ) return;
  643. event.preventDefault();
  644. }
  645. //
  646. scope.domElement.addEventListener( 'contextmenu', onContextMenu, false );
  647. scope.domElement.addEventListener( 'mousedown', onMouseDown, false );
  648. scope.domElement.addEventListener( 'wheel', onMouseWheel, false );
  649. scope.domElement.addEventListener( 'touchstart', onTouchStart, false );
  650. scope.domElement.addEventListener( 'touchend', onTouchEnd, false );
  651. scope.domElement.addEventListener( 'touchmove', onTouchMove, false );
  652. scope.domElement.addEventListener( 'keydown', onKeyDown, false );
  653. // make sure element can receive keys.
  654. if ( scope.domElement.tabIndex === - 1 ) {
  655. scope.domElement.tabIndex = 0;
  656. }
  657. // force an update at start
  658. this.update();
  659. };
  660. THREE.OrbitControls.prototype = Object.create( THREE.EventDispatcher.prototype );
  661. THREE.OrbitControls.prototype.constructor = THREE.OrbitControls;
  662. // This set of controls performs orbiting, dollying (zooming), and panning.
  663. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  664. // This is very similar to OrbitControls, another set of touch behavior
  665. //
  666. // Orbit - right mouse, or left mouse + ctrl/meta/shiftKey / touch: two-finger rotate
  667. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  668. // Pan - left mouse, or arrow keys / touch: one-finger move
  669. THREE.MapControls = function ( object, domElement ) {
  670. THREE.OrbitControls.call( this, object, domElement );
  671. this.mouseButtons.LEFT = THREE.MOUSE.PAN;
  672. this.mouseButtons.RIGHT = THREE.MOUSE.ROTATE;
  673. this.touches.ONE = THREE.TOUCH.PAN;
  674. this.touches.TWO = THREE.TOUCH.DOLLY_ROTATE;
  675. };
  676. THREE.MapControls.prototype = Object.create( THREE.EventDispatcher.prototype );
  677. THREE.MapControls.prototype.constructor = THREE.MapControls;
  678. /* three-orbitcontrols addendum */ module.exports = exports["default"] = THREE.OrbitControls;
  679. /***/ }),
  680. /***/ "./node_modules/three/build/three.module.js":
  681. /*!**************************************************!*\
  682. !*** ./node_modules/three/build/three.module.js ***!
  683. \**************************************************/
  684. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  685. "use strict";
  686. __webpack_require__.r(__webpack_exports__);
  687. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  688. /* harmony export */ "ACESFilmicToneMapping": () => (/* binding */ ACESFilmicToneMapping),
  689. /* harmony export */ "AddEquation": () => (/* binding */ AddEquation),
  690. /* harmony export */ "AddOperation": () => (/* binding */ AddOperation),
  691. /* harmony export */ "AdditiveAnimationBlendMode": () => (/* binding */ AdditiveAnimationBlendMode),
  692. /* harmony export */ "AdditiveBlending": () => (/* binding */ AdditiveBlending),
  693. /* harmony export */ "AlphaFormat": () => (/* binding */ AlphaFormat),
  694. /* harmony export */ "AlwaysDepth": () => (/* binding */ AlwaysDepth),
  695. /* harmony export */ "AlwaysStencilFunc": () => (/* binding */ AlwaysStencilFunc),
  696. /* harmony export */ "AmbientLight": () => (/* binding */ AmbientLight),
  697. /* harmony export */ "AmbientLightProbe": () => (/* binding */ AmbientLightProbe),
  698. /* harmony export */ "AnimationClip": () => (/* binding */ AnimationClip),
  699. /* harmony export */ "AnimationLoader": () => (/* binding */ AnimationLoader),
  700. /* harmony export */ "AnimationMixer": () => (/* binding */ AnimationMixer),
  701. /* harmony export */ "AnimationObjectGroup": () => (/* binding */ AnimationObjectGroup),
  702. /* harmony export */ "AnimationUtils": () => (/* binding */ AnimationUtils),
  703. /* harmony export */ "ArcCurve": () => (/* binding */ ArcCurve),
  704. /* harmony export */ "ArrayCamera": () => (/* binding */ ArrayCamera),
  705. /* harmony export */ "ArrowHelper": () => (/* binding */ ArrowHelper),
  706. /* harmony export */ "Audio": () => (/* binding */ Audio),
  707. /* harmony export */ "AudioAnalyser": () => (/* binding */ AudioAnalyser),
  708. /* harmony export */ "AudioContext": () => (/* binding */ AudioContext),
  709. /* harmony export */ "AudioListener": () => (/* binding */ AudioListener),
  710. /* harmony export */ "AudioLoader": () => (/* binding */ AudioLoader),
  711. /* harmony export */ "AxesHelper": () => (/* binding */ AxesHelper),
  712. /* harmony export */ "AxisHelper": () => (/* binding */ AxisHelper),
  713. /* harmony export */ "BackSide": () => (/* binding */ BackSide),
  714. /* harmony export */ "BasicDepthPacking": () => (/* binding */ BasicDepthPacking),
  715. /* harmony export */ "BasicShadowMap": () => (/* binding */ BasicShadowMap),
  716. /* harmony export */ "BinaryTextureLoader": () => (/* binding */ BinaryTextureLoader),
  717. /* harmony export */ "Bone": () => (/* binding */ Bone),
  718. /* harmony export */ "BooleanKeyframeTrack": () => (/* binding */ BooleanKeyframeTrack),
  719. /* harmony export */ "BoundingBoxHelper": () => (/* binding */ BoundingBoxHelper),
  720. /* harmony export */ "Box2": () => (/* binding */ Box2),
  721. /* harmony export */ "Box3": () => (/* binding */ Box3),
  722. /* harmony export */ "Box3Helper": () => (/* binding */ Box3Helper),
  723. /* harmony export */ "BoxBufferGeometry": () => (/* binding */ BoxGeometry),
  724. /* harmony export */ "BoxGeometry": () => (/* binding */ BoxGeometry),
  725. /* harmony export */ "BoxHelper": () => (/* binding */ BoxHelper),
  726. /* harmony export */ "BufferAttribute": () => (/* binding */ BufferAttribute),
  727. /* harmony export */ "BufferGeometry": () => (/* binding */ BufferGeometry),
  728. /* harmony export */ "BufferGeometryLoader": () => (/* binding */ BufferGeometryLoader),
  729. /* harmony export */ "ByteType": () => (/* binding */ ByteType),
  730. /* harmony export */ "Cache": () => (/* binding */ Cache),
  731. /* harmony export */ "Camera": () => (/* binding */ Camera),
  732. /* harmony export */ "CameraHelper": () => (/* binding */ CameraHelper),
  733. /* harmony export */ "CanvasRenderer": () => (/* binding */ CanvasRenderer),
  734. /* harmony export */ "CanvasTexture": () => (/* binding */ CanvasTexture),
  735. /* harmony export */ "CatmullRomCurve3": () => (/* binding */ CatmullRomCurve3),
  736. /* harmony export */ "CineonToneMapping": () => (/* binding */ CineonToneMapping),
  737. /* harmony export */ "CircleBufferGeometry": () => (/* binding */ CircleGeometry),
  738. /* harmony export */ "CircleGeometry": () => (/* binding */ CircleGeometry),
  739. /* harmony export */ "ClampToEdgeWrapping": () => (/* binding */ ClampToEdgeWrapping),
  740. /* harmony export */ "Clock": () => (/* binding */ Clock),
  741. /* harmony export */ "Color": () => (/* binding */ Color),
  742. /* harmony export */ "ColorKeyframeTrack": () => (/* binding */ ColorKeyframeTrack),
  743. /* harmony export */ "CompressedTexture": () => (/* binding */ CompressedTexture),
  744. /* harmony export */ "CompressedTextureLoader": () => (/* binding */ CompressedTextureLoader),
  745. /* harmony export */ "ConeBufferGeometry": () => (/* binding */ ConeGeometry),
  746. /* harmony export */ "ConeGeometry": () => (/* binding */ ConeGeometry),
  747. /* harmony export */ "CubeCamera": () => (/* binding */ CubeCamera),
  748. /* harmony export */ "CubeReflectionMapping": () => (/* binding */ CubeReflectionMapping),
  749. /* harmony export */ "CubeRefractionMapping": () => (/* binding */ CubeRefractionMapping),
  750. /* harmony export */ "CubeTexture": () => (/* binding */ CubeTexture),
  751. /* harmony export */ "CubeTextureLoader": () => (/* binding */ CubeTextureLoader),
  752. /* harmony export */ "CubeUVReflectionMapping": () => (/* binding */ CubeUVReflectionMapping),
  753. /* harmony export */ "CubeUVRefractionMapping": () => (/* binding */ CubeUVRefractionMapping),
  754. /* harmony export */ "CubicBezierCurve": () => (/* binding */ CubicBezierCurve),
  755. /* harmony export */ "CubicBezierCurve3": () => (/* binding */ CubicBezierCurve3),
  756. /* harmony export */ "CubicInterpolant": () => (/* binding */ CubicInterpolant),
  757. /* harmony export */ "CullFaceBack": () => (/* binding */ CullFaceBack),
  758. /* harmony export */ "CullFaceFront": () => (/* binding */ CullFaceFront),
  759. /* harmony export */ "CullFaceFrontBack": () => (/* binding */ CullFaceFrontBack),
  760. /* harmony export */ "CullFaceNone": () => (/* binding */ CullFaceNone),
  761. /* harmony export */ "Curve": () => (/* binding */ Curve),
  762. /* harmony export */ "CurvePath": () => (/* binding */ CurvePath),
  763. /* harmony export */ "CustomBlending": () => (/* binding */ CustomBlending),
  764. /* harmony export */ "CustomToneMapping": () => (/* binding */ CustomToneMapping),
  765. /* harmony export */ "CylinderBufferGeometry": () => (/* binding */ CylinderGeometry),
  766. /* harmony export */ "CylinderGeometry": () => (/* binding */ CylinderGeometry),
  767. /* harmony export */ "Cylindrical": () => (/* binding */ Cylindrical),
  768. /* harmony export */ "DataTexture": () => (/* binding */ DataTexture),
  769. /* harmony export */ "DataTexture2DArray": () => (/* binding */ DataTexture2DArray),
  770. /* harmony export */ "DataTexture3D": () => (/* binding */ DataTexture3D),
  771. /* harmony export */ "DataTextureLoader": () => (/* binding */ DataTextureLoader),
  772. /* harmony export */ "DataUtils": () => (/* binding */ DataUtils),
  773. /* harmony export */ "DecrementStencilOp": () => (/* binding */ DecrementStencilOp),
  774. /* harmony export */ "DecrementWrapStencilOp": () => (/* binding */ DecrementWrapStencilOp),
  775. /* harmony export */ "DefaultLoadingManager": () => (/* binding */ DefaultLoadingManager),
  776. /* harmony export */ "DepthFormat": () => (/* binding */ DepthFormat),
  777. /* harmony export */ "DepthStencilFormat": () => (/* binding */ DepthStencilFormat),
  778. /* harmony export */ "DepthTexture": () => (/* binding */ DepthTexture),
  779. /* harmony export */ "DirectionalLight": () => (/* binding */ DirectionalLight),
  780. /* harmony export */ "DirectionalLightHelper": () => (/* binding */ DirectionalLightHelper),
  781. /* harmony export */ "DiscreteInterpolant": () => (/* binding */ DiscreteInterpolant),
  782. /* harmony export */ "DodecahedronBufferGeometry": () => (/* binding */ DodecahedronGeometry),
  783. /* harmony export */ "DodecahedronGeometry": () => (/* binding */ DodecahedronGeometry),
  784. /* harmony export */ "DoubleSide": () => (/* binding */ DoubleSide),
  785. /* harmony export */ "DstAlphaFactor": () => (/* binding */ DstAlphaFactor),
  786. /* harmony export */ "DstColorFactor": () => (/* binding */ DstColorFactor),
  787. /* harmony export */ "DynamicBufferAttribute": () => (/* binding */ DynamicBufferAttribute),
  788. /* harmony export */ "DynamicCopyUsage": () => (/* binding */ DynamicCopyUsage),
  789. /* harmony export */ "DynamicDrawUsage": () => (/* binding */ DynamicDrawUsage),
  790. /* harmony export */ "DynamicReadUsage": () => (/* binding */ DynamicReadUsage),
  791. /* harmony export */ "EdgesGeometry": () => (/* binding */ EdgesGeometry),
  792. /* harmony export */ "EdgesHelper": () => (/* binding */ EdgesHelper),
  793. /* harmony export */ "EllipseCurve": () => (/* binding */ EllipseCurve),
  794. /* harmony export */ "EqualDepth": () => (/* binding */ EqualDepth),
  795. /* harmony export */ "EqualStencilFunc": () => (/* binding */ EqualStencilFunc),
  796. /* harmony export */ "EquirectangularReflectionMapping": () => (/* binding */ EquirectangularReflectionMapping),
  797. /* harmony export */ "EquirectangularRefractionMapping": () => (/* binding */ EquirectangularRefractionMapping),
  798. /* harmony export */ "Euler": () => (/* binding */ Euler),
  799. /* harmony export */ "EventDispatcher": () => (/* binding */ EventDispatcher),
  800. /* harmony export */ "ExtrudeBufferGeometry": () => (/* binding */ ExtrudeGeometry),
  801. /* harmony export */ "ExtrudeGeometry": () => (/* binding */ ExtrudeGeometry),
  802. /* harmony export */ "FaceColors": () => (/* binding */ FaceColors),
  803. /* harmony export */ "FileLoader": () => (/* binding */ FileLoader),
  804. /* harmony export */ "FlatShading": () => (/* binding */ FlatShading),
  805. /* harmony export */ "Float16BufferAttribute": () => (/* binding */ Float16BufferAttribute),
  806. /* harmony export */ "Float32Attribute": () => (/* binding */ Float32Attribute),
  807. /* harmony export */ "Float32BufferAttribute": () => (/* binding */ Float32BufferAttribute),
  808. /* harmony export */ "Float64Attribute": () => (/* binding */ Float64Attribute),
  809. /* harmony export */ "Float64BufferAttribute": () => (/* binding */ Float64BufferAttribute),
  810. /* harmony export */ "FloatType": () => (/* binding */ FloatType),
  811. /* harmony export */ "Fog": () => (/* binding */ Fog),
  812. /* harmony export */ "FogExp2": () => (/* binding */ FogExp2),
  813. /* harmony export */ "Font": () => (/* binding */ Font),
  814. /* harmony export */ "FontLoader": () => (/* binding */ FontLoader),
  815. /* harmony export */ "FrontSide": () => (/* binding */ FrontSide),
  816. /* harmony export */ "Frustum": () => (/* binding */ Frustum),
  817. /* harmony export */ "GLBufferAttribute": () => (/* binding */ GLBufferAttribute),
  818. /* harmony export */ "GLSL1": () => (/* binding */ GLSL1),
  819. /* harmony export */ "GLSL3": () => (/* binding */ GLSL3),
  820. /* harmony export */ "GammaEncoding": () => (/* binding */ GammaEncoding),
  821. /* harmony export */ "GreaterDepth": () => (/* binding */ GreaterDepth),
  822. /* harmony export */ "GreaterEqualDepth": () => (/* binding */ GreaterEqualDepth),
  823. /* harmony export */ "GreaterEqualStencilFunc": () => (/* binding */ GreaterEqualStencilFunc),
  824. /* harmony export */ "GreaterStencilFunc": () => (/* binding */ GreaterStencilFunc),
  825. /* harmony export */ "GridHelper": () => (/* binding */ GridHelper),
  826. /* harmony export */ "Group": () => (/* binding */ Group),
  827. /* harmony export */ "HalfFloatType": () => (/* binding */ HalfFloatType),
  828. /* harmony export */ "HemisphereLight": () => (/* binding */ HemisphereLight),
  829. /* harmony export */ "HemisphereLightHelper": () => (/* binding */ HemisphereLightHelper),
  830. /* harmony export */ "HemisphereLightProbe": () => (/* binding */ HemisphereLightProbe),
  831. /* harmony export */ "IcosahedronBufferGeometry": () => (/* binding */ IcosahedronGeometry),
  832. /* harmony export */ "IcosahedronGeometry": () => (/* binding */ IcosahedronGeometry),
  833. /* harmony export */ "ImageBitmapLoader": () => (/* binding */ ImageBitmapLoader),
  834. /* harmony export */ "ImageLoader": () => (/* binding */ ImageLoader),
  835. /* harmony export */ "ImageUtils": () => (/* binding */ ImageUtils),
  836. /* harmony export */ "ImmediateRenderObject": () => (/* binding */ ImmediateRenderObject),
  837. /* harmony export */ "IncrementStencilOp": () => (/* binding */ IncrementStencilOp),
  838. /* harmony export */ "IncrementWrapStencilOp": () => (/* binding */ IncrementWrapStencilOp),
  839. /* harmony export */ "InstancedBufferAttribute": () => (/* binding */ InstancedBufferAttribute),
  840. /* harmony export */ "InstancedBufferGeometry": () => (/* binding */ InstancedBufferGeometry),
  841. /* harmony export */ "InstancedInterleavedBuffer": () => (/* binding */ InstancedInterleavedBuffer),
  842. /* harmony export */ "InstancedMesh": () => (/* binding */ InstancedMesh),
  843. /* harmony export */ "Int16Attribute": () => (/* binding */ Int16Attribute),
  844. /* harmony export */ "Int16BufferAttribute": () => (/* binding */ Int16BufferAttribute),
  845. /* harmony export */ "Int32Attribute": () => (/* binding */ Int32Attribute),
  846. /* harmony export */ "Int32BufferAttribute": () => (/* binding */ Int32BufferAttribute),
  847. /* harmony export */ "Int8Attribute": () => (/* binding */ Int8Attribute),
  848. /* harmony export */ "Int8BufferAttribute": () => (/* binding */ Int8BufferAttribute),
  849. /* harmony export */ "IntType": () => (/* binding */ IntType),
  850. /* harmony export */ "InterleavedBuffer": () => (/* binding */ InterleavedBuffer),
  851. /* harmony export */ "InterleavedBufferAttribute": () => (/* binding */ InterleavedBufferAttribute),
  852. /* harmony export */ "Interpolant": () => (/* binding */ Interpolant),
  853. /* harmony export */ "InterpolateDiscrete": () => (/* binding */ InterpolateDiscrete),
  854. /* harmony export */ "InterpolateLinear": () => (/* binding */ InterpolateLinear),
  855. /* harmony export */ "InterpolateSmooth": () => (/* binding */ InterpolateSmooth),
  856. /* harmony export */ "InvertStencilOp": () => (/* binding */ InvertStencilOp),
  857. /* harmony export */ "JSONLoader": () => (/* binding */ JSONLoader),
  858. /* harmony export */ "KeepStencilOp": () => (/* binding */ KeepStencilOp),
  859. /* harmony export */ "KeyframeTrack": () => (/* binding */ KeyframeTrack),
  860. /* harmony export */ "LOD": () => (/* binding */ LOD),
  861. /* harmony export */ "LatheBufferGeometry": () => (/* binding */ LatheGeometry),
  862. /* harmony export */ "LatheGeometry": () => (/* binding */ LatheGeometry),
  863. /* harmony export */ "Layers": () => (/* binding */ Layers),
  864. /* harmony export */ "LensFlare": () => (/* binding */ LensFlare),
  865. /* harmony export */ "LessDepth": () => (/* binding */ LessDepth),
  866. /* harmony export */ "LessEqualDepth": () => (/* binding */ LessEqualDepth),
  867. /* harmony export */ "LessEqualStencilFunc": () => (/* binding */ LessEqualStencilFunc),
  868. /* harmony export */ "LessStencilFunc": () => (/* binding */ LessStencilFunc),
  869. /* harmony export */ "Light": () => (/* binding */ Light),
  870. /* harmony export */ "LightProbe": () => (/* binding */ LightProbe),
  871. /* harmony export */ "Line": () => (/* binding */ Line),
  872. /* harmony export */ "Line3": () => (/* binding */ Line3),
  873. /* harmony export */ "LineBasicMaterial": () => (/* binding */ LineBasicMaterial),
  874. /* harmony export */ "LineCurve": () => (/* binding */ LineCurve),
  875. /* harmony export */ "LineCurve3": () => (/* binding */ LineCurve3),
  876. /* harmony export */ "LineDashedMaterial": () => (/* binding */ LineDashedMaterial),
  877. /* harmony export */ "LineLoop": () => (/* binding */ LineLoop),
  878. /* harmony export */ "LinePieces": () => (/* binding */ LinePieces),
  879. /* harmony export */ "LineSegments": () => (/* binding */ LineSegments),
  880. /* harmony export */ "LineStrip": () => (/* binding */ LineStrip),
  881. /* harmony export */ "LinearEncoding": () => (/* binding */ LinearEncoding),
  882. /* harmony export */ "LinearFilter": () => (/* binding */ LinearFilter),
  883. /* harmony export */ "LinearInterpolant": () => (/* binding */ LinearInterpolant),
  884. /* harmony export */ "LinearMipMapLinearFilter": () => (/* binding */ LinearMipMapLinearFilter),
  885. /* harmony export */ "LinearMipMapNearestFilter": () => (/* binding */ LinearMipMapNearestFilter),
  886. /* harmony export */ "LinearMipmapLinearFilter": () => (/* binding */ LinearMipmapLinearFilter),
  887. /* harmony export */ "LinearMipmapNearestFilter": () => (/* binding */ LinearMipmapNearestFilter),
  888. /* harmony export */ "LinearToneMapping": () => (/* binding */ LinearToneMapping),
  889. /* harmony export */ "Loader": () => (/* binding */ Loader),
  890. /* harmony export */ "LoaderUtils": () => (/* binding */ LoaderUtils),
  891. /* harmony export */ "LoadingManager": () => (/* binding */ LoadingManager),
  892. /* harmony export */ "LogLuvEncoding": () => (/* binding */ LogLuvEncoding),
  893. /* harmony export */ "LoopOnce": () => (/* binding */ LoopOnce),
  894. /* harmony export */ "LoopPingPong": () => (/* binding */ LoopPingPong),
  895. /* harmony export */ "LoopRepeat": () => (/* binding */ LoopRepeat),
  896. /* harmony export */ "LuminanceAlphaFormat": () => (/* binding */ LuminanceAlphaFormat),
  897. /* harmony export */ "LuminanceFormat": () => (/* binding */ LuminanceFormat),
  898. /* harmony export */ "MOUSE": () => (/* binding */ MOUSE),
  899. /* harmony export */ "Material": () => (/* binding */ Material),
  900. /* harmony export */ "MaterialLoader": () => (/* binding */ MaterialLoader),
  901. /* harmony export */ "Math": () => (/* binding */ MathUtils),
  902. /* harmony export */ "MathUtils": () => (/* binding */ MathUtils),
  903. /* harmony export */ "Matrix3": () => (/* binding */ Matrix3),
  904. /* harmony export */ "Matrix4": () => (/* binding */ Matrix4),
  905. /* harmony export */ "MaxEquation": () => (/* binding */ MaxEquation),
  906. /* harmony export */ "Mesh": () => (/* binding */ Mesh),
  907. /* harmony export */ "MeshBasicMaterial": () => (/* binding */ MeshBasicMaterial),
  908. /* harmony export */ "MeshDepthMaterial": () => (/* binding */ MeshDepthMaterial),
  909. /* harmony export */ "MeshDistanceMaterial": () => (/* binding */ MeshDistanceMaterial),
  910. /* harmony export */ "MeshFaceMaterial": () => (/* binding */ MeshFaceMaterial),
  911. /* harmony export */ "MeshLambertMaterial": () => (/* binding */ MeshLambertMaterial),
  912. /* harmony export */ "MeshMatcapMaterial": () => (/* binding */ MeshMatcapMaterial),
  913. /* harmony export */ "MeshNormalMaterial": () => (/* binding */ MeshNormalMaterial),
  914. /* harmony export */ "MeshPhongMaterial": () => (/* binding */ MeshPhongMaterial),
  915. /* harmony export */ "MeshPhysicalMaterial": () => (/* binding */ MeshPhysicalMaterial),
  916. /* harmony export */ "MeshStandardMaterial": () => (/* binding */ MeshStandardMaterial),
  917. /* harmony export */ "MeshToonMaterial": () => (/* binding */ MeshToonMaterial),
  918. /* harmony export */ "MinEquation": () => (/* binding */ MinEquation),
  919. /* harmony export */ "MirroredRepeatWrapping": () => (/* binding */ MirroredRepeatWrapping),
  920. /* harmony export */ "MixOperation": () => (/* binding */ MixOperation),
  921. /* harmony export */ "MultiMaterial": () => (/* binding */ MultiMaterial),
  922. /* harmony export */ "MultiplyBlending": () => (/* binding */ MultiplyBlending),
  923. /* harmony export */ "MultiplyOperation": () => (/* binding */ MultiplyOperation),
  924. /* harmony export */ "NearestFilter": () => (/* binding */ NearestFilter),
  925. /* harmony export */ "NearestMipMapLinearFilter": () => (/* binding */ NearestMipMapLinearFilter),
  926. /* harmony export */ "NearestMipMapNearestFilter": () => (/* binding */ NearestMipMapNearestFilter),
  927. /* harmony export */ "NearestMipmapLinearFilter": () => (/* binding */ NearestMipmapLinearFilter),
  928. /* harmony export */ "NearestMipmapNearestFilter": () => (/* binding */ NearestMipmapNearestFilter),
  929. /* harmony export */ "NeverDepth": () => (/* binding */ NeverDepth),
  930. /* harmony export */ "NeverStencilFunc": () => (/* binding */ NeverStencilFunc),
  931. /* harmony export */ "NoBlending": () => (/* binding */ NoBlending),
  932. /* harmony export */ "NoColors": () => (/* binding */ NoColors),
  933. /* harmony export */ "NoToneMapping": () => (/* binding */ NoToneMapping),
  934. /* harmony export */ "NormalAnimationBlendMode": () => (/* binding */ NormalAnimationBlendMode),
  935. /* harmony export */ "NormalBlending": () => (/* binding */ NormalBlending),
  936. /* harmony export */ "NotEqualDepth": () => (/* binding */ NotEqualDepth),
  937. /* harmony export */ "NotEqualStencilFunc": () => (/* binding */ NotEqualStencilFunc),
  938. /* harmony export */ "NumberKeyframeTrack": () => (/* binding */ NumberKeyframeTrack),
  939. /* harmony export */ "Object3D": () => (/* binding */ Object3D),
  940. /* harmony export */ "ObjectLoader": () => (/* binding */ ObjectLoader),
  941. /* harmony export */ "ObjectSpaceNormalMap": () => (/* binding */ ObjectSpaceNormalMap),
  942. /* harmony export */ "OctahedronBufferGeometry": () => (/* binding */ OctahedronGeometry),
  943. /* harmony export */ "OctahedronGeometry": () => (/* binding */ OctahedronGeometry),
  944. /* harmony export */ "OneFactor": () => (/* binding */ OneFactor),
  945. /* harmony export */ "OneMinusDstAlphaFactor": () => (/* binding */ OneMinusDstAlphaFactor),
  946. /* harmony export */ "OneMinusDstColorFactor": () => (/* binding */ OneMinusDstColorFactor),
  947. /* harmony export */ "OneMinusSrcAlphaFactor": () => (/* binding */ OneMinusSrcAlphaFactor),
  948. /* harmony export */ "OneMinusSrcColorFactor": () => (/* binding */ OneMinusSrcColorFactor),
  949. /* harmony export */ "OrthographicCamera": () => (/* binding */ OrthographicCamera),
  950. /* harmony export */ "PCFShadowMap": () => (/* binding */ PCFShadowMap),
  951. /* harmony export */ "PCFSoftShadowMap": () => (/* binding */ PCFSoftShadowMap),
  952. /* harmony export */ "PMREMGenerator": () => (/* binding */ PMREMGenerator),
  953. /* harmony export */ "ParametricBufferGeometry": () => (/* binding */ ParametricGeometry),
  954. /* harmony export */ "ParametricGeometry": () => (/* binding */ ParametricGeometry),
  955. /* harmony export */ "Particle": () => (/* binding */ Particle),
  956. /* harmony export */ "ParticleBasicMaterial": () => (/* binding */ ParticleBasicMaterial),
  957. /* harmony export */ "ParticleSystem": () => (/* binding */ ParticleSystem),
  958. /* harmony export */ "ParticleSystemMaterial": () => (/* binding */ ParticleSystemMaterial),
  959. /* harmony export */ "Path": () => (/* binding */ Path),
  960. /* harmony export */ "PerspectiveCamera": () => (/* binding */ PerspectiveCamera),
  961. /* harmony export */ "Plane": () => (/* binding */ Plane),
  962. /* harmony export */ "PlaneBufferGeometry": () => (/* binding */ PlaneGeometry),
  963. /* harmony export */ "PlaneGeometry": () => (/* binding */ PlaneGeometry),
  964. /* harmony export */ "PlaneHelper": () => (/* binding */ PlaneHelper),
  965. /* harmony export */ "PointCloud": () => (/* binding */ PointCloud),
  966. /* harmony export */ "PointCloudMaterial": () => (/* binding */ PointCloudMaterial),
  967. /* harmony export */ "PointLight": () => (/* binding */ PointLight),
  968. /* harmony export */ "PointLightHelper": () => (/* binding */ PointLightHelper),
  969. /* harmony export */ "Points": () => (/* binding */ Points),
  970. /* harmony export */ "PointsMaterial": () => (/* binding */ PointsMaterial),
  971. /* harmony export */ "PolarGridHelper": () => (/* binding */ PolarGridHelper),
  972. /* harmony export */ "PolyhedronBufferGeometry": () => (/* binding */ PolyhedronGeometry),
  973. /* harmony export */ "PolyhedronGeometry": () => (/* binding */ PolyhedronGeometry),
  974. /* harmony export */ "PositionalAudio": () => (/* binding */ PositionalAudio),
  975. /* harmony export */ "PropertyBinding": () => (/* binding */ PropertyBinding),
  976. /* harmony export */ "PropertyMixer": () => (/* binding */ PropertyMixer),
  977. /* harmony export */ "QuadraticBezierCurve": () => (/* binding */ QuadraticBezierCurve),
  978. /* harmony export */ "QuadraticBezierCurve3": () => (/* binding */ QuadraticBezierCurve3),
  979. /* harmony export */ "Quaternion": () => (/* binding */ Quaternion),
  980. /* harmony export */ "QuaternionKeyframeTrack": () => (/* binding */ QuaternionKeyframeTrack),
  981. /* harmony export */ "QuaternionLinearInterpolant": () => (/* binding */ QuaternionLinearInterpolant),
  982. /* harmony export */ "REVISION": () => (/* binding */ REVISION),
  983. /* harmony export */ "RGBADepthPacking": () => (/* binding */ RGBADepthPacking),
  984. /* harmony export */ "RGBAFormat": () => (/* binding */ RGBAFormat),
  985. /* harmony export */ "RGBAIntegerFormat": () => (/* binding */ RGBAIntegerFormat),
  986. /* harmony export */ "RGBA_ASTC_10x10_Format": () => (/* binding */ RGBA_ASTC_10x10_Format),
  987. /* harmony export */ "RGBA_ASTC_10x5_Format": () => (/* binding */ RGBA_ASTC_10x5_Format),
  988. /* harmony export */ "RGBA_ASTC_10x6_Format": () => (/* binding */ RGBA_ASTC_10x6_Format),
  989. /* harmony export */ "RGBA_ASTC_10x8_Format": () => (/* binding */ RGBA_ASTC_10x8_Format),
  990. /* harmony export */ "RGBA_ASTC_12x10_Format": () => (/* binding */ RGBA_ASTC_12x10_Format),
  991. /* harmony export */ "RGBA_ASTC_12x12_Format": () => (/* binding */ RGBA_ASTC_12x12_Format),
  992. /* harmony export */ "RGBA_ASTC_4x4_Format": () => (/* binding */ RGBA_ASTC_4x4_Format),
  993. /* harmony export */ "RGBA_ASTC_5x4_Format": () => (/* binding */ RGBA_ASTC_5x4_Format),
  994. /* harmony export */ "RGBA_ASTC_5x5_Format": () => (/* binding */ RGBA_ASTC_5x5_Format),
  995. /* harmony export */ "RGBA_ASTC_6x5_Format": () => (/* binding */ RGBA_ASTC_6x5_Format),
  996. /* harmony export */ "RGBA_ASTC_6x6_Format": () => (/* binding */ RGBA_ASTC_6x6_Format),
  997. /* harmony export */ "RGBA_ASTC_8x5_Format": () => (/* binding */ RGBA_ASTC_8x5_Format),
  998. /* harmony export */ "RGBA_ASTC_8x6_Format": () => (/* binding */ RGBA_ASTC_8x6_Format),
  999. /* harmony export */ "RGBA_ASTC_8x8_Format": () => (/* binding */ RGBA_ASTC_8x8_Format),
  1000. /* harmony export */ "RGBA_BPTC_Format": () => (/* binding */ RGBA_BPTC_Format),
  1001. /* harmony export */ "RGBA_ETC2_EAC_Format": () => (/* binding */ RGBA_ETC2_EAC_Format),
  1002. /* harmony export */ "RGBA_PVRTC_2BPPV1_Format": () => (/* binding */ RGBA_PVRTC_2BPPV1_Format),
  1003. /* harmony export */ "RGBA_PVRTC_4BPPV1_Format": () => (/* binding */ RGBA_PVRTC_4BPPV1_Format),
  1004. /* harmony export */ "RGBA_S3TC_DXT1_Format": () => (/* binding */ RGBA_S3TC_DXT1_Format),
  1005. /* harmony export */ "RGBA_S3TC_DXT3_Format": () => (/* binding */ RGBA_S3TC_DXT3_Format),
  1006. /* harmony export */ "RGBA_S3TC_DXT5_Format": () => (/* binding */ RGBA_S3TC_DXT5_Format),
  1007. /* harmony export */ "RGBDEncoding": () => (/* binding */ RGBDEncoding),
  1008. /* harmony export */ "RGBEEncoding": () => (/* binding */ RGBEEncoding),
  1009. /* harmony export */ "RGBEFormat": () => (/* binding */ RGBEFormat),
  1010. /* harmony export */ "RGBFormat": () => (/* binding */ RGBFormat),
  1011. /* harmony export */ "RGBIntegerFormat": () => (/* binding */ RGBIntegerFormat),
  1012. /* harmony export */ "RGBM16Encoding": () => (/* binding */ RGBM16Encoding),
  1013. /* harmony export */ "RGBM7Encoding": () => (/* binding */ RGBM7Encoding),
  1014. /* harmony export */ "RGB_ETC1_Format": () => (/* binding */ RGB_ETC1_Format),
  1015. /* harmony export */ "RGB_ETC2_Format": () => (/* binding */ RGB_ETC2_Format),
  1016. /* harmony export */ "RGB_PVRTC_2BPPV1_Format": () => (/* binding */ RGB_PVRTC_2BPPV1_Format),
  1017. /* harmony export */ "RGB_PVRTC_4BPPV1_Format": () => (/* binding */ RGB_PVRTC_4BPPV1_Format),
  1018. /* harmony export */ "RGB_S3TC_DXT1_Format": () => (/* binding */ RGB_S3TC_DXT1_Format),
  1019. /* harmony export */ "RGFormat": () => (/* binding */ RGFormat),
  1020. /* harmony export */ "RGIntegerFormat": () => (/* binding */ RGIntegerFormat),
  1021. /* harmony export */ "RawShaderMaterial": () => (/* binding */ RawShaderMaterial),
  1022. /* harmony export */ "Ray": () => (/* binding */ Ray),
  1023. /* harmony export */ "Raycaster": () => (/* binding */ Raycaster),
  1024. /* harmony export */ "RectAreaLight": () => (/* binding */ RectAreaLight),
  1025. /* harmony export */ "RedFormat": () => (/* binding */ RedFormat),
  1026. /* harmony export */ "RedIntegerFormat": () => (/* binding */ RedIntegerFormat),
  1027. /* harmony export */ "ReinhardToneMapping": () => (/* binding */ ReinhardToneMapping),
  1028. /* harmony export */ "RepeatWrapping": () => (/* binding */ RepeatWrapping),
  1029. /* harmony export */ "ReplaceStencilOp": () => (/* binding */ ReplaceStencilOp),
  1030. /* harmony export */ "ReverseSubtractEquation": () => (/* binding */ ReverseSubtractEquation),
  1031. /* harmony export */ "RingBufferGeometry": () => (/* binding */ RingGeometry),
  1032. /* harmony export */ "RingGeometry": () => (/* binding */ RingGeometry),
  1033. /* harmony export */ "SRGB8_ALPHA8_ASTC_10x10_Format": () => (/* binding */ SRGB8_ALPHA8_ASTC_10x10_Format),
  1034. /* harmony export */ "SRGB8_ALPHA8_ASTC_10x5_Format": () => (/* binding */ SRGB8_ALPHA8_ASTC_10x5_Format),
  1035. /* harmony export */ "SRGB8_ALPHA8_ASTC_10x6_Format": () => (/* binding */ SRGB8_ALPHA8_ASTC_10x6_Format),
  1036. /* harmony export */ "SRGB8_ALPHA8_ASTC_10x8_Format": () => (/* binding */ SRGB8_ALPHA8_ASTC_10x8_Format),
  1037. /* harmony export */ "SRGB8_ALPHA8_ASTC_12x10_Format": () => (/* binding */ SRGB8_ALPHA8_ASTC_12x10_Format),
  1038. /* harmony export */ "SRGB8_ALPHA8_ASTC_12x12_Format": () => (/* binding */ SRGB8_ALPHA8_ASTC_12x12_Format),
  1039. /* harmony export */ "SRGB8_ALPHA8_ASTC_4x4_Format": () => (/* binding */ SRGB8_ALPHA8_ASTC_4x4_Format),
  1040. /* harmony export */ "SRGB8_ALPHA8_ASTC_5x4_Format": () => (/* binding */ SRGB8_ALPHA8_ASTC_5x4_Format),
  1041. /* harmony export */ "SRGB8_ALPHA8_ASTC_5x5_Format": () => (/* binding */ SRGB8_ALPHA8_ASTC_5x5_Format),
  1042. /* harmony export */ "SRGB8_ALPHA8_ASTC_6x5_Format": () => (/* binding */ SRGB8_ALPHA8_ASTC_6x5_Format),
  1043. /* harmony export */ "SRGB8_ALPHA8_ASTC_6x6_Format": () => (/* binding */ SRGB8_ALPHA8_ASTC_6x6_Format),
  1044. /* harmony export */ "SRGB8_ALPHA8_ASTC_8x5_Format": () => (/* binding */ SRGB8_ALPHA8_ASTC_8x5_Format),
  1045. /* harmony export */ "SRGB8_ALPHA8_ASTC_8x6_Format": () => (/* binding */ SRGB8_ALPHA8_ASTC_8x6_Format),
  1046. /* harmony export */ "SRGB8_ALPHA8_ASTC_8x8_Format": () => (/* binding */ SRGB8_ALPHA8_ASTC_8x8_Format),
  1047. /* harmony export */ "Scene": () => (/* binding */ Scene),
  1048. /* harmony export */ "SceneUtils": () => (/* binding */ SceneUtils),
  1049. /* harmony export */ "ShaderChunk": () => (/* binding */ ShaderChunk),
  1050. /* harmony export */ "ShaderLib": () => (/* binding */ ShaderLib),
  1051. /* harmony export */ "ShaderMaterial": () => (/* binding */ ShaderMaterial),
  1052. /* harmony export */ "ShadowMaterial": () => (/* binding */ ShadowMaterial),
  1053. /* harmony export */ "Shape": () => (/* binding */ Shape),
  1054. /* harmony export */ "ShapeBufferGeometry": () => (/* binding */ ShapeGeometry),
  1055. /* harmony export */ "ShapeGeometry": () => (/* binding */ ShapeGeometry),
  1056. /* harmony export */ "ShapePath": () => (/* binding */ ShapePath),
  1057. /* harmony export */ "ShapeUtils": () => (/* binding */ ShapeUtils),
  1058. /* harmony export */ "ShortType": () => (/* binding */ ShortType),
  1059. /* harmony export */ "Skeleton": () => (/* binding */ Skeleton),
  1060. /* harmony export */ "SkeletonHelper": () => (/* binding */ SkeletonHelper),
  1061. /* harmony export */ "SkinnedMesh": () => (/* binding */ SkinnedMesh),
  1062. /* harmony export */ "SmoothShading": () => (/* binding */ SmoothShading),
  1063. /* harmony export */ "Sphere": () => (/* binding */ Sphere),
  1064. /* harmony export */ "SphereBufferGeometry": () => (/* binding */ SphereGeometry),
  1065. /* harmony export */ "SphereGeometry": () => (/* binding */ SphereGeometry),
  1066. /* harmony export */ "Spherical": () => (/* binding */ Spherical),
  1067. /* harmony export */ "SphericalHarmonics3": () => (/* binding */ SphericalHarmonics3),
  1068. /* harmony export */ "SplineCurve": () => (/* binding */ SplineCurve),
  1069. /* harmony export */ "SpotLight": () => (/* binding */ SpotLight),
  1070. /* harmony export */ "SpotLightHelper": () => (/* binding */ SpotLightHelper),
  1071. /* harmony export */ "Sprite": () => (/* binding */ Sprite),
  1072. /* harmony export */ "SpriteMaterial": () => (/* binding */ SpriteMaterial),
  1073. /* harmony export */ "SrcAlphaFactor": () => (/* binding */ SrcAlphaFactor),
  1074. /* harmony export */ "SrcAlphaSaturateFactor": () => (/* binding */ SrcAlphaSaturateFactor),
  1075. /* harmony export */ "SrcColorFactor": () => (/* binding */ SrcColorFactor),
  1076. /* harmony export */ "StaticCopyUsage": () => (/* binding */ StaticCopyUsage),
  1077. /* harmony export */ "StaticDrawUsage": () => (/* binding */ StaticDrawUsage),
  1078. /* harmony export */ "StaticReadUsage": () => (/* binding */ StaticReadUsage),
  1079. /* harmony export */ "StereoCamera": () => (/* binding */ StereoCamera),
  1080. /* harmony export */ "StreamCopyUsage": () => (/* binding */ StreamCopyUsage),
  1081. /* harmony export */ "StreamDrawUsage": () => (/* binding */ StreamDrawUsage),
  1082. /* harmony export */ "StreamReadUsage": () => (/* binding */ StreamReadUsage),
  1083. /* harmony export */ "StringKeyframeTrack": () => (/* binding */ StringKeyframeTrack),
  1084. /* harmony export */ "SubtractEquation": () => (/* binding */ SubtractEquation),
  1085. /* harmony export */ "SubtractiveBlending": () => (/* binding */ SubtractiveBlending),
  1086. /* harmony export */ "TOUCH": () => (/* binding */ TOUCH),
  1087. /* harmony export */ "TangentSpaceNormalMap": () => (/* binding */ TangentSpaceNormalMap),
  1088. /* harmony export */ "TetrahedronBufferGeometry": () => (/* binding */ TetrahedronGeometry),
  1089. /* harmony export */ "TetrahedronGeometry": () => (/* binding */ TetrahedronGeometry),
  1090. /* harmony export */ "TextBufferGeometry": () => (/* binding */ TextGeometry),
  1091. /* harmony export */ "TextGeometry": () => (/* binding */ TextGeometry),
  1092. /* harmony export */ "Texture": () => (/* binding */ Texture),
  1093. /* harmony export */ "TextureLoader": () => (/* binding */ TextureLoader),
  1094. /* harmony export */ "TorusBufferGeometry": () => (/* binding */ TorusGeometry),
  1095. /* harmony export */ "TorusGeometry": () => (/* binding */ TorusGeometry),
  1096. /* harmony export */ "TorusKnotBufferGeometry": () => (/* binding */ TorusKnotGeometry),
  1097. /* harmony export */ "TorusKnotGeometry": () => (/* binding */ TorusKnotGeometry),
  1098. /* harmony export */ "Triangle": () => (/* binding */ Triangle),
  1099. /* harmony export */ "TriangleFanDrawMode": () => (/* binding */ TriangleFanDrawMode),
  1100. /* harmony export */ "TriangleStripDrawMode": () => (/* binding */ TriangleStripDrawMode),
  1101. /* harmony export */ "TrianglesDrawMode": () => (/* binding */ TrianglesDrawMode),
  1102. /* harmony export */ "TubeBufferGeometry": () => (/* binding */ TubeGeometry),
  1103. /* harmony export */ "TubeGeometry": () => (/* binding */ TubeGeometry),
  1104. /* harmony export */ "UVMapping": () => (/* binding */ UVMapping),
  1105. /* harmony export */ "Uint16Attribute": () => (/* binding */ Uint16Attribute),
  1106. /* harmony export */ "Uint16BufferAttribute": () => (/* binding */ Uint16BufferAttribute),
  1107. /* harmony export */ "Uint32Attribute": () => (/* binding */ Uint32Attribute),
  1108. /* harmony export */ "Uint32BufferAttribute": () => (/* binding */ Uint32BufferAttribute),
  1109. /* harmony export */ "Uint8Attribute": () => (/* binding */ Uint8Attribute),
  1110. /* harmony export */ "Uint8BufferAttribute": () => (/* binding */ Uint8BufferAttribute),
  1111. /* harmony export */ "Uint8ClampedAttribute": () => (/* binding */ Uint8ClampedAttribute),
  1112. /* harmony export */ "Uint8ClampedBufferAttribute": () => (/* binding */ Uint8ClampedBufferAttribute),
  1113. /* harmony export */ "Uniform": () => (/* binding */ Uniform),
  1114. /* harmony export */ "UniformsLib": () => (/* binding */ UniformsLib),
  1115. /* harmony export */ "UniformsUtils": () => (/* binding */ UniformsUtils),
  1116. /* harmony export */ "UnsignedByteType": () => (/* binding */ UnsignedByteType),
  1117. /* harmony export */ "UnsignedInt248Type": () => (/* binding */ UnsignedInt248Type),
  1118. /* harmony export */ "UnsignedIntType": () => (/* binding */ UnsignedIntType),
  1119. /* harmony export */ "UnsignedShort4444Type": () => (/* binding */ UnsignedShort4444Type),
  1120. /* harmony export */ "UnsignedShort5551Type": () => (/* binding */ UnsignedShort5551Type),
  1121. /* harmony export */ "UnsignedShort565Type": () => (/* binding */ UnsignedShort565Type),
  1122. /* harmony export */ "UnsignedShortType": () => (/* binding */ UnsignedShortType),
  1123. /* harmony export */ "VSMShadowMap": () => (/* binding */ VSMShadowMap),
  1124. /* harmony export */ "Vector2": () => (/* binding */ Vector2),
  1125. /* harmony export */ "Vector3": () => (/* binding */ Vector3),
  1126. /* harmony export */ "Vector4": () => (/* binding */ Vector4),
  1127. /* harmony export */ "VectorKeyframeTrack": () => (/* binding */ VectorKeyframeTrack),
  1128. /* harmony export */ "Vertex": () => (/* binding */ Vertex),
  1129. /* harmony export */ "VertexColors": () => (/* binding */ VertexColors),
  1130. /* harmony export */ "VideoTexture": () => (/* binding */ VideoTexture),
  1131. /* harmony export */ "WebGL1Renderer": () => (/* binding */ WebGL1Renderer),
  1132. /* harmony export */ "WebGLCubeRenderTarget": () => (/* binding */ WebGLCubeRenderTarget),
  1133. /* harmony export */ "WebGLMultipleRenderTargets": () => (/* binding */ WebGLMultipleRenderTargets),
  1134. /* harmony export */ "WebGLMultisampleRenderTarget": () => (/* binding */ WebGLMultisampleRenderTarget),
  1135. /* harmony export */ "WebGLRenderTarget": () => (/* binding */ WebGLRenderTarget),
  1136. /* harmony export */ "WebGLRenderTargetCube": () => (/* binding */ WebGLRenderTargetCube),
  1137. /* harmony export */ "WebGLRenderer": () => (/* binding */ WebGLRenderer),
  1138. /* harmony export */ "WebGLUtils": () => (/* binding */ WebGLUtils),
  1139. /* harmony export */ "WireframeGeometry": () => (/* binding */ WireframeGeometry),
  1140. /* harmony export */ "WireframeHelper": () => (/* binding */ WireframeHelper),
  1141. /* harmony export */ "WrapAroundEnding": () => (/* binding */ WrapAroundEnding),
  1142. /* harmony export */ "XHRLoader": () => (/* binding */ XHRLoader),
  1143. /* harmony export */ "ZeroCurvatureEnding": () => (/* binding */ ZeroCurvatureEnding),
  1144. /* harmony export */ "ZeroFactor": () => (/* binding */ ZeroFactor),
  1145. /* harmony export */ "ZeroSlopeEnding": () => (/* binding */ ZeroSlopeEnding),
  1146. /* harmony export */ "ZeroStencilOp": () => (/* binding */ ZeroStencilOp),
  1147. /* harmony export */ "sRGBEncoding": () => (/* binding */ sRGBEncoding)
  1148. /* harmony export */ });
  1149. /**
  1150. * @license
  1151. * Copyright 2010-2021 Three.js Authors
  1152. * SPDX-License-Identifier: MIT
  1153. */
  1154. const REVISION = '132';
  1155. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  1156. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  1157. const CullFaceNone = 0;
  1158. const CullFaceBack = 1;
  1159. const CullFaceFront = 2;
  1160. const CullFaceFrontBack = 3;
  1161. const BasicShadowMap = 0;
  1162. const PCFShadowMap = 1;
  1163. const PCFSoftShadowMap = 2;
  1164. const VSMShadowMap = 3;
  1165. const FrontSide = 0;
  1166. const BackSide = 1;
  1167. const DoubleSide = 2;
  1168. const FlatShading = 1;
  1169. const SmoothShading = 2;
  1170. const NoBlending = 0;
  1171. const NormalBlending = 1;
  1172. const AdditiveBlending = 2;
  1173. const SubtractiveBlending = 3;
  1174. const MultiplyBlending = 4;
  1175. const CustomBlending = 5;
  1176. const AddEquation = 100;
  1177. const SubtractEquation = 101;
  1178. const ReverseSubtractEquation = 102;
  1179. const MinEquation = 103;
  1180. const MaxEquation = 104;
  1181. const ZeroFactor = 200;
  1182. const OneFactor = 201;
  1183. const SrcColorFactor = 202;
  1184. const OneMinusSrcColorFactor = 203;
  1185. const SrcAlphaFactor = 204;
  1186. const OneMinusSrcAlphaFactor = 205;
  1187. const DstAlphaFactor = 206;
  1188. const OneMinusDstAlphaFactor = 207;
  1189. const DstColorFactor = 208;
  1190. const OneMinusDstColorFactor = 209;
  1191. const SrcAlphaSaturateFactor = 210;
  1192. const NeverDepth = 0;
  1193. const AlwaysDepth = 1;
  1194. const LessDepth = 2;
  1195. const LessEqualDepth = 3;
  1196. const EqualDepth = 4;
  1197. const GreaterEqualDepth = 5;
  1198. const GreaterDepth = 6;
  1199. const NotEqualDepth = 7;
  1200. const MultiplyOperation = 0;
  1201. const MixOperation = 1;
  1202. const AddOperation = 2;
  1203. const NoToneMapping = 0;
  1204. const LinearToneMapping = 1;
  1205. const ReinhardToneMapping = 2;
  1206. const CineonToneMapping = 3;
  1207. const ACESFilmicToneMapping = 4;
  1208. const CustomToneMapping = 5;
  1209. const UVMapping = 300;
  1210. const CubeReflectionMapping = 301;
  1211. const CubeRefractionMapping = 302;
  1212. const EquirectangularReflectionMapping = 303;
  1213. const EquirectangularRefractionMapping = 304;
  1214. const CubeUVReflectionMapping = 306;
  1215. const CubeUVRefractionMapping = 307;
  1216. const RepeatWrapping = 1000;
  1217. const ClampToEdgeWrapping = 1001;
  1218. const MirroredRepeatWrapping = 1002;
  1219. const NearestFilter = 1003;
  1220. const NearestMipmapNearestFilter = 1004;
  1221. const NearestMipMapNearestFilter = 1004;
  1222. const NearestMipmapLinearFilter = 1005;
  1223. const NearestMipMapLinearFilter = 1005;
  1224. const LinearFilter = 1006;
  1225. const LinearMipmapNearestFilter = 1007;
  1226. const LinearMipMapNearestFilter = 1007;
  1227. const LinearMipmapLinearFilter = 1008;
  1228. const LinearMipMapLinearFilter = 1008;
  1229. const UnsignedByteType = 1009;
  1230. const ByteType = 1010;
  1231. const ShortType = 1011;
  1232. const UnsignedShortType = 1012;
  1233. const IntType = 1013;
  1234. const UnsignedIntType = 1014;
  1235. const FloatType = 1015;
  1236. const HalfFloatType = 1016;
  1237. const UnsignedShort4444Type = 1017;
  1238. const UnsignedShort5551Type = 1018;
  1239. const UnsignedShort565Type = 1019;
  1240. const UnsignedInt248Type = 1020;
  1241. const AlphaFormat = 1021;
  1242. const RGBFormat = 1022;
  1243. const RGBAFormat = 1023;
  1244. const LuminanceFormat = 1024;
  1245. const LuminanceAlphaFormat = 1025;
  1246. const RGBEFormat = RGBAFormat;
  1247. const DepthFormat = 1026;
  1248. const DepthStencilFormat = 1027;
  1249. const RedFormat = 1028;
  1250. const RedIntegerFormat = 1029;
  1251. const RGFormat = 1030;
  1252. const RGIntegerFormat = 1031;
  1253. const RGBIntegerFormat = 1032;
  1254. const RGBAIntegerFormat = 1033;
  1255. const RGB_S3TC_DXT1_Format = 33776;
  1256. const RGBA_S3TC_DXT1_Format = 33777;
  1257. const RGBA_S3TC_DXT3_Format = 33778;
  1258. const RGBA_S3TC_DXT5_Format = 33779;
  1259. const RGB_PVRTC_4BPPV1_Format = 35840;
  1260. const RGB_PVRTC_2BPPV1_Format = 35841;
  1261. const RGBA_PVRTC_4BPPV1_Format = 35842;
  1262. const RGBA_PVRTC_2BPPV1_Format = 35843;
  1263. const RGB_ETC1_Format = 36196;
  1264. const RGB_ETC2_Format = 37492;
  1265. const RGBA_ETC2_EAC_Format = 37496;
  1266. const RGBA_ASTC_4x4_Format = 37808;
  1267. const RGBA_ASTC_5x4_Format = 37809;
  1268. const RGBA_ASTC_5x5_Format = 37810;
  1269. const RGBA_ASTC_6x5_Format = 37811;
  1270. const RGBA_ASTC_6x6_Format = 37812;
  1271. const RGBA_ASTC_8x5_Format = 37813;
  1272. const RGBA_ASTC_8x6_Format = 37814;
  1273. const RGBA_ASTC_8x8_Format = 37815;
  1274. const RGBA_ASTC_10x5_Format = 37816;
  1275. const RGBA_ASTC_10x6_Format = 37817;
  1276. const RGBA_ASTC_10x8_Format = 37818;
  1277. const RGBA_ASTC_10x10_Format = 37819;
  1278. const RGBA_ASTC_12x10_Format = 37820;
  1279. const RGBA_ASTC_12x12_Format = 37821;
  1280. const RGBA_BPTC_Format = 36492;
  1281. const SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  1282. const SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  1283. const SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  1284. const SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  1285. const SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  1286. const SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  1287. const SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  1288. const SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  1289. const SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  1290. const SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  1291. const SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  1292. const SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  1293. const SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  1294. const SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  1295. const LoopOnce = 2200;
  1296. const LoopRepeat = 2201;
  1297. const LoopPingPong = 2202;
  1298. const InterpolateDiscrete = 2300;
  1299. const InterpolateLinear = 2301;
  1300. const InterpolateSmooth = 2302;
  1301. const ZeroCurvatureEnding = 2400;
  1302. const ZeroSlopeEnding = 2401;
  1303. const WrapAroundEnding = 2402;
  1304. const NormalAnimationBlendMode = 2500;
  1305. const AdditiveAnimationBlendMode = 2501;
  1306. const TrianglesDrawMode = 0;
  1307. const TriangleStripDrawMode = 1;
  1308. const TriangleFanDrawMode = 2;
  1309. const LinearEncoding = 3000;
  1310. const sRGBEncoding = 3001;
  1311. const GammaEncoding = 3007;
  1312. const RGBEEncoding = 3002;
  1313. const LogLuvEncoding = 3003;
  1314. const RGBM7Encoding = 3004;
  1315. const RGBM16Encoding = 3005;
  1316. const RGBDEncoding = 3006;
  1317. const BasicDepthPacking = 3200;
  1318. const RGBADepthPacking = 3201;
  1319. const TangentSpaceNormalMap = 0;
  1320. const ObjectSpaceNormalMap = 1;
  1321. const ZeroStencilOp = 0;
  1322. const KeepStencilOp = 7680;
  1323. const ReplaceStencilOp = 7681;
  1324. const IncrementStencilOp = 7682;
  1325. const DecrementStencilOp = 7683;
  1326. const IncrementWrapStencilOp = 34055;
  1327. const DecrementWrapStencilOp = 34056;
  1328. const InvertStencilOp = 5386;
  1329. const NeverStencilFunc = 512;
  1330. const LessStencilFunc = 513;
  1331. const EqualStencilFunc = 514;
  1332. const LessEqualStencilFunc = 515;
  1333. const GreaterStencilFunc = 516;
  1334. const NotEqualStencilFunc = 517;
  1335. const GreaterEqualStencilFunc = 518;
  1336. const AlwaysStencilFunc = 519;
  1337. const StaticDrawUsage = 35044;
  1338. const DynamicDrawUsage = 35048;
  1339. const StreamDrawUsage = 35040;
  1340. const StaticReadUsage = 35045;
  1341. const DynamicReadUsage = 35049;
  1342. const StreamReadUsage = 35041;
  1343. const StaticCopyUsage = 35046;
  1344. const DynamicCopyUsage = 35050;
  1345. const StreamCopyUsage = 35042;
  1346. const GLSL1 = '100';
  1347. const GLSL3 = '300 es';
  1348. /**
  1349. * https://github.com/mrdoob/eventdispatcher.js/
  1350. */
  1351. class EventDispatcher {
  1352. addEventListener( type, listener ) {
  1353. if ( this._listeners === undefined ) this._listeners = {};
  1354. const listeners = this._listeners;
  1355. if ( listeners[ type ] === undefined ) {
  1356. listeners[ type ] = [];
  1357. }
  1358. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  1359. listeners[ type ].push( listener );
  1360. }
  1361. }
  1362. hasEventListener( type, listener ) {
  1363. if ( this._listeners === undefined ) return false;
  1364. const listeners = this._listeners;
  1365. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  1366. }
  1367. removeEventListener( type, listener ) {
  1368. if ( this._listeners === undefined ) return;
  1369. const listeners = this._listeners;
  1370. const listenerArray = listeners[ type ];
  1371. if ( listenerArray !== undefined ) {
  1372. const index = listenerArray.indexOf( listener );
  1373. if ( index !== - 1 ) {
  1374. listenerArray.splice( index, 1 );
  1375. }
  1376. }
  1377. }
  1378. dispatchEvent( event ) {
  1379. if ( this._listeners === undefined ) return;
  1380. const listeners = this._listeners;
  1381. const listenerArray = listeners[ event.type ];
  1382. if ( listenerArray !== undefined ) {
  1383. event.target = this;
  1384. // Make a copy, in case listeners are removed while iterating.
  1385. const array = listenerArray.slice( 0 );
  1386. for ( let i = 0, l = array.length; i < l; i ++ ) {
  1387. array[ i ].call( this, event );
  1388. }
  1389. event.target = null;
  1390. }
  1391. }
  1392. }
  1393. const _lut = [];
  1394. for ( let i = 0; i < 256; i ++ ) {
  1395. _lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 );
  1396. }
  1397. let _seed = 1234567;
  1398. const DEG2RAD = Math.PI / 180;
  1399. const RAD2DEG = 180 / Math.PI;
  1400. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1401. function generateUUID() {
  1402. const d0 = Math.random() * 0xffffffff | 0;
  1403. const d1 = Math.random() * 0xffffffff | 0;
  1404. const d2 = Math.random() * 0xffffffff | 0;
  1405. const d3 = Math.random() * 0xffffffff | 0;
  1406. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  1407. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  1408. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  1409. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  1410. // .toUpperCase() here flattens concatenated strings to save heap memory space.
  1411. return uuid.toUpperCase();
  1412. }
  1413. function clamp( value, min, max ) {
  1414. return Math.max( min, Math.min( max, value ) );
  1415. }
  1416. // compute euclidian modulo of m % n
  1417. // https://en.wikipedia.org/wiki/Modulo_operation
  1418. function euclideanModulo( n, m ) {
  1419. return ( ( n % m ) + m ) % m;
  1420. }
  1421. // Linear mapping from range <a1, a2> to range <b1, b2>
  1422. function mapLinear( x, a1, a2, b1, b2 ) {
  1423. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1424. }
  1425. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  1426. function inverseLerp( x, y, value ) {
  1427. if ( x !== y ) {
  1428. return ( value - x ) / ( y - x );
  1429. } else {
  1430. return 0;
  1431. }
  1432. }
  1433. // https://en.wikipedia.org/wiki/Linear_interpolation
  1434. function lerp( x, y, t ) {
  1435. return ( 1 - t ) * x + t * y;
  1436. }
  1437. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  1438. function damp( x, y, lambda, dt ) {
  1439. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  1440. }
  1441. // https://www.desmos.com/calculator/vcsjnyz7x4
  1442. function pingpong( x, length = 1 ) {
  1443. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  1444. }
  1445. // http://en.wikipedia.org/wiki/Smoothstep
  1446. function smoothstep( x, min, max ) {
  1447. if ( x <= min ) return 0;
  1448. if ( x >= max ) return 1;
  1449. x = ( x - min ) / ( max - min );
  1450. return x * x * ( 3 - 2 * x );
  1451. }
  1452. function smootherstep( x, min, max ) {
  1453. if ( x <= min ) return 0;
  1454. if ( x >= max ) return 1;
  1455. x = ( x - min ) / ( max - min );
  1456. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  1457. }
  1458. // Random integer from <low, high> interval
  1459. function randInt( low, high ) {
  1460. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  1461. }
  1462. // Random float from <low, high> interval
  1463. function randFloat( low, high ) {
  1464. return low + Math.random() * ( high - low );
  1465. }
  1466. // Random float from <-range/2, range/2> interval
  1467. function randFloatSpread( range ) {
  1468. return range * ( 0.5 - Math.random() );
  1469. }
  1470. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  1471. function seededRandom( s ) {
  1472. if ( s !== undefined ) _seed = s % 2147483647;
  1473. // Park-Miller algorithm
  1474. _seed = _seed * 16807 % 2147483647;
  1475. return ( _seed - 1 ) / 2147483646;
  1476. }
  1477. function degToRad( degrees ) {
  1478. return degrees * DEG2RAD;
  1479. }
  1480. function radToDeg( radians ) {
  1481. return radians * RAD2DEG;
  1482. }
  1483. function isPowerOfTwo( value ) {
  1484. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  1485. }
  1486. function ceilPowerOfTwo( value ) {
  1487. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  1488. }
  1489. function floorPowerOfTwo( value ) {
  1490. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  1491. }
  1492. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  1493. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  1494. // rotations are applied to the axes in the order specified by 'order'
  1495. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  1496. // angles are in radians
  1497. const cos = Math.cos;
  1498. const sin = Math.sin;
  1499. const c2 = cos( b / 2 );
  1500. const s2 = sin( b / 2 );
  1501. const c13 = cos( ( a + c ) / 2 );
  1502. const s13 = sin( ( a + c ) / 2 );
  1503. const c1_3 = cos( ( a - c ) / 2 );
  1504. const s1_3 = sin( ( a - c ) / 2 );
  1505. const c3_1 = cos( ( c - a ) / 2 );
  1506. const s3_1 = sin( ( c - a ) / 2 );
  1507. switch ( order ) {
  1508. case 'XYX':
  1509. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  1510. break;
  1511. case 'YZY':
  1512. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  1513. break;
  1514. case 'ZXZ':
  1515. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  1516. break;
  1517. case 'XZX':
  1518. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  1519. break;
  1520. case 'YXY':
  1521. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  1522. break;
  1523. case 'ZYZ':
  1524. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  1525. break;
  1526. default:
  1527. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  1528. }
  1529. }
  1530. var MathUtils = /*#__PURE__*/Object.freeze({
  1531. __proto__: null,
  1532. DEG2RAD: DEG2RAD,
  1533. RAD2DEG: RAD2DEG,
  1534. generateUUID: generateUUID,
  1535. clamp: clamp,
  1536. euclideanModulo: euclideanModulo,
  1537. mapLinear: mapLinear,
  1538. inverseLerp: inverseLerp,
  1539. lerp: lerp,
  1540. damp: damp,
  1541. pingpong: pingpong,
  1542. smoothstep: smoothstep,
  1543. smootherstep: smootherstep,
  1544. randInt: randInt,
  1545. randFloat: randFloat,
  1546. randFloatSpread: randFloatSpread,
  1547. seededRandom: seededRandom,
  1548. degToRad: degToRad,
  1549. radToDeg: radToDeg,
  1550. isPowerOfTwo: isPowerOfTwo,
  1551. ceilPowerOfTwo: ceilPowerOfTwo,
  1552. floorPowerOfTwo: floorPowerOfTwo,
  1553. setQuaternionFromProperEuler: setQuaternionFromProperEuler
  1554. });
  1555. class Vector2 {
  1556. constructor( x = 0, y = 0 ) {
  1557. this.x = x;
  1558. this.y = y;
  1559. }
  1560. get width() {
  1561. return this.x;
  1562. }
  1563. set width( value ) {
  1564. this.x = value;
  1565. }
  1566. get height() {
  1567. return this.y;
  1568. }
  1569. set height( value ) {
  1570. this.y = value;
  1571. }
  1572. set( x, y ) {
  1573. this.x = x;
  1574. this.y = y;
  1575. return this;
  1576. }
  1577. setScalar( scalar ) {
  1578. this.x = scalar;
  1579. this.y = scalar;
  1580. return this;
  1581. }
  1582. setX( x ) {
  1583. this.x = x;
  1584. return this;
  1585. }
  1586. setY( y ) {
  1587. this.y = y;
  1588. return this;
  1589. }
  1590. setComponent( index, value ) {
  1591. switch ( index ) {
  1592. case 0: this.x = value; break;
  1593. case 1: this.y = value; break;
  1594. default: throw new Error( 'index is out of range: ' + index );
  1595. }
  1596. return this;
  1597. }
  1598. getComponent( index ) {
  1599. switch ( index ) {
  1600. case 0: return this.x;
  1601. case 1: return this.y;
  1602. default: throw new Error( 'index is out of range: ' + index );
  1603. }
  1604. }
  1605. clone() {
  1606. return new this.constructor( this.x, this.y );
  1607. }
  1608. copy( v ) {
  1609. this.x = v.x;
  1610. this.y = v.y;
  1611. return this;
  1612. }
  1613. add( v, w ) {
  1614. if ( w !== undefined ) {
  1615. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1616. return this.addVectors( v, w );
  1617. }
  1618. this.x += v.x;
  1619. this.y += v.y;
  1620. return this;
  1621. }
  1622. addScalar( s ) {
  1623. this.x += s;
  1624. this.y += s;
  1625. return this;
  1626. }
  1627. addVectors( a, b ) {
  1628. this.x = a.x + b.x;
  1629. this.y = a.y + b.y;
  1630. return this;
  1631. }
  1632. addScaledVector( v, s ) {
  1633. this.x += v.x * s;
  1634. this.y += v.y * s;
  1635. return this;
  1636. }
  1637. sub( v, w ) {
  1638. if ( w !== undefined ) {
  1639. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1640. return this.subVectors( v, w );
  1641. }
  1642. this.x -= v.x;
  1643. this.y -= v.y;
  1644. return this;
  1645. }
  1646. subScalar( s ) {
  1647. this.x -= s;
  1648. this.y -= s;
  1649. return this;
  1650. }
  1651. subVectors( a, b ) {
  1652. this.x = a.x - b.x;
  1653. this.y = a.y - b.y;
  1654. return this;
  1655. }
  1656. multiply( v ) {
  1657. this.x *= v.x;
  1658. this.y *= v.y;
  1659. return this;
  1660. }
  1661. multiplyScalar( scalar ) {
  1662. this.x *= scalar;
  1663. this.y *= scalar;
  1664. return this;
  1665. }
  1666. divide( v ) {
  1667. this.x /= v.x;
  1668. this.y /= v.y;
  1669. return this;
  1670. }
  1671. divideScalar( scalar ) {
  1672. return this.multiplyScalar( 1 / scalar );
  1673. }
  1674. applyMatrix3( m ) {
  1675. const x = this.x, y = this.y;
  1676. const e = m.elements;
  1677. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  1678. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  1679. return this;
  1680. }
  1681. min( v ) {
  1682. this.x = Math.min( this.x, v.x );
  1683. this.y = Math.min( this.y, v.y );
  1684. return this;
  1685. }
  1686. max( v ) {
  1687. this.x = Math.max( this.x, v.x );
  1688. this.y = Math.max( this.y, v.y );
  1689. return this;
  1690. }
  1691. clamp( min, max ) {
  1692. // assumes min < max, componentwise
  1693. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1694. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1695. return this;
  1696. }
  1697. clampScalar( minVal, maxVal ) {
  1698. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1699. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1700. return this;
  1701. }
  1702. clampLength( min, max ) {
  1703. const length = this.length();
  1704. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1705. }
  1706. floor() {
  1707. this.x = Math.floor( this.x );
  1708. this.y = Math.floor( this.y );
  1709. return this;
  1710. }
  1711. ceil() {
  1712. this.x = Math.ceil( this.x );
  1713. this.y = Math.ceil( this.y );
  1714. return this;
  1715. }
  1716. round() {
  1717. this.x = Math.round( this.x );
  1718. this.y = Math.round( this.y );
  1719. return this;
  1720. }
  1721. roundToZero() {
  1722. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1723. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1724. return this;
  1725. }
  1726. negate() {
  1727. this.x = - this.x;
  1728. this.y = - this.y;
  1729. return this;
  1730. }
  1731. dot( v ) {
  1732. return this.x * v.x + this.y * v.y;
  1733. }
  1734. cross( v ) {
  1735. return this.x * v.y - this.y * v.x;
  1736. }
  1737. lengthSq() {
  1738. return this.x * this.x + this.y * this.y;
  1739. }
  1740. length() {
  1741. return Math.sqrt( this.x * this.x + this.y * this.y );
  1742. }
  1743. manhattanLength() {
  1744. return Math.abs( this.x ) + Math.abs( this.y );
  1745. }
  1746. normalize() {
  1747. return this.divideScalar( this.length() || 1 );
  1748. }
  1749. angle() {
  1750. // computes the angle in radians with respect to the positive x-axis
  1751. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  1752. return angle;
  1753. }
  1754. distanceTo( v ) {
  1755. return Math.sqrt( this.distanceToSquared( v ) );
  1756. }
  1757. distanceToSquared( v ) {
  1758. const dx = this.x - v.x, dy = this.y - v.y;
  1759. return dx * dx + dy * dy;
  1760. }
  1761. manhattanDistanceTo( v ) {
  1762. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  1763. }
  1764. setLength( length ) {
  1765. return this.normalize().multiplyScalar( length );
  1766. }
  1767. lerp( v, alpha ) {
  1768. this.x += ( v.x - this.x ) * alpha;
  1769. this.y += ( v.y - this.y ) * alpha;
  1770. return this;
  1771. }
  1772. lerpVectors( v1, v2, alpha ) {
  1773. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1774. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1775. return this;
  1776. }
  1777. equals( v ) {
  1778. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  1779. }
  1780. fromArray( array, offset = 0 ) {
  1781. this.x = array[ offset ];
  1782. this.y = array[ offset + 1 ];
  1783. return this;
  1784. }
  1785. toArray( array = [], offset = 0 ) {
  1786. array[ offset ] = this.x;
  1787. array[ offset + 1 ] = this.y;
  1788. return array;
  1789. }
  1790. fromBufferAttribute( attribute, index, offset ) {
  1791. if ( offset !== undefined ) {
  1792. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  1793. }
  1794. this.x = attribute.getX( index );
  1795. this.y = attribute.getY( index );
  1796. return this;
  1797. }
  1798. rotateAround( center, angle ) {
  1799. const c = Math.cos( angle ), s = Math.sin( angle );
  1800. const x = this.x - center.x;
  1801. const y = this.y - center.y;
  1802. this.x = x * c - y * s + center.x;
  1803. this.y = x * s + y * c + center.y;
  1804. return this;
  1805. }
  1806. random() {
  1807. this.x = Math.random();
  1808. this.y = Math.random();
  1809. return this;
  1810. }
  1811. }
  1812. Vector2.prototype.isVector2 = true;
  1813. class Matrix3 {
  1814. constructor() {
  1815. this.elements = [
  1816. 1, 0, 0,
  1817. 0, 1, 0,
  1818. 0, 0, 1
  1819. ];
  1820. if ( arguments.length > 0 ) {
  1821. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  1822. }
  1823. }
  1824. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1825. const te = this.elements;
  1826. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  1827. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  1828. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  1829. return this;
  1830. }
  1831. identity() {
  1832. this.set(
  1833. 1, 0, 0,
  1834. 0, 1, 0,
  1835. 0, 0, 1
  1836. );
  1837. return this;
  1838. }
  1839. copy( m ) {
  1840. const te = this.elements;
  1841. const me = m.elements;
  1842. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  1843. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  1844. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  1845. return this;
  1846. }
  1847. extractBasis( xAxis, yAxis, zAxis ) {
  1848. xAxis.setFromMatrix3Column( this, 0 );
  1849. yAxis.setFromMatrix3Column( this, 1 );
  1850. zAxis.setFromMatrix3Column( this, 2 );
  1851. return this;
  1852. }
  1853. setFromMatrix4( m ) {
  1854. const me = m.elements;
  1855. this.set(
  1856. me[ 0 ], me[ 4 ], me[ 8 ],
  1857. me[ 1 ], me[ 5 ], me[ 9 ],
  1858. me[ 2 ], me[ 6 ], me[ 10 ]
  1859. );
  1860. return this;
  1861. }
  1862. multiply( m ) {
  1863. return this.multiplyMatrices( this, m );
  1864. }
  1865. premultiply( m ) {
  1866. return this.multiplyMatrices( m, this );
  1867. }
  1868. multiplyMatrices( a, b ) {
  1869. const ae = a.elements;
  1870. const be = b.elements;
  1871. const te = this.elements;
  1872. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  1873. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  1874. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  1875. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  1876. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  1877. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  1878. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  1879. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  1880. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  1881. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  1882. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  1883. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  1884. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  1885. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  1886. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  1887. return this;
  1888. }
  1889. multiplyScalar( s ) {
  1890. const te = this.elements;
  1891. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  1892. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  1893. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  1894. return this;
  1895. }
  1896. determinant() {
  1897. const te = this.elements;
  1898. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  1899. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  1900. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  1901. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  1902. }
  1903. invert() {
  1904. const te = this.elements,
  1905. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  1906. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  1907. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  1908. t11 = n33 * n22 - n32 * n23,
  1909. t12 = n32 * n13 - n33 * n12,
  1910. t13 = n23 * n12 - n22 * n13,
  1911. det = n11 * t11 + n21 * t12 + n31 * t13;
  1912. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  1913. const detInv = 1 / det;
  1914. te[ 0 ] = t11 * detInv;
  1915. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  1916. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  1917. te[ 3 ] = t12 * detInv;
  1918. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  1919. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  1920. te[ 6 ] = t13 * detInv;
  1921. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  1922. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  1923. return this;
  1924. }
  1925. transpose() {
  1926. let tmp;
  1927. const m = this.elements;
  1928. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  1929. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  1930. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  1931. return this;
  1932. }
  1933. getNormalMatrix( matrix4 ) {
  1934. return this.setFromMatrix4( matrix4 ).invert().transpose();
  1935. }
  1936. transposeIntoArray( r ) {
  1937. const m = this.elements;
  1938. r[ 0 ] = m[ 0 ];
  1939. r[ 1 ] = m[ 3 ];
  1940. r[ 2 ] = m[ 6 ];
  1941. r[ 3 ] = m[ 1 ];
  1942. r[ 4 ] = m[ 4 ];
  1943. r[ 5 ] = m[ 7 ];
  1944. r[ 6 ] = m[ 2 ];
  1945. r[ 7 ] = m[ 5 ];
  1946. r[ 8 ] = m[ 8 ];
  1947. return this;
  1948. }
  1949. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  1950. const c = Math.cos( rotation );
  1951. const s = Math.sin( rotation );
  1952. this.set(
  1953. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  1954. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  1955. 0, 0, 1
  1956. );
  1957. return this;
  1958. }
  1959. scale( sx, sy ) {
  1960. const te = this.elements;
  1961. te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
  1962. te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;
  1963. return this;
  1964. }
  1965. rotate( theta ) {
  1966. const c = Math.cos( theta );
  1967. const s = Math.sin( theta );
  1968. const te = this.elements;
  1969. const a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
  1970. const a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];
  1971. te[ 0 ] = c * a11 + s * a21;
  1972. te[ 3 ] = c * a12 + s * a22;
  1973. te[ 6 ] = c * a13 + s * a23;
  1974. te[ 1 ] = - s * a11 + c * a21;
  1975. te[ 4 ] = - s * a12 + c * a22;
  1976. te[ 7 ] = - s * a13 + c * a23;
  1977. return this;
  1978. }
  1979. translate( tx, ty ) {
  1980. const te = this.elements;
  1981. te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
  1982. te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];
  1983. return this;
  1984. }
  1985. equals( matrix ) {
  1986. const te = this.elements;
  1987. const me = matrix.elements;
  1988. for ( let i = 0; i < 9; i ++ ) {
  1989. if ( te[ i ] !== me[ i ] ) return false;
  1990. }
  1991. return true;
  1992. }
  1993. fromArray( array, offset = 0 ) {
  1994. for ( let i = 0; i < 9; i ++ ) {
  1995. this.elements[ i ] = array[ i + offset ];
  1996. }
  1997. return this;
  1998. }
  1999. toArray( array = [], offset = 0 ) {
  2000. const te = this.elements;
  2001. array[ offset ] = te[ 0 ];
  2002. array[ offset + 1 ] = te[ 1 ];
  2003. array[ offset + 2 ] = te[ 2 ];
  2004. array[ offset + 3 ] = te[ 3 ];
  2005. array[ offset + 4 ] = te[ 4 ];
  2006. array[ offset + 5 ] = te[ 5 ];
  2007. array[ offset + 6 ] = te[ 6 ];
  2008. array[ offset + 7 ] = te[ 7 ];
  2009. array[ offset + 8 ] = te[ 8 ];
  2010. return array;
  2011. }
  2012. clone() {
  2013. return new this.constructor().fromArray( this.elements );
  2014. }
  2015. }
  2016. Matrix3.prototype.isMatrix3 = true;
  2017. let _canvas;
  2018. class ImageUtils {
  2019. static getDataURL( image ) {
  2020. if ( /^data:/i.test( image.src ) ) {
  2021. return image.src;
  2022. }
  2023. if ( typeof HTMLCanvasElement == 'undefined' ) {
  2024. return image.src;
  2025. }
  2026. let canvas;
  2027. if ( image instanceof HTMLCanvasElement ) {
  2028. canvas = image;
  2029. } else {
  2030. if ( _canvas === undefined ) _canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  2031. _canvas.width = image.width;
  2032. _canvas.height = image.height;
  2033. const context = _canvas.getContext( '2d' );
  2034. if ( image instanceof ImageData ) {
  2035. context.putImageData( image, 0, 0 );
  2036. } else {
  2037. context.drawImage( image, 0, 0, image.width, image.height );
  2038. }
  2039. canvas = _canvas;
  2040. }
  2041. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  2042. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  2043. return canvas.toDataURL( 'image/jpeg', 0.6 );
  2044. } else {
  2045. return canvas.toDataURL( 'image/png' );
  2046. }
  2047. }
  2048. }
  2049. let textureId = 0;
  2050. class Texture extends EventDispatcher {
  2051. constructor( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = 1, encoding = LinearEncoding ) {
  2052. super();
  2053. Object.defineProperty( this, 'id', { value: textureId ++ } );
  2054. this.uuid = generateUUID();
  2055. this.name = '';
  2056. this.image = image;
  2057. this.mipmaps = [];
  2058. this.mapping = mapping;
  2059. this.wrapS = wrapS;
  2060. this.wrapT = wrapT;
  2061. this.magFilter = magFilter;
  2062. this.minFilter = minFilter;
  2063. this.anisotropy = anisotropy;
  2064. this.format = format;
  2065. this.internalFormat = null;
  2066. this.type = type;
  2067. this.offset = new Vector2( 0, 0 );
  2068. this.repeat = new Vector2( 1, 1 );
  2069. this.center = new Vector2( 0, 0 );
  2070. this.rotation = 0;
  2071. this.matrixAutoUpdate = true;
  2072. this.matrix = new Matrix3();
  2073. this.generateMipmaps = true;
  2074. this.premultiplyAlpha = false;
  2075. this.flipY = true;
  2076. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  2077. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  2078. //
  2079. // Also changing the encoding after already used by a Material will not automatically make the Material
  2080. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  2081. this.encoding = encoding;
  2082. this.version = 0;
  2083. this.onUpdate = null;
  2084. this.isRenderTargetTexture = false;
  2085. }
  2086. updateMatrix() {
  2087. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  2088. }
  2089. clone() {
  2090. return new this.constructor().copy( this );
  2091. }
  2092. copy( source ) {
  2093. this.name = source.name;
  2094. this.image = source.image;
  2095. this.mipmaps = source.mipmaps.slice( 0 );
  2096. this.mapping = source.mapping;
  2097. this.wrapS = source.wrapS;
  2098. this.wrapT = source.wrapT;
  2099. this.magFilter = source.magFilter;
  2100. this.minFilter = source.minFilter;
  2101. this.anisotropy = source.anisotropy;
  2102. this.format = source.format;
  2103. this.internalFormat = source.internalFormat;
  2104. this.type = source.type;
  2105. this.offset.copy( source.offset );
  2106. this.repeat.copy( source.repeat );
  2107. this.center.copy( source.center );
  2108. this.rotation = source.rotation;
  2109. this.matrixAutoUpdate = source.matrixAutoUpdate;
  2110. this.matrix.copy( source.matrix );
  2111. this.generateMipmaps = source.generateMipmaps;
  2112. this.premultiplyAlpha = source.premultiplyAlpha;
  2113. this.flipY = source.flipY;
  2114. this.unpackAlignment = source.unpackAlignment;
  2115. this.encoding = source.encoding;
  2116. return this;
  2117. }
  2118. toJSON( meta ) {
  2119. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  2120. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  2121. return meta.textures[ this.uuid ];
  2122. }
  2123. const output = {
  2124. metadata: {
  2125. version: 4.5,
  2126. type: 'Texture',
  2127. generator: 'Texture.toJSON'
  2128. },
  2129. uuid: this.uuid,
  2130. name: this.name,
  2131. mapping: this.mapping,
  2132. repeat: [ this.repeat.x, this.repeat.y ],
  2133. offset: [ this.offset.x, this.offset.y ],
  2134. center: [ this.center.x, this.center.y ],
  2135. rotation: this.rotation,
  2136. wrap: [ this.wrapS, this.wrapT ],
  2137. format: this.format,
  2138. type: this.type,
  2139. encoding: this.encoding,
  2140. minFilter: this.minFilter,
  2141. magFilter: this.magFilter,
  2142. anisotropy: this.anisotropy,
  2143. flipY: this.flipY,
  2144. premultiplyAlpha: this.premultiplyAlpha,
  2145. unpackAlignment: this.unpackAlignment
  2146. };
  2147. if ( this.image !== undefined ) {
  2148. // TODO: Move to THREE.Image
  2149. const image = this.image;
  2150. if ( image.uuid === undefined ) {
  2151. image.uuid = generateUUID(); // UGH
  2152. }
  2153. if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) {
  2154. let url;
  2155. if ( Array.isArray( image ) ) {
  2156. // process array of images e.g. CubeTexture
  2157. url = [];
  2158. for ( let i = 0, l = image.length; i < l; i ++ ) {
  2159. // check cube texture with data textures
  2160. if ( image[ i ].isDataTexture ) {
  2161. url.push( serializeImage( image[ i ].image ) );
  2162. } else {
  2163. url.push( serializeImage( image[ i ] ) );
  2164. }
  2165. }
  2166. } else {
  2167. // process single image
  2168. url = serializeImage( image );
  2169. }
  2170. meta.images[ image.uuid ] = {
  2171. uuid: image.uuid,
  2172. url: url
  2173. };
  2174. }
  2175. output.image = image.uuid;
  2176. }
  2177. if ( ! isRootObject ) {
  2178. meta.textures[ this.uuid ] = output;
  2179. }
  2180. return output;
  2181. }
  2182. dispose() {
  2183. this.dispatchEvent( { type: 'dispose' } );
  2184. }
  2185. transformUv( uv ) {
  2186. if ( this.mapping !== UVMapping ) return uv;
  2187. uv.applyMatrix3( this.matrix );
  2188. if ( uv.x < 0 || uv.x > 1 ) {
  2189. switch ( this.wrapS ) {
  2190. case RepeatWrapping:
  2191. uv.x = uv.x - Math.floor( uv.x );
  2192. break;
  2193. case ClampToEdgeWrapping:
  2194. uv.x = uv.x < 0 ? 0 : 1;
  2195. break;
  2196. case MirroredRepeatWrapping:
  2197. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  2198. uv.x = Math.ceil( uv.x ) - uv.x;
  2199. } else {
  2200. uv.x = uv.x - Math.floor( uv.x );
  2201. }
  2202. break;
  2203. }
  2204. }
  2205. if ( uv.y < 0 || uv.y > 1 ) {
  2206. switch ( this.wrapT ) {
  2207. case RepeatWrapping:
  2208. uv.y = uv.y - Math.floor( uv.y );
  2209. break;
  2210. case ClampToEdgeWrapping:
  2211. uv.y = uv.y < 0 ? 0 : 1;
  2212. break;
  2213. case MirroredRepeatWrapping:
  2214. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  2215. uv.y = Math.ceil( uv.y ) - uv.y;
  2216. } else {
  2217. uv.y = uv.y - Math.floor( uv.y );
  2218. }
  2219. break;
  2220. }
  2221. }
  2222. if ( this.flipY ) {
  2223. uv.y = 1 - uv.y;
  2224. }
  2225. return uv;
  2226. }
  2227. set needsUpdate( value ) {
  2228. if ( value === true ) this.version ++;
  2229. }
  2230. }
  2231. Texture.DEFAULT_IMAGE = undefined;
  2232. Texture.DEFAULT_MAPPING = UVMapping;
  2233. Texture.prototype.isTexture = true;
  2234. function serializeImage( image ) {
  2235. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  2236. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  2237. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  2238. // default images
  2239. return ImageUtils.getDataURL( image );
  2240. } else {
  2241. if ( image.data ) {
  2242. // images of DataTexture
  2243. return {
  2244. data: Array.prototype.slice.call( image.data ),
  2245. width: image.width,
  2246. height: image.height,
  2247. type: image.data.constructor.name
  2248. };
  2249. } else {
  2250. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  2251. return {};
  2252. }
  2253. }
  2254. }
  2255. class Vector4 {
  2256. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2257. this.x = x;
  2258. this.y = y;
  2259. this.z = z;
  2260. this.w = w;
  2261. }
  2262. get width() {
  2263. return this.z;
  2264. }
  2265. set width( value ) {
  2266. this.z = value;
  2267. }
  2268. get height() {
  2269. return this.w;
  2270. }
  2271. set height( value ) {
  2272. this.w = value;
  2273. }
  2274. set( x, y, z, w ) {
  2275. this.x = x;
  2276. this.y = y;
  2277. this.z = z;
  2278. this.w = w;
  2279. return this;
  2280. }
  2281. setScalar( scalar ) {
  2282. this.x = scalar;
  2283. this.y = scalar;
  2284. this.z = scalar;
  2285. this.w = scalar;
  2286. return this;
  2287. }
  2288. setX( x ) {
  2289. this.x = x;
  2290. return this;
  2291. }
  2292. setY( y ) {
  2293. this.y = y;
  2294. return this;
  2295. }
  2296. setZ( z ) {
  2297. this.z = z;
  2298. return this;
  2299. }
  2300. setW( w ) {
  2301. this.w = w;
  2302. return this;
  2303. }
  2304. setComponent( index, value ) {
  2305. switch ( index ) {
  2306. case 0: this.x = value; break;
  2307. case 1: this.y = value; break;
  2308. case 2: this.z = value; break;
  2309. case 3: this.w = value; break;
  2310. default: throw new Error( 'index is out of range: ' + index );
  2311. }
  2312. return this;
  2313. }
  2314. getComponent( index ) {
  2315. switch ( index ) {
  2316. case 0: return this.x;
  2317. case 1: return this.y;
  2318. case 2: return this.z;
  2319. case 3: return this.w;
  2320. default: throw new Error( 'index is out of range: ' + index );
  2321. }
  2322. }
  2323. clone() {
  2324. return new this.constructor( this.x, this.y, this.z, this.w );
  2325. }
  2326. copy( v ) {
  2327. this.x = v.x;
  2328. this.y = v.y;
  2329. this.z = v.z;
  2330. this.w = ( v.w !== undefined ) ? v.w : 1;
  2331. return this;
  2332. }
  2333. add( v, w ) {
  2334. if ( w !== undefined ) {
  2335. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  2336. return this.addVectors( v, w );
  2337. }
  2338. this.x += v.x;
  2339. this.y += v.y;
  2340. this.z += v.z;
  2341. this.w += v.w;
  2342. return this;
  2343. }
  2344. addScalar( s ) {
  2345. this.x += s;
  2346. this.y += s;
  2347. this.z += s;
  2348. this.w += s;
  2349. return this;
  2350. }
  2351. addVectors( a, b ) {
  2352. this.x = a.x + b.x;
  2353. this.y = a.y + b.y;
  2354. this.z = a.z + b.z;
  2355. this.w = a.w + b.w;
  2356. return this;
  2357. }
  2358. addScaledVector( v, s ) {
  2359. this.x += v.x * s;
  2360. this.y += v.y * s;
  2361. this.z += v.z * s;
  2362. this.w += v.w * s;
  2363. return this;
  2364. }
  2365. sub( v, w ) {
  2366. if ( w !== undefined ) {
  2367. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  2368. return this.subVectors( v, w );
  2369. }
  2370. this.x -= v.x;
  2371. this.y -= v.y;
  2372. this.z -= v.z;
  2373. this.w -= v.w;
  2374. return this;
  2375. }
  2376. subScalar( s ) {
  2377. this.x -= s;
  2378. this.y -= s;
  2379. this.z -= s;
  2380. this.w -= s;
  2381. return this;
  2382. }
  2383. subVectors( a, b ) {
  2384. this.x = a.x - b.x;
  2385. this.y = a.y - b.y;
  2386. this.z = a.z - b.z;
  2387. this.w = a.w - b.w;
  2388. return this;
  2389. }
  2390. multiply( v ) {
  2391. this.x *= v.x;
  2392. this.y *= v.y;
  2393. this.z *= v.z;
  2394. this.w *= v.w;
  2395. return this;
  2396. }
  2397. multiplyScalar( scalar ) {
  2398. this.x *= scalar;
  2399. this.y *= scalar;
  2400. this.z *= scalar;
  2401. this.w *= scalar;
  2402. return this;
  2403. }
  2404. applyMatrix4( m ) {
  2405. const x = this.x, y = this.y, z = this.z, w = this.w;
  2406. const e = m.elements;
  2407. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  2408. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  2409. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  2410. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  2411. return this;
  2412. }
  2413. divideScalar( scalar ) {
  2414. return this.multiplyScalar( 1 / scalar );
  2415. }
  2416. setAxisAngleFromQuaternion( q ) {
  2417. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  2418. // q is assumed to be normalized
  2419. this.w = 2 * Math.acos( q.w );
  2420. const s = Math.sqrt( 1 - q.w * q.w );
  2421. if ( s < 0.0001 ) {
  2422. this.x = 1;
  2423. this.y = 0;
  2424. this.z = 0;
  2425. } else {
  2426. this.x = q.x / s;
  2427. this.y = q.y / s;
  2428. this.z = q.z / s;
  2429. }
  2430. return this;
  2431. }
  2432. setAxisAngleFromRotationMatrix( m ) {
  2433. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  2434. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2435. let angle, x, y, z; // variables for result
  2436. const epsilon = 0.01, // margin to allow for rounding errors
  2437. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  2438. te = m.elements,
  2439. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2440. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2441. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  2442. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  2443. ( Math.abs( m13 - m31 ) < epsilon ) &&
  2444. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  2445. // singularity found
  2446. // first check for identity matrix which must have +1 for all terms
  2447. // in leading diagonal and zero in other terms
  2448. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  2449. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  2450. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  2451. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  2452. // this singularity is identity matrix so angle = 0
  2453. this.set( 1, 0, 0, 0 );
  2454. return this; // zero angle, arbitrary axis
  2455. }
  2456. // otherwise this singularity is angle = 180
  2457. angle = Math.PI;
  2458. const xx = ( m11 + 1 ) / 2;
  2459. const yy = ( m22 + 1 ) / 2;
  2460. const zz = ( m33 + 1 ) / 2;
  2461. const xy = ( m12 + m21 ) / 4;
  2462. const xz = ( m13 + m31 ) / 4;
  2463. const yz = ( m23 + m32 ) / 4;
  2464. if ( ( xx > yy ) && ( xx > zz ) ) {
  2465. // m11 is the largest diagonal term
  2466. if ( xx < epsilon ) {
  2467. x = 0;
  2468. y = 0.707106781;
  2469. z = 0.707106781;
  2470. } else {
  2471. x = Math.sqrt( xx );
  2472. y = xy / x;
  2473. z = xz / x;
  2474. }
  2475. } else if ( yy > zz ) {
  2476. // m22 is the largest diagonal term
  2477. if ( yy < epsilon ) {
  2478. x = 0.707106781;
  2479. y = 0;
  2480. z = 0.707106781;
  2481. } else {
  2482. y = Math.sqrt( yy );
  2483. x = xy / y;
  2484. z = yz / y;
  2485. }
  2486. } else {
  2487. // m33 is the largest diagonal term so base result on this
  2488. if ( zz < epsilon ) {
  2489. x = 0.707106781;
  2490. y = 0.707106781;
  2491. z = 0;
  2492. } else {
  2493. z = Math.sqrt( zz );
  2494. x = xz / z;
  2495. y = yz / z;
  2496. }
  2497. }
  2498. this.set( x, y, z, angle );
  2499. return this; // return 180 deg rotation
  2500. }
  2501. // as we have reached here there are no singularities so we can handle normally
  2502. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  2503. ( m13 - m31 ) * ( m13 - m31 ) +
  2504. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  2505. if ( Math.abs( s ) < 0.001 ) s = 1;
  2506. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  2507. // caught by singularity test above, but I've left it in just in case
  2508. this.x = ( m32 - m23 ) / s;
  2509. this.y = ( m13 - m31 ) / s;
  2510. this.z = ( m21 - m12 ) / s;
  2511. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  2512. return this;
  2513. }
  2514. min( v ) {
  2515. this.x = Math.min( this.x, v.x );
  2516. this.y = Math.min( this.y, v.y );
  2517. this.z = Math.min( this.z, v.z );
  2518. this.w = Math.min( this.w, v.w );
  2519. return this;
  2520. }
  2521. max( v ) {
  2522. this.x = Math.max( this.x, v.x );
  2523. this.y = Math.max( this.y, v.y );
  2524. this.z = Math.max( this.z, v.z );
  2525. this.w = Math.max( this.w, v.w );
  2526. return this;
  2527. }
  2528. clamp( min, max ) {
  2529. // assumes min < max, componentwise
  2530. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2531. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2532. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2533. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  2534. return this;
  2535. }
  2536. clampScalar( minVal, maxVal ) {
  2537. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2538. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2539. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2540. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  2541. return this;
  2542. }
  2543. clampLength( min, max ) {
  2544. const length = this.length();
  2545. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2546. }
  2547. floor() {
  2548. this.x = Math.floor( this.x );
  2549. this.y = Math.floor( this.y );
  2550. this.z = Math.floor( this.z );
  2551. this.w = Math.floor( this.w );
  2552. return this;
  2553. }
  2554. ceil() {
  2555. this.x = Math.ceil( this.x );
  2556. this.y = Math.ceil( this.y );
  2557. this.z = Math.ceil( this.z );
  2558. this.w = Math.ceil( this.w );
  2559. return this;
  2560. }
  2561. round() {
  2562. this.x = Math.round( this.x );
  2563. this.y = Math.round( this.y );
  2564. this.z = Math.round( this.z );
  2565. this.w = Math.round( this.w );
  2566. return this;
  2567. }
  2568. roundToZero() {
  2569. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2570. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2571. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2572. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  2573. return this;
  2574. }
  2575. negate() {
  2576. this.x = - this.x;
  2577. this.y = - this.y;
  2578. this.z = - this.z;
  2579. this.w = - this.w;
  2580. return this;
  2581. }
  2582. dot( v ) {
  2583. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  2584. }
  2585. lengthSq() {
  2586. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  2587. }
  2588. length() {
  2589. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2590. }
  2591. manhattanLength() {
  2592. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  2593. }
  2594. normalize() {
  2595. return this.divideScalar( this.length() || 1 );
  2596. }
  2597. setLength( length ) {
  2598. return this.normalize().multiplyScalar( length );
  2599. }
  2600. lerp( v, alpha ) {
  2601. this.x += ( v.x - this.x ) * alpha;
  2602. this.y += ( v.y - this.y ) * alpha;
  2603. this.z += ( v.z - this.z ) * alpha;
  2604. this.w += ( v.w - this.w ) * alpha;
  2605. return this;
  2606. }
  2607. lerpVectors( v1, v2, alpha ) {
  2608. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2609. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2610. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2611. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  2612. return this;
  2613. }
  2614. equals( v ) {
  2615. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  2616. }
  2617. fromArray( array, offset = 0 ) {
  2618. this.x = array[ offset ];
  2619. this.y = array[ offset + 1 ];
  2620. this.z = array[ offset + 2 ];
  2621. this.w = array[ offset + 3 ];
  2622. return this;
  2623. }
  2624. toArray( array = [], offset = 0 ) {
  2625. array[ offset ] = this.x;
  2626. array[ offset + 1 ] = this.y;
  2627. array[ offset + 2 ] = this.z;
  2628. array[ offset + 3 ] = this.w;
  2629. return array;
  2630. }
  2631. fromBufferAttribute( attribute, index, offset ) {
  2632. if ( offset !== undefined ) {
  2633. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  2634. }
  2635. this.x = attribute.getX( index );
  2636. this.y = attribute.getY( index );
  2637. this.z = attribute.getZ( index );
  2638. this.w = attribute.getW( index );
  2639. return this;
  2640. }
  2641. random() {
  2642. this.x = Math.random();
  2643. this.y = Math.random();
  2644. this.z = Math.random();
  2645. this.w = Math.random();
  2646. return this;
  2647. }
  2648. }
  2649. Vector4.prototype.isVector4 = true;
  2650. /*
  2651. In options, we can specify:
  2652. * Texture parameters for an auto-generated target texture
  2653. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2654. */
  2655. class WebGLRenderTarget extends EventDispatcher {
  2656. constructor( width, height, options = {} ) {
  2657. super();
  2658. this.width = width;
  2659. this.height = height;
  2660. this.depth = 1;
  2661. this.scissor = new Vector4( 0, 0, width, height );
  2662. this.scissorTest = false;
  2663. this.viewport = new Vector4( 0, 0, width, height );
  2664. this.texture = new Texture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  2665. this.texture.isRenderTargetTexture = true;
  2666. this.texture.image = { width: width, height: height, depth: 1 };
  2667. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2668. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  2669. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2670. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2671. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  2672. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2673. }
  2674. setTexture( texture ) {
  2675. texture.image = {
  2676. width: this.width,
  2677. height: this.height,
  2678. depth: this.depth
  2679. };
  2680. this.texture = texture;
  2681. }
  2682. setSize( width, height, depth = 1 ) {
  2683. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  2684. this.width = width;
  2685. this.height = height;
  2686. this.depth = depth;
  2687. this.texture.image.width = width;
  2688. this.texture.image.height = height;
  2689. this.texture.image.depth = depth;
  2690. this.dispose();
  2691. }
  2692. this.viewport.set( 0, 0, width, height );
  2693. this.scissor.set( 0, 0, width, height );
  2694. }
  2695. clone() {
  2696. return new this.constructor().copy( this );
  2697. }
  2698. copy( source ) {
  2699. this.width = source.width;
  2700. this.height = source.height;
  2701. this.depth = source.depth;
  2702. this.viewport.copy( source.viewport );
  2703. this.texture = source.texture.clone();
  2704. this.texture.image = { ...this.texture.image }; // See #20328.
  2705. this.depthBuffer = source.depthBuffer;
  2706. this.stencilBuffer = source.stencilBuffer;
  2707. this.depthTexture = source.depthTexture;
  2708. return this;
  2709. }
  2710. dispose() {
  2711. this.dispatchEvent( { type: 'dispose' } );
  2712. }
  2713. }
  2714. WebGLRenderTarget.prototype.isWebGLRenderTarget = true;
  2715. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  2716. constructor( width, height, count ) {
  2717. super( width, height );
  2718. const texture = this.texture;
  2719. this.texture = [];
  2720. for ( let i = 0; i < count; i ++ ) {
  2721. this.texture[ i ] = texture.clone();
  2722. }
  2723. }
  2724. setSize( width, height, depth = 1 ) {
  2725. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  2726. this.width = width;
  2727. this.height = height;
  2728. this.depth = depth;
  2729. for ( let i = 0, il = this.texture.length; i < il; i ++ ) {
  2730. this.texture[ i ].image.width = width;
  2731. this.texture[ i ].image.height = height;
  2732. this.texture[ i ].image.depth = depth;
  2733. }
  2734. this.dispose();
  2735. }
  2736. this.viewport.set( 0, 0, width, height );
  2737. this.scissor.set( 0, 0, width, height );
  2738. return this;
  2739. }
  2740. copy( source ) {
  2741. this.dispose();
  2742. this.width = source.width;
  2743. this.height = source.height;
  2744. this.depth = source.depth;
  2745. this.viewport.set( 0, 0, this.width, this.height );
  2746. this.scissor.set( 0, 0, this.width, this.height );
  2747. this.depthBuffer = source.depthBuffer;
  2748. this.stencilBuffer = source.stencilBuffer;
  2749. this.depthTexture = source.depthTexture;
  2750. this.texture.length = 0;
  2751. for ( let i = 0, il = source.texture.length; i < il; i ++ ) {
  2752. this.texture[ i ] = source.texture[ i ].clone();
  2753. }
  2754. return this;
  2755. }
  2756. }
  2757. WebGLMultipleRenderTargets.prototype.isWebGLMultipleRenderTargets = true;
  2758. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  2759. constructor( width, height, options ) {
  2760. super( width, height, options );
  2761. this.samples = 4;
  2762. }
  2763. copy( source ) {
  2764. super.copy.call( this, source );
  2765. this.samples = source.samples;
  2766. return this;
  2767. }
  2768. }
  2769. WebGLMultisampleRenderTarget.prototype.isWebGLMultisampleRenderTarget = true;
  2770. class Quaternion {
  2771. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2772. this._x = x;
  2773. this._y = y;
  2774. this._z = z;
  2775. this._w = w;
  2776. }
  2777. static slerp( qa, qb, qm, t ) {
  2778. console.warn( 'THREE.Quaternion: Static .slerp() has been deprecated. Use qm.slerpQuaternions( qa, qb, t ) instead.' );
  2779. return qm.slerpQuaternions( qa, qb, t );
  2780. }
  2781. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  2782. // fuzz-free, array-based Quaternion SLERP operation
  2783. let x0 = src0[ srcOffset0 + 0 ],
  2784. y0 = src0[ srcOffset0 + 1 ],
  2785. z0 = src0[ srcOffset0 + 2 ],
  2786. w0 = src0[ srcOffset0 + 3 ];
  2787. const x1 = src1[ srcOffset1 + 0 ],
  2788. y1 = src1[ srcOffset1 + 1 ],
  2789. z1 = src1[ srcOffset1 + 2 ],
  2790. w1 = src1[ srcOffset1 + 3 ];
  2791. if ( t === 0 ) {
  2792. dst[ dstOffset + 0 ] = x0;
  2793. dst[ dstOffset + 1 ] = y0;
  2794. dst[ dstOffset + 2 ] = z0;
  2795. dst[ dstOffset + 3 ] = w0;
  2796. return;
  2797. }
  2798. if ( t === 1 ) {
  2799. dst[ dstOffset + 0 ] = x1;
  2800. dst[ dstOffset + 1 ] = y1;
  2801. dst[ dstOffset + 2 ] = z1;
  2802. dst[ dstOffset + 3 ] = w1;
  2803. return;
  2804. }
  2805. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  2806. let s = 1 - t;
  2807. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2808. dir = ( cos >= 0 ? 1 : - 1 ),
  2809. sqrSin = 1 - cos * cos;
  2810. // Skip the Slerp for tiny steps to avoid numeric problems:
  2811. if ( sqrSin > Number.EPSILON ) {
  2812. const sin = Math.sqrt( sqrSin ),
  2813. len = Math.atan2( sin, cos * dir );
  2814. s = Math.sin( s * len ) / sin;
  2815. t = Math.sin( t * len ) / sin;
  2816. }
  2817. const tDir = t * dir;
  2818. x0 = x0 * s + x1 * tDir;
  2819. y0 = y0 * s + y1 * tDir;
  2820. z0 = z0 * s + z1 * tDir;
  2821. w0 = w0 * s + w1 * tDir;
  2822. // Normalize in case we just did a lerp:
  2823. if ( s === 1 - t ) {
  2824. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2825. x0 *= f;
  2826. y0 *= f;
  2827. z0 *= f;
  2828. w0 *= f;
  2829. }
  2830. }
  2831. dst[ dstOffset ] = x0;
  2832. dst[ dstOffset + 1 ] = y0;
  2833. dst[ dstOffset + 2 ] = z0;
  2834. dst[ dstOffset + 3 ] = w0;
  2835. }
  2836. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2837. const x0 = src0[ srcOffset0 ];
  2838. const y0 = src0[ srcOffset0 + 1 ];
  2839. const z0 = src0[ srcOffset0 + 2 ];
  2840. const w0 = src0[ srcOffset0 + 3 ];
  2841. const x1 = src1[ srcOffset1 ];
  2842. const y1 = src1[ srcOffset1 + 1 ];
  2843. const z1 = src1[ srcOffset1 + 2 ];
  2844. const w1 = src1[ srcOffset1 + 3 ];
  2845. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2846. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2847. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2848. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2849. return dst;
  2850. }
  2851. get x() {
  2852. return this._x;
  2853. }
  2854. set x( value ) {
  2855. this._x = value;
  2856. this._onChangeCallback();
  2857. }
  2858. get y() {
  2859. return this._y;
  2860. }
  2861. set y( value ) {
  2862. this._y = value;
  2863. this._onChangeCallback();
  2864. }
  2865. get z() {
  2866. return this._z;
  2867. }
  2868. set z( value ) {
  2869. this._z = value;
  2870. this._onChangeCallback();
  2871. }
  2872. get w() {
  2873. return this._w;
  2874. }
  2875. set w( value ) {
  2876. this._w = value;
  2877. this._onChangeCallback();
  2878. }
  2879. set( x, y, z, w ) {
  2880. this._x = x;
  2881. this._y = y;
  2882. this._z = z;
  2883. this._w = w;
  2884. this._onChangeCallback();
  2885. return this;
  2886. }
  2887. clone() {
  2888. return new this.constructor( this._x, this._y, this._z, this._w );
  2889. }
  2890. copy( quaternion ) {
  2891. this._x = quaternion.x;
  2892. this._y = quaternion.y;
  2893. this._z = quaternion.z;
  2894. this._w = quaternion.w;
  2895. this._onChangeCallback();
  2896. return this;
  2897. }
  2898. setFromEuler( euler, update ) {
  2899. if ( ! ( euler && euler.isEuler ) ) {
  2900. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  2901. }
  2902. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2903. // http://www.mathworks.com/matlabcentral/fileexchange/
  2904. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2905. // content/SpinCalc.m
  2906. const cos = Math.cos;
  2907. const sin = Math.sin;
  2908. const c1 = cos( x / 2 );
  2909. const c2 = cos( y / 2 );
  2910. const c3 = cos( z / 2 );
  2911. const s1 = sin( x / 2 );
  2912. const s2 = sin( y / 2 );
  2913. const s3 = sin( z / 2 );
  2914. switch ( order ) {
  2915. case 'XYZ':
  2916. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2917. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2918. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2919. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2920. break;
  2921. case 'YXZ':
  2922. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2923. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2924. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2925. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2926. break;
  2927. case 'ZXY':
  2928. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2929. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2930. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2931. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2932. break;
  2933. case 'ZYX':
  2934. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2935. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2936. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2937. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2938. break;
  2939. case 'YZX':
  2940. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2941. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2942. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2943. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2944. break;
  2945. case 'XZY':
  2946. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2947. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2948. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2949. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2950. break;
  2951. default:
  2952. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2953. }
  2954. if ( update !== false ) this._onChangeCallback();
  2955. return this;
  2956. }
  2957. setFromAxisAngle( axis, angle ) {
  2958. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2959. // assumes axis is normalized
  2960. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2961. this._x = axis.x * s;
  2962. this._y = axis.y * s;
  2963. this._z = axis.z * s;
  2964. this._w = Math.cos( halfAngle );
  2965. this._onChangeCallback();
  2966. return this;
  2967. }
  2968. setFromRotationMatrix( m ) {
  2969. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2970. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2971. const te = m.elements,
  2972. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2973. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2974. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2975. trace = m11 + m22 + m33;
  2976. if ( trace > 0 ) {
  2977. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2978. this._w = 0.25 / s;
  2979. this._x = ( m32 - m23 ) * s;
  2980. this._y = ( m13 - m31 ) * s;
  2981. this._z = ( m21 - m12 ) * s;
  2982. } else if ( m11 > m22 && m11 > m33 ) {
  2983. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2984. this._w = ( m32 - m23 ) / s;
  2985. this._x = 0.25 * s;
  2986. this._y = ( m12 + m21 ) / s;
  2987. this._z = ( m13 + m31 ) / s;
  2988. } else if ( m22 > m33 ) {
  2989. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2990. this._w = ( m13 - m31 ) / s;
  2991. this._x = ( m12 + m21 ) / s;
  2992. this._y = 0.25 * s;
  2993. this._z = ( m23 + m32 ) / s;
  2994. } else {
  2995. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2996. this._w = ( m21 - m12 ) / s;
  2997. this._x = ( m13 + m31 ) / s;
  2998. this._y = ( m23 + m32 ) / s;
  2999. this._z = 0.25 * s;
  3000. }
  3001. this._onChangeCallback();
  3002. return this;
  3003. }
  3004. setFromUnitVectors( vFrom, vTo ) {
  3005. // assumes direction vectors vFrom and vTo are normalized
  3006. let r = vFrom.dot( vTo ) + 1;
  3007. if ( r < Number.EPSILON ) {
  3008. // vFrom and vTo point in opposite directions
  3009. r = 0;
  3010. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  3011. this._x = - vFrom.y;
  3012. this._y = vFrom.x;
  3013. this._z = 0;
  3014. this._w = r;
  3015. } else {
  3016. this._x = 0;
  3017. this._y = - vFrom.z;
  3018. this._z = vFrom.y;
  3019. this._w = r;
  3020. }
  3021. } else {
  3022. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  3023. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  3024. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  3025. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  3026. this._w = r;
  3027. }
  3028. return this.normalize();
  3029. }
  3030. angleTo( q ) {
  3031. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  3032. }
  3033. rotateTowards( q, step ) {
  3034. const angle = this.angleTo( q );
  3035. if ( angle === 0 ) return this;
  3036. const t = Math.min( 1, step / angle );
  3037. this.slerp( q, t );
  3038. return this;
  3039. }
  3040. identity() {
  3041. return this.set( 0, 0, 0, 1 );
  3042. }
  3043. invert() {
  3044. // quaternion is assumed to have unit length
  3045. return this.conjugate();
  3046. }
  3047. conjugate() {
  3048. this._x *= - 1;
  3049. this._y *= - 1;
  3050. this._z *= - 1;
  3051. this._onChangeCallback();
  3052. return this;
  3053. }
  3054. dot( v ) {
  3055. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  3056. }
  3057. lengthSq() {
  3058. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  3059. }
  3060. length() {
  3061. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  3062. }
  3063. normalize() {
  3064. let l = this.length();
  3065. if ( l === 0 ) {
  3066. this._x = 0;
  3067. this._y = 0;
  3068. this._z = 0;
  3069. this._w = 1;
  3070. } else {
  3071. l = 1 / l;
  3072. this._x = this._x * l;
  3073. this._y = this._y * l;
  3074. this._z = this._z * l;
  3075. this._w = this._w * l;
  3076. }
  3077. this._onChangeCallback();
  3078. return this;
  3079. }
  3080. multiply( q, p ) {
  3081. if ( p !== undefined ) {
  3082. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  3083. return this.multiplyQuaternions( q, p );
  3084. }
  3085. return this.multiplyQuaternions( this, q );
  3086. }
  3087. premultiply( q ) {
  3088. return this.multiplyQuaternions( q, this );
  3089. }
  3090. multiplyQuaternions( a, b ) {
  3091. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  3092. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  3093. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  3094. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  3095. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  3096. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  3097. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  3098. this._onChangeCallback();
  3099. return this;
  3100. }
  3101. slerp( qb, t ) {
  3102. if ( t === 0 ) return this;
  3103. if ( t === 1 ) return this.copy( qb );
  3104. const x = this._x, y = this._y, z = this._z, w = this._w;
  3105. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  3106. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  3107. if ( cosHalfTheta < 0 ) {
  3108. this._w = - qb._w;
  3109. this._x = - qb._x;
  3110. this._y = - qb._y;
  3111. this._z = - qb._z;
  3112. cosHalfTheta = - cosHalfTheta;
  3113. } else {
  3114. this.copy( qb );
  3115. }
  3116. if ( cosHalfTheta >= 1.0 ) {
  3117. this._w = w;
  3118. this._x = x;
  3119. this._y = y;
  3120. this._z = z;
  3121. return this;
  3122. }
  3123. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  3124. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  3125. const s = 1 - t;
  3126. this._w = s * w + t * this._w;
  3127. this._x = s * x + t * this._x;
  3128. this._y = s * y + t * this._y;
  3129. this._z = s * z + t * this._z;
  3130. this.normalize();
  3131. this._onChangeCallback();
  3132. return this;
  3133. }
  3134. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  3135. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  3136. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  3137. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  3138. this._w = ( w * ratioA + this._w * ratioB );
  3139. this._x = ( x * ratioA + this._x * ratioB );
  3140. this._y = ( y * ratioA + this._y * ratioB );
  3141. this._z = ( z * ratioA + this._z * ratioB );
  3142. this._onChangeCallback();
  3143. return this;
  3144. }
  3145. slerpQuaternions( qa, qb, t ) {
  3146. this.copy( qa ).slerp( qb, t );
  3147. }
  3148. equals( quaternion ) {
  3149. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  3150. }
  3151. fromArray( array, offset = 0 ) {
  3152. this._x = array[ offset ];
  3153. this._y = array[ offset + 1 ];
  3154. this._z = array[ offset + 2 ];
  3155. this._w = array[ offset + 3 ];
  3156. this._onChangeCallback();
  3157. return this;
  3158. }
  3159. toArray( array = [], offset = 0 ) {
  3160. array[ offset ] = this._x;
  3161. array[ offset + 1 ] = this._y;
  3162. array[ offset + 2 ] = this._z;
  3163. array[ offset + 3 ] = this._w;
  3164. return array;
  3165. }
  3166. fromBufferAttribute( attribute, index ) {
  3167. this._x = attribute.getX( index );
  3168. this._y = attribute.getY( index );
  3169. this._z = attribute.getZ( index );
  3170. this._w = attribute.getW( index );
  3171. return this;
  3172. }
  3173. _onChange( callback ) {
  3174. this._onChangeCallback = callback;
  3175. return this;
  3176. }
  3177. _onChangeCallback() {}
  3178. }
  3179. Quaternion.prototype.isQuaternion = true;
  3180. class Vector3 {
  3181. constructor( x = 0, y = 0, z = 0 ) {
  3182. this.x = x;
  3183. this.y = y;
  3184. this.z = z;
  3185. }
  3186. set( x, y, z ) {
  3187. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  3188. this.x = x;
  3189. this.y = y;
  3190. this.z = z;
  3191. return this;
  3192. }
  3193. setScalar( scalar ) {
  3194. this.x = scalar;
  3195. this.y = scalar;
  3196. this.z = scalar;
  3197. return this;
  3198. }
  3199. setX( x ) {
  3200. this.x = x;
  3201. return this;
  3202. }
  3203. setY( y ) {
  3204. this.y = y;
  3205. return this;
  3206. }
  3207. setZ( z ) {
  3208. this.z = z;
  3209. return this;
  3210. }
  3211. setComponent( index, value ) {
  3212. switch ( index ) {
  3213. case 0: this.x = value; break;
  3214. case 1: this.y = value; break;
  3215. case 2: this.z = value; break;
  3216. default: throw new Error( 'index is out of range: ' + index );
  3217. }
  3218. return this;
  3219. }
  3220. getComponent( index ) {
  3221. switch ( index ) {
  3222. case 0: return this.x;
  3223. case 1: return this.y;
  3224. case 2: return this.z;
  3225. default: throw new Error( 'index is out of range: ' + index );
  3226. }
  3227. }
  3228. clone() {
  3229. return new this.constructor( this.x, this.y, this.z );
  3230. }
  3231. copy( v ) {
  3232. this.x = v.x;
  3233. this.y = v.y;
  3234. this.z = v.z;
  3235. return this;
  3236. }
  3237. add( v, w ) {
  3238. if ( w !== undefined ) {
  3239. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  3240. return this.addVectors( v, w );
  3241. }
  3242. this.x += v.x;
  3243. this.y += v.y;
  3244. this.z += v.z;
  3245. return this;
  3246. }
  3247. addScalar( s ) {
  3248. this.x += s;
  3249. this.y += s;
  3250. this.z += s;
  3251. return this;
  3252. }
  3253. addVectors( a, b ) {
  3254. this.x = a.x + b.x;
  3255. this.y = a.y + b.y;
  3256. this.z = a.z + b.z;
  3257. return this;
  3258. }
  3259. addScaledVector( v, s ) {
  3260. this.x += v.x * s;
  3261. this.y += v.y * s;
  3262. this.z += v.z * s;
  3263. return this;
  3264. }
  3265. sub( v, w ) {
  3266. if ( w !== undefined ) {
  3267. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  3268. return this.subVectors( v, w );
  3269. }
  3270. this.x -= v.x;
  3271. this.y -= v.y;
  3272. this.z -= v.z;
  3273. return this;
  3274. }
  3275. subScalar( s ) {
  3276. this.x -= s;
  3277. this.y -= s;
  3278. this.z -= s;
  3279. return this;
  3280. }
  3281. subVectors( a, b ) {
  3282. this.x = a.x - b.x;
  3283. this.y = a.y - b.y;
  3284. this.z = a.z - b.z;
  3285. return this;
  3286. }
  3287. multiply( v, w ) {
  3288. if ( w !== undefined ) {
  3289. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  3290. return this.multiplyVectors( v, w );
  3291. }
  3292. this.x *= v.x;
  3293. this.y *= v.y;
  3294. this.z *= v.z;
  3295. return this;
  3296. }
  3297. multiplyScalar( scalar ) {
  3298. this.x *= scalar;
  3299. this.y *= scalar;
  3300. this.z *= scalar;
  3301. return this;
  3302. }
  3303. multiplyVectors( a, b ) {
  3304. this.x = a.x * b.x;
  3305. this.y = a.y * b.y;
  3306. this.z = a.z * b.z;
  3307. return this;
  3308. }
  3309. applyEuler( euler ) {
  3310. if ( ! ( euler && euler.isEuler ) ) {
  3311. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  3312. }
  3313. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  3314. }
  3315. applyAxisAngle( axis, angle ) {
  3316. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  3317. }
  3318. applyMatrix3( m ) {
  3319. const x = this.x, y = this.y, z = this.z;
  3320. const e = m.elements;
  3321. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  3322. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  3323. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  3324. return this;
  3325. }
  3326. applyNormalMatrix( m ) {
  3327. return this.applyMatrix3( m ).normalize();
  3328. }
  3329. applyMatrix4( m ) {
  3330. const x = this.x, y = this.y, z = this.z;
  3331. const e = m.elements;
  3332. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  3333. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  3334. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  3335. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  3336. return this;
  3337. }
  3338. applyQuaternion( q ) {
  3339. const x = this.x, y = this.y, z = this.z;
  3340. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  3341. // calculate quat * vector
  3342. const ix = qw * x + qy * z - qz * y;
  3343. const iy = qw * y + qz * x - qx * z;
  3344. const iz = qw * z + qx * y - qy * x;
  3345. const iw = - qx * x - qy * y - qz * z;
  3346. // calculate result * inverse quat
  3347. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  3348. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  3349. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  3350. return this;
  3351. }
  3352. project( camera ) {
  3353. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  3354. }
  3355. unproject( camera ) {
  3356. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  3357. }
  3358. transformDirection( m ) {
  3359. // input: THREE.Matrix4 affine matrix
  3360. // vector interpreted as a direction
  3361. const x = this.x, y = this.y, z = this.z;
  3362. const e = m.elements;
  3363. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  3364. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  3365. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  3366. return this.normalize();
  3367. }
  3368. divide( v ) {
  3369. this.x /= v.x;
  3370. this.y /= v.y;
  3371. this.z /= v.z;
  3372. return this;
  3373. }
  3374. divideScalar( scalar ) {
  3375. return this.multiplyScalar( 1 / scalar );
  3376. }
  3377. min( v ) {
  3378. this.x = Math.min( this.x, v.x );
  3379. this.y = Math.min( this.y, v.y );
  3380. this.z = Math.min( this.z, v.z );
  3381. return this;
  3382. }
  3383. max( v ) {
  3384. this.x = Math.max( this.x, v.x );
  3385. this.y = Math.max( this.y, v.y );
  3386. this.z = Math.max( this.z, v.z );
  3387. return this;
  3388. }
  3389. clamp( min, max ) {
  3390. // assumes min < max, componentwise
  3391. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  3392. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  3393. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  3394. return this;
  3395. }
  3396. clampScalar( minVal, maxVal ) {
  3397. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  3398. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  3399. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  3400. return this;
  3401. }
  3402. clampLength( min, max ) {
  3403. const length = this.length();
  3404. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  3405. }
  3406. floor() {
  3407. this.x = Math.floor( this.x );
  3408. this.y = Math.floor( this.y );
  3409. this.z = Math.floor( this.z );
  3410. return this;
  3411. }
  3412. ceil() {
  3413. this.x = Math.ceil( this.x );
  3414. this.y = Math.ceil( this.y );
  3415. this.z = Math.ceil( this.z );
  3416. return this;
  3417. }
  3418. round() {
  3419. this.x = Math.round( this.x );
  3420. this.y = Math.round( this.y );
  3421. this.z = Math.round( this.z );
  3422. return this;
  3423. }
  3424. roundToZero() {
  3425. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  3426. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  3427. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  3428. return this;
  3429. }
  3430. negate() {
  3431. this.x = - this.x;
  3432. this.y = - this.y;
  3433. this.z = - this.z;
  3434. return this;
  3435. }
  3436. dot( v ) {
  3437. return this.x * v.x + this.y * v.y + this.z * v.z;
  3438. }
  3439. // TODO lengthSquared?
  3440. lengthSq() {
  3441. return this.x * this.x + this.y * this.y + this.z * this.z;
  3442. }
  3443. length() {
  3444. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  3445. }
  3446. manhattanLength() {
  3447. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  3448. }
  3449. normalize() {
  3450. return this.divideScalar( this.length() || 1 );
  3451. }
  3452. setLength( length ) {
  3453. return this.normalize().multiplyScalar( length );
  3454. }
  3455. lerp( v, alpha ) {
  3456. this.x += ( v.x - this.x ) * alpha;
  3457. this.y += ( v.y - this.y ) * alpha;
  3458. this.z += ( v.z - this.z ) * alpha;
  3459. return this;
  3460. }
  3461. lerpVectors( v1, v2, alpha ) {
  3462. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  3463. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  3464. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  3465. return this;
  3466. }
  3467. cross( v, w ) {
  3468. if ( w !== undefined ) {
  3469. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  3470. return this.crossVectors( v, w );
  3471. }
  3472. return this.crossVectors( this, v );
  3473. }
  3474. crossVectors( a, b ) {
  3475. const ax = a.x, ay = a.y, az = a.z;
  3476. const bx = b.x, by = b.y, bz = b.z;
  3477. this.x = ay * bz - az * by;
  3478. this.y = az * bx - ax * bz;
  3479. this.z = ax * by - ay * bx;
  3480. return this;
  3481. }
  3482. projectOnVector( v ) {
  3483. const denominator = v.lengthSq();
  3484. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  3485. const scalar = v.dot( this ) / denominator;
  3486. return this.copy( v ).multiplyScalar( scalar );
  3487. }
  3488. projectOnPlane( planeNormal ) {
  3489. _vector$c.copy( this ).projectOnVector( planeNormal );
  3490. return this.sub( _vector$c );
  3491. }
  3492. reflect( normal ) {
  3493. // reflect incident vector off plane orthogonal to normal
  3494. // normal is assumed to have unit length
  3495. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  3496. }
  3497. angleTo( v ) {
  3498. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  3499. if ( denominator === 0 ) return Math.PI / 2;
  3500. const theta = this.dot( v ) / denominator;
  3501. // clamp, to handle numerical problems
  3502. return Math.acos( clamp( theta, - 1, 1 ) );
  3503. }
  3504. distanceTo( v ) {
  3505. return Math.sqrt( this.distanceToSquared( v ) );
  3506. }
  3507. distanceToSquared( v ) {
  3508. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  3509. return dx * dx + dy * dy + dz * dz;
  3510. }
  3511. manhattanDistanceTo( v ) {
  3512. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  3513. }
  3514. setFromSpherical( s ) {
  3515. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  3516. }
  3517. setFromSphericalCoords( radius, phi, theta ) {
  3518. const sinPhiRadius = Math.sin( phi ) * radius;
  3519. this.x = sinPhiRadius * Math.sin( theta );
  3520. this.y = Math.cos( phi ) * radius;
  3521. this.z = sinPhiRadius * Math.cos( theta );
  3522. return this;
  3523. }
  3524. setFromCylindrical( c ) {
  3525. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  3526. }
  3527. setFromCylindricalCoords( radius, theta, y ) {
  3528. this.x = radius * Math.sin( theta );
  3529. this.y = y;
  3530. this.z = radius * Math.cos( theta );
  3531. return this;
  3532. }
  3533. setFromMatrixPosition( m ) {
  3534. const e = m.elements;
  3535. this.x = e[ 12 ];
  3536. this.y = e[ 13 ];
  3537. this.z = e[ 14 ];
  3538. return this;
  3539. }
  3540. setFromMatrixScale( m ) {
  3541. const sx = this.setFromMatrixColumn( m, 0 ).length();
  3542. const sy = this.setFromMatrixColumn( m, 1 ).length();
  3543. const sz = this.setFromMatrixColumn( m, 2 ).length();
  3544. this.x = sx;
  3545. this.y = sy;
  3546. this.z = sz;
  3547. return this;
  3548. }
  3549. setFromMatrixColumn( m, index ) {
  3550. return this.fromArray( m.elements, index * 4 );
  3551. }
  3552. setFromMatrix3Column( m, index ) {
  3553. return this.fromArray( m.elements, index * 3 );
  3554. }
  3555. equals( v ) {
  3556. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  3557. }
  3558. fromArray( array, offset = 0 ) {
  3559. this.x = array[ offset ];
  3560. this.y = array[ offset + 1 ];
  3561. this.z = array[ offset + 2 ];
  3562. return this;
  3563. }
  3564. toArray( array = [], offset = 0 ) {
  3565. array[ offset ] = this.x;
  3566. array[ offset + 1 ] = this.y;
  3567. array[ offset + 2 ] = this.z;
  3568. return array;
  3569. }
  3570. fromBufferAttribute( attribute, index, offset ) {
  3571. if ( offset !== undefined ) {
  3572. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  3573. }
  3574. this.x = attribute.getX( index );
  3575. this.y = attribute.getY( index );
  3576. this.z = attribute.getZ( index );
  3577. return this;
  3578. }
  3579. random() {
  3580. this.x = Math.random();
  3581. this.y = Math.random();
  3582. this.z = Math.random();
  3583. return this;
  3584. }
  3585. }
  3586. Vector3.prototype.isVector3 = true;
  3587. const _vector$c = /*@__PURE__*/ new Vector3();
  3588. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  3589. class Box3 {
  3590. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  3591. this.min = min;
  3592. this.max = max;
  3593. }
  3594. set( min, max ) {
  3595. this.min.copy( min );
  3596. this.max.copy( max );
  3597. return this;
  3598. }
  3599. setFromArray( array ) {
  3600. let minX = + Infinity;
  3601. let minY = + Infinity;
  3602. let minZ = + Infinity;
  3603. let maxX = - Infinity;
  3604. let maxY = - Infinity;
  3605. let maxZ = - Infinity;
  3606. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  3607. const x = array[ i ];
  3608. const y = array[ i + 1 ];
  3609. const z = array[ i + 2 ];
  3610. if ( x < minX ) minX = x;
  3611. if ( y < minY ) minY = y;
  3612. if ( z < minZ ) minZ = z;
  3613. if ( x > maxX ) maxX = x;
  3614. if ( y > maxY ) maxY = y;
  3615. if ( z > maxZ ) maxZ = z;
  3616. }
  3617. this.min.set( minX, minY, minZ );
  3618. this.max.set( maxX, maxY, maxZ );
  3619. return this;
  3620. }
  3621. setFromBufferAttribute( attribute ) {
  3622. let minX = + Infinity;
  3623. let minY = + Infinity;
  3624. let minZ = + Infinity;
  3625. let maxX = - Infinity;
  3626. let maxY = - Infinity;
  3627. let maxZ = - Infinity;
  3628. for ( let i = 0, l = attribute.count; i < l; i ++ ) {
  3629. const x = attribute.getX( i );
  3630. const y = attribute.getY( i );
  3631. const z = attribute.getZ( i );
  3632. if ( x < minX ) minX = x;
  3633. if ( y < minY ) minY = y;
  3634. if ( z < minZ ) minZ = z;
  3635. if ( x > maxX ) maxX = x;
  3636. if ( y > maxY ) maxY = y;
  3637. if ( z > maxZ ) maxZ = z;
  3638. }
  3639. this.min.set( minX, minY, minZ );
  3640. this.max.set( maxX, maxY, maxZ );
  3641. return this;
  3642. }
  3643. setFromPoints( points ) {
  3644. this.makeEmpty();
  3645. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3646. this.expandByPoint( points[ i ] );
  3647. }
  3648. return this;
  3649. }
  3650. setFromCenterAndSize( center, size ) {
  3651. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  3652. this.min.copy( center ).sub( halfSize );
  3653. this.max.copy( center ).add( halfSize );
  3654. return this;
  3655. }
  3656. setFromObject( object ) {
  3657. this.makeEmpty();
  3658. return this.expandByObject( object );
  3659. }
  3660. clone() {
  3661. return new this.constructor().copy( this );
  3662. }
  3663. copy( box ) {
  3664. this.min.copy( box.min );
  3665. this.max.copy( box.max );
  3666. return this;
  3667. }
  3668. makeEmpty() {
  3669. this.min.x = this.min.y = this.min.z = + Infinity;
  3670. this.max.x = this.max.y = this.max.z = - Infinity;
  3671. return this;
  3672. }
  3673. isEmpty() {
  3674. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3675. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  3676. }
  3677. getCenter( target ) {
  3678. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  3679. }
  3680. getSize( target ) {
  3681. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  3682. }
  3683. expandByPoint( point ) {
  3684. this.min.min( point );
  3685. this.max.max( point );
  3686. return this;
  3687. }
  3688. expandByVector( vector ) {
  3689. this.min.sub( vector );
  3690. this.max.add( vector );
  3691. return this;
  3692. }
  3693. expandByScalar( scalar ) {
  3694. this.min.addScalar( - scalar );
  3695. this.max.addScalar( scalar );
  3696. return this;
  3697. }
  3698. expandByObject( object ) {
  3699. // Computes the world-axis-aligned bounding box of an object (including its children),
  3700. // accounting for both the object's, and children's, world transforms
  3701. object.updateWorldMatrix( false, false );
  3702. const geometry = object.geometry;
  3703. if ( geometry !== undefined ) {
  3704. if ( geometry.boundingBox === null ) {
  3705. geometry.computeBoundingBox();
  3706. }
  3707. _box$3.copy( geometry.boundingBox );
  3708. _box$3.applyMatrix4( object.matrixWorld );
  3709. this.union( _box$3 );
  3710. }
  3711. const children = object.children;
  3712. for ( let i = 0, l = children.length; i < l; i ++ ) {
  3713. this.expandByObject( children[ i ] );
  3714. }
  3715. return this;
  3716. }
  3717. containsPoint( point ) {
  3718. return point.x < this.min.x || point.x > this.max.x ||
  3719. point.y < this.min.y || point.y > this.max.y ||
  3720. point.z < this.min.z || point.z > this.max.z ? false : true;
  3721. }
  3722. containsBox( box ) {
  3723. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  3724. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  3725. this.min.z <= box.min.z && box.max.z <= this.max.z;
  3726. }
  3727. getParameter( point, target ) {
  3728. // This can potentially have a divide by zero if the box
  3729. // has a size dimension of 0.
  3730. return target.set(
  3731. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  3732. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  3733. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  3734. );
  3735. }
  3736. intersectsBox( box ) {
  3737. // using 6 splitting planes to rule out intersections.
  3738. return box.max.x < this.min.x || box.min.x > this.max.x ||
  3739. box.max.y < this.min.y || box.min.y > this.max.y ||
  3740. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  3741. }
  3742. intersectsSphere( sphere ) {
  3743. // Find the point on the AABB closest to the sphere center.
  3744. this.clampPoint( sphere.center, _vector$b );
  3745. // If that point is inside the sphere, the AABB and sphere intersect.
  3746. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  3747. }
  3748. intersectsPlane( plane ) {
  3749. // We compute the minimum and maximum dot product values. If those values
  3750. // are on the same side (back or front) of the plane, then there is no intersection.
  3751. let min, max;
  3752. if ( plane.normal.x > 0 ) {
  3753. min = plane.normal.x * this.min.x;
  3754. max = plane.normal.x * this.max.x;
  3755. } else {
  3756. min = plane.normal.x * this.max.x;
  3757. max = plane.normal.x * this.min.x;
  3758. }
  3759. if ( plane.normal.y > 0 ) {
  3760. min += plane.normal.y * this.min.y;
  3761. max += plane.normal.y * this.max.y;
  3762. } else {
  3763. min += plane.normal.y * this.max.y;
  3764. max += plane.normal.y * this.min.y;
  3765. }
  3766. if ( plane.normal.z > 0 ) {
  3767. min += plane.normal.z * this.min.z;
  3768. max += plane.normal.z * this.max.z;
  3769. } else {
  3770. min += plane.normal.z * this.max.z;
  3771. max += plane.normal.z * this.min.z;
  3772. }
  3773. return ( min <= - plane.constant && max >= - plane.constant );
  3774. }
  3775. intersectsTriangle( triangle ) {
  3776. if ( this.isEmpty() ) {
  3777. return false;
  3778. }
  3779. // compute box center and extents
  3780. this.getCenter( _center );
  3781. _extents.subVectors( this.max, _center );
  3782. // translate triangle to aabb origin
  3783. _v0$2.subVectors( triangle.a, _center );
  3784. _v1$7.subVectors( triangle.b, _center );
  3785. _v2$3.subVectors( triangle.c, _center );
  3786. // compute edge vectors for triangle
  3787. _f0.subVectors( _v1$7, _v0$2 );
  3788. _f1.subVectors( _v2$3, _v1$7 );
  3789. _f2.subVectors( _v0$2, _v2$3 );
  3790. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  3791. // 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
  3792. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3793. let axes = [
  3794. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  3795. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  3796. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  3797. ];
  3798. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents ) ) {
  3799. return false;
  3800. }
  3801. // test 3 face normals from the aabb
  3802. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  3803. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents ) ) {
  3804. return false;
  3805. }
  3806. // finally testing the face normal of the triangle
  3807. // use already existing triangle edge vectors here
  3808. _triangleNormal.crossVectors( _f0, _f1 );
  3809. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  3810. return satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents );
  3811. }
  3812. clampPoint( point, target ) {
  3813. return target.copy( point ).clamp( this.min, this.max );
  3814. }
  3815. distanceToPoint( point ) {
  3816. const clampedPoint = _vector$b.copy( point ).clamp( this.min, this.max );
  3817. return clampedPoint.sub( point ).length();
  3818. }
  3819. getBoundingSphere( target ) {
  3820. this.getCenter( target.center );
  3821. target.radius = this.getSize( _vector$b ).length() * 0.5;
  3822. return target;
  3823. }
  3824. intersect( box ) {
  3825. this.min.max( box.min );
  3826. this.max.min( box.max );
  3827. // 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.
  3828. if ( this.isEmpty() ) this.makeEmpty();
  3829. return this;
  3830. }
  3831. union( box ) {
  3832. this.min.min( box.min );
  3833. this.max.max( box.max );
  3834. return this;
  3835. }
  3836. applyMatrix4( matrix ) {
  3837. // transform of empty box is an empty box.
  3838. if ( this.isEmpty() ) return this;
  3839. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3840. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3841. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3842. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3843. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3844. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3845. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3846. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3847. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3848. this.setFromPoints( _points );
  3849. return this;
  3850. }
  3851. translate( offset ) {
  3852. this.min.add( offset );
  3853. this.max.add( offset );
  3854. return this;
  3855. }
  3856. equals( box ) {
  3857. return box.min.equals( this.min ) && box.max.equals( this.max );
  3858. }
  3859. }
  3860. Box3.prototype.isBox3 = true;
  3861. const _points = [
  3862. /*@__PURE__*/ new Vector3(),
  3863. /*@__PURE__*/ new Vector3(),
  3864. /*@__PURE__*/ new Vector3(),
  3865. /*@__PURE__*/ new Vector3(),
  3866. /*@__PURE__*/ new Vector3(),
  3867. /*@__PURE__*/ new Vector3(),
  3868. /*@__PURE__*/ new Vector3(),
  3869. /*@__PURE__*/ new Vector3()
  3870. ];
  3871. const _vector$b = /*@__PURE__*/ new Vector3();
  3872. const _box$3 = /*@__PURE__*/ new Box3();
  3873. // triangle centered vertices
  3874. const _v0$2 = /*@__PURE__*/ new Vector3();
  3875. const _v1$7 = /*@__PURE__*/ new Vector3();
  3876. const _v2$3 = /*@__PURE__*/ new Vector3();
  3877. // triangle edge vectors
  3878. const _f0 = /*@__PURE__*/ new Vector3();
  3879. const _f1 = /*@__PURE__*/ new Vector3();
  3880. const _f2 = /*@__PURE__*/ new Vector3();
  3881. const _center = /*@__PURE__*/ new Vector3();
  3882. const _extents = /*@__PURE__*/ new Vector3();
  3883. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3884. const _testAxis = /*@__PURE__*/ new Vector3();
  3885. function satForAxes( axes, v0, v1, v2, extents ) {
  3886. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3887. _testAxis.fromArray( axes, i );
  3888. // project the aabb onto the seperating axis
  3889. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3890. // project all 3 vertices of the triangle onto the seperating axis
  3891. const p0 = v0.dot( _testAxis );
  3892. const p1 = v1.dot( _testAxis );
  3893. const p2 = v2.dot( _testAxis );
  3894. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3895. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3896. // points of the projected triangle are outside the projected half-length of the aabb
  3897. // the axis is seperating and we can exit
  3898. return false;
  3899. }
  3900. }
  3901. return true;
  3902. }
  3903. const _box$2 = /*@__PURE__*/ new Box3();
  3904. const _v1$6 = /*@__PURE__*/ new Vector3();
  3905. const _toFarthestPoint = /*@__PURE__*/ new Vector3();
  3906. const _toPoint = /*@__PURE__*/ new Vector3();
  3907. class Sphere {
  3908. constructor( center = new Vector3(), radius = - 1 ) {
  3909. this.center = center;
  3910. this.radius = radius;
  3911. }
  3912. set( center, radius ) {
  3913. this.center.copy( center );
  3914. this.radius = radius;
  3915. return this;
  3916. }
  3917. setFromPoints( points, optionalCenter ) {
  3918. const center = this.center;
  3919. if ( optionalCenter !== undefined ) {
  3920. center.copy( optionalCenter );
  3921. } else {
  3922. _box$2.setFromPoints( points ).getCenter( center );
  3923. }
  3924. let maxRadiusSq = 0;
  3925. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3926. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3927. }
  3928. this.radius = Math.sqrt( maxRadiusSq );
  3929. return this;
  3930. }
  3931. copy( sphere ) {
  3932. this.center.copy( sphere.center );
  3933. this.radius = sphere.radius;
  3934. return this;
  3935. }
  3936. isEmpty() {
  3937. return ( this.radius < 0 );
  3938. }
  3939. makeEmpty() {
  3940. this.center.set( 0, 0, 0 );
  3941. this.radius = - 1;
  3942. return this;
  3943. }
  3944. containsPoint( point ) {
  3945. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3946. }
  3947. distanceToPoint( point ) {
  3948. return ( point.distanceTo( this.center ) - this.radius );
  3949. }
  3950. intersectsSphere( sphere ) {
  3951. const radiusSum = this.radius + sphere.radius;
  3952. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3953. }
  3954. intersectsBox( box ) {
  3955. return box.intersectsSphere( this );
  3956. }
  3957. intersectsPlane( plane ) {
  3958. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3959. }
  3960. clampPoint( point, target ) {
  3961. const deltaLengthSq = this.center.distanceToSquared( point );
  3962. target.copy( point );
  3963. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3964. target.sub( this.center ).normalize();
  3965. target.multiplyScalar( this.radius ).add( this.center );
  3966. }
  3967. return target;
  3968. }
  3969. getBoundingBox( target ) {
  3970. if ( this.isEmpty() ) {
  3971. // Empty sphere produces empty bounding box
  3972. target.makeEmpty();
  3973. return target;
  3974. }
  3975. target.set( this.center, this.center );
  3976. target.expandByScalar( this.radius );
  3977. return target;
  3978. }
  3979. applyMatrix4( matrix ) {
  3980. this.center.applyMatrix4( matrix );
  3981. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3982. return this;
  3983. }
  3984. translate( offset ) {
  3985. this.center.add( offset );
  3986. return this;
  3987. }
  3988. expandByPoint( point ) {
  3989. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  3990. _toPoint.subVectors( point, this.center );
  3991. const lengthSq = _toPoint.lengthSq();
  3992. if ( lengthSq > ( this.radius * this.radius ) ) {
  3993. const length = Math.sqrt( lengthSq );
  3994. const missingRadiusHalf = ( length - this.radius ) * 0.5;
  3995. // Nudge this sphere towards the target point. Add half the missing distance to radius,
  3996. // and the other half to position. This gives a tighter enclosure, instead of if
  3997. // the whole missing distance were just added to radius.
  3998. this.center.add( _toPoint.multiplyScalar( missingRadiusHalf / length ) );
  3999. this.radius += missingRadiusHalf;
  4000. }
  4001. return this;
  4002. }
  4003. union( sphere ) {
  4004. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  4005. // To enclose another sphere into this sphere, we only need to enclose two points:
  4006. // 1) Enclose the farthest point on the other sphere into this sphere.
  4007. // 2) Enclose the opposite point of the farthest point into this sphere.
  4008. _toFarthestPoint.subVectors( sphere.center, this.center ).normalize().multiplyScalar( sphere.radius );
  4009. this.expandByPoint( _v1$6.copy( sphere.center ).add( _toFarthestPoint ) );
  4010. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _toFarthestPoint ) );
  4011. return this;
  4012. }
  4013. equals( sphere ) {
  4014. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  4015. }
  4016. clone() {
  4017. return new this.constructor().copy( this );
  4018. }
  4019. }
  4020. const _vector$a = /*@__PURE__*/ new Vector3();
  4021. const _segCenter = /*@__PURE__*/ new Vector3();
  4022. const _segDir = /*@__PURE__*/ new Vector3();
  4023. const _diff = /*@__PURE__*/ new Vector3();
  4024. const _edge1 = /*@__PURE__*/ new Vector3();
  4025. const _edge2 = /*@__PURE__*/ new Vector3();
  4026. const _normal$1 = /*@__PURE__*/ new Vector3();
  4027. class Ray {
  4028. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  4029. this.origin = origin;
  4030. this.direction = direction;
  4031. }
  4032. set( origin, direction ) {
  4033. this.origin.copy( origin );
  4034. this.direction.copy( direction );
  4035. return this;
  4036. }
  4037. copy( ray ) {
  4038. this.origin.copy( ray.origin );
  4039. this.direction.copy( ray.direction );
  4040. return this;
  4041. }
  4042. at( t, target ) {
  4043. return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  4044. }
  4045. lookAt( v ) {
  4046. this.direction.copy( v ).sub( this.origin ).normalize();
  4047. return this;
  4048. }
  4049. recast( t ) {
  4050. this.origin.copy( this.at( t, _vector$a ) );
  4051. return this;
  4052. }
  4053. closestPointToPoint( point, target ) {
  4054. target.subVectors( point, this.origin );
  4055. const directionDistance = target.dot( this.direction );
  4056. if ( directionDistance < 0 ) {
  4057. return target.copy( this.origin );
  4058. }
  4059. return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  4060. }
  4061. distanceToPoint( point ) {
  4062. return Math.sqrt( this.distanceSqToPoint( point ) );
  4063. }
  4064. distanceSqToPoint( point ) {
  4065. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  4066. // point behind the ray
  4067. if ( directionDistance < 0 ) {
  4068. return this.origin.distanceToSquared( point );
  4069. }
  4070. _vector$a.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  4071. return _vector$a.distanceToSquared( point );
  4072. }
  4073. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  4074. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  4075. // It returns the min distance between the ray and the segment
  4076. // defined by v0 and v1
  4077. // It can also set two optional targets :
  4078. // - The closest point on the ray
  4079. // - The closest point on the segment
  4080. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  4081. _segDir.copy( v1 ).sub( v0 ).normalize();
  4082. _diff.copy( this.origin ).sub( _segCenter );
  4083. const segExtent = v0.distanceTo( v1 ) * 0.5;
  4084. const a01 = - this.direction.dot( _segDir );
  4085. const b0 = _diff.dot( this.direction );
  4086. const b1 = - _diff.dot( _segDir );
  4087. const c = _diff.lengthSq();
  4088. const det = Math.abs( 1 - a01 * a01 );
  4089. let s0, s1, sqrDist, extDet;
  4090. if ( det > 0 ) {
  4091. // The ray and segment are not parallel.
  4092. s0 = a01 * b1 - b0;
  4093. s1 = a01 * b0 - b1;
  4094. extDet = segExtent * det;
  4095. if ( s0 >= 0 ) {
  4096. if ( s1 >= - extDet ) {
  4097. if ( s1 <= extDet ) {
  4098. // region 0
  4099. // Minimum at interior points of ray and segment.
  4100. const invDet = 1 / det;
  4101. s0 *= invDet;
  4102. s1 *= invDet;
  4103. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  4104. } else {
  4105. // region 1
  4106. s1 = segExtent;
  4107. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  4108. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  4109. }
  4110. } else {
  4111. // region 5
  4112. s1 = - segExtent;
  4113. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  4114. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  4115. }
  4116. } else {
  4117. if ( s1 <= - extDet ) {
  4118. // region 4
  4119. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  4120. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  4121. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  4122. } else if ( s1 <= extDet ) {
  4123. // region 3
  4124. s0 = 0;
  4125. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  4126. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  4127. } else {
  4128. // region 2
  4129. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  4130. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  4131. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  4132. }
  4133. }
  4134. } else {
  4135. // Ray and segment are parallel.
  4136. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  4137. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  4138. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  4139. }
  4140. if ( optionalPointOnRay ) {
  4141. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  4142. }
  4143. if ( optionalPointOnSegment ) {
  4144. optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter );
  4145. }
  4146. return sqrDist;
  4147. }
  4148. intersectSphere( sphere, target ) {
  4149. _vector$a.subVectors( sphere.center, this.origin );
  4150. const tca = _vector$a.dot( this.direction );
  4151. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  4152. const radius2 = sphere.radius * sphere.radius;
  4153. if ( d2 > radius2 ) return null;
  4154. const thc = Math.sqrt( radius2 - d2 );
  4155. // t0 = first intersect point - entrance on front of sphere
  4156. const t0 = tca - thc;
  4157. // t1 = second intersect point - exit point on back of sphere
  4158. const t1 = tca + thc;
  4159. // test to see if both t0 and t1 are behind the ray - if so, return null
  4160. if ( t0 < 0 && t1 < 0 ) return null;
  4161. // test to see if t0 is behind the ray:
  4162. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  4163. // in order to always return an intersect point that is in front of the ray.
  4164. if ( t0 < 0 ) return this.at( t1, target );
  4165. // else t0 is in front of the ray, so return the first collision point scaled by t0
  4166. return this.at( t0, target );
  4167. }
  4168. intersectsSphere( sphere ) {
  4169. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  4170. }
  4171. distanceToPlane( plane ) {
  4172. const denominator = plane.normal.dot( this.direction );
  4173. if ( denominator === 0 ) {
  4174. // line is coplanar, return origin
  4175. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  4176. return 0;
  4177. }
  4178. // Null is preferable to undefined since undefined means.... it is undefined
  4179. return null;
  4180. }
  4181. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  4182. // Return if the ray never intersects the plane
  4183. return t >= 0 ? t : null;
  4184. }
  4185. intersectPlane( plane, target ) {
  4186. const t = this.distanceToPlane( plane );
  4187. if ( t === null ) {
  4188. return null;
  4189. }
  4190. return this.at( t, target );
  4191. }
  4192. intersectsPlane( plane ) {
  4193. // check if the ray lies on the plane first
  4194. const distToPoint = plane.distanceToPoint( this.origin );
  4195. if ( distToPoint === 0 ) {
  4196. return true;
  4197. }
  4198. const denominator = plane.normal.dot( this.direction );
  4199. if ( denominator * distToPoint < 0 ) {
  4200. return true;
  4201. }
  4202. // ray origin is behind the plane (and is pointing behind it)
  4203. return false;
  4204. }
  4205. intersectBox( box, target ) {
  4206. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  4207. const invdirx = 1 / this.direction.x,
  4208. invdiry = 1 / this.direction.y,
  4209. invdirz = 1 / this.direction.z;
  4210. const origin = this.origin;
  4211. if ( invdirx >= 0 ) {
  4212. tmin = ( box.min.x - origin.x ) * invdirx;
  4213. tmax = ( box.max.x - origin.x ) * invdirx;
  4214. } else {
  4215. tmin = ( box.max.x - origin.x ) * invdirx;
  4216. tmax = ( box.min.x - origin.x ) * invdirx;
  4217. }
  4218. if ( invdiry >= 0 ) {
  4219. tymin = ( box.min.y - origin.y ) * invdiry;
  4220. tymax = ( box.max.y - origin.y ) * invdiry;
  4221. } else {
  4222. tymin = ( box.max.y - origin.y ) * invdiry;
  4223. tymax = ( box.min.y - origin.y ) * invdiry;
  4224. }
  4225. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  4226. // These lines also handle the case where tmin or tmax is NaN
  4227. // (result of 0 * Infinity). x !== x returns true if x is NaN
  4228. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  4229. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  4230. if ( invdirz >= 0 ) {
  4231. tzmin = ( box.min.z - origin.z ) * invdirz;
  4232. tzmax = ( box.max.z - origin.z ) * invdirz;
  4233. } else {
  4234. tzmin = ( box.max.z - origin.z ) * invdirz;
  4235. tzmax = ( box.min.z - origin.z ) * invdirz;
  4236. }
  4237. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  4238. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  4239. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  4240. //return point closest to the ray (positive side)
  4241. if ( tmax < 0 ) return null;
  4242. return this.at( tmin >= 0 ? tmin : tmax, target );
  4243. }
  4244. intersectsBox( box ) {
  4245. return this.intersectBox( box, _vector$a ) !== null;
  4246. }
  4247. intersectTriangle( a, b, c, backfaceCulling, target ) {
  4248. // Compute the offset origin, edges, and normal.
  4249. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  4250. _edge1.subVectors( b, a );
  4251. _edge2.subVectors( c, a );
  4252. _normal$1.crossVectors( _edge1, _edge2 );
  4253. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  4254. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  4255. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  4256. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  4257. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  4258. let DdN = this.direction.dot( _normal$1 );
  4259. let sign;
  4260. if ( DdN > 0 ) {
  4261. if ( backfaceCulling ) return null;
  4262. sign = 1;
  4263. } else if ( DdN < 0 ) {
  4264. sign = - 1;
  4265. DdN = - DdN;
  4266. } else {
  4267. return null;
  4268. }
  4269. _diff.subVectors( this.origin, a );
  4270. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  4271. // b1 < 0, no intersection
  4272. if ( DdQxE2 < 0 ) {
  4273. return null;
  4274. }
  4275. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  4276. // b2 < 0, no intersection
  4277. if ( DdE1xQ < 0 ) {
  4278. return null;
  4279. }
  4280. // b1+b2 > 1, no intersection
  4281. if ( DdQxE2 + DdE1xQ > DdN ) {
  4282. return null;
  4283. }
  4284. // Line intersects triangle, check if ray does.
  4285. const QdN = - sign * _diff.dot( _normal$1 );
  4286. // t < 0, no intersection
  4287. if ( QdN < 0 ) {
  4288. return null;
  4289. }
  4290. // Ray intersects triangle.
  4291. return this.at( QdN / DdN, target );
  4292. }
  4293. applyMatrix4( matrix4 ) {
  4294. this.origin.applyMatrix4( matrix4 );
  4295. this.direction.transformDirection( matrix4 );
  4296. return this;
  4297. }
  4298. equals( ray ) {
  4299. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  4300. }
  4301. clone() {
  4302. return new this.constructor().copy( this );
  4303. }
  4304. }
  4305. class Matrix4 {
  4306. constructor() {
  4307. this.elements = [
  4308. 1, 0, 0, 0,
  4309. 0, 1, 0, 0,
  4310. 0, 0, 1, 0,
  4311. 0, 0, 0, 1
  4312. ];
  4313. if ( arguments.length > 0 ) {
  4314. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  4315. }
  4316. }
  4317. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  4318. const te = this.elements;
  4319. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  4320. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  4321. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  4322. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  4323. return this;
  4324. }
  4325. identity() {
  4326. this.set(
  4327. 1, 0, 0, 0,
  4328. 0, 1, 0, 0,
  4329. 0, 0, 1, 0,
  4330. 0, 0, 0, 1
  4331. );
  4332. return this;
  4333. }
  4334. clone() {
  4335. return new Matrix4().fromArray( this.elements );
  4336. }
  4337. copy( m ) {
  4338. const te = this.elements;
  4339. const me = m.elements;
  4340. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  4341. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  4342. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  4343. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  4344. return this;
  4345. }
  4346. copyPosition( m ) {
  4347. const te = this.elements, me = m.elements;
  4348. te[ 12 ] = me[ 12 ];
  4349. te[ 13 ] = me[ 13 ];
  4350. te[ 14 ] = me[ 14 ];
  4351. return this;
  4352. }
  4353. setFromMatrix3( m ) {
  4354. const me = m.elements;
  4355. this.set(
  4356. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  4357. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  4358. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  4359. 0, 0, 0, 1
  4360. );
  4361. return this;
  4362. }
  4363. extractBasis( xAxis, yAxis, zAxis ) {
  4364. xAxis.setFromMatrixColumn( this, 0 );
  4365. yAxis.setFromMatrixColumn( this, 1 );
  4366. zAxis.setFromMatrixColumn( this, 2 );
  4367. return this;
  4368. }
  4369. makeBasis( xAxis, yAxis, zAxis ) {
  4370. this.set(
  4371. xAxis.x, yAxis.x, zAxis.x, 0,
  4372. xAxis.y, yAxis.y, zAxis.y, 0,
  4373. xAxis.z, yAxis.z, zAxis.z, 0,
  4374. 0, 0, 0, 1
  4375. );
  4376. return this;
  4377. }
  4378. extractRotation( m ) {
  4379. // this method does not support reflection matrices
  4380. const te = this.elements;
  4381. const me = m.elements;
  4382. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  4383. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  4384. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  4385. te[ 0 ] = me[ 0 ] * scaleX;
  4386. te[ 1 ] = me[ 1 ] * scaleX;
  4387. te[ 2 ] = me[ 2 ] * scaleX;
  4388. te[ 3 ] = 0;
  4389. te[ 4 ] = me[ 4 ] * scaleY;
  4390. te[ 5 ] = me[ 5 ] * scaleY;
  4391. te[ 6 ] = me[ 6 ] * scaleY;
  4392. te[ 7 ] = 0;
  4393. te[ 8 ] = me[ 8 ] * scaleZ;
  4394. te[ 9 ] = me[ 9 ] * scaleZ;
  4395. te[ 10 ] = me[ 10 ] * scaleZ;
  4396. te[ 11 ] = 0;
  4397. te[ 12 ] = 0;
  4398. te[ 13 ] = 0;
  4399. te[ 14 ] = 0;
  4400. te[ 15 ] = 1;
  4401. return this;
  4402. }
  4403. makeRotationFromEuler( euler ) {
  4404. if ( ! ( euler && euler.isEuler ) ) {
  4405. console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  4406. }
  4407. const te = this.elements;
  4408. const x = euler.x, y = euler.y, z = euler.z;
  4409. const a = Math.cos( x ), b = Math.sin( x );
  4410. const c = Math.cos( y ), d = Math.sin( y );
  4411. const e = Math.cos( z ), f = Math.sin( z );
  4412. if ( euler.order === 'XYZ' ) {
  4413. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  4414. te[ 0 ] = c * e;
  4415. te[ 4 ] = - c * f;
  4416. te[ 8 ] = d;
  4417. te[ 1 ] = af + be * d;
  4418. te[ 5 ] = ae - bf * d;
  4419. te[ 9 ] = - b * c;
  4420. te[ 2 ] = bf - ae * d;
  4421. te[ 6 ] = be + af * d;
  4422. te[ 10 ] = a * c;
  4423. } else if ( euler.order === 'YXZ' ) {
  4424. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  4425. te[ 0 ] = ce + df * b;
  4426. te[ 4 ] = de * b - cf;
  4427. te[ 8 ] = a * d;
  4428. te[ 1 ] = a * f;
  4429. te[ 5 ] = a * e;
  4430. te[ 9 ] = - b;
  4431. te[ 2 ] = cf * b - de;
  4432. te[ 6 ] = df + ce * b;
  4433. te[ 10 ] = a * c;
  4434. } else if ( euler.order === 'ZXY' ) {
  4435. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  4436. te[ 0 ] = ce - df * b;
  4437. te[ 4 ] = - a * f;
  4438. te[ 8 ] = de + cf * b;
  4439. te[ 1 ] = cf + de * b;
  4440. te[ 5 ] = a * e;
  4441. te[ 9 ] = df - ce * b;
  4442. te[ 2 ] = - a * d;
  4443. te[ 6 ] = b;
  4444. te[ 10 ] = a * c;
  4445. } else if ( euler.order === 'ZYX' ) {
  4446. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  4447. te[ 0 ] = c * e;
  4448. te[ 4 ] = be * d - af;
  4449. te[ 8 ] = ae * d + bf;
  4450. te[ 1 ] = c * f;
  4451. te[ 5 ] = bf * d + ae;
  4452. te[ 9 ] = af * d - be;
  4453. te[ 2 ] = - d;
  4454. te[ 6 ] = b * c;
  4455. te[ 10 ] = a * c;
  4456. } else if ( euler.order === 'YZX' ) {
  4457. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  4458. te[ 0 ] = c * e;
  4459. te[ 4 ] = bd - ac * f;
  4460. te[ 8 ] = bc * f + ad;
  4461. te[ 1 ] = f;
  4462. te[ 5 ] = a * e;
  4463. te[ 9 ] = - b * e;
  4464. te[ 2 ] = - d * e;
  4465. te[ 6 ] = ad * f + bc;
  4466. te[ 10 ] = ac - bd * f;
  4467. } else if ( euler.order === 'XZY' ) {
  4468. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  4469. te[ 0 ] = c * e;
  4470. te[ 4 ] = - f;
  4471. te[ 8 ] = d * e;
  4472. te[ 1 ] = ac * f + bd;
  4473. te[ 5 ] = a * e;
  4474. te[ 9 ] = ad * f - bc;
  4475. te[ 2 ] = bc * f - ad;
  4476. te[ 6 ] = b * e;
  4477. te[ 10 ] = bd * f + ac;
  4478. }
  4479. // bottom row
  4480. te[ 3 ] = 0;
  4481. te[ 7 ] = 0;
  4482. te[ 11 ] = 0;
  4483. // last column
  4484. te[ 12 ] = 0;
  4485. te[ 13 ] = 0;
  4486. te[ 14 ] = 0;
  4487. te[ 15 ] = 1;
  4488. return this;
  4489. }
  4490. makeRotationFromQuaternion( q ) {
  4491. return this.compose( _zero, q, _one );
  4492. }
  4493. lookAt( eye, target, up ) {
  4494. const te = this.elements;
  4495. _z.subVectors( eye, target );
  4496. if ( _z.lengthSq() === 0 ) {
  4497. // eye and target are in the same position
  4498. _z.z = 1;
  4499. }
  4500. _z.normalize();
  4501. _x.crossVectors( up, _z );
  4502. if ( _x.lengthSq() === 0 ) {
  4503. // up and z are parallel
  4504. if ( Math.abs( up.z ) === 1 ) {
  4505. _z.x += 0.0001;
  4506. } else {
  4507. _z.z += 0.0001;
  4508. }
  4509. _z.normalize();
  4510. _x.crossVectors( up, _z );
  4511. }
  4512. _x.normalize();
  4513. _y.crossVectors( _z, _x );
  4514. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  4515. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  4516. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  4517. return this;
  4518. }
  4519. multiply( m, n ) {
  4520. if ( n !== undefined ) {
  4521. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  4522. return this.multiplyMatrices( m, n );
  4523. }
  4524. return this.multiplyMatrices( this, m );
  4525. }
  4526. premultiply( m ) {
  4527. return this.multiplyMatrices( m, this );
  4528. }
  4529. multiplyMatrices( a, b ) {
  4530. const ae = a.elements;
  4531. const be = b.elements;
  4532. const te = this.elements;
  4533. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  4534. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  4535. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  4536. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  4537. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  4538. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  4539. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  4540. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  4541. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  4542. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  4543. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  4544. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  4545. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  4546. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  4547. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  4548. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  4549. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  4550. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  4551. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  4552. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  4553. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  4554. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  4555. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  4556. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  4557. return this;
  4558. }
  4559. multiplyScalar( s ) {
  4560. const te = this.elements;
  4561. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  4562. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  4563. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  4564. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  4565. return this;
  4566. }
  4567. determinant() {
  4568. const te = this.elements;
  4569. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  4570. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  4571. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  4572. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  4573. //TODO: make this more efficient
  4574. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  4575. return (
  4576. n41 * (
  4577. + n14 * n23 * n32
  4578. - n13 * n24 * n32
  4579. - n14 * n22 * n33
  4580. + n12 * n24 * n33
  4581. + n13 * n22 * n34
  4582. - n12 * n23 * n34
  4583. ) +
  4584. n42 * (
  4585. + n11 * n23 * n34
  4586. - n11 * n24 * n33
  4587. + n14 * n21 * n33
  4588. - n13 * n21 * n34
  4589. + n13 * n24 * n31
  4590. - n14 * n23 * n31
  4591. ) +
  4592. n43 * (
  4593. + n11 * n24 * n32
  4594. - n11 * n22 * n34
  4595. - n14 * n21 * n32
  4596. + n12 * n21 * n34
  4597. + n14 * n22 * n31
  4598. - n12 * n24 * n31
  4599. ) +
  4600. n44 * (
  4601. - n13 * n22 * n31
  4602. - n11 * n23 * n32
  4603. + n11 * n22 * n33
  4604. + n13 * n21 * n32
  4605. - n12 * n21 * n33
  4606. + n12 * n23 * n31
  4607. )
  4608. );
  4609. }
  4610. transpose() {
  4611. const te = this.elements;
  4612. let tmp;
  4613. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  4614. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  4615. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  4616. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  4617. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  4618. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  4619. return this;
  4620. }
  4621. setPosition( x, y, z ) {
  4622. const te = this.elements;
  4623. if ( x.isVector3 ) {
  4624. te[ 12 ] = x.x;
  4625. te[ 13 ] = x.y;
  4626. te[ 14 ] = x.z;
  4627. } else {
  4628. te[ 12 ] = x;
  4629. te[ 13 ] = y;
  4630. te[ 14 ] = z;
  4631. }
  4632. return this;
  4633. }
  4634. invert() {
  4635. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4636. const te = this.elements,
  4637. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  4638. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  4639. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  4640. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  4641. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4642. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4643. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4644. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4645. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4646. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4647. const detInv = 1 / det;
  4648. te[ 0 ] = t11 * detInv;
  4649. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  4650. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  4651. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  4652. te[ 4 ] = t12 * detInv;
  4653. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  4654. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  4655. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  4656. te[ 8 ] = t13 * detInv;
  4657. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  4658. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  4659. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  4660. te[ 12 ] = t14 * detInv;
  4661. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  4662. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  4663. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  4664. return this;
  4665. }
  4666. scale( v ) {
  4667. const te = this.elements;
  4668. const x = v.x, y = v.y, z = v.z;
  4669. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  4670. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  4671. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  4672. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  4673. return this;
  4674. }
  4675. getMaxScaleOnAxis() {
  4676. const te = this.elements;
  4677. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  4678. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  4679. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  4680. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  4681. }
  4682. makeTranslation( x, y, z ) {
  4683. this.set(
  4684. 1, 0, 0, x,
  4685. 0, 1, 0, y,
  4686. 0, 0, 1, z,
  4687. 0, 0, 0, 1
  4688. );
  4689. return this;
  4690. }
  4691. makeRotationX( theta ) {
  4692. const c = Math.cos( theta ), s = Math.sin( theta );
  4693. this.set(
  4694. 1, 0, 0, 0,
  4695. 0, c, - s, 0,
  4696. 0, s, c, 0,
  4697. 0, 0, 0, 1
  4698. );
  4699. return this;
  4700. }
  4701. makeRotationY( theta ) {
  4702. const c = Math.cos( theta ), s = Math.sin( theta );
  4703. this.set(
  4704. c, 0, s, 0,
  4705. 0, 1, 0, 0,
  4706. - s, 0, c, 0,
  4707. 0, 0, 0, 1
  4708. );
  4709. return this;
  4710. }
  4711. makeRotationZ( theta ) {
  4712. const c = Math.cos( theta ), s = Math.sin( theta );
  4713. this.set(
  4714. c, - s, 0, 0,
  4715. s, c, 0, 0,
  4716. 0, 0, 1, 0,
  4717. 0, 0, 0, 1
  4718. );
  4719. return this;
  4720. }
  4721. makeRotationAxis( axis, angle ) {
  4722. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4723. const c = Math.cos( angle );
  4724. const s = Math.sin( angle );
  4725. const t = 1 - c;
  4726. const x = axis.x, y = axis.y, z = axis.z;
  4727. const tx = t * x, ty = t * y;
  4728. this.set(
  4729. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  4730. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  4731. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  4732. 0, 0, 0, 1
  4733. );
  4734. return this;
  4735. }
  4736. makeScale( x, y, z ) {
  4737. this.set(
  4738. x, 0, 0, 0,
  4739. 0, y, 0, 0,
  4740. 0, 0, z, 0,
  4741. 0, 0, 0, 1
  4742. );
  4743. return this;
  4744. }
  4745. makeShear( xy, xz, yx, yz, zx, zy ) {
  4746. this.set(
  4747. 1, yx, zx, 0,
  4748. xy, 1, zy, 0,
  4749. xz, yz, 1, 0,
  4750. 0, 0, 0, 1
  4751. );
  4752. return this;
  4753. }
  4754. compose( position, quaternion, scale ) {
  4755. const te = this.elements;
  4756. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  4757. const x2 = x + x, y2 = y + y, z2 = z + z;
  4758. const xx = x * x2, xy = x * y2, xz = x * z2;
  4759. const yy = y * y2, yz = y * z2, zz = z * z2;
  4760. const wx = w * x2, wy = w * y2, wz = w * z2;
  4761. const sx = scale.x, sy = scale.y, sz = scale.z;
  4762. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  4763. te[ 1 ] = ( xy + wz ) * sx;
  4764. te[ 2 ] = ( xz - wy ) * sx;
  4765. te[ 3 ] = 0;
  4766. te[ 4 ] = ( xy - wz ) * sy;
  4767. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  4768. te[ 6 ] = ( yz + wx ) * sy;
  4769. te[ 7 ] = 0;
  4770. te[ 8 ] = ( xz + wy ) * sz;
  4771. te[ 9 ] = ( yz - wx ) * sz;
  4772. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  4773. te[ 11 ] = 0;
  4774. te[ 12 ] = position.x;
  4775. te[ 13 ] = position.y;
  4776. te[ 14 ] = position.z;
  4777. te[ 15 ] = 1;
  4778. return this;
  4779. }
  4780. decompose( position, quaternion, scale ) {
  4781. const te = this.elements;
  4782. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  4783. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  4784. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  4785. // if determine is negative, we need to invert one scale
  4786. const det = this.determinant();
  4787. if ( det < 0 ) sx = - sx;
  4788. position.x = te[ 12 ];
  4789. position.y = te[ 13 ];
  4790. position.z = te[ 14 ];
  4791. // scale the rotation part
  4792. _m1$2.copy( this );
  4793. const invSX = 1 / sx;
  4794. const invSY = 1 / sy;
  4795. const invSZ = 1 / sz;
  4796. _m1$2.elements[ 0 ] *= invSX;
  4797. _m1$2.elements[ 1 ] *= invSX;
  4798. _m1$2.elements[ 2 ] *= invSX;
  4799. _m1$2.elements[ 4 ] *= invSY;
  4800. _m1$2.elements[ 5 ] *= invSY;
  4801. _m1$2.elements[ 6 ] *= invSY;
  4802. _m1$2.elements[ 8 ] *= invSZ;
  4803. _m1$2.elements[ 9 ] *= invSZ;
  4804. _m1$2.elements[ 10 ] *= invSZ;
  4805. quaternion.setFromRotationMatrix( _m1$2 );
  4806. scale.x = sx;
  4807. scale.y = sy;
  4808. scale.z = sz;
  4809. return this;
  4810. }
  4811. makePerspective( left, right, top, bottom, near, far ) {
  4812. if ( far === undefined ) {
  4813. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  4814. }
  4815. const te = this.elements;
  4816. const x = 2 * near / ( right - left );
  4817. const y = 2 * near / ( top - bottom );
  4818. const a = ( right + left ) / ( right - left );
  4819. const b = ( top + bottom ) / ( top - bottom );
  4820. const c = - ( far + near ) / ( far - near );
  4821. const d = - 2 * far * near / ( far - near );
  4822. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4823. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4824. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4825. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4826. return this;
  4827. }
  4828. makeOrthographic( left, right, top, bottom, near, far ) {
  4829. const te = this.elements;
  4830. const w = 1.0 / ( right - left );
  4831. const h = 1.0 / ( top - bottom );
  4832. const p = 1.0 / ( far - near );
  4833. const x = ( right + left ) * w;
  4834. const y = ( top + bottom ) * h;
  4835. const z = ( far + near ) * p;
  4836. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4837. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4838. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  4839. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4840. return this;
  4841. }
  4842. equals( matrix ) {
  4843. const te = this.elements;
  4844. const me = matrix.elements;
  4845. for ( let i = 0; i < 16; i ++ ) {
  4846. if ( te[ i ] !== me[ i ] ) return false;
  4847. }
  4848. return true;
  4849. }
  4850. fromArray( array, offset = 0 ) {
  4851. for ( let i = 0; i < 16; i ++ ) {
  4852. this.elements[ i ] = array[ i + offset ];
  4853. }
  4854. return this;
  4855. }
  4856. toArray( array = [], offset = 0 ) {
  4857. const te = this.elements;
  4858. array[ offset ] = te[ 0 ];
  4859. array[ offset + 1 ] = te[ 1 ];
  4860. array[ offset + 2 ] = te[ 2 ];
  4861. array[ offset + 3 ] = te[ 3 ];
  4862. array[ offset + 4 ] = te[ 4 ];
  4863. array[ offset + 5 ] = te[ 5 ];
  4864. array[ offset + 6 ] = te[ 6 ];
  4865. array[ offset + 7 ] = te[ 7 ];
  4866. array[ offset + 8 ] = te[ 8 ];
  4867. array[ offset + 9 ] = te[ 9 ];
  4868. array[ offset + 10 ] = te[ 10 ];
  4869. array[ offset + 11 ] = te[ 11 ];
  4870. array[ offset + 12 ] = te[ 12 ];
  4871. array[ offset + 13 ] = te[ 13 ];
  4872. array[ offset + 14 ] = te[ 14 ];
  4873. array[ offset + 15 ] = te[ 15 ];
  4874. return array;
  4875. }
  4876. }
  4877. Matrix4.prototype.isMatrix4 = true;
  4878. const _v1$5 = /*@__PURE__*/ new Vector3();
  4879. const _m1$2 = /*@__PURE__*/ new Matrix4();
  4880. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4881. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4882. const _x = /*@__PURE__*/ new Vector3();
  4883. const _y = /*@__PURE__*/ new Vector3();
  4884. const _z = /*@__PURE__*/ new Vector3();
  4885. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  4886. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4887. class Euler {
  4888. constructor( x = 0, y = 0, z = 0, order = Euler.DefaultOrder ) {
  4889. this._x = x;
  4890. this._y = y;
  4891. this._z = z;
  4892. this._order = order;
  4893. }
  4894. get x() {
  4895. return this._x;
  4896. }
  4897. set x( value ) {
  4898. this._x = value;
  4899. this._onChangeCallback();
  4900. }
  4901. get y() {
  4902. return this._y;
  4903. }
  4904. set y( value ) {
  4905. this._y = value;
  4906. this._onChangeCallback();
  4907. }
  4908. get z() {
  4909. return this._z;
  4910. }
  4911. set z( value ) {
  4912. this._z = value;
  4913. this._onChangeCallback();
  4914. }
  4915. get order() {
  4916. return this._order;
  4917. }
  4918. set order( value ) {
  4919. this._order = value;
  4920. this._onChangeCallback();
  4921. }
  4922. set( x, y, z, order = this._order ) {
  4923. this._x = x;
  4924. this._y = y;
  4925. this._z = z;
  4926. this._order = order;
  4927. this._onChangeCallback();
  4928. return this;
  4929. }
  4930. clone() {
  4931. return new this.constructor( this._x, this._y, this._z, this._order );
  4932. }
  4933. copy( euler ) {
  4934. this._x = euler._x;
  4935. this._y = euler._y;
  4936. this._z = euler._z;
  4937. this._order = euler._order;
  4938. this._onChangeCallback();
  4939. return this;
  4940. }
  4941. setFromRotationMatrix( m, order = this._order, update = true ) {
  4942. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4943. const te = m.elements;
  4944. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4945. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4946. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4947. switch ( order ) {
  4948. case 'XYZ':
  4949. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  4950. if ( Math.abs( m13 ) < 0.9999999 ) {
  4951. this._x = Math.atan2( - m23, m33 );
  4952. this._z = Math.atan2( - m12, m11 );
  4953. } else {
  4954. this._x = Math.atan2( m32, m22 );
  4955. this._z = 0;
  4956. }
  4957. break;
  4958. case 'YXZ':
  4959. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  4960. if ( Math.abs( m23 ) < 0.9999999 ) {
  4961. this._y = Math.atan2( m13, m33 );
  4962. this._z = Math.atan2( m21, m22 );
  4963. } else {
  4964. this._y = Math.atan2( - m31, m11 );
  4965. this._z = 0;
  4966. }
  4967. break;
  4968. case 'ZXY':
  4969. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  4970. if ( Math.abs( m32 ) < 0.9999999 ) {
  4971. this._y = Math.atan2( - m31, m33 );
  4972. this._z = Math.atan2( - m12, m22 );
  4973. } else {
  4974. this._y = 0;
  4975. this._z = Math.atan2( m21, m11 );
  4976. }
  4977. break;
  4978. case 'ZYX':
  4979. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  4980. if ( Math.abs( m31 ) < 0.9999999 ) {
  4981. this._x = Math.atan2( m32, m33 );
  4982. this._z = Math.atan2( m21, m11 );
  4983. } else {
  4984. this._x = 0;
  4985. this._z = Math.atan2( - m12, m22 );
  4986. }
  4987. break;
  4988. case 'YZX':
  4989. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  4990. if ( Math.abs( m21 ) < 0.9999999 ) {
  4991. this._x = Math.atan2( - m23, m22 );
  4992. this._y = Math.atan2( - m31, m11 );
  4993. } else {
  4994. this._x = 0;
  4995. this._y = Math.atan2( m13, m33 );
  4996. }
  4997. break;
  4998. case 'XZY':
  4999. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  5000. if ( Math.abs( m12 ) < 0.9999999 ) {
  5001. this._x = Math.atan2( m32, m22 );
  5002. this._y = Math.atan2( m13, m11 );
  5003. } else {
  5004. this._x = Math.atan2( - m23, m33 );
  5005. this._y = 0;
  5006. }
  5007. break;
  5008. default:
  5009. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  5010. }
  5011. this._order = order;
  5012. if ( update === true ) this._onChangeCallback();
  5013. return this;
  5014. }
  5015. setFromQuaternion( q, order, update ) {
  5016. _matrix$1.makeRotationFromQuaternion( q );
  5017. return this.setFromRotationMatrix( _matrix$1, order, update );
  5018. }
  5019. setFromVector3( v, order = this._order ) {
  5020. return this.set( v.x, v.y, v.z, order );
  5021. }
  5022. reorder( newOrder ) {
  5023. // WARNING: this discards revolution information -bhouston
  5024. _quaternion$3.setFromEuler( this );
  5025. return this.setFromQuaternion( _quaternion$3, newOrder );
  5026. }
  5027. equals( euler ) {
  5028. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  5029. }
  5030. fromArray( array ) {
  5031. this._x = array[ 0 ];
  5032. this._y = array[ 1 ];
  5033. this._z = array[ 2 ];
  5034. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  5035. this._onChangeCallback();
  5036. return this;
  5037. }
  5038. toArray( array = [], offset = 0 ) {
  5039. array[ offset ] = this._x;
  5040. array[ offset + 1 ] = this._y;
  5041. array[ offset + 2 ] = this._z;
  5042. array[ offset + 3 ] = this._order;
  5043. return array;
  5044. }
  5045. toVector3( optionalResult ) {
  5046. if ( optionalResult ) {
  5047. return optionalResult.set( this._x, this._y, this._z );
  5048. } else {
  5049. return new Vector3( this._x, this._y, this._z );
  5050. }
  5051. }
  5052. _onChange( callback ) {
  5053. this._onChangeCallback = callback;
  5054. return this;
  5055. }
  5056. _onChangeCallback() {}
  5057. }
  5058. Euler.prototype.isEuler = true;
  5059. Euler.DefaultOrder = 'XYZ';
  5060. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  5061. class Layers {
  5062. constructor() {
  5063. this.mask = 1 | 0;
  5064. }
  5065. set( channel ) {
  5066. this.mask = 1 << channel | 0;
  5067. }
  5068. enable( channel ) {
  5069. this.mask |= 1 << channel | 0;
  5070. }
  5071. enableAll() {
  5072. this.mask = 0xffffffff | 0;
  5073. }
  5074. toggle( channel ) {
  5075. this.mask ^= 1 << channel | 0;
  5076. }
  5077. disable( channel ) {
  5078. this.mask &= ~ ( 1 << channel | 0 );
  5079. }
  5080. disableAll() {
  5081. this.mask = 0;
  5082. }
  5083. test( layers ) {
  5084. return ( this.mask & layers.mask ) !== 0;
  5085. }
  5086. }
  5087. let _object3DId = 0;
  5088. const _v1$4 = /*@__PURE__*/ new Vector3();
  5089. const _q1 = /*@__PURE__*/ new Quaternion();
  5090. const _m1$1 = /*@__PURE__*/ new Matrix4();
  5091. const _target = /*@__PURE__*/ new Vector3();
  5092. const _position$3 = /*@__PURE__*/ new Vector3();
  5093. const _scale$2 = /*@__PURE__*/ new Vector3();
  5094. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  5095. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  5096. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  5097. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  5098. const _addedEvent = { type: 'added' };
  5099. const _removedEvent = { type: 'removed' };
  5100. class Object3D extends EventDispatcher {
  5101. constructor() {
  5102. super();
  5103. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  5104. this.uuid = generateUUID();
  5105. this.name = '';
  5106. this.type = 'Object3D';
  5107. this.parent = null;
  5108. this.children = [];
  5109. this.up = Object3D.DefaultUp.clone();
  5110. const position = new Vector3();
  5111. const rotation = new Euler();
  5112. const quaternion = new Quaternion();
  5113. const scale = new Vector3( 1, 1, 1 );
  5114. function onRotationChange() {
  5115. quaternion.setFromEuler( rotation, false );
  5116. }
  5117. function onQuaternionChange() {
  5118. rotation.setFromQuaternion( quaternion, undefined, false );
  5119. }
  5120. rotation._onChange( onRotationChange );
  5121. quaternion._onChange( onQuaternionChange );
  5122. Object.defineProperties( this, {
  5123. position: {
  5124. configurable: true,
  5125. enumerable: true,
  5126. value: position
  5127. },
  5128. rotation: {
  5129. configurable: true,
  5130. enumerable: true,
  5131. value: rotation
  5132. },
  5133. quaternion: {
  5134. configurable: true,
  5135. enumerable: true,
  5136. value: quaternion
  5137. },
  5138. scale: {
  5139. configurable: true,
  5140. enumerable: true,
  5141. value: scale
  5142. },
  5143. modelViewMatrix: {
  5144. value: new Matrix4()
  5145. },
  5146. normalMatrix: {
  5147. value: new Matrix3()
  5148. }
  5149. } );
  5150. this.matrix = new Matrix4();
  5151. this.matrixWorld = new Matrix4();
  5152. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  5153. this.matrixWorldNeedsUpdate = false;
  5154. this.layers = new Layers();
  5155. this.visible = true;
  5156. this.castShadow = false;
  5157. this.receiveShadow = false;
  5158. this.frustumCulled = true;
  5159. this.renderOrder = 0;
  5160. this.animations = [];
  5161. this.userData = {};
  5162. }
  5163. onBeforeRender() {}
  5164. onAfterRender() {}
  5165. applyMatrix4( matrix ) {
  5166. if ( this.matrixAutoUpdate ) this.updateMatrix();
  5167. this.matrix.premultiply( matrix );
  5168. this.matrix.decompose( this.position, this.quaternion, this.scale );
  5169. }
  5170. applyQuaternion( q ) {
  5171. this.quaternion.premultiply( q );
  5172. return this;
  5173. }
  5174. setRotationFromAxisAngle( axis, angle ) {
  5175. // assumes axis is normalized
  5176. this.quaternion.setFromAxisAngle( axis, angle );
  5177. }
  5178. setRotationFromEuler( euler ) {
  5179. this.quaternion.setFromEuler( euler, true );
  5180. }
  5181. setRotationFromMatrix( m ) {
  5182. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  5183. this.quaternion.setFromRotationMatrix( m );
  5184. }
  5185. setRotationFromQuaternion( q ) {
  5186. // assumes q is normalized
  5187. this.quaternion.copy( q );
  5188. }
  5189. rotateOnAxis( axis, angle ) {
  5190. // rotate object on axis in object space
  5191. // axis is assumed to be normalized
  5192. _q1.setFromAxisAngle( axis, angle );
  5193. this.quaternion.multiply( _q1 );
  5194. return this;
  5195. }
  5196. rotateOnWorldAxis( axis, angle ) {
  5197. // rotate object on axis in world space
  5198. // axis is assumed to be normalized
  5199. // method assumes no rotated parent
  5200. _q1.setFromAxisAngle( axis, angle );
  5201. this.quaternion.premultiply( _q1 );
  5202. return this;
  5203. }
  5204. rotateX( angle ) {
  5205. return this.rotateOnAxis( _xAxis, angle );
  5206. }
  5207. rotateY( angle ) {
  5208. return this.rotateOnAxis( _yAxis, angle );
  5209. }
  5210. rotateZ( angle ) {
  5211. return this.rotateOnAxis( _zAxis, angle );
  5212. }
  5213. translateOnAxis( axis, distance ) {
  5214. // translate object by distance along axis in object space
  5215. // axis is assumed to be normalized
  5216. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  5217. this.position.add( _v1$4.multiplyScalar( distance ) );
  5218. return this;
  5219. }
  5220. translateX( distance ) {
  5221. return this.translateOnAxis( _xAxis, distance );
  5222. }
  5223. translateY( distance ) {
  5224. return this.translateOnAxis( _yAxis, distance );
  5225. }
  5226. translateZ( distance ) {
  5227. return this.translateOnAxis( _zAxis, distance );
  5228. }
  5229. localToWorld( vector ) {
  5230. return vector.applyMatrix4( this.matrixWorld );
  5231. }
  5232. worldToLocal( vector ) {
  5233. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  5234. }
  5235. lookAt( x, y, z ) {
  5236. // This method does not support objects having non-uniformly-scaled parent(s)
  5237. if ( x.isVector3 ) {
  5238. _target.copy( x );
  5239. } else {
  5240. _target.set( x, y, z );
  5241. }
  5242. const parent = this.parent;
  5243. this.updateWorldMatrix( true, false );
  5244. _position$3.setFromMatrixPosition( this.matrixWorld );
  5245. if ( this.isCamera || this.isLight ) {
  5246. _m1$1.lookAt( _position$3, _target, this.up );
  5247. } else {
  5248. _m1$1.lookAt( _target, _position$3, this.up );
  5249. }
  5250. this.quaternion.setFromRotationMatrix( _m1$1 );
  5251. if ( parent ) {
  5252. _m1$1.extractRotation( parent.matrixWorld );
  5253. _q1.setFromRotationMatrix( _m1$1 );
  5254. this.quaternion.premultiply( _q1.invert() );
  5255. }
  5256. }
  5257. add( object ) {
  5258. if ( arguments.length > 1 ) {
  5259. for ( let i = 0; i < arguments.length; i ++ ) {
  5260. this.add( arguments[ i ] );
  5261. }
  5262. return this;
  5263. }
  5264. if ( object === this ) {
  5265. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  5266. return this;
  5267. }
  5268. if ( object && object.isObject3D ) {
  5269. if ( object.parent !== null ) {
  5270. object.parent.remove( object );
  5271. }
  5272. object.parent = this;
  5273. this.children.push( object );
  5274. object.dispatchEvent( _addedEvent );
  5275. } else {
  5276. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  5277. }
  5278. return this;
  5279. }
  5280. remove( object ) {
  5281. if ( arguments.length > 1 ) {
  5282. for ( let i = 0; i < arguments.length; i ++ ) {
  5283. this.remove( arguments[ i ] );
  5284. }
  5285. return this;
  5286. }
  5287. const index = this.children.indexOf( object );
  5288. if ( index !== - 1 ) {
  5289. object.parent = null;
  5290. this.children.splice( index, 1 );
  5291. object.dispatchEvent( _removedEvent );
  5292. }
  5293. return this;
  5294. }
  5295. removeFromParent() {
  5296. const parent = this.parent;
  5297. if ( parent !== null ) {
  5298. parent.remove( this );
  5299. }
  5300. return this;
  5301. }
  5302. clear() {
  5303. for ( let i = 0; i < this.children.length; i ++ ) {
  5304. const object = this.children[ i ];
  5305. object.parent = null;
  5306. object.dispatchEvent( _removedEvent );
  5307. }
  5308. this.children.length = 0;
  5309. return this;
  5310. }
  5311. attach( object ) {
  5312. // adds object as a child of this, while maintaining the object's world transform
  5313. this.updateWorldMatrix( true, false );
  5314. _m1$1.copy( this.matrixWorld ).invert();
  5315. if ( object.parent !== null ) {
  5316. object.parent.updateWorldMatrix( true, false );
  5317. _m1$1.multiply( object.parent.matrixWorld );
  5318. }
  5319. object.applyMatrix4( _m1$1 );
  5320. this.add( object );
  5321. object.updateWorldMatrix( false, true );
  5322. return this;
  5323. }
  5324. getObjectById( id ) {
  5325. return this.getObjectByProperty( 'id', id );
  5326. }
  5327. getObjectByName( name ) {
  5328. return this.getObjectByProperty( 'name', name );
  5329. }
  5330. getObjectByProperty( name, value ) {
  5331. if ( this[ name ] === value ) return this;
  5332. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  5333. const child = this.children[ i ];
  5334. const object = child.getObjectByProperty( name, value );
  5335. if ( object !== undefined ) {
  5336. return object;
  5337. }
  5338. }
  5339. return undefined;
  5340. }
  5341. getWorldPosition( target ) {
  5342. this.updateWorldMatrix( true, false );
  5343. return target.setFromMatrixPosition( this.matrixWorld );
  5344. }
  5345. getWorldQuaternion( target ) {
  5346. this.updateWorldMatrix( true, false );
  5347. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  5348. return target;
  5349. }
  5350. getWorldScale( target ) {
  5351. this.updateWorldMatrix( true, false );
  5352. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  5353. return target;
  5354. }
  5355. getWorldDirection( target ) {
  5356. this.updateWorldMatrix( true, false );
  5357. const e = this.matrixWorld.elements;
  5358. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  5359. }
  5360. raycast() {}
  5361. traverse( callback ) {
  5362. callback( this );
  5363. const children = this.children;
  5364. for ( let i = 0, l = children.length; i < l; i ++ ) {
  5365. children[ i ].traverse( callback );
  5366. }
  5367. }
  5368. traverseVisible( callback ) {
  5369. if ( this.visible === false ) return;
  5370. callback( this );
  5371. const children = this.children;
  5372. for ( let i = 0, l = children.length; i < l; i ++ ) {
  5373. children[ i ].traverseVisible( callback );
  5374. }
  5375. }
  5376. traverseAncestors( callback ) {
  5377. const parent = this.parent;
  5378. if ( parent !== null ) {
  5379. callback( parent );
  5380. parent.traverseAncestors( callback );
  5381. }
  5382. }
  5383. updateMatrix() {
  5384. this.matrix.compose( this.position, this.quaternion, this.scale );
  5385. this.matrixWorldNeedsUpdate = true;
  5386. }
  5387. updateMatrixWorld( force ) {
  5388. if ( this.matrixAutoUpdate ) this.updateMatrix();
  5389. if ( this.matrixWorldNeedsUpdate || force ) {
  5390. if ( this.parent === null ) {
  5391. this.matrixWorld.copy( this.matrix );
  5392. } else {
  5393. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  5394. }
  5395. this.matrixWorldNeedsUpdate = false;
  5396. force = true;
  5397. }
  5398. // update children
  5399. const children = this.children;
  5400. for ( let i = 0, l = children.length; i < l; i ++ ) {
  5401. children[ i ].updateMatrixWorld( force );
  5402. }
  5403. }
  5404. updateWorldMatrix( updateParents, updateChildren ) {
  5405. const parent = this.parent;
  5406. if ( updateParents === true && parent !== null ) {
  5407. parent.updateWorldMatrix( true, false );
  5408. }
  5409. if ( this.matrixAutoUpdate ) this.updateMatrix();
  5410. if ( this.parent === null ) {
  5411. this.matrixWorld.copy( this.matrix );
  5412. } else {
  5413. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  5414. }
  5415. // update children
  5416. if ( updateChildren === true ) {
  5417. const children = this.children;
  5418. for ( let i = 0, l = children.length; i < l; i ++ ) {
  5419. children[ i ].updateWorldMatrix( false, true );
  5420. }
  5421. }
  5422. }
  5423. toJSON( meta ) {
  5424. // meta is a string when called from JSON.stringify
  5425. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5426. const output = {};
  5427. // meta is a hash used to collect geometries, materials.
  5428. // not providing it implies that this is the root object
  5429. // being serialized.
  5430. if ( isRootObject ) {
  5431. // initialize meta obj
  5432. meta = {
  5433. geometries: {},
  5434. materials: {},
  5435. textures: {},
  5436. images: {},
  5437. shapes: {},
  5438. skeletons: {},
  5439. animations: {}
  5440. };
  5441. output.metadata = {
  5442. version: 4.5,
  5443. type: 'Object',
  5444. generator: 'Object3D.toJSON'
  5445. };
  5446. }
  5447. // standard Object3D serialization
  5448. const object = {};
  5449. object.uuid = this.uuid;
  5450. object.type = this.type;
  5451. if ( this.name !== '' ) object.name = this.name;
  5452. if ( this.castShadow === true ) object.castShadow = true;
  5453. if ( this.receiveShadow === true ) object.receiveShadow = true;
  5454. if ( this.visible === false ) object.visible = false;
  5455. if ( this.frustumCulled === false ) object.frustumCulled = false;
  5456. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  5457. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  5458. object.layers = this.layers.mask;
  5459. object.matrix = this.matrix.toArray();
  5460. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  5461. // object specific properties
  5462. if ( this.isInstancedMesh ) {
  5463. object.type = 'InstancedMesh';
  5464. object.count = this.count;
  5465. object.instanceMatrix = this.instanceMatrix.toJSON();
  5466. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  5467. }
  5468. //
  5469. function serialize( library, element ) {
  5470. if ( library[ element.uuid ] === undefined ) {
  5471. library[ element.uuid ] = element.toJSON( meta );
  5472. }
  5473. return element.uuid;
  5474. }
  5475. if ( this.isScene ) {
  5476. if ( this.background ) {
  5477. if ( this.background.isColor ) {
  5478. object.background = this.background.toJSON();
  5479. } else if ( this.background.isTexture ) {
  5480. object.background = this.background.toJSON( meta ).uuid;
  5481. }
  5482. }
  5483. if ( this.environment && this.environment.isTexture ) {
  5484. object.environment = this.environment.toJSON( meta ).uuid;
  5485. }
  5486. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  5487. object.geometry = serialize( meta.geometries, this.geometry );
  5488. const parameters = this.geometry.parameters;
  5489. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  5490. const shapes = parameters.shapes;
  5491. if ( Array.isArray( shapes ) ) {
  5492. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  5493. const shape = shapes[ i ];
  5494. serialize( meta.shapes, shape );
  5495. }
  5496. } else {
  5497. serialize( meta.shapes, shapes );
  5498. }
  5499. }
  5500. }
  5501. if ( this.isSkinnedMesh ) {
  5502. object.bindMode = this.bindMode;
  5503. object.bindMatrix = this.bindMatrix.toArray();
  5504. if ( this.skeleton !== undefined ) {
  5505. serialize( meta.skeletons, this.skeleton );
  5506. object.skeleton = this.skeleton.uuid;
  5507. }
  5508. }
  5509. if ( this.material !== undefined ) {
  5510. if ( Array.isArray( this.material ) ) {
  5511. const uuids = [];
  5512. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  5513. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  5514. }
  5515. object.material = uuids;
  5516. } else {
  5517. object.material = serialize( meta.materials, this.material );
  5518. }
  5519. }
  5520. //
  5521. if ( this.children.length > 0 ) {
  5522. object.children = [];
  5523. for ( let i = 0; i < this.children.length; i ++ ) {
  5524. object.children.push( this.children[ i ].toJSON( meta ).object );
  5525. }
  5526. }
  5527. //
  5528. if ( this.animations.length > 0 ) {
  5529. object.animations = [];
  5530. for ( let i = 0; i < this.animations.length; i ++ ) {
  5531. const animation = this.animations[ i ];
  5532. object.animations.push( serialize( meta.animations, animation ) );
  5533. }
  5534. }
  5535. if ( isRootObject ) {
  5536. const geometries = extractFromCache( meta.geometries );
  5537. const materials = extractFromCache( meta.materials );
  5538. const textures = extractFromCache( meta.textures );
  5539. const images = extractFromCache( meta.images );
  5540. const shapes = extractFromCache( meta.shapes );
  5541. const skeletons = extractFromCache( meta.skeletons );
  5542. const animations = extractFromCache( meta.animations );
  5543. if ( geometries.length > 0 ) output.geometries = geometries;
  5544. if ( materials.length > 0 ) output.materials = materials;
  5545. if ( textures.length > 0 ) output.textures = textures;
  5546. if ( images.length > 0 ) output.images = images;
  5547. if ( shapes.length > 0 ) output.shapes = shapes;
  5548. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  5549. if ( animations.length > 0 ) output.animations = animations;
  5550. }
  5551. output.object = object;
  5552. return output;
  5553. // extract data from the cache hash
  5554. // remove metadata on each item
  5555. // and return as array
  5556. function extractFromCache( cache ) {
  5557. const values = [];
  5558. for ( const key in cache ) {
  5559. const data = cache[ key ];
  5560. delete data.metadata;
  5561. values.push( data );
  5562. }
  5563. return values;
  5564. }
  5565. }
  5566. clone( recursive ) {
  5567. return new this.constructor().copy( this, recursive );
  5568. }
  5569. copy( source, recursive = true ) {
  5570. this.name = source.name;
  5571. this.up.copy( source.up );
  5572. this.position.copy( source.position );
  5573. this.rotation.order = source.rotation.order;
  5574. this.quaternion.copy( source.quaternion );
  5575. this.scale.copy( source.scale );
  5576. this.matrix.copy( source.matrix );
  5577. this.matrixWorld.copy( source.matrixWorld );
  5578. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5579. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5580. this.layers.mask = source.layers.mask;
  5581. this.visible = source.visible;
  5582. this.castShadow = source.castShadow;
  5583. this.receiveShadow = source.receiveShadow;
  5584. this.frustumCulled = source.frustumCulled;
  5585. this.renderOrder = source.renderOrder;
  5586. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5587. if ( recursive === true ) {
  5588. for ( let i = 0; i < source.children.length; i ++ ) {
  5589. const child = source.children[ i ];
  5590. this.add( child.clone() );
  5591. }
  5592. }
  5593. return this;
  5594. }
  5595. }
  5596. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  5597. Object3D.DefaultMatrixAutoUpdate = true;
  5598. Object3D.prototype.isObject3D = true;
  5599. const _v0$1 = /*@__PURE__*/ new Vector3();
  5600. const _v1$3 = /*@__PURE__*/ new Vector3();
  5601. const _v2$2 = /*@__PURE__*/ new Vector3();
  5602. const _v3$1 = /*@__PURE__*/ new Vector3();
  5603. const _vab = /*@__PURE__*/ new Vector3();
  5604. const _vac = /*@__PURE__*/ new Vector3();
  5605. const _vbc = /*@__PURE__*/ new Vector3();
  5606. const _vap = /*@__PURE__*/ new Vector3();
  5607. const _vbp = /*@__PURE__*/ new Vector3();
  5608. const _vcp = /*@__PURE__*/ new Vector3();
  5609. class Triangle {
  5610. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  5611. this.a = a;
  5612. this.b = b;
  5613. this.c = c;
  5614. }
  5615. static getNormal( a, b, c, target ) {
  5616. target.subVectors( c, b );
  5617. _v0$1.subVectors( a, b );
  5618. target.cross( _v0$1 );
  5619. const targetLengthSq = target.lengthSq();
  5620. if ( targetLengthSq > 0 ) {
  5621. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  5622. }
  5623. return target.set( 0, 0, 0 );
  5624. }
  5625. // static/instance method to calculate barycentric coordinates
  5626. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  5627. static getBarycoord( point, a, b, c, target ) {
  5628. _v0$1.subVectors( c, a );
  5629. _v1$3.subVectors( b, a );
  5630. _v2$2.subVectors( point, a );
  5631. const dot00 = _v0$1.dot( _v0$1 );
  5632. const dot01 = _v0$1.dot( _v1$3 );
  5633. const dot02 = _v0$1.dot( _v2$2 );
  5634. const dot11 = _v1$3.dot( _v1$3 );
  5635. const dot12 = _v1$3.dot( _v2$2 );
  5636. const denom = ( dot00 * dot11 - dot01 * dot01 );
  5637. // collinear or singular triangle
  5638. if ( denom === 0 ) {
  5639. // arbitrary location outside of triangle?
  5640. // not sure if this is the best idea, maybe should be returning undefined
  5641. return target.set( - 2, - 1, - 1 );
  5642. }
  5643. const invDenom = 1 / denom;
  5644. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  5645. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  5646. // barycentric coordinates must always sum to 1
  5647. return target.set( 1 - u - v, v, u );
  5648. }
  5649. static containsPoint( point, a, b, c ) {
  5650. this.getBarycoord( point, a, b, c, _v3$1 );
  5651. return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 );
  5652. }
  5653. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  5654. this.getBarycoord( point, p1, p2, p3, _v3$1 );
  5655. target.set( 0, 0 );
  5656. target.addScaledVector( uv1, _v3$1.x );
  5657. target.addScaledVector( uv2, _v3$1.y );
  5658. target.addScaledVector( uv3, _v3$1.z );
  5659. return target;
  5660. }
  5661. static isFrontFacing( a, b, c, direction ) {
  5662. _v0$1.subVectors( c, b );
  5663. _v1$3.subVectors( a, b );
  5664. // strictly front facing
  5665. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  5666. }
  5667. set( a, b, c ) {
  5668. this.a.copy( a );
  5669. this.b.copy( b );
  5670. this.c.copy( c );
  5671. return this;
  5672. }
  5673. setFromPointsAndIndices( points, i0, i1, i2 ) {
  5674. this.a.copy( points[ i0 ] );
  5675. this.b.copy( points[ i1 ] );
  5676. this.c.copy( points[ i2 ] );
  5677. return this;
  5678. }
  5679. clone() {
  5680. return new this.constructor().copy( this );
  5681. }
  5682. copy( triangle ) {
  5683. this.a.copy( triangle.a );
  5684. this.b.copy( triangle.b );
  5685. this.c.copy( triangle.c );
  5686. return this;
  5687. }
  5688. getArea() {
  5689. _v0$1.subVectors( this.c, this.b );
  5690. _v1$3.subVectors( this.a, this.b );
  5691. return _v0$1.cross( _v1$3 ).length() * 0.5;
  5692. }
  5693. getMidpoint( target ) {
  5694. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  5695. }
  5696. getNormal( target ) {
  5697. return Triangle.getNormal( this.a, this.b, this.c, target );
  5698. }
  5699. getPlane( target ) {
  5700. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  5701. }
  5702. getBarycoord( point, target ) {
  5703. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  5704. }
  5705. getUV( point, uv1, uv2, uv3, target ) {
  5706. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  5707. }
  5708. containsPoint( point ) {
  5709. return Triangle.containsPoint( point, this.a, this.b, this.c );
  5710. }
  5711. isFrontFacing( direction ) {
  5712. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  5713. }
  5714. intersectsBox( box ) {
  5715. return box.intersectsTriangle( this );
  5716. }
  5717. closestPointToPoint( p, target ) {
  5718. const a = this.a, b = this.b, c = this.c;
  5719. let v, w;
  5720. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5721. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5722. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5723. // basically, we're distinguishing which of the voronoi regions of the triangle
  5724. // the point lies in with the minimum amount of redundant computation.
  5725. _vab.subVectors( b, a );
  5726. _vac.subVectors( c, a );
  5727. _vap.subVectors( p, a );
  5728. const d1 = _vab.dot( _vap );
  5729. const d2 = _vac.dot( _vap );
  5730. if ( d1 <= 0 && d2 <= 0 ) {
  5731. // vertex region of A; barycentric coords (1, 0, 0)
  5732. return target.copy( a );
  5733. }
  5734. _vbp.subVectors( p, b );
  5735. const d3 = _vab.dot( _vbp );
  5736. const d4 = _vac.dot( _vbp );
  5737. if ( d3 >= 0 && d4 <= d3 ) {
  5738. // vertex region of B; barycentric coords (0, 1, 0)
  5739. return target.copy( b );
  5740. }
  5741. const vc = d1 * d4 - d3 * d2;
  5742. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5743. v = d1 / ( d1 - d3 );
  5744. // edge region of AB; barycentric coords (1-v, v, 0)
  5745. return target.copy( a ).addScaledVector( _vab, v );
  5746. }
  5747. _vcp.subVectors( p, c );
  5748. const d5 = _vab.dot( _vcp );
  5749. const d6 = _vac.dot( _vcp );
  5750. if ( d6 >= 0 && d5 <= d6 ) {
  5751. // vertex region of C; barycentric coords (0, 0, 1)
  5752. return target.copy( c );
  5753. }
  5754. const vb = d5 * d2 - d1 * d6;
  5755. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5756. w = d2 / ( d2 - d6 );
  5757. // edge region of AC; barycentric coords (1-w, 0, w)
  5758. return target.copy( a ).addScaledVector( _vac, w );
  5759. }
  5760. const va = d3 * d6 - d5 * d4;
  5761. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5762. _vbc.subVectors( c, b );
  5763. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5764. // edge region of BC; barycentric coords (0, 1-w, w)
  5765. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5766. }
  5767. // face region
  5768. const denom = 1 / ( va + vb + vc );
  5769. // u = va * denom
  5770. v = vb * denom;
  5771. w = vc * denom;
  5772. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5773. }
  5774. equals( triangle ) {
  5775. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5776. }
  5777. }
  5778. let materialId = 0;
  5779. class Material extends EventDispatcher {
  5780. constructor() {
  5781. super();
  5782. Object.defineProperty( this, 'id', { value: materialId ++ } );
  5783. this.uuid = generateUUID();
  5784. this.name = '';
  5785. this.type = 'Material';
  5786. this.fog = true;
  5787. this.blending = NormalBlending;
  5788. this.side = FrontSide;
  5789. this.vertexColors = false;
  5790. this.opacity = 1;
  5791. this.format = RGBAFormat;
  5792. this.transparent = false;
  5793. this.blendSrc = SrcAlphaFactor;
  5794. this.blendDst = OneMinusSrcAlphaFactor;
  5795. this.blendEquation = AddEquation;
  5796. this.blendSrcAlpha = null;
  5797. this.blendDstAlpha = null;
  5798. this.blendEquationAlpha = null;
  5799. this.depthFunc = LessEqualDepth;
  5800. this.depthTest = true;
  5801. this.depthWrite = true;
  5802. this.stencilWriteMask = 0xff;
  5803. this.stencilFunc = AlwaysStencilFunc;
  5804. this.stencilRef = 0;
  5805. this.stencilFuncMask = 0xff;
  5806. this.stencilFail = KeepStencilOp;
  5807. this.stencilZFail = KeepStencilOp;
  5808. this.stencilZPass = KeepStencilOp;
  5809. this.stencilWrite = false;
  5810. this.clippingPlanes = null;
  5811. this.clipIntersection = false;
  5812. this.clipShadows = false;
  5813. this.shadowSide = null;
  5814. this.colorWrite = true;
  5815. this.precision = null; // override the renderer's default precision for this material
  5816. this.polygonOffset = false;
  5817. this.polygonOffsetFactor = 0;
  5818. this.polygonOffsetUnits = 0;
  5819. this.dithering = false;
  5820. this.alphaToCoverage = false;
  5821. this.premultipliedAlpha = false;
  5822. this.visible = true;
  5823. this.toneMapped = true;
  5824. this.userData = {};
  5825. this.version = 0;
  5826. this._alphaTest = 0;
  5827. }
  5828. get alphaTest() {
  5829. return this._alphaTest;
  5830. }
  5831. set alphaTest( value ) {
  5832. if ( this._alphaTest > 0 !== value > 0 ) {
  5833. this.version ++;
  5834. }
  5835. this._alphaTest = value;
  5836. }
  5837. onBuild( /* shaderobject, renderer */ ) {}
  5838. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5839. customProgramCacheKey() {
  5840. return this.onBeforeCompile.toString();
  5841. }
  5842. setValues( values ) {
  5843. if ( values === undefined ) return;
  5844. for ( const key in values ) {
  5845. const newValue = values[ key ];
  5846. if ( newValue === undefined ) {
  5847. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  5848. continue;
  5849. }
  5850. // for backward compatability if shading is set in the constructor
  5851. if ( key === 'shading' ) {
  5852. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  5853. this.flatShading = ( newValue === FlatShading ) ? true : false;
  5854. continue;
  5855. }
  5856. const currentValue = this[ key ];
  5857. if ( currentValue === undefined ) {
  5858. console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' );
  5859. continue;
  5860. }
  5861. if ( currentValue && currentValue.isColor ) {
  5862. currentValue.set( newValue );
  5863. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5864. currentValue.copy( newValue );
  5865. } else {
  5866. this[ key ] = newValue;
  5867. }
  5868. }
  5869. }
  5870. toJSON( meta ) {
  5871. const isRoot = ( meta === undefined || typeof meta === 'string' );
  5872. if ( isRoot ) {
  5873. meta = {
  5874. textures: {},
  5875. images: {}
  5876. };
  5877. }
  5878. const data = {
  5879. metadata: {
  5880. version: 4.5,
  5881. type: 'Material',
  5882. generator: 'Material.toJSON'
  5883. }
  5884. };
  5885. // standard Material serialization
  5886. data.uuid = this.uuid;
  5887. data.type = this.type;
  5888. if ( this.name !== '' ) data.name = this.name;
  5889. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5890. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5891. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5892. if ( this.sheenTint && this.sheenTint.isColor ) data.sheenTint = this.sheenTint.getHex();
  5893. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5894. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5895. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5896. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5897. if ( this.specularTint && this.specularTint.isColor ) data.specularTint = this.specularTint.getHex();
  5898. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5899. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5900. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5901. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5902. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5903. }
  5904. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5905. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5906. }
  5907. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5908. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5909. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5910. }
  5911. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5912. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5913. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5914. if ( this.lightMap && this.lightMap.isTexture ) {
  5915. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5916. data.lightMapIntensity = this.lightMapIntensity;
  5917. }
  5918. if ( this.aoMap && this.aoMap.isTexture ) {
  5919. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5920. data.aoMapIntensity = this.aoMapIntensity;
  5921. }
  5922. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5923. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5924. data.bumpScale = this.bumpScale;
  5925. }
  5926. if ( this.normalMap && this.normalMap.isTexture ) {
  5927. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5928. data.normalMapType = this.normalMapType;
  5929. data.normalScale = this.normalScale.toArray();
  5930. }
  5931. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5932. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5933. data.displacementScale = this.displacementScale;
  5934. data.displacementBias = this.displacementBias;
  5935. }
  5936. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5937. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5938. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5939. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5940. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5941. if ( this.specularTintMap && this.specularTintMap.isTexture ) data.specularTintMap = this.specularTintMap.toJSON( meta ).uuid;
  5942. if ( this.envMap && this.envMap.isTexture ) {
  5943. data.envMap = this.envMap.toJSON( meta ).uuid;
  5944. if ( this.combine !== undefined ) data.combine = this.combine;
  5945. }
  5946. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5947. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5948. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5949. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5950. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5951. }
  5952. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5953. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5954. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5955. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5956. if ( this.attenuationDistance !== undefined ) data.attenuationDistance = this.attenuationDistance;
  5957. if ( this.attenuationTint !== undefined ) data.attenuationTint = this.attenuationTint.getHex();
  5958. if ( this.size !== undefined ) data.size = this.size;
  5959. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5960. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5961. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5962. if ( this.side !== FrontSide ) data.side = this.side;
  5963. if ( this.vertexColors ) data.vertexColors = true;
  5964. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5965. if ( this.format !== RGBAFormat ) data.format = this.format;
  5966. if ( this.transparent === true ) data.transparent = this.transparent;
  5967. data.depthFunc = this.depthFunc;
  5968. data.depthTest = this.depthTest;
  5969. data.depthWrite = this.depthWrite;
  5970. data.colorWrite = this.colorWrite;
  5971. data.stencilWrite = this.stencilWrite;
  5972. data.stencilWriteMask = this.stencilWriteMask;
  5973. data.stencilFunc = this.stencilFunc;
  5974. data.stencilRef = this.stencilRef;
  5975. data.stencilFuncMask = this.stencilFuncMask;
  5976. data.stencilFail = this.stencilFail;
  5977. data.stencilZFail = this.stencilZFail;
  5978. data.stencilZPass = this.stencilZPass;
  5979. // rotation (SpriteMaterial)
  5980. if ( this.rotation && this.rotation !== 0 ) data.rotation = this.rotation;
  5981. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5982. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5983. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5984. if ( this.linewidth && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5985. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5986. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5987. if ( this.scale !== undefined ) data.scale = this.scale;
  5988. if ( this.dithering === true ) data.dithering = true;
  5989. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5990. if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage;
  5991. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  5992. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  5993. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5994. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5995. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5996. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  5997. if ( this.visible === false ) data.visible = false;
  5998. if ( this.toneMapped === false ) data.toneMapped = false;
  5999. if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
  6000. // TODO: Copied from Object3D.toJSON
  6001. function extractFromCache( cache ) {
  6002. const values = [];
  6003. for ( const key in cache ) {
  6004. const data = cache[ key ];
  6005. delete data.metadata;
  6006. values.push( data );
  6007. }
  6008. return values;
  6009. }
  6010. if ( isRoot ) {
  6011. const textures = extractFromCache( meta.textures );
  6012. const images = extractFromCache( meta.images );
  6013. if ( textures.length > 0 ) data.textures = textures;
  6014. if ( images.length > 0 ) data.images = images;
  6015. }
  6016. return data;
  6017. }
  6018. clone() {
  6019. return new this.constructor().copy( this );
  6020. }
  6021. copy( source ) {
  6022. this.name = source.name;
  6023. this.fog = source.fog;
  6024. this.blending = source.blending;
  6025. this.side = source.side;
  6026. this.vertexColors = source.vertexColors;
  6027. this.opacity = source.opacity;
  6028. this.format = source.format;
  6029. this.transparent = source.transparent;
  6030. this.blendSrc = source.blendSrc;
  6031. this.blendDst = source.blendDst;
  6032. this.blendEquation = source.blendEquation;
  6033. this.blendSrcAlpha = source.blendSrcAlpha;
  6034. this.blendDstAlpha = source.blendDstAlpha;
  6035. this.blendEquationAlpha = source.blendEquationAlpha;
  6036. this.depthFunc = source.depthFunc;
  6037. this.depthTest = source.depthTest;
  6038. this.depthWrite = source.depthWrite;
  6039. this.stencilWriteMask = source.stencilWriteMask;
  6040. this.stencilFunc = source.stencilFunc;
  6041. this.stencilRef = source.stencilRef;
  6042. this.stencilFuncMask = source.stencilFuncMask;
  6043. this.stencilFail = source.stencilFail;
  6044. this.stencilZFail = source.stencilZFail;
  6045. this.stencilZPass = source.stencilZPass;
  6046. this.stencilWrite = source.stencilWrite;
  6047. const srcPlanes = source.clippingPlanes;
  6048. let dstPlanes = null;
  6049. if ( srcPlanes !== null ) {
  6050. const n = srcPlanes.length;
  6051. dstPlanes = new Array( n );
  6052. for ( let i = 0; i !== n; ++ i ) {
  6053. dstPlanes[ i ] = srcPlanes[ i ].clone();
  6054. }
  6055. }
  6056. this.clippingPlanes = dstPlanes;
  6057. this.clipIntersection = source.clipIntersection;
  6058. this.clipShadows = source.clipShadows;
  6059. this.shadowSide = source.shadowSide;
  6060. this.colorWrite = source.colorWrite;
  6061. this.precision = source.precision;
  6062. this.polygonOffset = source.polygonOffset;
  6063. this.polygonOffsetFactor = source.polygonOffsetFactor;
  6064. this.polygonOffsetUnits = source.polygonOffsetUnits;
  6065. this.dithering = source.dithering;
  6066. this.alphaTest = source.alphaTest;
  6067. this.alphaToCoverage = source.alphaToCoverage;
  6068. this.premultipliedAlpha = source.premultipliedAlpha;
  6069. this.visible = source.visible;
  6070. this.toneMapped = source.toneMapped;
  6071. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  6072. return this;
  6073. }
  6074. dispose() {
  6075. this.dispatchEvent( { type: 'dispose' } );
  6076. }
  6077. set needsUpdate( value ) {
  6078. if ( value === true ) this.version ++;
  6079. }
  6080. }
  6081. Material.prototype.isMaterial = true;
  6082. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  6083. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  6084. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  6085. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  6086. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  6087. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  6088. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  6089. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  6090. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  6091. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  6092. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  6093. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  6094. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  6095. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  6096. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  6097. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  6098. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  6099. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  6100. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  6101. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  6102. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  6103. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  6104. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  6105. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  6106. const _hslA = { h: 0, s: 0, l: 0 };
  6107. const _hslB = { h: 0, s: 0, l: 0 };
  6108. function hue2rgb( p, q, t ) {
  6109. if ( t < 0 ) t += 1;
  6110. if ( t > 1 ) t -= 1;
  6111. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  6112. if ( t < 1 / 2 ) return q;
  6113. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  6114. return p;
  6115. }
  6116. function SRGBToLinear( c ) {
  6117. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  6118. }
  6119. function LinearToSRGB( c ) {
  6120. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  6121. }
  6122. class Color {
  6123. constructor( r, g, b ) {
  6124. if ( g === undefined && b === undefined ) {
  6125. // r is THREE.Color, hex or string
  6126. return this.set( r );
  6127. }
  6128. return this.setRGB( r, g, b );
  6129. }
  6130. set( value ) {
  6131. if ( value && value.isColor ) {
  6132. this.copy( value );
  6133. } else if ( typeof value === 'number' ) {
  6134. this.setHex( value );
  6135. } else if ( typeof value === 'string' ) {
  6136. this.setStyle( value );
  6137. }
  6138. return this;
  6139. }
  6140. setScalar( scalar ) {
  6141. this.r = scalar;
  6142. this.g = scalar;
  6143. this.b = scalar;
  6144. return this;
  6145. }
  6146. setHex( hex ) {
  6147. hex = Math.floor( hex );
  6148. this.r = ( hex >> 16 & 255 ) / 255;
  6149. this.g = ( hex >> 8 & 255 ) / 255;
  6150. this.b = ( hex & 255 ) / 255;
  6151. return this;
  6152. }
  6153. setRGB( r, g, b ) {
  6154. this.r = r;
  6155. this.g = g;
  6156. this.b = b;
  6157. return this;
  6158. }
  6159. setHSL( h, s, l ) {
  6160. // h,s,l ranges are in 0.0 - 1.0
  6161. h = euclideanModulo( h, 1 );
  6162. s = clamp( s, 0, 1 );
  6163. l = clamp( l, 0, 1 );
  6164. if ( s === 0 ) {
  6165. this.r = this.g = this.b = l;
  6166. } else {
  6167. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  6168. const q = ( 2 * l ) - p;
  6169. this.r = hue2rgb( q, p, h + 1 / 3 );
  6170. this.g = hue2rgb( q, p, h );
  6171. this.b = hue2rgb( q, p, h - 1 / 3 );
  6172. }
  6173. return this;
  6174. }
  6175. setStyle( style ) {
  6176. function handleAlpha( string ) {
  6177. if ( string === undefined ) return;
  6178. if ( parseFloat( string ) < 1 ) {
  6179. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  6180. }
  6181. }
  6182. let m;
  6183. if ( m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec( style ) ) {
  6184. // rgb / hsl
  6185. let color;
  6186. const name = m[ 1 ];
  6187. const components = m[ 2 ];
  6188. switch ( name ) {
  6189. case 'rgb':
  6190. case 'rgba':
  6191. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  6192. // rgb(255,0,0) rgba(255,0,0,0.5)
  6193. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  6194. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  6195. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  6196. handleAlpha( color[ 4 ] );
  6197. return this;
  6198. }
  6199. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  6200. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  6201. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  6202. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  6203. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  6204. handleAlpha( color[ 4 ] );
  6205. return this;
  6206. }
  6207. break;
  6208. case 'hsl':
  6209. case 'hsla':
  6210. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  6211. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  6212. const h = parseFloat( color[ 1 ] ) / 360;
  6213. const s = parseInt( color[ 2 ], 10 ) / 100;
  6214. const l = parseInt( color[ 3 ], 10 ) / 100;
  6215. handleAlpha( color[ 4 ] );
  6216. return this.setHSL( h, s, l );
  6217. }
  6218. break;
  6219. }
  6220. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  6221. // hex color
  6222. const hex = m[ 1 ];
  6223. const size = hex.length;
  6224. if ( size === 3 ) {
  6225. // #ff0
  6226. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  6227. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  6228. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  6229. return this;
  6230. } else if ( size === 6 ) {
  6231. // #ff0000
  6232. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  6233. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  6234. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  6235. return this;
  6236. }
  6237. }
  6238. if ( style && style.length > 0 ) {
  6239. return this.setColorName( style );
  6240. }
  6241. return this;
  6242. }
  6243. setColorName( style ) {
  6244. // color keywords
  6245. const hex = _colorKeywords[ style.toLowerCase() ];
  6246. if ( hex !== undefined ) {
  6247. // red
  6248. this.setHex( hex );
  6249. } else {
  6250. // unknown color
  6251. console.warn( 'THREE.Color: Unknown color ' + style );
  6252. }
  6253. return this;
  6254. }
  6255. clone() {
  6256. return new this.constructor( this.r, this.g, this.b );
  6257. }
  6258. copy( color ) {
  6259. this.r = color.r;
  6260. this.g = color.g;
  6261. this.b = color.b;
  6262. return this;
  6263. }
  6264. copyGammaToLinear( color, gammaFactor = 2.0 ) {
  6265. this.r = Math.pow( color.r, gammaFactor );
  6266. this.g = Math.pow( color.g, gammaFactor );
  6267. this.b = Math.pow( color.b, gammaFactor );
  6268. return this;
  6269. }
  6270. copyLinearToGamma( color, gammaFactor = 2.0 ) {
  6271. const safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  6272. this.r = Math.pow( color.r, safeInverse );
  6273. this.g = Math.pow( color.g, safeInverse );
  6274. this.b = Math.pow( color.b, safeInverse );
  6275. return this;
  6276. }
  6277. convertGammaToLinear( gammaFactor ) {
  6278. this.copyGammaToLinear( this, gammaFactor );
  6279. return this;
  6280. }
  6281. convertLinearToGamma( gammaFactor ) {
  6282. this.copyLinearToGamma( this, gammaFactor );
  6283. return this;
  6284. }
  6285. copySRGBToLinear( color ) {
  6286. this.r = SRGBToLinear( color.r );
  6287. this.g = SRGBToLinear( color.g );
  6288. this.b = SRGBToLinear( color.b );
  6289. return this;
  6290. }
  6291. copyLinearToSRGB( color ) {
  6292. this.r = LinearToSRGB( color.r );
  6293. this.g = LinearToSRGB( color.g );
  6294. this.b = LinearToSRGB( color.b );
  6295. return this;
  6296. }
  6297. convertSRGBToLinear() {
  6298. this.copySRGBToLinear( this );
  6299. return this;
  6300. }
  6301. convertLinearToSRGB() {
  6302. this.copyLinearToSRGB( this );
  6303. return this;
  6304. }
  6305. getHex() {
  6306. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  6307. }
  6308. getHexString() {
  6309. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  6310. }
  6311. getHSL( target ) {
  6312. // h,s,l ranges are in 0.0 - 1.0
  6313. const r = this.r, g = this.g, b = this.b;
  6314. const max = Math.max( r, g, b );
  6315. const min = Math.min( r, g, b );
  6316. let hue, saturation;
  6317. const lightness = ( min + max ) / 2.0;
  6318. if ( min === max ) {
  6319. hue = 0;
  6320. saturation = 0;
  6321. } else {
  6322. const delta = max - min;
  6323. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  6324. switch ( max ) {
  6325. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  6326. case g: hue = ( b - r ) / delta + 2; break;
  6327. case b: hue = ( r - g ) / delta + 4; break;
  6328. }
  6329. hue /= 6;
  6330. }
  6331. target.h = hue;
  6332. target.s = saturation;
  6333. target.l = lightness;
  6334. return target;
  6335. }
  6336. getStyle() {
  6337. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  6338. }
  6339. offsetHSL( h, s, l ) {
  6340. this.getHSL( _hslA );
  6341. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  6342. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  6343. return this;
  6344. }
  6345. add( color ) {
  6346. this.r += color.r;
  6347. this.g += color.g;
  6348. this.b += color.b;
  6349. return this;
  6350. }
  6351. addColors( color1, color2 ) {
  6352. this.r = color1.r + color2.r;
  6353. this.g = color1.g + color2.g;
  6354. this.b = color1.b + color2.b;
  6355. return this;
  6356. }
  6357. addScalar( s ) {
  6358. this.r += s;
  6359. this.g += s;
  6360. this.b += s;
  6361. return this;
  6362. }
  6363. sub( color ) {
  6364. this.r = Math.max( 0, this.r - color.r );
  6365. this.g = Math.max( 0, this.g - color.g );
  6366. this.b = Math.max( 0, this.b - color.b );
  6367. return this;
  6368. }
  6369. multiply( color ) {
  6370. this.r *= color.r;
  6371. this.g *= color.g;
  6372. this.b *= color.b;
  6373. return this;
  6374. }
  6375. multiplyScalar( s ) {
  6376. this.r *= s;
  6377. this.g *= s;
  6378. this.b *= s;
  6379. return this;
  6380. }
  6381. lerp( color, alpha ) {
  6382. this.r += ( color.r - this.r ) * alpha;
  6383. this.g += ( color.g - this.g ) * alpha;
  6384. this.b += ( color.b - this.b ) * alpha;
  6385. return this;
  6386. }
  6387. lerpColors( color1, color2, alpha ) {
  6388. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  6389. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  6390. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  6391. return this;
  6392. }
  6393. lerpHSL( color, alpha ) {
  6394. this.getHSL( _hslA );
  6395. color.getHSL( _hslB );
  6396. const h = lerp( _hslA.h, _hslB.h, alpha );
  6397. const s = lerp( _hslA.s, _hslB.s, alpha );
  6398. const l = lerp( _hslA.l, _hslB.l, alpha );
  6399. this.setHSL( h, s, l );
  6400. return this;
  6401. }
  6402. equals( c ) {
  6403. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  6404. }
  6405. fromArray( array, offset = 0 ) {
  6406. this.r = array[ offset ];
  6407. this.g = array[ offset + 1 ];
  6408. this.b = array[ offset + 2 ];
  6409. return this;
  6410. }
  6411. toArray( array = [], offset = 0 ) {
  6412. array[ offset ] = this.r;
  6413. array[ offset + 1 ] = this.g;
  6414. array[ offset + 2 ] = this.b;
  6415. return array;
  6416. }
  6417. fromBufferAttribute( attribute, index ) {
  6418. this.r = attribute.getX( index );
  6419. this.g = attribute.getY( index );
  6420. this.b = attribute.getZ( index );
  6421. if ( attribute.normalized === true ) {
  6422. // assuming Uint8Array
  6423. this.r /= 255;
  6424. this.g /= 255;
  6425. this.b /= 255;
  6426. }
  6427. return this;
  6428. }
  6429. toJSON() {
  6430. return this.getHex();
  6431. }
  6432. }
  6433. Color.NAMES = _colorKeywords;
  6434. Color.prototype.isColor = true;
  6435. Color.prototype.r = 1;
  6436. Color.prototype.g = 1;
  6437. Color.prototype.b = 1;
  6438. /**
  6439. * parameters = {
  6440. * color: <hex>,
  6441. * opacity: <float>,
  6442. * map: new THREE.Texture( <Image> ),
  6443. *
  6444. * lightMap: new THREE.Texture( <Image> ),
  6445. * lightMapIntensity: <float>
  6446. *
  6447. * aoMap: new THREE.Texture( <Image> ),
  6448. * aoMapIntensity: <float>
  6449. *
  6450. * specularMap: new THREE.Texture( <Image> ),
  6451. *
  6452. * alphaMap: new THREE.Texture( <Image> ),
  6453. *
  6454. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  6455. * combine: THREE.Multiply,
  6456. * reflectivity: <float>,
  6457. * refractionRatio: <float>,
  6458. *
  6459. * depthTest: <bool>,
  6460. * depthWrite: <bool>,
  6461. *
  6462. * wireframe: <boolean>,
  6463. * wireframeLinewidth: <float>,
  6464. * }
  6465. */
  6466. class MeshBasicMaterial extends Material {
  6467. constructor( parameters ) {
  6468. super();
  6469. this.type = 'MeshBasicMaterial';
  6470. this.color = new Color( 0xffffff ); // emissive
  6471. this.map = null;
  6472. this.lightMap = null;
  6473. this.lightMapIntensity = 1.0;
  6474. this.aoMap = null;
  6475. this.aoMapIntensity = 1.0;
  6476. this.specularMap = null;
  6477. this.alphaMap = null;
  6478. this.envMap = null;
  6479. this.combine = MultiplyOperation;
  6480. this.reflectivity = 1;
  6481. this.refractionRatio = 0.98;
  6482. this.wireframe = false;
  6483. this.wireframeLinewidth = 1;
  6484. this.wireframeLinecap = 'round';
  6485. this.wireframeLinejoin = 'round';
  6486. this.setValues( parameters );
  6487. }
  6488. copy( source ) {
  6489. super.copy( source );
  6490. this.color.copy( source.color );
  6491. this.map = source.map;
  6492. this.lightMap = source.lightMap;
  6493. this.lightMapIntensity = source.lightMapIntensity;
  6494. this.aoMap = source.aoMap;
  6495. this.aoMapIntensity = source.aoMapIntensity;
  6496. this.specularMap = source.specularMap;
  6497. this.alphaMap = source.alphaMap;
  6498. this.envMap = source.envMap;
  6499. this.combine = source.combine;
  6500. this.reflectivity = source.reflectivity;
  6501. this.refractionRatio = source.refractionRatio;
  6502. this.wireframe = source.wireframe;
  6503. this.wireframeLinewidth = source.wireframeLinewidth;
  6504. this.wireframeLinecap = source.wireframeLinecap;
  6505. this.wireframeLinejoin = source.wireframeLinejoin;
  6506. return this;
  6507. }
  6508. }
  6509. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  6510. const _vector$9 = /*@__PURE__*/ new Vector3();
  6511. const _vector2$1 = /*@__PURE__*/ new Vector2();
  6512. class BufferAttribute {
  6513. constructor( array, itemSize, normalized ) {
  6514. if ( Array.isArray( array ) ) {
  6515. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  6516. }
  6517. this.name = '';
  6518. this.array = array;
  6519. this.itemSize = itemSize;
  6520. this.count = array !== undefined ? array.length / itemSize : 0;
  6521. this.normalized = normalized === true;
  6522. this.usage = StaticDrawUsage;
  6523. this.updateRange = { offset: 0, count: - 1 };
  6524. this.version = 0;
  6525. }
  6526. onUploadCallback() {}
  6527. set needsUpdate( value ) {
  6528. if ( value === true ) this.version ++;
  6529. }
  6530. setUsage( value ) {
  6531. this.usage = value;
  6532. return this;
  6533. }
  6534. copy( source ) {
  6535. this.name = source.name;
  6536. this.array = new source.array.constructor( source.array );
  6537. this.itemSize = source.itemSize;
  6538. this.count = source.count;
  6539. this.normalized = source.normalized;
  6540. this.usage = source.usage;
  6541. return this;
  6542. }
  6543. copyAt( index1, attribute, index2 ) {
  6544. index1 *= this.itemSize;
  6545. index2 *= attribute.itemSize;
  6546. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  6547. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  6548. }
  6549. return this;
  6550. }
  6551. copyArray( array ) {
  6552. this.array.set( array );
  6553. return this;
  6554. }
  6555. copyColorsArray( colors ) {
  6556. const array = this.array;
  6557. let offset = 0;
  6558. for ( let i = 0, l = colors.length; i < l; i ++ ) {
  6559. let color = colors[ i ];
  6560. if ( color === undefined ) {
  6561. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  6562. color = new Color();
  6563. }
  6564. array[ offset ++ ] = color.r;
  6565. array[ offset ++ ] = color.g;
  6566. array[ offset ++ ] = color.b;
  6567. }
  6568. return this;
  6569. }
  6570. copyVector2sArray( vectors ) {
  6571. const array = this.array;
  6572. let offset = 0;
  6573. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  6574. let vector = vectors[ i ];
  6575. if ( vector === undefined ) {
  6576. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  6577. vector = new Vector2();
  6578. }
  6579. array[ offset ++ ] = vector.x;
  6580. array[ offset ++ ] = vector.y;
  6581. }
  6582. return this;
  6583. }
  6584. copyVector3sArray( vectors ) {
  6585. const array = this.array;
  6586. let offset = 0;
  6587. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  6588. let vector = vectors[ i ];
  6589. if ( vector === undefined ) {
  6590. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  6591. vector = new Vector3();
  6592. }
  6593. array[ offset ++ ] = vector.x;
  6594. array[ offset ++ ] = vector.y;
  6595. array[ offset ++ ] = vector.z;
  6596. }
  6597. return this;
  6598. }
  6599. copyVector4sArray( vectors ) {
  6600. const array = this.array;
  6601. let offset = 0;
  6602. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  6603. let vector = vectors[ i ];
  6604. if ( vector === undefined ) {
  6605. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  6606. vector = new Vector4();
  6607. }
  6608. array[ offset ++ ] = vector.x;
  6609. array[ offset ++ ] = vector.y;
  6610. array[ offset ++ ] = vector.z;
  6611. array[ offset ++ ] = vector.w;
  6612. }
  6613. return this;
  6614. }
  6615. applyMatrix3( m ) {
  6616. if ( this.itemSize === 2 ) {
  6617. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6618. _vector2$1.fromBufferAttribute( this, i );
  6619. _vector2$1.applyMatrix3( m );
  6620. this.setXY( i, _vector2$1.x, _vector2$1.y );
  6621. }
  6622. } else if ( this.itemSize === 3 ) {
  6623. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6624. _vector$9.fromBufferAttribute( this, i );
  6625. _vector$9.applyMatrix3( m );
  6626. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6627. }
  6628. }
  6629. return this;
  6630. }
  6631. applyMatrix4( m ) {
  6632. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6633. _vector$9.x = this.getX( i );
  6634. _vector$9.y = this.getY( i );
  6635. _vector$9.z = this.getZ( i );
  6636. _vector$9.applyMatrix4( m );
  6637. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6638. }
  6639. return this;
  6640. }
  6641. applyNormalMatrix( m ) {
  6642. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6643. _vector$9.x = this.getX( i );
  6644. _vector$9.y = this.getY( i );
  6645. _vector$9.z = this.getZ( i );
  6646. _vector$9.applyNormalMatrix( m );
  6647. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6648. }
  6649. return this;
  6650. }
  6651. transformDirection( m ) {
  6652. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6653. _vector$9.x = this.getX( i );
  6654. _vector$9.y = this.getY( i );
  6655. _vector$9.z = this.getZ( i );
  6656. _vector$9.transformDirection( m );
  6657. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6658. }
  6659. return this;
  6660. }
  6661. set( value, offset = 0 ) {
  6662. this.array.set( value, offset );
  6663. return this;
  6664. }
  6665. getX( index ) {
  6666. return this.array[ index * this.itemSize ];
  6667. }
  6668. setX( index, x ) {
  6669. this.array[ index * this.itemSize ] = x;
  6670. return this;
  6671. }
  6672. getY( index ) {
  6673. return this.array[ index * this.itemSize + 1 ];
  6674. }
  6675. setY( index, y ) {
  6676. this.array[ index * this.itemSize + 1 ] = y;
  6677. return this;
  6678. }
  6679. getZ( index ) {
  6680. return this.array[ index * this.itemSize + 2 ];
  6681. }
  6682. setZ( index, z ) {
  6683. this.array[ index * this.itemSize + 2 ] = z;
  6684. return this;
  6685. }
  6686. getW( index ) {
  6687. return this.array[ index * this.itemSize + 3 ];
  6688. }
  6689. setW( index, w ) {
  6690. this.array[ index * this.itemSize + 3 ] = w;
  6691. return this;
  6692. }
  6693. setXY( index, x, y ) {
  6694. index *= this.itemSize;
  6695. this.array[ index + 0 ] = x;
  6696. this.array[ index + 1 ] = y;
  6697. return this;
  6698. }
  6699. setXYZ( index, x, y, z ) {
  6700. index *= this.itemSize;
  6701. this.array[ index + 0 ] = x;
  6702. this.array[ index + 1 ] = y;
  6703. this.array[ index + 2 ] = z;
  6704. return this;
  6705. }
  6706. setXYZW( index, x, y, z, w ) {
  6707. index *= this.itemSize;
  6708. this.array[ index + 0 ] = x;
  6709. this.array[ index + 1 ] = y;
  6710. this.array[ index + 2 ] = z;
  6711. this.array[ index + 3 ] = w;
  6712. return this;
  6713. }
  6714. onUpload( callback ) {
  6715. this.onUploadCallback = callback;
  6716. return this;
  6717. }
  6718. clone() {
  6719. return new this.constructor( this.array, this.itemSize ).copy( this );
  6720. }
  6721. toJSON() {
  6722. const data = {
  6723. itemSize: this.itemSize,
  6724. type: this.array.constructor.name,
  6725. array: Array.prototype.slice.call( this.array ),
  6726. normalized: this.normalized
  6727. };
  6728. if ( this.name !== '' ) data.name = this.name;
  6729. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  6730. if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange;
  6731. return data;
  6732. }
  6733. }
  6734. BufferAttribute.prototype.isBufferAttribute = true;
  6735. //
  6736. class Int8BufferAttribute extends BufferAttribute {
  6737. constructor( array, itemSize, normalized ) {
  6738. super( new Int8Array( array ), itemSize, normalized );
  6739. }
  6740. }
  6741. class Uint8BufferAttribute extends BufferAttribute {
  6742. constructor( array, itemSize, normalized ) {
  6743. super( new Uint8Array( array ), itemSize, normalized );
  6744. }
  6745. }
  6746. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6747. constructor( array, itemSize, normalized ) {
  6748. super( new Uint8ClampedArray( array ), itemSize, normalized );
  6749. }
  6750. }
  6751. class Int16BufferAttribute extends BufferAttribute {
  6752. constructor( array, itemSize, normalized ) {
  6753. super( new Int16Array( array ), itemSize, normalized );
  6754. }
  6755. }
  6756. class Uint16BufferAttribute extends BufferAttribute {
  6757. constructor( array, itemSize, normalized ) {
  6758. super( new Uint16Array( array ), itemSize, normalized );
  6759. }
  6760. }
  6761. class Int32BufferAttribute extends BufferAttribute {
  6762. constructor( array, itemSize, normalized ) {
  6763. super( new Int32Array( array ), itemSize, normalized );
  6764. }
  6765. }
  6766. class Uint32BufferAttribute extends BufferAttribute {
  6767. constructor( array, itemSize, normalized ) {
  6768. super( new Uint32Array( array ), itemSize, normalized );
  6769. }
  6770. }
  6771. class Float16BufferAttribute extends BufferAttribute {
  6772. constructor( array, itemSize, normalized ) {
  6773. super( new Uint16Array( array ), itemSize, normalized );
  6774. }
  6775. }
  6776. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  6777. class Float32BufferAttribute extends BufferAttribute {
  6778. constructor( array, itemSize, normalized ) {
  6779. super( new Float32Array( array ), itemSize, normalized );
  6780. }
  6781. }
  6782. class Float64BufferAttribute extends BufferAttribute {
  6783. constructor( array, itemSize, normalized ) {
  6784. super( new Float64Array( array ), itemSize, normalized );
  6785. }
  6786. }
  6787. function arrayMax( array ) {
  6788. if ( array.length === 0 ) return - Infinity;
  6789. let max = array[ 0 ];
  6790. for ( let i = 1, l = array.length; i < l; ++ i ) {
  6791. if ( array[ i ] > max ) max = array[ i ];
  6792. }
  6793. return max;
  6794. }
  6795. const TYPED_ARRAYS = {
  6796. Int8Array: Int8Array,
  6797. Uint8Array: Uint8Array,
  6798. Uint8ClampedArray: Uint8ClampedArray,
  6799. Int16Array: Int16Array,
  6800. Uint16Array: Uint16Array,
  6801. Int32Array: Int32Array,
  6802. Uint32Array: Uint32Array,
  6803. Float32Array: Float32Array,
  6804. Float64Array: Float64Array
  6805. };
  6806. function getTypedArray( type, buffer ) {
  6807. return new TYPED_ARRAYS[ type ]( buffer );
  6808. }
  6809. let _id = 0;
  6810. const _m1 = /*@__PURE__*/ new Matrix4();
  6811. const _obj = /*@__PURE__*/ new Object3D();
  6812. const _offset = /*@__PURE__*/ new Vector3();
  6813. const _box$1 = /*@__PURE__*/ new Box3();
  6814. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  6815. const _vector$8 = /*@__PURE__*/ new Vector3();
  6816. class BufferGeometry extends EventDispatcher {
  6817. constructor() {
  6818. super();
  6819. Object.defineProperty( this, 'id', { value: _id ++ } );
  6820. this.uuid = generateUUID();
  6821. this.name = '';
  6822. this.type = 'BufferGeometry';
  6823. this.index = null;
  6824. this.attributes = {};
  6825. this.morphAttributes = {};
  6826. this.morphTargetsRelative = false;
  6827. this.groups = [];
  6828. this.boundingBox = null;
  6829. this.boundingSphere = null;
  6830. this.drawRange = { start: 0, count: Infinity };
  6831. this.userData = {};
  6832. }
  6833. getIndex() {
  6834. return this.index;
  6835. }
  6836. setIndex( index ) {
  6837. if ( Array.isArray( index ) ) {
  6838. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6839. } else {
  6840. this.index = index;
  6841. }
  6842. return this;
  6843. }
  6844. getAttribute( name ) {
  6845. return this.attributes[ name ];
  6846. }
  6847. setAttribute( name, attribute ) {
  6848. this.attributes[ name ] = attribute;
  6849. return this;
  6850. }
  6851. deleteAttribute( name ) {
  6852. delete this.attributes[ name ];
  6853. return this;
  6854. }
  6855. hasAttribute( name ) {
  6856. return this.attributes[ name ] !== undefined;
  6857. }
  6858. addGroup( start, count, materialIndex = 0 ) {
  6859. this.groups.push( {
  6860. start: start,
  6861. count: count,
  6862. materialIndex: materialIndex
  6863. } );
  6864. }
  6865. clearGroups() {
  6866. this.groups = [];
  6867. }
  6868. setDrawRange( start, count ) {
  6869. this.drawRange.start = start;
  6870. this.drawRange.count = count;
  6871. }
  6872. applyMatrix4( matrix ) {
  6873. const position = this.attributes.position;
  6874. if ( position !== undefined ) {
  6875. position.applyMatrix4( matrix );
  6876. position.needsUpdate = true;
  6877. }
  6878. const normal = this.attributes.normal;
  6879. if ( normal !== undefined ) {
  6880. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6881. normal.applyNormalMatrix( normalMatrix );
  6882. normal.needsUpdate = true;
  6883. }
  6884. const tangent = this.attributes.tangent;
  6885. if ( tangent !== undefined ) {
  6886. tangent.transformDirection( matrix );
  6887. tangent.needsUpdate = true;
  6888. }
  6889. if ( this.boundingBox !== null ) {
  6890. this.computeBoundingBox();
  6891. }
  6892. if ( this.boundingSphere !== null ) {
  6893. this.computeBoundingSphere();
  6894. }
  6895. return this;
  6896. }
  6897. applyQuaternion( q ) {
  6898. _m1.makeRotationFromQuaternion( q );
  6899. this.applyMatrix4( _m1 );
  6900. return this;
  6901. }
  6902. rotateX( angle ) {
  6903. // rotate geometry around world x-axis
  6904. _m1.makeRotationX( angle );
  6905. this.applyMatrix4( _m1 );
  6906. return this;
  6907. }
  6908. rotateY( angle ) {
  6909. // rotate geometry around world y-axis
  6910. _m1.makeRotationY( angle );
  6911. this.applyMatrix4( _m1 );
  6912. return this;
  6913. }
  6914. rotateZ( angle ) {
  6915. // rotate geometry around world z-axis
  6916. _m1.makeRotationZ( angle );
  6917. this.applyMatrix4( _m1 );
  6918. return this;
  6919. }
  6920. translate( x, y, z ) {
  6921. // translate geometry
  6922. _m1.makeTranslation( x, y, z );
  6923. this.applyMatrix4( _m1 );
  6924. return this;
  6925. }
  6926. scale( x, y, z ) {
  6927. // scale geometry
  6928. _m1.makeScale( x, y, z );
  6929. this.applyMatrix4( _m1 );
  6930. return this;
  6931. }
  6932. lookAt( vector ) {
  6933. _obj.lookAt( vector );
  6934. _obj.updateMatrix();
  6935. this.applyMatrix4( _obj.matrix );
  6936. return this;
  6937. }
  6938. center() {
  6939. this.computeBoundingBox();
  6940. this.boundingBox.getCenter( _offset ).negate();
  6941. this.translate( _offset.x, _offset.y, _offset.z );
  6942. return this;
  6943. }
  6944. setFromPoints( points ) {
  6945. const position = [];
  6946. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6947. const point = points[ i ];
  6948. position.push( point.x, point.y, point.z || 0 );
  6949. }
  6950. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6951. return this;
  6952. }
  6953. computeBoundingBox() {
  6954. if ( this.boundingBox === null ) {
  6955. this.boundingBox = new Box3();
  6956. }
  6957. const position = this.attributes.position;
  6958. const morphAttributesPosition = this.morphAttributes.position;
  6959. if ( position && position.isGLBufferAttribute ) {
  6960. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  6961. this.boundingBox.set(
  6962. new Vector3( - Infinity, - Infinity, - Infinity ),
  6963. new Vector3( + Infinity, + Infinity, + Infinity )
  6964. );
  6965. return;
  6966. }
  6967. if ( position !== undefined ) {
  6968. this.boundingBox.setFromBufferAttribute( position );
  6969. // process morph attributes if present
  6970. if ( morphAttributesPosition ) {
  6971. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6972. const morphAttribute = morphAttributesPosition[ i ];
  6973. _box$1.setFromBufferAttribute( morphAttribute );
  6974. if ( this.morphTargetsRelative ) {
  6975. _vector$8.addVectors( this.boundingBox.min, _box$1.min );
  6976. this.boundingBox.expandByPoint( _vector$8 );
  6977. _vector$8.addVectors( this.boundingBox.max, _box$1.max );
  6978. this.boundingBox.expandByPoint( _vector$8 );
  6979. } else {
  6980. this.boundingBox.expandByPoint( _box$1.min );
  6981. this.boundingBox.expandByPoint( _box$1.max );
  6982. }
  6983. }
  6984. }
  6985. } else {
  6986. this.boundingBox.makeEmpty();
  6987. }
  6988. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6989. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6990. }
  6991. }
  6992. computeBoundingSphere() {
  6993. if ( this.boundingSphere === null ) {
  6994. this.boundingSphere = new Sphere();
  6995. }
  6996. const position = this.attributes.position;
  6997. const morphAttributesPosition = this.morphAttributes.position;
  6998. if ( position && position.isGLBufferAttribute ) {
  6999. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  7000. this.boundingSphere.set( new Vector3(), Infinity );
  7001. return;
  7002. }
  7003. if ( position ) {
  7004. // first, find the center of the bounding sphere
  7005. const center = this.boundingSphere.center;
  7006. _box$1.setFromBufferAttribute( position );
  7007. // process morph attributes if present
  7008. if ( morphAttributesPosition ) {
  7009. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  7010. const morphAttribute = morphAttributesPosition[ i ];
  7011. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  7012. if ( this.morphTargetsRelative ) {
  7013. _vector$8.addVectors( _box$1.min, _boxMorphTargets.min );
  7014. _box$1.expandByPoint( _vector$8 );
  7015. _vector$8.addVectors( _box$1.max, _boxMorphTargets.max );
  7016. _box$1.expandByPoint( _vector$8 );
  7017. } else {
  7018. _box$1.expandByPoint( _boxMorphTargets.min );
  7019. _box$1.expandByPoint( _boxMorphTargets.max );
  7020. }
  7021. }
  7022. }
  7023. _box$1.getCenter( center );
  7024. // second, try to find a boundingSphere with a radius smaller than the
  7025. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  7026. let maxRadiusSq = 0;
  7027. for ( let i = 0, il = position.count; i < il; i ++ ) {
  7028. _vector$8.fromBufferAttribute( position, i );
  7029. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  7030. }
  7031. // process morph attributes if present
  7032. if ( morphAttributesPosition ) {
  7033. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  7034. const morphAttribute = morphAttributesPosition[ i ];
  7035. const morphTargetsRelative = this.morphTargetsRelative;
  7036. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  7037. _vector$8.fromBufferAttribute( morphAttribute, j );
  7038. if ( morphTargetsRelative ) {
  7039. _offset.fromBufferAttribute( position, j );
  7040. _vector$8.add( _offset );
  7041. }
  7042. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  7043. }
  7044. }
  7045. }
  7046. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  7047. if ( isNaN( this.boundingSphere.radius ) ) {
  7048. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  7049. }
  7050. }
  7051. }
  7052. computeTangents() {
  7053. const index = this.index;
  7054. const attributes = this.attributes;
  7055. // based on http://www.terathon.com/code/tangent.html
  7056. // (per vertex tangents)
  7057. if ( index === null ||
  7058. attributes.position === undefined ||
  7059. attributes.normal === undefined ||
  7060. attributes.uv === undefined ) {
  7061. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  7062. return;
  7063. }
  7064. const indices = index.array;
  7065. const positions = attributes.position.array;
  7066. const normals = attributes.normal.array;
  7067. const uvs = attributes.uv.array;
  7068. const nVertices = positions.length / 3;
  7069. if ( attributes.tangent === undefined ) {
  7070. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  7071. }
  7072. const tangents = attributes.tangent.array;
  7073. const tan1 = [], tan2 = [];
  7074. for ( let i = 0; i < nVertices; i ++ ) {
  7075. tan1[ i ] = new Vector3();
  7076. tan2[ i ] = new Vector3();
  7077. }
  7078. const vA = new Vector3(),
  7079. vB = new Vector3(),
  7080. vC = new Vector3(),
  7081. uvA = new Vector2(),
  7082. uvB = new Vector2(),
  7083. uvC = new Vector2(),
  7084. sdir = new Vector3(),
  7085. tdir = new Vector3();
  7086. function handleTriangle( a, b, c ) {
  7087. vA.fromArray( positions, a * 3 );
  7088. vB.fromArray( positions, b * 3 );
  7089. vC.fromArray( positions, c * 3 );
  7090. uvA.fromArray( uvs, a * 2 );
  7091. uvB.fromArray( uvs, b * 2 );
  7092. uvC.fromArray( uvs, c * 2 );
  7093. vB.sub( vA );
  7094. vC.sub( vA );
  7095. uvB.sub( uvA );
  7096. uvC.sub( uvA );
  7097. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  7098. // silently ignore degenerate uv triangles having coincident or colinear vertices
  7099. if ( ! isFinite( r ) ) return;
  7100. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  7101. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  7102. tan1[ a ].add( sdir );
  7103. tan1[ b ].add( sdir );
  7104. tan1[ c ].add( sdir );
  7105. tan2[ a ].add( tdir );
  7106. tan2[ b ].add( tdir );
  7107. tan2[ c ].add( tdir );
  7108. }
  7109. let groups = this.groups;
  7110. if ( groups.length === 0 ) {
  7111. groups = [ {
  7112. start: 0,
  7113. count: indices.length
  7114. } ];
  7115. }
  7116. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  7117. const group = groups[ i ];
  7118. const start = group.start;
  7119. const count = group.count;
  7120. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  7121. handleTriangle(
  7122. indices[ j + 0 ],
  7123. indices[ j + 1 ],
  7124. indices[ j + 2 ]
  7125. );
  7126. }
  7127. }
  7128. const tmp = new Vector3(), tmp2 = new Vector3();
  7129. const n = new Vector3(), n2 = new Vector3();
  7130. function handleVertex( v ) {
  7131. n.fromArray( normals, v * 3 );
  7132. n2.copy( n );
  7133. const t = tan1[ v ];
  7134. // Gram-Schmidt orthogonalize
  7135. tmp.copy( t );
  7136. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  7137. // Calculate handedness
  7138. tmp2.crossVectors( n2, t );
  7139. const test = tmp2.dot( tan2[ v ] );
  7140. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  7141. tangents[ v * 4 ] = tmp.x;
  7142. tangents[ v * 4 + 1 ] = tmp.y;
  7143. tangents[ v * 4 + 2 ] = tmp.z;
  7144. tangents[ v * 4 + 3 ] = w;
  7145. }
  7146. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  7147. const group = groups[ i ];
  7148. const start = group.start;
  7149. const count = group.count;
  7150. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  7151. handleVertex( indices[ j + 0 ] );
  7152. handleVertex( indices[ j + 1 ] );
  7153. handleVertex( indices[ j + 2 ] );
  7154. }
  7155. }
  7156. }
  7157. computeVertexNormals() {
  7158. const index = this.index;
  7159. const positionAttribute = this.getAttribute( 'position' );
  7160. if ( positionAttribute !== undefined ) {
  7161. let normalAttribute = this.getAttribute( 'normal' );
  7162. if ( normalAttribute === undefined ) {
  7163. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  7164. this.setAttribute( 'normal', normalAttribute );
  7165. } else {
  7166. // reset existing normals to zero
  7167. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  7168. normalAttribute.setXYZ( i, 0, 0, 0 );
  7169. }
  7170. }
  7171. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  7172. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  7173. const cb = new Vector3(), ab = new Vector3();
  7174. // indexed elements
  7175. if ( index ) {
  7176. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  7177. const vA = index.getX( i + 0 );
  7178. const vB = index.getX( i + 1 );
  7179. const vC = index.getX( i + 2 );
  7180. pA.fromBufferAttribute( positionAttribute, vA );
  7181. pB.fromBufferAttribute( positionAttribute, vB );
  7182. pC.fromBufferAttribute( positionAttribute, vC );
  7183. cb.subVectors( pC, pB );
  7184. ab.subVectors( pA, pB );
  7185. cb.cross( ab );
  7186. nA.fromBufferAttribute( normalAttribute, vA );
  7187. nB.fromBufferAttribute( normalAttribute, vB );
  7188. nC.fromBufferAttribute( normalAttribute, vC );
  7189. nA.add( cb );
  7190. nB.add( cb );
  7191. nC.add( cb );
  7192. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  7193. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  7194. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  7195. }
  7196. } else {
  7197. // non-indexed elements (unconnected triangle soup)
  7198. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  7199. pA.fromBufferAttribute( positionAttribute, i + 0 );
  7200. pB.fromBufferAttribute( positionAttribute, i + 1 );
  7201. pC.fromBufferAttribute( positionAttribute, i + 2 );
  7202. cb.subVectors( pC, pB );
  7203. ab.subVectors( pA, pB );
  7204. cb.cross( ab );
  7205. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  7206. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  7207. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  7208. }
  7209. }
  7210. this.normalizeNormals();
  7211. normalAttribute.needsUpdate = true;
  7212. }
  7213. }
  7214. merge( geometry, offset ) {
  7215. if ( ! ( geometry && geometry.isBufferGeometry ) ) {
  7216. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  7217. return;
  7218. }
  7219. if ( offset === undefined ) {
  7220. offset = 0;
  7221. console.warn(
  7222. 'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. '
  7223. + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.'
  7224. );
  7225. }
  7226. const attributes = this.attributes;
  7227. for ( const key in attributes ) {
  7228. if ( geometry.attributes[ key ] === undefined ) continue;
  7229. const attribute1 = attributes[ key ];
  7230. const attributeArray1 = attribute1.array;
  7231. const attribute2 = geometry.attributes[ key ];
  7232. const attributeArray2 = attribute2.array;
  7233. const attributeOffset = attribute2.itemSize * offset;
  7234. const length = Math.min( attributeArray2.length, attributeArray1.length - attributeOffset );
  7235. for ( let i = 0, j = attributeOffset; i < length; i ++, j ++ ) {
  7236. attributeArray1[ j ] = attributeArray2[ i ];
  7237. }
  7238. }
  7239. return this;
  7240. }
  7241. normalizeNormals() {
  7242. const normals = this.attributes.normal;
  7243. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  7244. _vector$8.fromBufferAttribute( normals, i );
  7245. _vector$8.normalize();
  7246. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  7247. }
  7248. }
  7249. toNonIndexed() {
  7250. function convertBufferAttribute( attribute, indices ) {
  7251. const array = attribute.array;
  7252. const itemSize = attribute.itemSize;
  7253. const normalized = attribute.normalized;
  7254. const array2 = new array.constructor( indices.length * itemSize );
  7255. let index = 0, index2 = 0;
  7256. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  7257. if ( attribute.isInterleavedBufferAttribute ) {
  7258. index = indices[ i ] * attribute.data.stride + attribute.offset;
  7259. } else {
  7260. index = indices[ i ] * itemSize;
  7261. }
  7262. for ( let j = 0; j < itemSize; j ++ ) {
  7263. array2[ index2 ++ ] = array[ index ++ ];
  7264. }
  7265. }
  7266. return new BufferAttribute( array2, itemSize, normalized );
  7267. }
  7268. //
  7269. if ( this.index === null ) {
  7270. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  7271. return this;
  7272. }
  7273. const geometry2 = new BufferGeometry();
  7274. const indices = this.index.array;
  7275. const attributes = this.attributes;
  7276. // attributes
  7277. for ( const name in attributes ) {
  7278. const attribute = attributes[ name ];
  7279. const newAttribute = convertBufferAttribute( attribute, indices );
  7280. geometry2.setAttribute( name, newAttribute );
  7281. }
  7282. // morph attributes
  7283. const morphAttributes = this.morphAttributes;
  7284. for ( const name in morphAttributes ) {
  7285. const morphArray = [];
  7286. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  7287. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  7288. const attribute = morphAttribute[ i ];
  7289. const newAttribute = convertBufferAttribute( attribute, indices );
  7290. morphArray.push( newAttribute );
  7291. }
  7292. geometry2.morphAttributes[ name ] = morphArray;
  7293. }
  7294. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  7295. // groups
  7296. const groups = this.groups;
  7297. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  7298. const group = groups[ i ];
  7299. geometry2.addGroup( group.start, group.count, group.materialIndex );
  7300. }
  7301. return geometry2;
  7302. }
  7303. toJSON() {
  7304. const data = {
  7305. metadata: {
  7306. version: 4.5,
  7307. type: 'BufferGeometry',
  7308. generator: 'BufferGeometry.toJSON'
  7309. }
  7310. };
  7311. // standard BufferGeometry serialization
  7312. data.uuid = this.uuid;
  7313. data.type = this.type;
  7314. if ( this.name !== '' ) data.name = this.name;
  7315. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  7316. if ( this.parameters !== undefined ) {
  7317. const parameters = this.parameters;
  7318. for ( const key in parameters ) {
  7319. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  7320. }
  7321. return data;
  7322. }
  7323. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  7324. data.data = { attributes: {} };
  7325. const index = this.index;
  7326. if ( index !== null ) {
  7327. data.data.index = {
  7328. type: index.array.constructor.name,
  7329. array: Array.prototype.slice.call( index.array )
  7330. };
  7331. }
  7332. const attributes = this.attributes;
  7333. for ( const key in attributes ) {
  7334. const attribute = attributes[ key ];
  7335. data.data.attributes[ key ] = attribute.toJSON( data.data );
  7336. }
  7337. const morphAttributes = {};
  7338. let hasMorphAttributes = false;
  7339. for ( const key in this.morphAttributes ) {
  7340. const attributeArray = this.morphAttributes[ key ];
  7341. const array = [];
  7342. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  7343. const attribute = attributeArray[ i ];
  7344. array.push( attribute.toJSON( data.data ) );
  7345. }
  7346. if ( array.length > 0 ) {
  7347. morphAttributes[ key ] = array;
  7348. hasMorphAttributes = true;
  7349. }
  7350. }
  7351. if ( hasMorphAttributes ) {
  7352. data.data.morphAttributes = morphAttributes;
  7353. data.data.morphTargetsRelative = this.morphTargetsRelative;
  7354. }
  7355. const groups = this.groups;
  7356. if ( groups.length > 0 ) {
  7357. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  7358. }
  7359. const boundingSphere = this.boundingSphere;
  7360. if ( boundingSphere !== null ) {
  7361. data.data.boundingSphere = {
  7362. center: boundingSphere.center.toArray(),
  7363. radius: boundingSphere.radius
  7364. };
  7365. }
  7366. return data;
  7367. }
  7368. clone() {
  7369. /*
  7370. // Handle primitives
  7371. const parameters = this.parameters;
  7372. if ( parameters !== undefined ) {
  7373. const values = [];
  7374. for ( const key in parameters ) {
  7375. values.push( parameters[ key ] );
  7376. }
  7377. const geometry = Object.create( this.constructor.prototype );
  7378. this.constructor.apply( geometry, values );
  7379. return geometry;
  7380. }
  7381. return new this.constructor().copy( this );
  7382. */
  7383. return new BufferGeometry().copy( this );
  7384. }
  7385. copy( source ) {
  7386. // reset
  7387. this.index = null;
  7388. this.attributes = {};
  7389. this.morphAttributes = {};
  7390. this.groups = [];
  7391. this.boundingBox = null;
  7392. this.boundingSphere = null;
  7393. // used for storing cloned, shared data
  7394. const data = {};
  7395. // name
  7396. this.name = source.name;
  7397. // index
  7398. const index = source.index;
  7399. if ( index !== null ) {
  7400. this.setIndex( index.clone( data ) );
  7401. }
  7402. // attributes
  7403. const attributes = source.attributes;
  7404. for ( const name in attributes ) {
  7405. const attribute = attributes[ name ];
  7406. this.setAttribute( name, attribute.clone( data ) );
  7407. }
  7408. // morph attributes
  7409. const morphAttributes = source.morphAttributes;
  7410. for ( const name in morphAttributes ) {
  7411. const array = [];
  7412. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  7413. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  7414. array.push( morphAttribute[ i ].clone( data ) );
  7415. }
  7416. this.morphAttributes[ name ] = array;
  7417. }
  7418. this.morphTargetsRelative = source.morphTargetsRelative;
  7419. // groups
  7420. const groups = source.groups;
  7421. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  7422. const group = groups[ i ];
  7423. this.addGroup( group.start, group.count, group.materialIndex );
  7424. }
  7425. // bounding box
  7426. const boundingBox = source.boundingBox;
  7427. if ( boundingBox !== null ) {
  7428. this.boundingBox = boundingBox.clone();
  7429. }
  7430. // bounding sphere
  7431. const boundingSphere = source.boundingSphere;
  7432. if ( boundingSphere !== null ) {
  7433. this.boundingSphere = boundingSphere.clone();
  7434. }
  7435. // draw range
  7436. this.drawRange.start = source.drawRange.start;
  7437. this.drawRange.count = source.drawRange.count;
  7438. // user data
  7439. this.userData = source.userData;
  7440. return this;
  7441. }
  7442. dispose() {
  7443. this.dispatchEvent( { type: 'dispose' } );
  7444. }
  7445. }
  7446. BufferGeometry.prototype.isBufferGeometry = true;
  7447. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  7448. const _ray$2 = /*@__PURE__*/ new Ray();
  7449. const _sphere$3 = /*@__PURE__*/ new Sphere();
  7450. const _vA$1 = /*@__PURE__*/ new Vector3();
  7451. const _vB$1 = /*@__PURE__*/ new Vector3();
  7452. const _vC$1 = /*@__PURE__*/ new Vector3();
  7453. const _tempA = /*@__PURE__*/ new Vector3();
  7454. const _tempB = /*@__PURE__*/ new Vector3();
  7455. const _tempC = /*@__PURE__*/ new Vector3();
  7456. const _morphA = /*@__PURE__*/ new Vector3();
  7457. const _morphB = /*@__PURE__*/ new Vector3();
  7458. const _morphC = /*@__PURE__*/ new Vector3();
  7459. const _uvA$1 = /*@__PURE__*/ new Vector2();
  7460. const _uvB$1 = /*@__PURE__*/ new Vector2();
  7461. const _uvC$1 = /*@__PURE__*/ new Vector2();
  7462. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  7463. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  7464. class Mesh extends Object3D {
  7465. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  7466. super();
  7467. this.type = 'Mesh';
  7468. this.geometry = geometry;
  7469. this.material = material;
  7470. this.updateMorphTargets();
  7471. }
  7472. copy( source ) {
  7473. super.copy( source );
  7474. if ( source.morphTargetInfluences !== undefined ) {
  7475. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  7476. }
  7477. if ( source.morphTargetDictionary !== undefined ) {
  7478. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  7479. }
  7480. this.material = source.material;
  7481. this.geometry = source.geometry;
  7482. return this;
  7483. }
  7484. updateMorphTargets() {
  7485. const geometry = this.geometry;
  7486. if ( geometry.isBufferGeometry ) {
  7487. const morphAttributes = geometry.morphAttributes;
  7488. const keys = Object.keys( morphAttributes );
  7489. if ( keys.length > 0 ) {
  7490. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  7491. if ( morphAttribute !== undefined ) {
  7492. this.morphTargetInfluences = [];
  7493. this.morphTargetDictionary = {};
  7494. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  7495. const name = morphAttribute[ m ].name || String( m );
  7496. this.morphTargetInfluences.push( 0 );
  7497. this.morphTargetDictionary[ name ] = m;
  7498. }
  7499. }
  7500. }
  7501. } else {
  7502. const morphTargets = geometry.morphTargets;
  7503. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  7504. console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  7505. }
  7506. }
  7507. }
  7508. raycast( raycaster, intersects ) {
  7509. const geometry = this.geometry;
  7510. const material = this.material;
  7511. const matrixWorld = this.matrixWorld;
  7512. if ( material === undefined ) return;
  7513. // Checking boundingSphere distance to ray
  7514. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7515. _sphere$3.copy( geometry.boundingSphere );
  7516. _sphere$3.applyMatrix4( matrixWorld );
  7517. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  7518. //
  7519. _inverseMatrix$2.copy( matrixWorld ).invert();
  7520. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  7521. // Check boundingBox before continuing
  7522. if ( geometry.boundingBox !== null ) {
  7523. if ( _ray$2.intersectsBox( geometry.boundingBox ) === false ) return;
  7524. }
  7525. let intersection;
  7526. if ( geometry.isBufferGeometry ) {
  7527. const index = geometry.index;
  7528. const position = geometry.attributes.position;
  7529. const morphPosition = geometry.morphAttributes.position;
  7530. const morphTargetsRelative = geometry.morphTargetsRelative;
  7531. const uv = geometry.attributes.uv;
  7532. const uv2 = geometry.attributes.uv2;
  7533. const groups = geometry.groups;
  7534. const drawRange = geometry.drawRange;
  7535. if ( index !== null ) {
  7536. // indexed buffer geometry
  7537. if ( Array.isArray( material ) ) {
  7538. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7539. const group = groups[ i ];
  7540. const groupMaterial = material[ group.materialIndex ];
  7541. const start = Math.max( group.start, drawRange.start );
  7542. const end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  7543. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7544. const a = index.getX( j );
  7545. const b = index.getX( j + 1 );
  7546. const c = index.getX( j + 2 );
  7547. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  7548. if ( intersection ) {
  7549. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  7550. intersection.face.materialIndex = group.materialIndex;
  7551. intersects.push( intersection );
  7552. }
  7553. }
  7554. }
  7555. } else {
  7556. const start = Math.max( 0, drawRange.start );
  7557. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  7558. for ( let i = start, il = end; i < il; i += 3 ) {
  7559. const a = index.getX( i );
  7560. const b = index.getX( i + 1 );
  7561. const c = index.getX( i + 2 );
  7562. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  7563. if ( intersection ) {
  7564. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  7565. intersects.push( intersection );
  7566. }
  7567. }
  7568. }
  7569. } else if ( position !== undefined ) {
  7570. // non-indexed buffer geometry
  7571. if ( Array.isArray( material ) ) {
  7572. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7573. const group = groups[ i ];
  7574. const groupMaterial = material[ group.materialIndex ];
  7575. const start = Math.max( group.start, drawRange.start );
  7576. const end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  7577. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7578. const a = j;
  7579. const b = j + 1;
  7580. const c = j + 2;
  7581. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  7582. if ( intersection ) {
  7583. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  7584. intersection.face.materialIndex = group.materialIndex;
  7585. intersects.push( intersection );
  7586. }
  7587. }
  7588. }
  7589. } else {
  7590. const start = Math.max( 0, drawRange.start );
  7591. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  7592. for ( let i = start, il = end; i < il; i += 3 ) {
  7593. const a = i;
  7594. const b = i + 1;
  7595. const c = i + 2;
  7596. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  7597. if ( intersection ) {
  7598. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  7599. intersects.push( intersection );
  7600. }
  7601. }
  7602. }
  7603. }
  7604. } else if ( geometry.isGeometry ) {
  7605. console.error( 'THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  7606. }
  7607. }
  7608. }
  7609. Mesh.prototype.isMesh = true;
  7610. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  7611. let intersect;
  7612. if ( material.side === BackSide ) {
  7613. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  7614. } else {
  7615. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  7616. }
  7617. if ( intersect === null ) return null;
  7618. _intersectionPointWorld.copy( point );
  7619. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  7620. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  7621. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  7622. return {
  7623. distance: distance,
  7624. point: _intersectionPointWorld.clone(),
  7625. object: object
  7626. };
  7627. }
  7628. function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ) {
  7629. _vA$1.fromBufferAttribute( position, a );
  7630. _vB$1.fromBufferAttribute( position, b );
  7631. _vC$1.fromBufferAttribute( position, c );
  7632. const morphInfluences = object.morphTargetInfluences;
  7633. if ( morphPosition && morphInfluences ) {
  7634. _morphA.set( 0, 0, 0 );
  7635. _morphB.set( 0, 0, 0 );
  7636. _morphC.set( 0, 0, 0 );
  7637. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  7638. const influence = morphInfluences[ i ];
  7639. const morphAttribute = morphPosition[ i ];
  7640. if ( influence === 0 ) continue;
  7641. _tempA.fromBufferAttribute( morphAttribute, a );
  7642. _tempB.fromBufferAttribute( morphAttribute, b );
  7643. _tempC.fromBufferAttribute( morphAttribute, c );
  7644. if ( morphTargetsRelative ) {
  7645. _morphA.addScaledVector( _tempA, influence );
  7646. _morphB.addScaledVector( _tempB, influence );
  7647. _morphC.addScaledVector( _tempC, influence );
  7648. } else {
  7649. _morphA.addScaledVector( _tempA.sub( _vA$1 ), influence );
  7650. _morphB.addScaledVector( _tempB.sub( _vB$1 ), influence );
  7651. _morphC.addScaledVector( _tempC.sub( _vC$1 ), influence );
  7652. }
  7653. }
  7654. _vA$1.add( _morphA );
  7655. _vB$1.add( _morphB );
  7656. _vC$1.add( _morphC );
  7657. }
  7658. if ( object.isSkinnedMesh ) {
  7659. object.boneTransform( a, _vA$1 );
  7660. object.boneTransform( b, _vB$1 );
  7661. object.boneTransform( c, _vC$1 );
  7662. }
  7663. const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  7664. if ( intersection ) {
  7665. if ( uv ) {
  7666. _uvA$1.fromBufferAttribute( uv, a );
  7667. _uvB$1.fromBufferAttribute( uv, b );
  7668. _uvC$1.fromBufferAttribute( uv, c );
  7669. intersection.uv = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7670. }
  7671. if ( uv2 ) {
  7672. _uvA$1.fromBufferAttribute( uv2, a );
  7673. _uvB$1.fromBufferAttribute( uv2, b );
  7674. _uvC$1.fromBufferAttribute( uv2, c );
  7675. intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7676. }
  7677. const face = {
  7678. a: a,
  7679. b: b,
  7680. c: c,
  7681. normal: new Vector3(),
  7682. materialIndex: 0
  7683. };
  7684. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  7685. intersection.face = face;
  7686. }
  7687. return intersection;
  7688. }
  7689. class BoxGeometry extends BufferGeometry {
  7690. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  7691. super();
  7692. this.type = 'BoxGeometry';
  7693. this.parameters = {
  7694. width: width,
  7695. height: height,
  7696. depth: depth,
  7697. widthSegments: widthSegments,
  7698. heightSegments: heightSegments,
  7699. depthSegments: depthSegments
  7700. };
  7701. const scope = this;
  7702. // segments
  7703. widthSegments = Math.floor( widthSegments );
  7704. heightSegments = Math.floor( heightSegments );
  7705. depthSegments = Math.floor( depthSegments );
  7706. // buffers
  7707. const indices = [];
  7708. const vertices = [];
  7709. const normals = [];
  7710. const uvs = [];
  7711. // helper variables
  7712. let numberOfVertices = 0;
  7713. let groupStart = 0;
  7714. // build each side of the box geometry
  7715. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7716. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7717. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7718. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7719. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7720. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7721. // build geometry
  7722. this.setIndex( indices );
  7723. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7724. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7725. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7726. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7727. const segmentWidth = width / gridX;
  7728. const segmentHeight = height / gridY;
  7729. const widthHalf = width / 2;
  7730. const heightHalf = height / 2;
  7731. const depthHalf = depth / 2;
  7732. const gridX1 = gridX + 1;
  7733. const gridY1 = gridY + 1;
  7734. let vertexCounter = 0;
  7735. let groupCount = 0;
  7736. const vector = new Vector3();
  7737. // generate vertices, normals and uvs
  7738. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7739. const y = iy * segmentHeight - heightHalf;
  7740. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7741. const x = ix * segmentWidth - widthHalf;
  7742. // set values to correct vector component
  7743. vector[ u ] = x * udir;
  7744. vector[ v ] = y * vdir;
  7745. vector[ w ] = depthHalf;
  7746. // now apply vector to vertex buffer
  7747. vertices.push( vector.x, vector.y, vector.z );
  7748. // set values to correct vector component
  7749. vector[ u ] = 0;
  7750. vector[ v ] = 0;
  7751. vector[ w ] = depth > 0 ? 1 : - 1;
  7752. // now apply vector to normal buffer
  7753. normals.push( vector.x, vector.y, vector.z );
  7754. // uvs
  7755. uvs.push( ix / gridX );
  7756. uvs.push( 1 - ( iy / gridY ) );
  7757. // counters
  7758. vertexCounter += 1;
  7759. }
  7760. }
  7761. // indices
  7762. // 1. you need three indices to draw a single face
  7763. // 2. a single segment consists of two faces
  7764. // 3. so we need to generate six (2*3) indices per segment
  7765. for ( let iy = 0; iy < gridY; iy ++ ) {
  7766. for ( let ix = 0; ix < gridX; ix ++ ) {
  7767. const a = numberOfVertices + ix + gridX1 * iy;
  7768. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7769. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7770. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7771. // faces
  7772. indices.push( a, b, d );
  7773. indices.push( b, c, d );
  7774. // increase counter
  7775. groupCount += 6;
  7776. }
  7777. }
  7778. // add a group to the geometry. this will ensure multi material support
  7779. scope.addGroup( groupStart, groupCount, materialIndex );
  7780. // calculate new start value for groups
  7781. groupStart += groupCount;
  7782. // update total number of vertices
  7783. numberOfVertices += vertexCounter;
  7784. }
  7785. }
  7786. static fromJSON( data ) {
  7787. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  7788. }
  7789. }
  7790. /**
  7791. * Uniform Utilities
  7792. */
  7793. function cloneUniforms( src ) {
  7794. const dst = {};
  7795. for ( const u in src ) {
  7796. dst[ u ] = {};
  7797. for ( const p in src[ u ] ) {
  7798. const property = src[ u ][ p ];
  7799. if ( property && ( property.isColor ||
  7800. property.isMatrix3 || property.isMatrix4 ||
  7801. property.isVector2 || property.isVector3 || property.isVector4 ||
  7802. property.isTexture || property.isQuaternion ) ) {
  7803. dst[ u ][ p ] = property.clone();
  7804. } else if ( Array.isArray( property ) ) {
  7805. dst[ u ][ p ] = property.slice();
  7806. } else {
  7807. dst[ u ][ p ] = property;
  7808. }
  7809. }
  7810. }
  7811. return dst;
  7812. }
  7813. function mergeUniforms( uniforms ) {
  7814. const merged = {};
  7815. for ( let u = 0; u < uniforms.length; u ++ ) {
  7816. const tmp = cloneUniforms( uniforms[ u ] );
  7817. for ( const p in tmp ) {
  7818. merged[ p ] = tmp[ p ];
  7819. }
  7820. }
  7821. return merged;
  7822. }
  7823. // Legacy
  7824. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  7825. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7826. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7827. /**
  7828. * parameters = {
  7829. * defines: { "label" : "value" },
  7830. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  7831. *
  7832. * fragmentShader: <string>,
  7833. * vertexShader: <string>,
  7834. *
  7835. * wireframe: <boolean>,
  7836. * wireframeLinewidth: <float>,
  7837. *
  7838. * lights: <bool>
  7839. * }
  7840. */
  7841. class ShaderMaterial extends Material {
  7842. constructor( parameters ) {
  7843. super();
  7844. this.type = 'ShaderMaterial';
  7845. this.defines = {};
  7846. this.uniforms = {};
  7847. this.vertexShader = default_vertex;
  7848. this.fragmentShader = default_fragment;
  7849. this.linewidth = 1;
  7850. this.wireframe = false;
  7851. this.wireframeLinewidth = 1;
  7852. this.fog = false; // set to use scene fog
  7853. this.lights = false; // set to use scene lights
  7854. this.clipping = false; // set to use user-defined clipping planes
  7855. this.extensions = {
  7856. derivatives: false, // set to use derivatives
  7857. fragDepth: false, // set to use fragment depth values
  7858. drawBuffers: false, // set to use draw buffers
  7859. shaderTextureLOD: false // set to use shader texture LOD
  7860. };
  7861. // When rendered geometry doesn't include these attributes but the material does,
  7862. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7863. this.defaultAttributeValues = {
  7864. 'color': [ 1, 1, 1 ],
  7865. 'uv': [ 0, 0 ],
  7866. 'uv2': [ 0, 0 ]
  7867. };
  7868. this.index0AttributeName = undefined;
  7869. this.uniformsNeedUpdate = false;
  7870. this.glslVersion = null;
  7871. if ( parameters !== undefined ) {
  7872. if ( parameters.attributes !== undefined ) {
  7873. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  7874. }
  7875. this.setValues( parameters );
  7876. }
  7877. }
  7878. copy( source ) {
  7879. super.copy( source );
  7880. this.fragmentShader = source.fragmentShader;
  7881. this.vertexShader = source.vertexShader;
  7882. this.uniforms = cloneUniforms( source.uniforms );
  7883. this.defines = Object.assign( {}, source.defines );
  7884. this.wireframe = source.wireframe;
  7885. this.wireframeLinewidth = source.wireframeLinewidth;
  7886. this.lights = source.lights;
  7887. this.clipping = source.clipping;
  7888. this.extensions = Object.assign( {}, source.extensions );
  7889. this.glslVersion = source.glslVersion;
  7890. return this;
  7891. }
  7892. toJSON( meta ) {
  7893. const data = super.toJSON( meta );
  7894. data.glslVersion = this.glslVersion;
  7895. data.uniforms = {};
  7896. for ( const name in this.uniforms ) {
  7897. const uniform = this.uniforms[ name ];
  7898. const value = uniform.value;
  7899. if ( value && value.isTexture ) {
  7900. data.uniforms[ name ] = {
  7901. type: 't',
  7902. value: value.toJSON( meta ).uuid
  7903. };
  7904. } else if ( value && value.isColor ) {
  7905. data.uniforms[ name ] = {
  7906. type: 'c',
  7907. value: value.getHex()
  7908. };
  7909. } else if ( value && value.isVector2 ) {
  7910. data.uniforms[ name ] = {
  7911. type: 'v2',
  7912. value: value.toArray()
  7913. };
  7914. } else if ( value && value.isVector3 ) {
  7915. data.uniforms[ name ] = {
  7916. type: 'v3',
  7917. value: value.toArray()
  7918. };
  7919. } else if ( value && value.isVector4 ) {
  7920. data.uniforms[ name ] = {
  7921. type: 'v4',
  7922. value: value.toArray()
  7923. };
  7924. } else if ( value && value.isMatrix3 ) {
  7925. data.uniforms[ name ] = {
  7926. type: 'm3',
  7927. value: value.toArray()
  7928. };
  7929. } else if ( value && value.isMatrix4 ) {
  7930. data.uniforms[ name ] = {
  7931. type: 'm4',
  7932. value: value.toArray()
  7933. };
  7934. } else {
  7935. data.uniforms[ name ] = {
  7936. value: value
  7937. };
  7938. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7939. }
  7940. }
  7941. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7942. data.vertexShader = this.vertexShader;
  7943. data.fragmentShader = this.fragmentShader;
  7944. const extensions = {};
  7945. for ( const key in this.extensions ) {
  7946. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7947. }
  7948. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7949. return data;
  7950. }
  7951. }
  7952. ShaderMaterial.prototype.isShaderMaterial = true;
  7953. class Camera extends Object3D {
  7954. constructor() {
  7955. super();
  7956. this.type = 'Camera';
  7957. this.matrixWorldInverse = new Matrix4();
  7958. this.projectionMatrix = new Matrix4();
  7959. this.projectionMatrixInverse = new Matrix4();
  7960. }
  7961. copy( source, recursive ) {
  7962. super.copy( source, recursive );
  7963. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7964. this.projectionMatrix.copy( source.projectionMatrix );
  7965. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7966. return this;
  7967. }
  7968. getWorldDirection( target ) {
  7969. this.updateWorldMatrix( true, false );
  7970. const e = this.matrixWorld.elements;
  7971. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  7972. }
  7973. updateMatrixWorld( force ) {
  7974. super.updateMatrixWorld( force );
  7975. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7976. }
  7977. updateWorldMatrix( updateParents, updateChildren ) {
  7978. super.updateWorldMatrix( updateParents, updateChildren );
  7979. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7980. }
  7981. clone() {
  7982. return new this.constructor().copy( this );
  7983. }
  7984. }
  7985. Camera.prototype.isCamera = true;
  7986. class PerspectiveCamera extends Camera {
  7987. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7988. super();
  7989. this.type = 'PerspectiveCamera';
  7990. this.fov = fov;
  7991. this.zoom = 1;
  7992. this.near = near;
  7993. this.far = far;
  7994. this.focus = 10;
  7995. this.aspect = aspect;
  7996. this.view = null;
  7997. this.filmGauge = 35; // width of the film (default in millimeters)
  7998. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7999. this.updateProjectionMatrix();
  8000. }
  8001. copy( source, recursive ) {
  8002. super.copy( source, recursive );
  8003. this.fov = source.fov;
  8004. this.zoom = source.zoom;
  8005. this.near = source.near;
  8006. this.far = source.far;
  8007. this.focus = source.focus;
  8008. this.aspect = source.aspect;
  8009. this.view = source.view === null ? null : Object.assign( {}, source.view );
  8010. this.filmGauge = source.filmGauge;
  8011. this.filmOffset = source.filmOffset;
  8012. return this;
  8013. }
  8014. /**
  8015. * Sets the FOV by focal length in respect to the current .filmGauge.
  8016. *
  8017. * The default film gauge is 35, so that the focal length can be specified for
  8018. * a 35mm (full frame) camera.
  8019. *
  8020. * Values for focal length and film gauge must have the same unit.
  8021. */
  8022. setFocalLength( focalLength ) {
  8023. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  8024. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  8025. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  8026. this.updateProjectionMatrix();
  8027. }
  8028. /**
  8029. * Calculates the focal length from the current .fov and .filmGauge.
  8030. */
  8031. getFocalLength() {
  8032. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  8033. return 0.5 * this.getFilmHeight() / vExtentSlope;
  8034. }
  8035. getEffectiveFOV() {
  8036. return RAD2DEG * 2 * Math.atan(
  8037. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  8038. }
  8039. getFilmWidth() {
  8040. // film not completely covered in portrait format (aspect < 1)
  8041. return this.filmGauge * Math.min( this.aspect, 1 );
  8042. }
  8043. getFilmHeight() {
  8044. // film not completely covered in landscape format (aspect > 1)
  8045. return this.filmGauge / Math.max( this.aspect, 1 );
  8046. }
  8047. /**
  8048. * Sets an offset in a larger frustum. This is useful for multi-window or
  8049. * multi-monitor/multi-machine setups.
  8050. *
  8051. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  8052. * the monitors are in grid like this
  8053. *
  8054. * +---+---+---+
  8055. * | A | B | C |
  8056. * +---+---+---+
  8057. * | D | E | F |
  8058. * +---+---+---+
  8059. *
  8060. * then for each monitor you would call it like this
  8061. *
  8062. * const w = 1920;
  8063. * const h = 1080;
  8064. * const fullWidth = w * 3;
  8065. * const fullHeight = h * 2;
  8066. *
  8067. * --A--
  8068. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  8069. * --B--
  8070. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  8071. * --C--
  8072. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  8073. * --D--
  8074. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  8075. * --E--
  8076. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  8077. * --F--
  8078. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  8079. *
  8080. * Note there is no reason monitors have to be the same size or in a grid.
  8081. */
  8082. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  8083. this.aspect = fullWidth / fullHeight;
  8084. if ( this.view === null ) {
  8085. this.view = {
  8086. enabled: true,
  8087. fullWidth: 1,
  8088. fullHeight: 1,
  8089. offsetX: 0,
  8090. offsetY: 0,
  8091. width: 1,
  8092. height: 1
  8093. };
  8094. }
  8095. this.view.enabled = true;
  8096. this.view.fullWidth = fullWidth;
  8097. this.view.fullHeight = fullHeight;
  8098. this.view.offsetX = x;
  8099. this.view.offsetY = y;
  8100. this.view.width = width;
  8101. this.view.height = height;
  8102. this.updateProjectionMatrix();
  8103. }
  8104. clearViewOffset() {
  8105. if ( this.view !== null ) {
  8106. this.view.enabled = false;
  8107. }
  8108. this.updateProjectionMatrix();
  8109. }
  8110. updateProjectionMatrix() {
  8111. const near = this.near;
  8112. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  8113. let height = 2 * top;
  8114. let width = this.aspect * height;
  8115. let left = - 0.5 * width;
  8116. const view = this.view;
  8117. if ( this.view !== null && this.view.enabled ) {
  8118. const fullWidth = view.fullWidth,
  8119. fullHeight = view.fullHeight;
  8120. left += view.offsetX * width / fullWidth;
  8121. top -= view.offsetY * height / fullHeight;
  8122. width *= view.width / fullWidth;
  8123. height *= view.height / fullHeight;
  8124. }
  8125. const skew = this.filmOffset;
  8126. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  8127. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  8128. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  8129. }
  8130. toJSON( meta ) {
  8131. const data = super.toJSON( meta );
  8132. data.object.fov = this.fov;
  8133. data.object.zoom = this.zoom;
  8134. data.object.near = this.near;
  8135. data.object.far = this.far;
  8136. data.object.focus = this.focus;
  8137. data.object.aspect = this.aspect;
  8138. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  8139. data.object.filmGauge = this.filmGauge;
  8140. data.object.filmOffset = this.filmOffset;
  8141. return data;
  8142. }
  8143. }
  8144. PerspectiveCamera.prototype.isPerspectiveCamera = true;
  8145. const fov = 90, aspect = 1;
  8146. class CubeCamera extends Object3D {
  8147. constructor( near, far, renderTarget ) {
  8148. super();
  8149. this.type = 'CubeCamera';
  8150. if ( renderTarget.isWebGLCubeRenderTarget !== true ) {
  8151. console.error( 'THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.' );
  8152. return;
  8153. }
  8154. this.renderTarget = renderTarget;
  8155. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  8156. cameraPX.layers = this.layers;
  8157. cameraPX.up.set( 0, - 1, 0 );
  8158. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  8159. this.add( cameraPX );
  8160. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  8161. cameraNX.layers = this.layers;
  8162. cameraNX.up.set( 0, - 1, 0 );
  8163. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  8164. this.add( cameraNX );
  8165. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  8166. cameraPY.layers = this.layers;
  8167. cameraPY.up.set( 0, 0, 1 );
  8168. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  8169. this.add( cameraPY );
  8170. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  8171. cameraNY.layers = this.layers;
  8172. cameraNY.up.set( 0, 0, - 1 );
  8173. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  8174. this.add( cameraNY );
  8175. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  8176. cameraPZ.layers = this.layers;
  8177. cameraPZ.up.set( 0, - 1, 0 );
  8178. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  8179. this.add( cameraPZ );
  8180. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  8181. cameraNZ.layers = this.layers;
  8182. cameraNZ.up.set( 0, - 1, 0 );
  8183. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  8184. this.add( cameraNZ );
  8185. }
  8186. update( renderer, scene ) {
  8187. if ( this.parent === null ) this.updateMatrixWorld();
  8188. const renderTarget = this.renderTarget;
  8189. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  8190. const currentXrEnabled = renderer.xr.enabled;
  8191. const currentRenderTarget = renderer.getRenderTarget();
  8192. renderer.xr.enabled = false;
  8193. const generateMipmaps = renderTarget.texture.generateMipmaps;
  8194. renderTarget.texture.generateMipmaps = false;
  8195. renderer.setRenderTarget( renderTarget, 0 );
  8196. renderer.render( scene, cameraPX );
  8197. renderer.setRenderTarget( renderTarget, 1 );
  8198. renderer.render( scene, cameraNX );
  8199. renderer.setRenderTarget( renderTarget, 2 );
  8200. renderer.render( scene, cameraPY );
  8201. renderer.setRenderTarget( renderTarget, 3 );
  8202. renderer.render( scene, cameraNY );
  8203. renderer.setRenderTarget( renderTarget, 4 );
  8204. renderer.render( scene, cameraPZ );
  8205. renderTarget.texture.generateMipmaps = generateMipmaps;
  8206. renderer.setRenderTarget( renderTarget, 5 );
  8207. renderer.render( scene, cameraNZ );
  8208. renderer.setRenderTarget( currentRenderTarget );
  8209. renderer.xr.enabled = currentXrEnabled;
  8210. }
  8211. }
  8212. class CubeTexture extends Texture {
  8213. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  8214. images = images !== undefined ? images : [];
  8215. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  8216. format = format !== undefined ? format : RGBFormat;
  8217. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  8218. this.flipY = false;
  8219. }
  8220. get images() {
  8221. return this.image;
  8222. }
  8223. set images( value ) {
  8224. this.image = value;
  8225. }
  8226. }
  8227. CubeTexture.prototype.isCubeTexture = true;
  8228. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  8229. constructor( size, options, dummy ) {
  8230. if ( Number.isInteger( options ) ) {
  8231. console.warn( 'THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )' );
  8232. options = dummy;
  8233. }
  8234. super( size, size, options );
  8235. options = options || {};
  8236. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  8237. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  8238. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  8239. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  8240. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  8241. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  8242. this.texture = new CubeTexture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  8243. this.texture.isRenderTargetTexture = true;
  8244. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  8245. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  8246. this.texture._needsFlipEnvMap = false;
  8247. }
  8248. fromEquirectangularTexture( renderer, texture ) {
  8249. this.texture.type = texture.type;
  8250. this.texture.format = RGBAFormat; // see #18859
  8251. this.texture.encoding = texture.encoding;
  8252. this.texture.generateMipmaps = texture.generateMipmaps;
  8253. this.texture.minFilter = texture.minFilter;
  8254. this.texture.magFilter = texture.magFilter;
  8255. const shader = {
  8256. uniforms: {
  8257. tEquirect: { value: null },
  8258. },
  8259. vertexShader: /* glsl */`
  8260. varying vec3 vWorldDirection;
  8261. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  8262. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  8263. }
  8264. void main() {
  8265. vWorldDirection = transformDirection( position, modelMatrix );
  8266. #include <begin_vertex>
  8267. #include <project_vertex>
  8268. }
  8269. `,
  8270. fragmentShader: /* glsl */`
  8271. uniform sampler2D tEquirect;
  8272. varying vec3 vWorldDirection;
  8273. #include <common>
  8274. void main() {
  8275. vec3 direction = normalize( vWorldDirection );
  8276. vec2 sampleUV = equirectUv( direction );
  8277. gl_FragColor = texture2D( tEquirect, sampleUV );
  8278. }
  8279. `
  8280. };
  8281. const geometry = new BoxGeometry( 5, 5, 5 );
  8282. const material = new ShaderMaterial( {
  8283. name: 'CubemapFromEquirect',
  8284. uniforms: cloneUniforms( shader.uniforms ),
  8285. vertexShader: shader.vertexShader,
  8286. fragmentShader: shader.fragmentShader,
  8287. side: BackSide,
  8288. blending: NoBlending
  8289. } );
  8290. material.uniforms.tEquirect.value = texture;
  8291. const mesh = new Mesh( geometry, material );
  8292. const currentMinFilter = texture.minFilter;
  8293. // Avoid blurred poles
  8294. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  8295. const camera = new CubeCamera( 1, 10, this );
  8296. camera.update( renderer, mesh );
  8297. texture.minFilter = currentMinFilter;
  8298. mesh.geometry.dispose();
  8299. mesh.material.dispose();
  8300. return this;
  8301. }
  8302. clear( renderer, color, depth, stencil ) {
  8303. const currentRenderTarget = renderer.getRenderTarget();
  8304. for ( let i = 0; i < 6; i ++ ) {
  8305. renderer.setRenderTarget( this, i );
  8306. renderer.clear( color, depth, stencil );
  8307. }
  8308. renderer.setRenderTarget( currentRenderTarget );
  8309. }
  8310. }
  8311. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  8312. const _vector1 = /*@__PURE__*/ new Vector3();
  8313. const _vector2 = /*@__PURE__*/ new Vector3();
  8314. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  8315. class Plane {
  8316. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  8317. // normal is assumed to be normalized
  8318. this.normal = normal;
  8319. this.constant = constant;
  8320. }
  8321. set( normal, constant ) {
  8322. this.normal.copy( normal );
  8323. this.constant = constant;
  8324. return this;
  8325. }
  8326. setComponents( x, y, z, w ) {
  8327. this.normal.set( x, y, z );
  8328. this.constant = w;
  8329. return this;
  8330. }
  8331. setFromNormalAndCoplanarPoint( normal, point ) {
  8332. this.normal.copy( normal );
  8333. this.constant = - point.dot( this.normal );
  8334. return this;
  8335. }
  8336. setFromCoplanarPoints( a, b, c ) {
  8337. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  8338. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  8339. this.setFromNormalAndCoplanarPoint( normal, a );
  8340. return this;
  8341. }
  8342. copy( plane ) {
  8343. this.normal.copy( plane.normal );
  8344. this.constant = plane.constant;
  8345. return this;
  8346. }
  8347. normalize() {
  8348. // Note: will lead to a divide by zero if the plane is invalid.
  8349. const inverseNormalLength = 1.0 / this.normal.length();
  8350. this.normal.multiplyScalar( inverseNormalLength );
  8351. this.constant *= inverseNormalLength;
  8352. return this;
  8353. }
  8354. negate() {
  8355. this.constant *= - 1;
  8356. this.normal.negate();
  8357. return this;
  8358. }
  8359. distanceToPoint( point ) {
  8360. return this.normal.dot( point ) + this.constant;
  8361. }
  8362. distanceToSphere( sphere ) {
  8363. return this.distanceToPoint( sphere.center ) - sphere.radius;
  8364. }
  8365. projectPoint( point, target ) {
  8366. return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  8367. }
  8368. intersectLine( line, target ) {
  8369. const direction = line.delta( _vector1 );
  8370. const denominator = this.normal.dot( direction );
  8371. if ( denominator === 0 ) {
  8372. // line is coplanar, return origin
  8373. if ( this.distanceToPoint( line.start ) === 0 ) {
  8374. return target.copy( line.start );
  8375. }
  8376. // Unsure if this is the correct method to handle this case.
  8377. return null;
  8378. }
  8379. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  8380. if ( t < 0 || t > 1 ) {
  8381. return null;
  8382. }
  8383. return target.copy( direction ).multiplyScalar( t ).add( line.start );
  8384. }
  8385. intersectsLine( line ) {
  8386. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  8387. const startSign = this.distanceToPoint( line.start );
  8388. const endSign = this.distanceToPoint( line.end );
  8389. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  8390. }
  8391. intersectsBox( box ) {
  8392. return box.intersectsPlane( this );
  8393. }
  8394. intersectsSphere( sphere ) {
  8395. return sphere.intersectsPlane( this );
  8396. }
  8397. coplanarPoint( target ) {
  8398. return target.copy( this.normal ).multiplyScalar( - this.constant );
  8399. }
  8400. applyMatrix4( matrix, optionalNormalMatrix ) {
  8401. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  8402. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  8403. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  8404. this.constant = - referencePoint.dot( normal );
  8405. return this;
  8406. }
  8407. translate( offset ) {
  8408. this.constant -= offset.dot( this.normal );
  8409. return this;
  8410. }
  8411. equals( plane ) {
  8412. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  8413. }
  8414. clone() {
  8415. return new this.constructor().copy( this );
  8416. }
  8417. }
  8418. Plane.prototype.isPlane = true;
  8419. const _sphere$2 = /*@__PURE__*/ new Sphere();
  8420. const _vector$7 = /*@__PURE__*/ new Vector3();
  8421. class Frustum {
  8422. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  8423. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  8424. }
  8425. set( p0, p1, p2, p3, p4, p5 ) {
  8426. const planes = this.planes;
  8427. planes[ 0 ].copy( p0 );
  8428. planes[ 1 ].copy( p1 );
  8429. planes[ 2 ].copy( p2 );
  8430. planes[ 3 ].copy( p3 );
  8431. planes[ 4 ].copy( p4 );
  8432. planes[ 5 ].copy( p5 );
  8433. return this;
  8434. }
  8435. copy( frustum ) {
  8436. const planes = this.planes;
  8437. for ( let i = 0; i < 6; i ++ ) {
  8438. planes[ i ].copy( frustum.planes[ i ] );
  8439. }
  8440. return this;
  8441. }
  8442. setFromProjectionMatrix( m ) {
  8443. const planes = this.planes;
  8444. const me = m.elements;
  8445. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  8446. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  8447. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  8448. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  8449. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  8450. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  8451. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  8452. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  8453. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  8454. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  8455. return this;
  8456. }
  8457. intersectsObject( object ) {
  8458. const geometry = object.geometry;
  8459. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8460. _sphere$2.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  8461. return this.intersectsSphere( _sphere$2 );
  8462. }
  8463. intersectsSprite( sprite ) {
  8464. _sphere$2.center.set( 0, 0, 0 );
  8465. _sphere$2.radius = 0.7071067811865476;
  8466. _sphere$2.applyMatrix4( sprite.matrixWorld );
  8467. return this.intersectsSphere( _sphere$2 );
  8468. }
  8469. intersectsSphere( sphere ) {
  8470. const planes = this.planes;
  8471. const center = sphere.center;
  8472. const negRadius = - sphere.radius;
  8473. for ( let i = 0; i < 6; i ++ ) {
  8474. const distance = planes[ i ].distanceToPoint( center );
  8475. if ( distance < negRadius ) {
  8476. return false;
  8477. }
  8478. }
  8479. return true;
  8480. }
  8481. intersectsBox( box ) {
  8482. const planes = this.planes;
  8483. for ( let i = 0; i < 6; i ++ ) {
  8484. const plane = planes[ i ];
  8485. // corner at max distance
  8486. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  8487. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  8488. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  8489. if ( plane.distanceToPoint( _vector$7 ) < 0 ) {
  8490. return false;
  8491. }
  8492. }
  8493. return true;
  8494. }
  8495. containsPoint( point ) {
  8496. const planes = this.planes;
  8497. for ( let i = 0; i < 6; i ++ ) {
  8498. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  8499. return false;
  8500. }
  8501. }
  8502. return true;
  8503. }
  8504. clone() {
  8505. return new this.constructor().copy( this );
  8506. }
  8507. }
  8508. function WebGLAnimation() {
  8509. let context = null;
  8510. let isAnimating = false;
  8511. let animationLoop = null;
  8512. let requestId = null;
  8513. function onAnimationFrame( time, frame ) {
  8514. animationLoop( time, frame );
  8515. requestId = context.requestAnimationFrame( onAnimationFrame );
  8516. }
  8517. return {
  8518. start: function () {
  8519. if ( isAnimating === true ) return;
  8520. if ( animationLoop === null ) return;
  8521. requestId = context.requestAnimationFrame( onAnimationFrame );
  8522. isAnimating = true;
  8523. },
  8524. stop: function () {
  8525. context.cancelAnimationFrame( requestId );
  8526. isAnimating = false;
  8527. },
  8528. setAnimationLoop: function ( callback ) {
  8529. animationLoop = callback;
  8530. },
  8531. setContext: function ( value ) {
  8532. context = value;
  8533. }
  8534. };
  8535. }
  8536. function WebGLAttributes( gl, capabilities ) {
  8537. const isWebGL2 = capabilities.isWebGL2;
  8538. const buffers = new WeakMap();
  8539. function createBuffer( attribute, bufferType ) {
  8540. const array = attribute.array;
  8541. const usage = attribute.usage;
  8542. const buffer = gl.createBuffer();
  8543. gl.bindBuffer( bufferType, buffer );
  8544. gl.bufferData( bufferType, array, usage );
  8545. attribute.onUploadCallback();
  8546. let type = 5126;
  8547. if ( array instanceof Float32Array ) {
  8548. type = 5126;
  8549. } else if ( array instanceof Float64Array ) {
  8550. console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );
  8551. } else if ( array instanceof Uint16Array ) {
  8552. if ( attribute.isFloat16BufferAttribute ) {
  8553. if ( isWebGL2 ) {
  8554. type = 5131;
  8555. } else {
  8556. console.warn( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  8557. }
  8558. } else {
  8559. type = 5123;
  8560. }
  8561. } else if ( array instanceof Int16Array ) {
  8562. type = 5122;
  8563. } else if ( array instanceof Uint32Array ) {
  8564. type = 5125;
  8565. } else if ( array instanceof Int32Array ) {
  8566. type = 5124;
  8567. } else if ( array instanceof Int8Array ) {
  8568. type = 5120;
  8569. } else if ( array instanceof Uint8Array ) {
  8570. type = 5121;
  8571. } else if ( array instanceof Uint8ClampedArray ) {
  8572. type = 5121;
  8573. }
  8574. return {
  8575. buffer: buffer,
  8576. type: type,
  8577. bytesPerElement: array.BYTES_PER_ELEMENT,
  8578. version: attribute.version
  8579. };
  8580. }
  8581. function updateBuffer( buffer, attribute, bufferType ) {
  8582. const array = attribute.array;
  8583. const updateRange = attribute.updateRange;
  8584. gl.bindBuffer( bufferType, buffer );
  8585. if ( updateRange.count === - 1 ) {
  8586. // Not using update ranges
  8587. gl.bufferSubData( bufferType, 0, array );
  8588. } else {
  8589. if ( isWebGL2 ) {
  8590. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  8591. array, updateRange.offset, updateRange.count );
  8592. } else {
  8593. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  8594. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  8595. }
  8596. updateRange.count = - 1; // reset range
  8597. }
  8598. }
  8599. //
  8600. function get( attribute ) {
  8601. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8602. return buffers.get( attribute );
  8603. }
  8604. function remove( attribute ) {
  8605. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8606. const data = buffers.get( attribute );
  8607. if ( data ) {
  8608. gl.deleteBuffer( data.buffer );
  8609. buffers.delete( attribute );
  8610. }
  8611. }
  8612. function update( attribute, bufferType ) {
  8613. if ( attribute.isGLBufferAttribute ) {
  8614. const cached = buffers.get( attribute );
  8615. if ( ! cached || cached.version < attribute.version ) {
  8616. buffers.set( attribute, {
  8617. buffer: attribute.buffer,
  8618. type: attribute.type,
  8619. bytesPerElement: attribute.elementSize,
  8620. version: attribute.version
  8621. } );
  8622. }
  8623. return;
  8624. }
  8625. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8626. const data = buffers.get( attribute );
  8627. if ( data === undefined ) {
  8628. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  8629. } else if ( data.version < attribute.version ) {
  8630. updateBuffer( data.buffer, attribute, bufferType );
  8631. data.version = attribute.version;
  8632. }
  8633. }
  8634. return {
  8635. get: get,
  8636. remove: remove,
  8637. update: update
  8638. };
  8639. }
  8640. class PlaneGeometry extends BufferGeometry {
  8641. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  8642. super();
  8643. this.type = 'PlaneGeometry';
  8644. this.parameters = {
  8645. width: width,
  8646. height: height,
  8647. widthSegments: widthSegments,
  8648. heightSegments: heightSegments
  8649. };
  8650. const width_half = width / 2;
  8651. const height_half = height / 2;
  8652. const gridX = Math.floor( widthSegments );
  8653. const gridY = Math.floor( heightSegments );
  8654. const gridX1 = gridX + 1;
  8655. const gridY1 = gridY + 1;
  8656. const segment_width = width / gridX;
  8657. const segment_height = height / gridY;
  8658. //
  8659. const indices = [];
  8660. const vertices = [];
  8661. const normals = [];
  8662. const uvs = [];
  8663. for ( let iy = 0; iy < gridY1; iy ++ ) {
  8664. const y = iy * segment_height - height_half;
  8665. for ( let ix = 0; ix < gridX1; ix ++ ) {
  8666. const x = ix * segment_width - width_half;
  8667. vertices.push( x, - y, 0 );
  8668. normals.push( 0, 0, 1 );
  8669. uvs.push( ix / gridX );
  8670. uvs.push( 1 - ( iy / gridY ) );
  8671. }
  8672. }
  8673. for ( let iy = 0; iy < gridY; iy ++ ) {
  8674. for ( let ix = 0; ix < gridX; ix ++ ) {
  8675. const a = ix + gridX1 * iy;
  8676. const b = ix + gridX1 * ( iy + 1 );
  8677. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  8678. const d = ( ix + 1 ) + gridX1 * iy;
  8679. indices.push( a, b, d );
  8680. indices.push( b, c, d );
  8681. }
  8682. }
  8683. this.setIndex( indices );
  8684. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  8685. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  8686. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  8687. }
  8688. static fromJSON( data ) {
  8689. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  8690. }
  8691. }
  8692. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  8693. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8694. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  8695. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  8696. 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";
  8697. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  8698. var begin_vertex = "vec3 transformed = vec3( position );";
  8699. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  8700. var bsdfs = "vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_GGX( const in IncidentLight incidentLight, 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( incidentLight.direction + viewDir );\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotVH = saturate( dot( geometry.viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float NoH ) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float NoV, float NoL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( NoL + NoV - NoL * NoV ) ) );\n}\nvec3 BRDF_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif";
  8701. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif";
  8702. 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";
  8703. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  8704. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  8705. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  8706. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  8707. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  8708. 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";
  8709. 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";
  8710. var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}";
  8711. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_maxMipLevel 8.0\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_maxTileSize 256.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\tfloat texelSize = 1.0 / ( 3.0 * cubeUV_maxTileSize );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 1.0 );\n\t\tvec2 f = fract( uv );\n\t\tuv += 0.5 - f;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tif ( mipInt < cubeUV_maxMipLevel ) {\n\t\t\tuv.y += 2.0 * cubeUV_maxTileSize;\n\t\t}\n\t\tuv.y += filterInt * 2.0 * cubeUV_minTileSize;\n\t\tuv.x += 3.0 * max( 0.0, cubeUV_maxTileSize - 2.0 * faceSize );\n\t\tuv *= texelSize;\n\t\tvec3 tl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x += texelSize;\n\t\tvec3 tr = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.y += texelSize;\n\t\tvec3 br = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x -= texelSize;\n\t\tvec3 bl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tvec3 tm = mix( tl, tr, f.x );\n\t\tvec3 bm = mix( bl, br, f.x );\n\t\treturn mix( tm, bm, f.y );\n\t}\n\t#define r0 1.0\n\t#define v0 0.339\n\t#define m0 - 2.0\n\t#define r1 0.8\n\t#define v1 0.276\n\t#define m1 - 1.0\n\t#define r4 0.4\n\t#define v4 0.046\n\t#define m4 2.0\n\t#define r5 0.305\n\t#define v5 0.016\n\t#define m5 3.0\n\t#define r6 0.21\n\t#define v6 0.0038\n\t#define m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= r1 ) {\n\t\t\tmip = ( r0 - roughness ) * ( m1 - m0 ) / ( r0 - r1 ) + m0;\n\t\t} else if ( roughness >= r4 ) {\n\t\t\tmip = ( r1 - roughness ) * ( m4 - m1 ) / ( r1 - r4 ) + m1;\n\t\t} else if ( roughness >= r5 ) {\n\t\t\tmip = ( r4 - roughness ) * ( m5 - m4 ) / ( r4 - r5 ) + m4;\n\t\t} else if ( roughness >= r6 ) {\n\t\t\tmip = ( r5 - roughness ) * ( m6 - m5 ) / ( r5 - r6 ) + m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), m0, cubeUV_maxMipLevel );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif";
  8712. 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";
  8713. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  8714. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  8715. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  8716. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  8717. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  8718. var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = clamp( floor( D ) / 255.0, 0.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = cLogLuvM * value.rgb;\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract( Le );\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb;\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\n}";
  8719. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  8720. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif";
  8721. var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif";
  8722. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif";
  8723. 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";
  8724. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  8725. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  8726. 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";
  8727. 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";
  8728. var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn texture2D( gradientMap, coord ).rgb;\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";
  8729. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tlightMapIrradiance *= PI;\n\t#endif\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  8730. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  8731. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointLightInfo( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotLightInfo( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalLightInfo( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif";
  8732. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#else\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif";
  8733. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getIBLIrradiance( const in GeometricContext geometry ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 reflectVec;\n\t\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\t\treflectVec = reflect( - viewDir, normal );\n\t\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\t#else\n\t\t\t\treflectVec = refract( - viewDir, normal, refractionRatio );\n\t\t\t#endif\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n#endif";
  8734. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  8735. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)";
  8736. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  8737. 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, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";
  8738. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularTintFactor = specularTint;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARTINTMAP\n\t\t\tspecularTintFactor *= specularTintMapTexelToLinear( texture2D( specularTintMap, 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 specularTintFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( ior - 1.0 ) / ( ior + 1.0 ) ) * specularTintFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenTint = sheenTint;\n#endif";
  8739. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenTint;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\tvec3 FssEss = specularColor * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += irradiance * BRDF_Sheen( material.roughness, directLight.direction, geometry, material.sheenTint );\n\t#else\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  8740. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  8741. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry );\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";
  8742. 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";
  8743. 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";
  8744. 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";
  8745. 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";
  8746. 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";
  8747. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  8748. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  8749. var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
  8750. 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";
  8751. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  8752. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  8753. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n#endif";
  8754. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifndef USE_MORPHNORMALS\n\t\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\t\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
  8755. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t#endif\n#endif";
  8756. var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * faceDirection;\n\t\t\tbitangent = bitangent * faceDirection;\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;";
  8757. 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";
  8758. 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";
  8759. 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";
  8760. 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";
  8761. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\t\treturn normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\t}\n#endif";
  8762. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  8763. 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";
  8764. 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";
  8765. var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
  8766. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}";
  8767. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8768. 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;";
  8769. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8770. 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";
  8771. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8772. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8773. var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif";
  8774. var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif";
  8775. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif";
  8776. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}";
  8777. 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";
  8778. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif";
  8779. 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";
  8780. 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";
  8781. 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";
  8782. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8783. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8784. 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; }";
  8785. var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tfloat transmissionAlpha = 1.0;\n\tfloat transmissionFactor = transmission;\n\tfloat thicknessFactor = thickness;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\ttransmissionFactor *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tthicknessFactor *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = getIBLVolumeRefraction(\n\t\tn, v, roughnessFactor, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, ior, thicknessFactor,\n\t\tattenuationTint, attenuationDistance );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, transmissionFactor );\n\ttransmissionAlpha = transmission.a;\n#endif";
  8786. var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationTint;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( vec3 n, vec3 v, float thickness, float ior, mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( float roughness, float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( vec2 fragCoord, float roughness, float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( vec3 radiance, float transmissionDistance, vec3 attenuationColor, float attenuationDistance ) {\n\t\tif ( attenuationDistance == 0.0 ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( vec3 n, vec3 v, float roughness, vec3 diffuseColor, vec3 specularColor, float specularF90,\n\t\tvec3 position, mat4 modelMatrix, mat4 viewMatrix, mat4 projMatrix, float ior, float thickness,\n\t\tvec3 attenuationColor, float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif";
  8787. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  8788. 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";
  8789. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  8790. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  8791. 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";
  8792. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  8793. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION )\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
  8794. var background_frag = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  8795. var background_vert = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}";
  8796. var cube_frag = "#include <envmap_common_pars_fragment>\nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  8797. var cube_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";
  8798. var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <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}";
  8799. var depth_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}";
  8800. var distanceRGBA_frag = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <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}";
  8801. var distanceRGBA_vert = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}";
  8802. var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  8803. var equirect_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
  8804. var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\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}";
  8805. var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  8806. var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8807. var meshbasic_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#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}";
  8808. var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8809. var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8810. var meshmatcap_frag = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8811. var meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  8812. var meshnormal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}";
  8813. var meshnormal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  8814. var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8815. var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8816. var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularTint;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARTINTMAP\n\t\tuniform sampler2D specularTintMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenTint;\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_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 - clearcoat * Fcc ) + clearcoatSpecular * 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}";
  8817. var meshphysical_vert = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}";
  8818. var meshtoon_frag = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <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}";
  8819. var meshtoon_vert = "#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8820. var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <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}";
  8821. var points_vert = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";
  8822. var shadow_frag = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  8823. var shadow_vert = "#include <common>\n#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8824. var sprite_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <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}";
  8825. var sprite_vert = "uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  8826. const ShaderChunk = {
  8827. alphamap_fragment: alphamap_fragment,
  8828. alphamap_pars_fragment: alphamap_pars_fragment,
  8829. alphatest_fragment: alphatest_fragment,
  8830. alphatest_pars_fragment: alphatest_pars_fragment,
  8831. aomap_fragment: aomap_fragment,
  8832. aomap_pars_fragment: aomap_pars_fragment,
  8833. begin_vertex: begin_vertex,
  8834. beginnormal_vertex: beginnormal_vertex,
  8835. bsdfs: bsdfs,
  8836. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8837. clipping_planes_fragment: clipping_planes_fragment,
  8838. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8839. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8840. clipping_planes_vertex: clipping_planes_vertex,
  8841. color_fragment: color_fragment,
  8842. color_pars_fragment: color_pars_fragment,
  8843. color_pars_vertex: color_pars_vertex,
  8844. color_vertex: color_vertex,
  8845. common: common,
  8846. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8847. defaultnormal_vertex: defaultnormal_vertex,
  8848. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8849. displacementmap_vertex: displacementmap_vertex,
  8850. emissivemap_fragment: emissivemap_fragment,
  8851. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8852. encodings_fragment: encodings_fragment,
  8853. encodings_pars_fragment: encodings_pars_fragment,
  8854. envmap_fragment: envmap_fragment,
  8855. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8856. envmap_pars_fragment: envmap_pars_fragment,
  8857. envmap_pars_vertex: envmap_pars_vertex,
  8858. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8859. envmap_vertex: envmap_vertex,
  8860. fog_vertex: fog_vertex,
  8861. fog_pars_vertex: fog_pars_vertex,
  8862. fog_fragment: fog_fragment,
  8863. fog_pars_fragment: fog_pars_fragment,
  8864. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8865. lightmap_fragment: lightmap_fragment,
  8866. lightmap_pars_fragment: lightmap_pars_fragment,
  8867. lights_lambert_vertex: lights_lambert_vertex,
  8868. lights_pars_begin: lights_pars_begin,
  8869. lights_toon_fragment: lights_toon_fragment,
  8870. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8871. lights_phong_fragment: lights_phong_fragment,
  8872. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8873. lights_physical_fragment: lights_physical_fragment,
  8874. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8875. lights_fragment_begin: lights_fragment_begin,
  8876. lights_fragment_maps: lights_fragment_maps,
  8877. lights_fragment_end: lights_fragment_end,
  8878. logdepthbuf_fragment: logdepthbuf_fragment,
  8879. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8880. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8881. logdepthbuf_vertex: logdepthbuf_vertex,
  8882. map_fragment: map_fragment,
  8883. map_pars_fragment: map_pars_fragment,
  8884. map_particle_fragment: map_particle_fragment,
  8885. map_particle_pars_fragment: map_particle_pars_fragment,
  8886. metalnessmap_fragment: metalnessmap_fragment,
  8887. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8888. morphnormal_vertex: morphnormal_vertex,
  8889. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8890. morphtarget_vertex: morphtarget_vertex,
  8891. normal_fragment_begin: normal_fragment_begin,
  8892. normal_fragment_maps: normal_fragment_maps,
  8893. normal_pars_fragment: normal_pars_fragment,
  8894. normal_pars_vertex: normal_pars_vertex,
  8895. normal_vertex: normal_vertex,
  8896. normalmap_pars_fragment: normalmap_pars_fragment,
  8897. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8898. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8899. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8900. output_fragment: output_fragment,
  8901. packing: packing,
  8902. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8903. project_vertex: project_vertex,
  8904. dithering_fragment: dithering_fragment,
  8905. dithering_pars_fragment: dithering_pars_fragment,
  8906. roughnessmap_fragment: roughnessmap_fragment,
  8907. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8908. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8909. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8910. shadowmap_vertex: shadowmap_vertex,
  8911. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8912. skinbase_vertex: skinbase_vertex,
  8913. skinning_pars_vertex: skinning_pars_vertex,
  8914. skinning_vertex: skinning_vertex,
  8915. skinnormal_vertex: skinnormal_vertex,
  8916. specularmap_fragment: specularmap_fragment,
  8917. specularmap_pars_fragment: specularmap_pars_fragment,
  8918. tonemapping_fragment: tonemapping_fragment,
  8919. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8920. transmission_fragment: transmission_fragment,
  8921. transmission_pars_fragment: transmission_pars_fragment,
  8922. uv_pars_fragment: uv_pars_fragment,
  8923. uv_pars_vertex: uv_pars_vertex,
  8924. uv_vertex: uv_vertex,
  8925. uv2_pars_fragment: uv2_pars_fragment,
  8926. uv2_pars_vertex: uv2_pars_vertex,
  8927. uv2_vertex: uv2_vertex,
  8928. worldpos_vertex: worldpos_vertex,
  8929. background_frag: background_frag,
  8930. background_vert: background_vert,
  8931. cube_frag: cube_frag,
  8932. cube_vert: cube_vert,
  8933. depth_frag: depth_frag,
  8934. depth_vert: depth_vert,
  8935. distanceRGBA_frag: distanceRGBA_frag,
  8936. distanceRGBA_vert: distanceRGBA_vert,
  8937. equirect_frag: equirect_frag,
  8938. equirect_vert: equirect_vert,
  8939. linedashed_frag: linedashed_frag,
  8940. linedashed_vert: linedashed_vert,
  8941. meshbasic_frag: meshbasic_frag,
  8942. meshbasic_vert: meshbasic_vert,
  8943. meshlambert_frag: meshlambert_frag,
  8944. meshlambert_vert: meshlambert_vert,
  8945. meshmatcap_frag: meshmatcap_frag,
  8946. meshmatcap_vert: meshmatcap_vert,
  8947. meshnormal_frag: meshnormal_frag,
  8948. meshnormal_vert: meshnormal_vert,
  8949. meshphong_frag: meshphong_frag,
  8950. meshphong_vert: meshphong_vert,
  8951. meshphysical_frag: meshphysical_frag,
  8952. meshphysical_vert: meshphysical_vert,
  8953. meshtoon_frag: meshtoon_frag,
  8954. meshtoon_vert: meshtoon_vert,
  8955. points_frag: points_frag,
  8956. points_vert: points_vert,
  8957. shadow_frag: shadow_frag,
  8958. shadow_vert: shadow_vert,
  8959. sprite_frag: sprite_frag,
  8960. sprite_vert: sprite_vert
  8961. };
  8962. /**
  8963. * Uniforms library for shared webgl shaders
  8964. */
  8965. const UniformsLib = {
  8966. common: {
  8967. diffuse: { value: new Color( 0xffffff ) },
  8968. opacity: { value: 1.0 },
  8969. map: { value: null },
  8970. uvTransform: { value: new Matrix3() },
  8971. uv2Transform: { value: new Matrix3() },
  8972. alphaMap: { value: null },
  8973. alphaTest: { value: 0 }
  8974. },
  8975. specularmap: {
  8976. specularMap: { value: null },
  8977. },
  8978. envmap: {
  8979. envMap: { value: null },
  8980. flipEnvMap: { value: - 1 },
  8981. reflectivity: { value: 1.0 }, // basic, lambert, phong
  8982. ior: { value: 1.5 }, // standard, physical
  8983. refractionRatio: { value: 0.98 },
  8984. maxMipLevel: { value: 0 }
  8985. },
  8986. aomap: {
  8987. aoMap: { value: null },
  8988. aoMapIntensity: { value: 1 }
  8989. },
  8990. lightmap: {
  8991. lightMap: { value: null },
  8992. lightMapIntensity: { value: 1 }
  8993. },
  8994. emissivemap: {
  8995. emissiveMap: { value: null }
  8996. },
  8997. bumpmap: {
  8998. bumpMap: { value: null },
  8999. bumpScale: { value: 1 }
  9000. },
  9001. normalmap: {
  9002. normalMap: { value: null },
  9003. normalScale: { value: new Vector2( 1, 1 ) }
  9004. },
  9005. displacementmap: {
  9006. displacementMap: { value: null },
  9007. displacementScale: { value: 1 },
  9008. displacementBias: { value: 0 }
  9009. },
  9010. roughnessmap: {
  9011. roughnessMap: { value: null }
  9012. },
  9013. metalnessmap: {
  9014. metalnessMap: { value: null }
  9015. },
  9016. gradientmap: {
  9017. gradientMap: { value: null }
  9018. },
  9019. fog: {
  9020. fogDensity: { value: 0.00025 },
  9021. fogNear: { value: 1 },
  9022. fogFar: { value: 2000 },
  9023. fogColor: { value: new Color( 0xffffff ) }
  9024. },
  9025. lights: {
  9026. ambientLightColor: { value: [] },
  9027. lightProbe: { value: [] },
  9028. directionalLights: { value: [], properties: {
  9029. direction: {},
  9030. color: {}
  9031. } },
  9032. directionalLightShadows: { value: [], properties: {
  9033. shadowBias: {},
  9034. shadowNormalBias: {},
  9035. shadowRadius: {},
  9036. shadowMapSize: {}
  9037. } },
  9038. directionalShadowMap: { value: [] },
  9039. directionalShadowMatrix: { value: [] },
  9040. spotLights: { value: [], properties: {
  9041. color: {},
  9042. position: {},
  9043. direction: {},
  9044. distance: {},
  9045. coneCos: {},
  9046. penumbraCos: {},
  9047. decay: {}
  9048. } },
  9049. spotLightShadows: { value: [], properties: {
  9050. shadowBias: {},
  9051. shadowNormalBias: {},
  9052. shadowRadius: {},
  9053. shadowMapSize: {}
  9054. } },
  9055. spotShadowMap: { value: [] },
  9056. spotShadowMatrix: { value: [] },
  9057. pointLights: { value: [], properties: {
  9058. color: {},
  9059. position: {},
  9060. decay: {},
  9061. distance: {}
  9062. } },
  9063. pointLightShadows: { value: [], properties: {
  9064. shadowBias: {},
  9065. shadowNormalBias: {},
  9066. shadowRadius: {},
  9067. shadowMapSize: {},
  9068. shadowCameraNear: {},
  9069. shadowCameraFar: {}
  9070. } },
  9071. pointShadowMap: { value: [] },
  9072. pointShadowMatrix: { value: [] },
  9073. hemisphereLights: { value: [], properties: {
  9074. direction: {},
  9075. skyColor: {},
  9076. groundColor: {}
  9077. } },
  9078. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  9079. rectAreaLights: { value: [], properties: {
  9080. color: {},
  9081. position: {},
  9082. width: {},
  9083. height: {}
  9084. } },
  9085. ltc_1: { value: null },
  9086. ltc_2: { value: null }
  9087. },
  9088. points: {
  9089. diffuse: { value: new Color( 0xffffff ) },
  9090. opacity: { value: 1.0 },
  9091. size: { value: 1.0 },
  9092. scale: { value: 1.0 },
  9093. map: { value: null },
  9094. alphaMap: { value: null },
  9095. alphaTest: { value: 0 },
  9096. uvTransform: { value: new Matrix3() }
  9097. },
  9098. sprite: {
  9099. diffuse: { value: new Color( 0xffffff ) },
  9100. opacity: { value: 1.0 },
  9101. center: { value: new Vector2( 0.5, 0.5 ) },
  9102. rotation: { value: 0.0 },
  9103. map: { value: null },
  9104. alphaMap: { value: null },
  9105. alphaTest: { value: 0 },
  9106. uvTransform: { value: new Matrix3() }
  9107. }
  9108. };
  9109. const ShaderLib = {
  9110. basic: {
  9111. uniforms: mergeUniforms( [
  9112. UniformsLib.common,
  9113. UniformsLib.specularmap,
  9114. UniformsLib.envmap,
  9115. UniformsLib.aomap,
  9116. UniformsLib.lightmap,
  9117. UniformsLib.fog
  9118. ] ),
  9119. vertexShader: ShaderChunk.meshbasic_vert,
  9120. fragmentShader: ShaderChunk.meshbasic_frag
  9121. },
  9122. lambert: {
  9123. uniforms: mergeUniforms( [
  9124. UniformsLib.common,
  9125. UniformsLib.specularmap,
  9126. UniformsLib.envmap,
  9127. UniformsLib.aomap,
  9128. UniformsLib.lightmap,
  9129. UniformsLib.emissivemap,
  9130. UniformsLib.fog,
  9131. UniformsLib.lights,
  9132. {
  9133. emissive: { value: new Color( 0x000000 ) }
  9134. }
  9135. ] ),
  9136. vertexShader: ShaderChunk.meshlambert_vert,
  9137. fragmentShader: ShaderChunk.meshlambert_frag
  9138. },
  9139. phong: {
  9140. uniforms: mergeUniforms( [
  9141. UniformsLib.common,
  9142. UniformsLib.specularmap,
  9143. UniformsLib.envmap,
  9144. UniformsLib.aomap,
  9145. UniformsLib.lightmap,
  9146. UniformsLib.emissivemap,
  9147. UniformsLib.bumpmap,
  9148. UniformsLib.normalmap,
  9149. UniformsLib.displacementmap,
  9150. UniformsLib.fog,
  9151. UniformsLib.lights,
  9152. {
  9153. emissive: { value: new Color( 0x000000 ) },
  9154. specular: { value: new Color( 0x111111 ) },
  9155. shininess: { value: 30 }
  9156. }
  9157. ] ),
  9158. vertexShader: ShaderChunk.meshphong_vert,
  9159. fragmentShader: ShaderChunk.meshphong_frag
  9160. },
  9161. standard: {
  9162. uniforms: mergeUniforms( [
  9163. UniformsLib.common,
  9164. UniformsLib.envmap,
  9165. UniformsLib.aomap,
  9166. UniformsLib.lightmap,
  9167. UniformsLib.emissivemap,
  9168. UniformsLib.bumpmap,
  9169. UniformsLib.normalmap,
  9170. UniformsLib.displacementmap,
  9171. UniformsLib.roughnessmap,
  9172. UniformsLib.metalnessmap,
  9173. UniformsLib.fog,
  9174. UniformsLib.lights,
  9175. {
  9176. emissive: { value: new Color( 0x000000 ) },
  9177. roughness: { value: 1.0 },
  9178. metalness: { value: 0.0 },
  9179. envMapIntensity: { value: 1 } // temporary
  9180. }
  9181. ] ),
  9182. vertexShader: ShaderChunk.meshphysical_vert,
  9183. fragmentShader: ShaderChunk.meshphysical_frag
  9184. },
  9185. toon: {
  9186. uniforms: mergeUniforms( [
  9187. UniformsLib.common,
  9188. UniformsLib.aomap,
  9189. UniformsLib.lightmap,
  9190. UniformsLib.emissivemap,
  9191. UniformsLib.bumpmap,
  9192. UniformsLib.normalmap,
  9193. UniformsLib.displacementmap,
  9194. UniformsLib.gradientmap,
  9195. UniformsLib.fog,
  9196. UniformsLib.lights,
  9197. {
  9198. emissive: { value: new Color( 0x000000 ) }
  9199. }
  9200. ] ),
  9201. vertexShader: ShaderChunk.meshtoon_vert,
  9202. fragmentShader: ShaderChunk.meshtoon_frag
  9203. },
  9204. matcap: {
  9205. uniforms: mergeUniforms( [
  9206. UniformsLib.common,
  9207. UniformsLib.bumpmap,
  9208. UniformsLib.normalmap,
  9209. UniformsLib.displacementmap,
  9210. UniformsLib.fog,
  9211. {
  9212. matcap: { value: null }
  9213. }
  9214. ] ),
  9215. vertexShader: ShaderChunk.meshmatcap_vert,
  9216. fragmentShader: ShaderChunk.meshmatcap_frag
  9217. },
  9218. points: {
  9219. uniforms: mergeUniforms( [
  9220. UniformsLib.points,
  9221. UniformsLib.fog
  9222. ] ),
  9223. vertexShader: ShaderChunk.points_vert,
  9224. fragmentShader: ShaderChunk.points_frag
  9225. },
  9226. dashed: {
  9227. uniforms: mergeUniforms( [
  9228. UniformsLib.common,
  9229. UniformsLib.fog,
  9230. {
  9231. scale: { value: 1 },
  9232. dashSize: { value: 1 },
  9233. totalSize: { value: 2 }
  9234. }
  9235. ] ),
  9236. vertexShader: ShaderChunk.linedashed_vert,
  9237. fragmentShader: ShaderChunk.linedashed_frag
  9238. },
  9239. depth: {
  9240. uniforms: mergeUniforms( [
  9241. UniformsLib.common,
  9242. UniformsLib.displacementmap
  9243. ] ),
  9244. vertexShader: ShaderChunk.depth_vert,
  9245. fragmentShader: ShaderChunk.depth_frag
  9246. },
  9247. normal: {
  9248. uniforms: mergeUniforms( [
  9249. UniformsLib.common,
  9250. UniformsLib.bumpmap,
  9251. UniformsLib.normalmap,
  9252. UniformsLib.displacementmap,
  9253. {
  9254. opacity: { value: 1.0 }
  9255. }
  9256. ] ),
  9257. vertexShader: ShaderChunk.meshnormal_vert,
  9258. fragmentShader: ShaderChunk.meshnormal_frag
  9259. },
  9260. sprite: {
  9261. uniforms: mergeUniforms( [
  9262. UniformsLib.sprite,
  9263. UniformsLib.fog
  9264. ] ),
  9265. vertexShader: ShaderChunk.sprite_vert,
  9266. fragmentShader: ShaderChunk.sprite_frag
  9267. },
  9268. background: {
  9269. uniforms: {
  9270. uvTransform: { value: new Matrix3() },
  9271. t2D: { value: null },
  9272. },
  9273. vertexShader: ShaderChunk.background_vert,
  9274. fragmentShader: ShaderChunk.background_frag
  9275. },
  9276. /* -------------------------------------------------------------------------
  9277. // Cube map shader
  9278. ------------------------------------------------------------------------- */
  9279. cube: {
  9280. uniforms: mergeUniforms( [
  9281. UniformsLib.envmap,
  9282. {
  9283. opacity: { value: 1.0 }
  9284. }
  9285. ] ),
  9286. vertexShader: ShaderChunk.cube_vert,
  9287. fragmentShader: ShaderChunk.cube_frag
  9288. },
  9289. equirect: {
  9290. uniforms: {
  9291. tEquirect: { value: null },
  9292. },
  9293. vertexShader: ShaderChunk.equirect_vert,
  9294. fragmentShader: ShaderChunk.equirect_frag
  9295. },
  9296. distanceRGBA: {
  9297. uniforms: mergeUniforms( [
  9298. UniformsLib.common,
  9299. UniformsLib.displacementmap,
  9300. {
  9301. referencePosition: { value: new Vector3() },
  9302. nearDistance: { value: 1 },
  9303. farDistance: { value: 1000 }
  9304. }
  9305. ] ),
  9306. vertexShader: ShaderChunk.distanceRGBA_vert,
  9307. fragmentShader: ShaderChunk.distanceRGBA_frag
  9308. },
  9309. shadow: {
  9310. uniforms: mergeUniforms( [
  9311. UniformsLib.lights,
  9312. UniformsLib.fog,
  9313. {
  9314. color: { value: new Color( 0x00000 ) },
  9315. opacity: { value: 1.0 }
  9316. },
  9317. ] ),
  9318. vertexShader: ShaderChunk.shadow_vert,
  9319. fragmentShader: ShaderChunk.shadow_frag
  9320. }
  9321. };
  9322. ShaderLib.physical = {
  9323. uniforms: mergeUniforms( [
  9324. ShaderLib.standard.uniforms,
  9325. {
  9326. clearcoat: { value: 0 },
  9327. clearcoatMap: { value: null },
  9328. clearcoatRoughness: { value: 0 },
  9329. clearcoatRoughnessMap: { value: null },
  9330. clearcoatNormalScale: { value: new Vector2( 1, 1 ) },
  9331. clearcoatNormalMap: { value: null },
  9332. sheenTint: { value: new Color( 0x000000 ) },
  9333. transmission: { value: 0 },
  9334. transmissionMap: { value: null },
  9335. transmissionSamplerSize: { value: new Vector2() },
  9336. transmissionSamplerMap: { value: null },
  9337. thickness: { value: 0 },
  9338. thicknessMap: { value: null },
  9339. attenuationDistance: { value: 0 },
  9340. attenuationTint: { value: new Color( 0x000000 ) },
  9341. specularIntensity: { value: 0 },
  9342. specularIntensityMap: { value: null },
  9343. specularTint: { value: new Color( 1, 1, 1 ) },
  9344. specularTintMap: { value: null },
  9345. }
  9346. ] ),
  9347. vertexShader: ShaderChunk.meshphysical_vert,
  9348. fragmentShader: ShaderChunk.meshphysical_frag
  9349. };
  9350. function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha ) {
  9351. const clearColor = new Color( 0x000000 );
  9352. let clearAlpha = 0;
  9353. let planeMesh;
  9354. let boxMesh;
  9355. let currentBackground = null;
  9356. let currentBackgroundVersion = 0;
  9357. let currentTonemapping = null;
  9358. function render( renderList, scene ) {
  9359. let forceClear = false;
  9360. let background = scene.isScene === true ? scene.background : null;
  9361. if ( background && background.isTexture ) {
  9362. background = cubemaps.get( background );
  9363. }
  9364. // Ignore background in AR
  9365. // TODO: Reconsider this.
  9366. const xr = renderer.xr;
  9367. const session = xr.getSession && xr.getSession();
  9368. if ( session && session.environmentBlendMode === 'additive' ) {
  9369. background = null;
  9370. }
  9371. if ( background === null ) {
  9372. setClear( clearColor, clearAlpha );
  9373. } else if ( background && background.isColor ) {
  9374. setClear( background, 1 );
  9375. forceClear = true;
  9376. }
  9377. if ( renderer.autoClear || forceClear ) {
  9378. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  9379. }
  9380. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  9381. if ( boxMesh === undefined ) {
  9382. boxMesh = new Mesh(
  9383. new BoxGeometry( 1, 1, 1 ),
  9384. new ShaderMaterial( {
  9385. name: 'BackgroundCubeMaterial',
  9386. uniforms: cloneUniforms( ShaderLib.cube.uniforms ),
  9387. vertexShader: ShaderLib.cube.vertexShader,
  9388. fragmentShader: ShaderLib.cube.fragmentShader,
  9389. side: BackSide,
  9390. depthTest: false,
  9391. depthWrite: false,
  9392. fog: false
  9393. } )
  9394. );
  9395. boxMesh.geometry.deleteAttribute( 'normal' );
  9396. boxMesh.geometry.deleteAttribute( 'uv' );
  9397. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  9398. this.matrixWorld.copyPosition( camera.matrixWorld );
  9399. };
  9400. // enable code injection for non-built-in material
  9401. Object.defineProperty( boxMesh.material, 'envMap', {
  9402. get: function () {
  9403. return this.uniforms.envMap.value;
  9404. }
  9405. } );
  9406. objects.update( boxMesh );
  9407. }
  9408. boxMesh.material.uniforms.envMap.value = background;
  9409. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  9410. if ( currentBackground !== background ||
  9411. currentBackgroundVersion !== background.version ||
  9412. currentTonemapping !== renderer.toneMapping ) {
  9413. boxMesh.material.needsUpdate = true;
  9414. currentBackground = background;
  9415. currentBackgroundVersion = background.version;
  9416. currentTonemapping = renderer.toneMapping;
  9417. }
  9418. // push to the pre-sorted opaque render list
  9419. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  9420. } else if ( background && background.isTexture ) {
  9421. if ( planeMesh === undefined ) {
  9422. planeMesh = new Mesh(
  9423. new PlaneGeometry( 2, 2 ),
  9424. new ShaderMaterial( {
  9425. name: 'BackgroundMaterial',
  9426. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  9427. vertexShader: ShaderLib.background.vertexShader,
  9428. fragmentShader: ShaderLib.background.fragmentShader,
  9429. side: FrontSide,
  9430. depthTest: false,
  9431. depthWrite: false,
  9432. fog: false
  9433. } )
  9434. );
  9435. planeMesh.geometry.deleteAttribute( 'normal' );
  9436. // enable code injection for non-built-in material
  9437. Object.defineProperty( planeMesh.material, 'map', {
  9438. get: function () {
  9439. return this.uniforms.t2D.value;
  9440. }
  9441. } );
  9442. objects.update( planeMesh );
  9443. }
  9444. planeMesh.material.uniforms.t2D.value = background;
  9445. if ( background.matrixAutoUpdate === true ) {
  9446. background.updateMatrix();
  9447. }
  9448. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  9449. if ( currentBackground !== background ||
  9450. currentBackgroundVersion !== background.version ||
  9451. currentTonemapping !== renderer.toneMapping ) {
  9452. planeMesh.material.needsUpdate = true;
  9453. currentBackground = background;
  9454. currentBackgroundVersion = background.version;
  9455. currentTonemapping = renderer.toneMapping;
  9456. }
  9457. // push to the pre-sorted opaque render list
  9458. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  9459. }
  9460. }
  9461. function setClear( color, alpha ) {
  9462. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  9463. }
  9464. return {
  9465. getClearColor: function () {
  9466. return clearColor;
  9467. },
  9468. setClearColor: function ( color, alpha = 1 ) {
  9469. clearColor.set( color );
  9470. clearAlpha = alpha;
  9471. setClear( clearColor, clearAlpha );
  9472. },
  9473. getClearAlpha: function () {
  9474. return clearAlpha;
  9475. },
  9476. setClearAlpha: function ( alpha ) {
  9477. clearAlpha = alpha;
  9478. setClear( clearColor, clearAlpha );
  9479. },
  9480. render: render
  9481. };
  9482. }
  9483. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  9484. const maxVertexAttributes = gl.getParameter( 34921 );
  9485. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  9486. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  9487. const bindingStates = {};
  9488. const defaultState = createBindingState( null );
  9489. let currentState = defaultState;
  9490. function setup( object, material, program, geometry, index ) {
  9491. let updateBuffers = false;
  9492. if ( vaoAvailable ) {
  9493. const state = getBindingState( geometry, program, material );
  9494. if ( currentState !== state ) {
  9495. currentState = state;
  9496. bindVertexArrayObject( currentState.object );
  9497. }
  9498. updateBuffers = needsUpdate( geometry, index );
  9499. if ( updateBuffers ) saveCache( geometry, index );
  9500. } else {
  9501. const wireframe = ( material.wireframe === true );
  9502. if ( currentState.geometry !== geometry.id ||
  9503. currentState.program !== program.id ||
  9504. currentState.wireframe !== wireframe ) {
  9505. currentState.geometry = geometry.id;
  9506. currentState.program = program.id;
  9507. currentState.wireframe = wireframe;
  9508. updateBuffers = true;
  9509. }
  9510. }
  9511. if ( object.isInstancedMesh === true ) {
  9512. updateBuffers = true;
  9513. }
  9514. if ( index !== null ) {
  9515. attributes.update( index, 34963 );
  9516. }
  9517. if ( updateBuffers ) {
  9518. setupVertexAttributes( object, material, program, geometry );
  9519. if ( index !== null ) {
  9520. gl.bindBuffer( 34963, attributes.get( index ).buffer );
  9521. }
  9522. }
  9523. }
  9524. function createVertexArrayObject() {
  9525. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  9526. return extension.createVertexArrayOES();
  9527. }
  9528. function bindVertexArrayObject( vao ) {
  9529. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  9530. return extension.bindVertexArrayOES( vao );
  9531. }
  9532. function deleteVertexArrayObject( vao ) {
  9533. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  9534. return extension.deleteVertexArrayOES( vao );
  9535. }
  9536. function getBindingState( geometry, program, material ) {
  9537. const wireframe = ( material.wireframe === true );
  9538. let programMap = bindingStates[ geometry.id ];
  9539. if ( programMap === undefined ) {
  9540. programMap = {};
  9541. bindingStates[ geometry.id ] = programMap;
  9542. }
  9543. let stateMap = programMap[ program.id ];
  9544. if ( stateMap === undefined ) {
  9545. stateMap = {};
  9546. programMap[ program.id ] = stateMap;
  9547. }
  9548. let state = stateMap[ wireframe ];
  9549. if ( state === undefined ) {
  9550. state = createBindingState( createVertexArrayObject() );
  9551. stateMap[ wireframe ] = state;
  9552. }
  9553. return state;
  9554. }
  9555. function createBindingState( vao ) {
  9556. const newAttributes = [];
  9557. const enabledAttributes = [];
  9558. const attributeDivisors = [];
  9559. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  9560. newAttributes[ i ] = 0;
  9561. enabledAttributes[ i ] = 0;
  9562. attributeDivisors[ i ] = 0;
  9563. }
  9564. return {
  9565. // for backward compatibility on non-VAO support browser
  9566. geometry: null,
  9567. program: null,
  9568. wireframe: false,
  9569. newAttributes: newAttributes,
  9570. enabledAttributes: enabledAttributes,
  9571. attributeDivisors: attributeDivisors,
  9572. object: vao,
  9573. attributes: {},
  9574. index: null
  9575. };
  9576. }
  9577. function needsUpdate( geometry, index ) {
  9578. const cachedAttributes = currentState.attributes;
  9579. const geometryAttributes = geometry.attributes;
  9580. let attributesNum = 0;
  9581. for ( const key in geometryAttributes ) {
  9582. const cachedAttribute = cachedAttributes[ key ];
  9583. const geometryAttribute = geometryAttributes[ key ];
  9584. if ( cachedAttribute === undefined ) return true;
  9585. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  9586. if ( cachedAttribute.data !== geometryAttribute.data ) return true;
  9587. attributesNum ++;
  9588. }
  9589. if ( currentState.attributesNum !== attributesNum ) return true;
  9590. if ( currentState.index !== index ) return true;
  9591. return false;
  9592. }
  9593. function saveCache( geometry, index ) {
  9594. const cache = {};
  9595. const attributes = geometry.attributes;
  9596. let attributesNum = 0;
  9597. for ( const key in attributes ) {
  9598. const attribute = attributes[ key ];
  9599. const data = {};
  9600. data.attribute = attribute;
  9601. if ( attribute.data ) {
  9602. data.data = attribute.data;
  9603. }
  9604. cache[ key ] = data;
  9605. attributesNum ++;
  9606. }
  9607. currentState.attributes = cache;
  9608. currentState.attributesNum = attributesNum;
  9609. currentState.index = index;
  9610. }
  9611. function initAttributes() {
  9612. const newAttributes = currentState.newAttributes;
  9613. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  9614. newAttributes[ i ] = 0;
  9615. }
  9616. }
  9617. function enableAttribute( attribute ) {
  9618. enableAttributeAndDivisor( attribute, 0 );
  9619. }
  9620. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  9621. const newAttributes = currentState.newAttributes;
  9622. const enabledAttributes = currentState.enabledAttributes;
  9623. const attributeDivisors = currentState.attributeDivisors;
  9624. newAttributes[ attribute ] = 1;
  9625. if ( enabledAttributes[ attribute ] === 0 ) {
  9626. gl.enableVertexAttribArray( attribute );
  9627. enabledAttributes[ attribute ] = 1;
  9628. }
  9629. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  9630. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  9631. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  9632. attributeDivisors[ attribute ] = meshPerAttribute;
  9633. }
  9634. }
  9635. function disableUnusedAttributes() {
  9636. const newAttributes = currentState.newAttributes;
  9637. const enabledAttributes = currentState.enabledAttributes;
  9638. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  9639. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  9640. gl.disableVertexAttribArray( i );
  9641. enabledAttributes[ i ] = 0;
  9642. }
  9643. }
  9644. }
  9645. function vertexAttribPointer( index, size, type, normalized, stride, offset ) {
  9646. if ( capabilities.isWebGL2 === true && ( type === 5124 || type === 5125 ) ) {
  9647. gl.vertexAttribIPointer( index, size, type, stride, offset );
  9648. } else {
  9649. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  9650. }
  9651. }
  9652. function setupVertexAttributes( object, material, program, geometry ) {
  9653. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  9654. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  9655. }
  9656. initAttributes();
  9657. const geometryAttributes = geometry.attributes;
  9658. const programAttributes = program.getAttributes();
  9659. const materialDefaultAttributeValues = material.defaultAttributeValues;
  9660. for ( const name in programAttributes ) {
  9661. const programAttribute = programAttributes[ name ];
  9662. if ( programAttribute.location >= 0 ) {
  9663. let geometryAttribute = geometryAttributes[ name ];
  9664. if ( geometryAttribute === undefined ) {
  9665. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  9666. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  9667. }
  9668. if ( geometryAttribute !== undefined ) {
  9669. const normalized = geometryAttribute.normalized;
  9670. const size = geometryAttribute.itemSize;
  9671. const attribute = attributes.get( geometryAttribute );
  9672. // TODO Attribute may not be available on context restore
  9673. if ( attribute === undefined ) continue;
  9674. const buffer = attribute.buffer;
  9675. const type = attribute.type;
  9676. const bytesPerElement = attribute.bytesPerElement;
  9677. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  9678. const data = geometryAttribute.data;
  9679. const stride = data.stride;
  9680. const offset = geometryAttribute.offset;
  9681. if ( data && data.isInstancedInterleavedBuffer ) {
  9682. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9683. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  9684. }
  9685. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  9686. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  9687. }
  9688. } else {
  9689. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9690. enableAttribute( programAttribute.location + i );
  9691. }
  9692. }
  9693. gl.bindBuffer( 34962, buffer );
  9694. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9695. vertexAttribPointer(
  9696. programAttribute.location + i,
  9697. size / programAttribute.locationSize,
  9698. type,
  9699. normalized,
  9700. stride * bytesPerElement,
  9701. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement
  9702. );
  9703. }
  9704. } else {
  9705. if ( geometryAttribute.isInstancedBufferAttribute ) {
  9706. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9707. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  9708. }
  9709. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  9710. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  9711. }
  9712. } else {
  9713. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9714. enableAttribute( programAttribute.location + i );
  9715. }
  9716. }
  9717. gl.bindBuffer( 34962, buffer );
  9718. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9719. vertexAttribPointer(
  9720. programAttribute.location + i,
  9721. size / programAttribute.locationSize,
  9722. type,
  9723. normalized,
  9724. size * bytesPerElement,
  9725. ( size / programAttribute.locationSize ) * i * bytesPerElement
  9726. );
  9727. }
  9728. }
  9729. } else if ( materialDefaultAttributeValues !== undefined ) {
  9730. const value = materialDefaultAttributeValues[ name ];
  9731. if ( value !== undefined ) {
  9732. switch ( value.length ) {
  9733. case 2:
  9734. gl.vertexAttrib2fv( programAttribute.location, value );
  9735. break;
  9736. case 3:
  9737. gl.vertexAttrib3fv( programAttribute.location, value );
  9738. break;
  9739. case 4:
  9740. gl.vertexAttrib4fv( programAttribute.location, value );
  9741. break;
  9742. default:
  9743. gl.vertexAttrib1fv( programAttribute.location, value );
  9744. }
  9745. }
  9746. }
  9747. }
  9748. }
  9749. disableUnusedAttributes();
  9750. }
  9751. function dispose() {
  9752. reset();
  9753. for ( const geometryId in bindingStates ) {
  9754. const programMap = bindingStates[ geometryId ];
  9755. for ( const programId in programMap ) {
  9756. const stateMap = programMap[ programId ];
  9757. for ( const wireframe in stateMap ) {
  9758. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9759. delete stateMap[ wireframe ];
  9760. }
  9761. delete programMap[ programId ];
  9762. }
  9763. delete bindingStates[ geometryId ];
  9764. }
  9765. }
  9766. function releaseStatesOfGeometry( geometry ) {
  9767. if ( bindingStates[ geometry.id ] === undefined ) return;
  9768. const programMap = bindingStates[ geometry.id ];
  9769. for ( const programId in programMap ) {
  9770. const stateMap = programMap[ programId ];
  9771. for ( const wireframe in stateMap ) {
  9772. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9773. delete stateMap[ wireframe ];
  9774. }
  9775. delete programMap[ programId ];
  9776. }
  9777. delete bindingStates[ geometry.id ];
  9778. }
  9779. function releaseStatesOfProgram( program ) {
  9780. for ( const geometryId in bindingStates ) {
  9781. const programMap = bindingStates[ geometryId ];
  9782. if ( programMap[ program.id ] === undefined ) continue;
  9783. const stateMap = programMap[ program.id ];
  9784. for ( const wireframe in stateMap ) {
  9785. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9786. delete stateMap[ wireframe ];
  9787. }
  9788. delete programMap[ program.id ];
  9789. }
  9790. }
  9791. function reset() {
  9792. resetDefaultState();
  9793. if ( currentState === defaultState ) return;
  9794. currentState = defaultState;
  9795. bindVertexArrayObject( currentState.object );
  9796. }
  9797. // for backward-compatilibity
  9798. function resetDefaultState() {
  9799. defaultState.geometry = null;
  9800. defaultState.program = null;
  9801. defaultState.wireframe = false;
  9802. }
  9803. return {
  9804. setup: setup,
  9805. reset: reset,
  9806. resetDefaultState: resetDefaultState,
  9807. dispose: dispose,
  9808. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9809. releaseStatesOfProgram: releaseStatesOfProgram,
  9810. initAttributes: initAttributes,
  9811. enableAttribute: enableAttribute,
  9812. disableUnusedAttributes: disableUnusedAttributes
  9813. };
  9814. }
  9815. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  9816. const isWebGL2 = capabilities.isWebGL2;
  9817. let mode;
  9818. function setMode( value ) {
  9819. mode = value;
  9820. }
  9821. function render( start, count ) {
  9822. gl.drawArrays( mode, start, count );
  9823. info.update( count, mode, 1 );
  9824. }
  9825. function renderInstances( start, count, primcount ) {
  9826. if ( primcount === 0 ) return;
  9827. let extension, methodName;
  9828. if ( isWebGL2 ) {
  9829. extension = gl;
  9830. methodName = 'drawArraysInstanced';
  9831. } else {
  9832. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9833. methodName = 'drawArraysInstancedANGLE';
  9834. if ( extension === null ) {
  9835. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9836. return;
  9837. }
  9838. }
  9839. extension[ methodName ]( mode, start, count, primcount );
  9840. info.update( count, mode, primcount );
  9841. }
  9842. //
  9843. this.setMode = setMode;
  9844. this.render = render;
  9845. this.renderInstances = renderInstances;
  9846. }
  9847. function WebGLCapabilities( gl, extensions, parameters ) {
  9848. let maxAnisotropy;
  9849. function getMaxAnisotropy() {
  9850. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  9851. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  9852. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  9853. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  9854. } else {
  9855. maxAnisotropy = 0;
  9856. }
  9857. return maxAnisotropy;
  9858. }
  9859. function getMaxPrecision( precision ) {
  9860. if ( precision === 'highp' ) {
  9861. if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
  9862. gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {
  9863. return 'highp';
  9864. }
  9865. precision = 'mediump';
  9866. }
  9867. if ( precision === 'mediump' ) {
  9868. if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
  9869. gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {
  9870. return 'mediump';
  9871. }
  9872. }
  9873. return 'lowp';
  9874. }
  9875. /* eslint-disable no-undef */
  9876. const isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext ) ||
  9877. ( typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext );
  9878. /* eslint-enable no-undef */
  9879. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9880. const maxPrecision = getMaxPrecision( precision );
  9881. if ( maxPrecision !== precision ) {
  9882. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  9883. precision = maxPrecision;
  9884. }
  9885. const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' );
  9886. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9887. const maxTextures = gl.getParameter( 34930 );
  9888. const maxVertexTextures = gl.getParameter( 35660 );
  9889. const maxTextureSize = gl.getParameter( 3379 );
  9890. const maxCubemapSize = gl.getParameter( 34076 );
  9891. const maxAttributes = gl.getParameter( 34921 );
  9892. const maxVertexUniforms = gl.getParameter( 36347 );
  9893. const maxVaryings = gl.getParameter( 36348 );
  9894. const maxFragmentUniforms = gl.getParameter( 36349 );
  9895. const vertexTextures = maxVertexTextures > 0;
  9896. const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' );
  9897. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9898. const maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;
  9899. return {
  9900. isWebGL2: isWebGL2,
  9901. drawBuffers: drawBuffers,
  9902. getMaxAnisotropy: getMaxAnisotropy,
  9903. getMaxPrecision: getMaxPrecision,
  9904. precision: precision,
  9905. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9906. maxTextures: maxTextures,
  9907. maxVertexTextures: maxVertexTextures,
  9908. maxTextureSize: maxTextureSize,
  9909. maxCubemapSize: maxCubemapSize,
  9910. maxAttributes: maxAttributes,
  9911. maxVertexUniforms: maxVertexUniforms,
  9912. maxVaryings: maxVaryings,
  9913. maxFragmentUniforms: maxFragmentUniforms,
  9914. vertexTextures: vertexTextures,
  9915. floatFragmentTextures: floatFragmentTextures,
  9916. floatVertexTextures: floatVertexTextures,
  9917. maxSamples: maxSamples
  9918. };
  9919. }
  9920. function WebGLClipping( properties ) {
  9921. const scope = this;
  9922. let globalState = null,
  9923. numGlobalPlanes = 0,
  9924. localClippingEnabled = false,
  9925. renderingShadows = false;
  9926. const plane = new Plane(),
  9927. viewNormalMatrix = new Matrix3(),
  9928. uniform = { value: null, needsUpdate: false };
  9929. this.uniform = uniform;
  9930. this.numPlanes = 0;
  9931. this.numIntersection = 0;
  9932. this.init = function ( planes, enableLocalClipping, camera ) {
  9933. const enabled =
  9934. planes.length !== 0 ||
  9935. enableLocalClipping ||
  9936. // enable state of previous frame - the clipping code has to
  9937. // run another frame in order to reset the state:
  9938. numGlobalPlanes !== 0 ||
  9939. localClippingEnabled;
  9940. localClippingEnabled = enableLocalClipping;
  9941. globalState = projectPlanes( planes, camera, 0 );
  9942. numGlobalPlanes = planes.length;
  9943. return enabled;
  9944. };
  9945. this.beginShadows = function () {
  9946. renderingShadows = true;
  9947. projectPlanes( null );
  9948. };
  9949. this.endShadows = function () {
  9950. renderingShadows = false;
  9951. resetGlobalState();
  9952. };
  9953. this.setState = function ( material, camera, useCache ) {
  9954. const planes = material.clippingPlanes,
  9955. clipIntersection = material.clipIntersection,
  9956. clipShadows = material.clipShadows;
  9957. const materialProperties = properties.get( material );
  9958. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  9959. // there's no local clipping
  9960. if ( renderingShadows ) {
  9961. // there's no global clipping
  9962. projectPlanes( null );
  9963. } else {
  9964. resetGlobalState();
  9965. }
  9966. } else {
  9967. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9968. lGlobal = nGlobal * 4;
  9969. let dstArray = materialProperties.clippingState || null;
  9970. uniform.value = dstArray; // ensure unique state
  9971. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  9972. for ( let i = 0; i !== lGlobal; ++ i ) {
  9973. dstArray[ i ] = globalState[ i ];
  9974. }
  9975. materialProperties.clippingState = dstArray;
  9976. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9977. this.numPlanes += nGlobal;
  9978. }
  9979. };
  9980. function resetGlobalState() {
  9981. if ( uniform.value !== globalState ) {
  9982. uniform.value = globalState;
  9983. uniform.needsUpdate = numGlobalPlanes > 0;
  9984. }
  9985. scope.numPlanes = numGlobalPlanes;
  9986. scope.numIntersection = 0;
  9987. }
  9988. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  9989. const nPlanes = planes !== null ? planes.length : 0;
  9990. let dstArray = null;
  9991. if ( nPlanes !== 0 ) {
  9992. dstArray = uniform.value;
  9993. if ( skipTransform !== true || dstArray === null ) {
  9994. const flatSize = dstOffset + nPlanes * 4,
  9995. viewMatrix = camera.matrixWorldInverse;
  9996. viewNormalMatrix.getNormalMatrix( viewMatrix );
  9997. if ( dstArray === null || dstArray.length < flatSize ) {
  9998. dstArray = new Float32Array( flatSize );
  9999. }
  10000. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  10001. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  10002. plane.normal.toArray( dstArray, i4 );
  10003. dstArray[ i4 + 3 ] = plane.constant;
  10004. }
  10005. }
  10006. uniform.value = dstArray;
  10007. uniform.needsUpdate = true;
  10008. }
  10009. scope.numPlanes = nPlanes;
  10010. scope.numIntersection = 0;
  10011. return dstArray;
  10012. }
  10013. }
  10014. function WebGLCubeMaps( renderer ) {
  10015. let cubemaps = new WeakMap();
  10016. function mapTextureMapping( texture, mapping ) {
  10017. if ( mapping === EquirectangularReflectionMapping ) {
  10018. texture.mapping = CubeReflectionMapping;
  10019. } else if ( mapping === EquirectangularRefractionMapping ) {
  10020. texture.mapping = CubeRefractionMapping;
  10021. }
  10022. return texture;
  10023. }
  10024. function get( texture ) {
  10025. if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
  10026. const mapping = texture.mapping;
  10027. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  10028. if ( cubemaps.has( texture ) ) {
  10029. const cubemap = cubemaps.get( texture ).texture;
  10030. return mapTextureMapping( cubemap, texture.mapping );
  10031. } else {
  10032. const image = texture.image;
  10033. if ( image && image.height > 0 ) {
  10034. const currentRenderTarget = renderer.getRenderTarget();
  10035. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  10036. renderTarget.fromEquirectangularTexture( renderer, texture );
  10037. cubemaps.set( texture, renderTarget );
  10038. renderer.setRenderTarget( currentRenderTarget );
  10039. texture.addEventListener( 'dispose', onTextureDispose );
  10040. return mapTextureMapping( renderTarget.texture, texture.mapping );
  10041. } else {
  10042. // image not yet ready. try the conversion next frame
  10043. return null;
  10044. }
  10045. }
  10046. }
  10047. }
  10048. return texture;
  10049. }
  10050. function onTextureDispose( event ) {
  10051. const texture = event.target;
  10052. texture.removeEventListener( 'dispose', onTextureDispose );
  10053. const cubemap = cubemaps.get( texture );
  10054. if ( cubemap !== undefined ) {
  10055. cubemaps.delete( texture );
  10056. cubemap.dispose();
  10057. }
  10058. }
  10059. function dispose() {
  10060. cubemaps = new WeakMap();
  10061. }
  10062. return {
  10063. get: get,
  10064. dispose: dispose
  10065. };
  10066. }
  10067. class OrthographicCamera extends Camera {
  10068. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  10069. super();
  10070. this.type = 'OrthographicCamera';
  10071. this.zoom = 1;
  10072. this.view = null;
  10073. this.left = left;
  10074. this.right = right;
  10075. this.top = top;
  10076. this.bottom = bottom;
  10077. this.near = near;
  10078. this.far = far;
  10079. this.updateProjectionMatrix();
  10080. }
  10081. copy( source, recursive ) {
  10082. super.copy( source, recursive );
  10083. this.left = source.left;
  10084. this.right = source.right;
  10085. this.top = source.top;
  10086. this.bottom = source.bottom;
  10087. this.near = source.near;
  10088. this.far = source.far;
  10089. this.zoom = source.zoom;
  10090. this.view = source.view === null ? null : Object.assign( {}, source.view );
  10091. return this;
  10092. }
  10093. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  10094. if ( this.view === null ) {
  10095. this.view = {
  10096. enabled: true,
  10097. fullWidth: 1,
  10098. fullHeight: 1,
  10099. offsetX: 0,
  10100. offsetY: 0,
  10101. width: 1,
  10102. height: 1
  10103. };
  10104. }
  10105. this.view.enabled = true;
  10106. this.view.fullWidth = fullWidth;
  10107. this.view.fullHeight = fullHeight;
  10108. this.view.offsetX = x;
  10109. this.view.offsetY = y;
  10110. this.view.width = width;
  10111. this.view.height = height;
  10112. this.updateProjectionMatrix();
  10113. }
  10114. clearViewOffset() {
  10115. if ( this.view !== null ) {
  10116. this.view.enabled = false;
  10117. }
  10118. this.updateProjectionMatrix();
  10119. }
  10120. updateProjectionMatrix() {
  10121. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  10122. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  10123. const cx = ( this.right + this.left ) / 2;
  10124. const cy = ( this.top + this.bottom ) / 2;
  10125. let left = cx - dx;
  10126. let right = cx + dx;
  10127. let top = cy + dy;
  10128. let bottom = cy - dy;
  10129. if ( this.view !== null && this.view.enabled ) {
  10130. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  10131. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  10132. left += scaleW * this.view.offsetX;
  10133. right = left + scaleW * this.view.width;
  10134. top -= scaleH * this.view.offsetY;
  10135. bottom = top - scaleH * this.view.height;
  10136. }
  10137. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  10138. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  10139. }
  10140. toJSON( meta ) {
  10141. const data = super.toJSON( meta );
  10142. data.object.zoom = this.zoom;
  10143. data.object.left = this.left;
  10144. data.object.right = this.right;
  10145. data.object.top = this.top;
  10146. data.object.bottom = this.bottom;
  10147. data.object.near = this.near;
  10148. data.object.far = this.far;
  10149. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  10150. return data;
  10151. }
  10152. }
  10153. OrthographicCamera.prototype.isOrthographicCamera = true;
  10154. class RawShaderMaterial extends ShaderMaterial {
  10155. constructor( parameters ) {
  10156. super( parameters );
  10157. this.type = 'RawShaderMaterial';
  10158. }
  10159. }
  10160. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  10161. const LOD_MIN = 4;
  10162. const LOD_MAX = 8;
  10163. const SIZE_MAX = Math.pow( 2, LOD_MAX );
  10164. // The standard deviations (radians) associated with the extra mips. These are
  10165. // chosen to approximate a Trowbridge-Reitz distribution function times the
  10166. // geometric shadowing function. These sigma values squared must match the
  10167. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  10168. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  10169. const TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  10170. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  10171. // samples and exit early, but not recompile the shader.
  10172. const MAX_SAMPLES = 20;
  10173. const ENCODINGS = {
  10174. [ LinearEncoding ]: 0,
  10175. [ sRGBEncoding ]: 1,
  10176. [ RGBEEncoding ]: 2,
  10177. [ RGBM7Encoding ]: 3,
  10178. [ RGBM16Encoding ]: 4,
  10179. [ RGBDEncoding ]: 5,
  10180. [ GammaEncoding ]: 6
  10181. };
  10182. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  10183. const { _lodPlanes, _sizeLods, _sigmas } = /*@__PURE__*/ _createPlanes();
  10184. const _clearColor = /*@__PURE__*/ new Color();
  10185. let _oldTarget = null;
  10186. // Golden Ratio
  10187. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  10188. const INV_PHI = 1 / PHI;
  10189. // Vertices of a dodecahedron (except the opposites, which represent the
  10190. // same axis), used as axis directions evenly spread on a sphere.
  10191. const _axisDirections = [
  10192. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  10193. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  10194. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  10195. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  10196. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  10197. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  10198. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  10199. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  10200. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  10201. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  10202. /**
  10203. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  10204. * (PMREM) from a cubeMap environment texture. This allows different levels of
  10205. * blur to be quickly accessed based on material roughness. It is packed into a
  10206. * special CubeUV format that allows us to perform custom interpolation so that
  10207. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  10208. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  10209. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  10210. * higher roughness levels. In this way we maintain resolution to smoothly
  10211. * interpolate diffuse lighting while limiting sampling computation.
  10212. *
  10213. * Paper: Fast, Accurate Image-Based Lighting
  10214. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  10215. */
  10216. class PMREMGenerator {
  10217. constructor( renderer ) {
  10218. this._renderer = renderer;
  10219. this._pingPongRenderTarget = null;
  10220. this._blurMaterial = _getBlurShader( MAX_SAMPLES );
  10221. this._equirectShader = null;
  10222. this._cubemapShader = null;
  10223. this._compileMaterial( this._blurMaterial );
  10224. }
  10225. /**
  10226. * Generates a PMREM from a supplied Scene, which can be faster than using an
  10227. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  10228. * in radians to be applied to the scene before PMREM generation. Optional near
  10229. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  10230. * is placed at the origin).
  10231. */
  10232. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  10233. _oldTarget = this._renderer.getRenderTarget();
  10234. const cubeUVRenderTarget = this._allocateTargets();
  10235. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  10236. if ( sigma > 0 ) {
  10237. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  10238. }
  10239. this._applyPMREM( cubeUVRenderTarget );
  10240. this._cleanup( cubeUVRenderTarget );
  10241. return cubeUVRenderTarget;
  10242. }
  10243. /**
  10244. * Generates a PMREM from an equirectangular texture, which can be either LDR
  10245. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  10246. * as this matches best with the 256 x 256 cubemap output.
  10247. */
  10248. fromEquirectangular( equirectangular ) {
  10249. return this._fromTexture( equirectangular );
  10250. }
  10251. /**
  10252. * Generates a PMREM from an cubemap texture, which can be either LDR
  10253. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  10254. * as this matches best with the 256 x 256 cubemap output.
  10255. */
  10256. fromCubemap( cubemap ) {
  10257. return this._fromTexture( cubemap );
  10258. }
  10259. /**
  10260. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  10261. * your texture's network fetch for increased concurrency.
  10262. */
  10263. compileCubemapShader() {
  10264. if ( this._cubemapShader === null ) {
  10265. this._cubemapShader = _getCubemapShader();
  10266. this._compileMaterial( this._cubemapShader );
  10267. }
  10268. }
  10269. /**
  10270. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  10271. * your texture's network fetch for increased concurrency.
  10272. */
  10273. compileEquirectangularShader() {
  10274. if ( this._equirectShader === null ) {
  10275. this._equirectShader = _getEquirectShader();
  10276. this._compileMaterial( this._equirectShader );
  10277. }
  10278. }
  10279. /**
  10280. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  10281. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  10282. * one of them will cause any others to also become unusable.
  10283. */
  10284. dispose() {
  10285. this._blurMaterial.dispose();
  10286. if ( this._cubemapShader !== null ) this._cubemapShader.dispose();
  10287. if ( this._equirectShader !== null ) this._equirectShader.dispose();
  10288. for ( let i = 0; i < _lodPlanes.length; i ++ ) {
  10289. _lodPlanes[ i ].dispose();
  10290. }
  10291. }
  10292. // private interface
  10293. _cleanup( outputTarget ) {
  10294. this._pingPongRenderTarget.dispose();
  10295. this._renderer.setRenderTarget( _oldTarget );
  10296. outputTarget.scissorTest = false;
  10297. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  10298. }
  10299. _fromTexture( texture ) {
  10300. _oldTarget = this._renderer.getRenderTarget();
  10301. const cubeUVRenderTarget = this._allocateTargets( texture );
  10302. this._textureToCubeUV( texture, cubeUVRenderTarget );
  10303. this._applyPMREM( cubeUVRenderTarget );
  10304. this._cleanup( cubeUVRenderTarget );
  10305. return cubeUVRenderTarget;
  10306. }
  10307. _allocateTargets( texture ) { // warning: null texture is valid
  10308. const params = {
  10309. magFilter: NearestFilter,
  10310. minFilter: NearestFilter,
  10311. generateMipmaps: false,
  10312. type: UnsignedByteType,
  10313. format: RGBEFormat,
  10314. encoding: _isLDR( texture ) ? texture.encoding : RGBEEncoding,
  10315. depthBuffer: false
  10316. };
  10317. const cubeUVRenderTarget = _createRenderTarget( params );
  10318. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  10319. this._pingPongRenderTarget = _createRenderTarget( params );
  10320. return cubeUVRenderTarget;
  10321. }
  10322. _compileMaterial( material ) {
  10323. const tmpMesh = new Mesh( _lodPlanes[ 0 ], material );
  10324. this._renderer.compile( tmpMesh, _flatCamera );
  10325. }
  10326. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  10327. const fov = 90;
  10328. const aspect = 1;
  10329. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  10330. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  10331. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  10332. const renderer = this._renderer;
  10333. const originalAutoClear = renderer.autoClear;
  10334. const outputEncoding = renderer.outputEncoding;
  10335. const toneMapping = renderer.toneMapping;
  10336. renderer.getClearColor( _clearColor );
  10337. renderer.toneMapping = NoToneMapping;
  10338. renderer.outputEncoding = LinearEncoding;
  10339. renderer.autoClear = false;
  10340. const backgroundMaterial = new MeshBasicMaterial( {
  10341. name: 'PMREM.Background',
  10342. side: BackSide,
  10343. depthWrite: false,
  10344. depthTest: false,
  10345. } );
  10346. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  10347. let useSolidColor = false;
  10348. const background = scene.background;
  10349. if ( background ) {
  10350. if ( background.isColor ) {
  10351. backgroundMaterial.color.copy( background );
  10352. scene.background = null;
  10353. useSolidColor = true;
  10354. }
  10355. } else {
  10356. backgroundMaterial.color.copy( _clearColor );
  10357. useSolidColor = true;
  10358. }
  10359. for ( let i = 0; i < 6; i ++ ) {
  10360. const col = i % 3;
  10361. if ( col == 0 ) {
  10362. cubeCamera.up.set( 0, upSign[ i ], 0 );
  10363. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  10364. } else if ( col == 1 ) {
  10365. cubeCamera.up.set( 0, 0, upSign[ i ] );
  10366. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  10367. } else {
  10368. cubeCamera.up.set( 0, upSign[ i ], 0 );
  10369. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  10370. }
  10371. _setViewport( cubeUVRenderTarget,
  10372. col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX );
  10373. renderer.setRenderTarget( cubeUVRenderTarget );
  10374. if ( useSolidColor ) {
  10375. renderer.render( backgroundBox, cubeCamera );
  10376. }
  10377. renderer.render( scene, cubeCamera );
  10378. }
  10379. backgroundBox.geometry.dispose();
  10380. backgroundBox.material.dispose();
  10381. renderer.toneMapping = toneMapping;
  10382. renderer.outputEncoding = outputEncoding;
  10383. renderer.autoClear = originalAutoClear;
  10384. scene.background = background;
  10385. }
  10386. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  10387. const renderer = this._renderer;
  10388. if ( texture.isCubeTexture ) {
  10389. if ( this._cubemapShader == null ) {
  10390. this._cubemapShader = _getCubemapShader();
  10391. }
  10392. } else {
  10393. if ( this._equirectShader == null ) {
  10394. this._equirectShader = _getEquirectShader();
  10395. }
  10396. }
  10397. const material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
  10398. const mesh = new Mesh( _lodPlanes[ 0 ], material );
  10399. const uniforms = material.uniforms;
  10400. uniforms[ 'envMap' ].value = texture;
  10401. if ( ! texture.isCubeTexture ) {
  10402. uniforms[ 'texelSize' ].value.set( 1.0 / texture.image.width, 1.0 / texture.image.height );
  10403. }
  10404. uniforms[ 'inputEncoding' ].value = ENCODINGS[ texture.encoding ];
  10405. uniforms[ 'outputEncoding' ].value = ENCODINGS[ cubeUVRenderTarget.texture.encoding ];
  10406. _setViewport( cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX );
  10407. renderer.setRenderTarget( cubeUVRenderTarget );
  10408. renderer.render( mesh, _flatCamera );
  10409. }
  10410. _applyPMREM( cubeUVRenderTarget ) {
  10411. const renderer = this._renderer;
  10412. const autoClear = renderer.autoClear;
  10413. renderer.autoClear = false;
  10414. for ( let i = 1; i < TOTAL_LODS; i ++ ) {
  10415. const sigma = Math.sqrt( _sigmas[ i ] * _sigmas[ i ] - _sigmas[ i - 1 ] * _sigmas[ i - 1 ] );
  10416. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  10417. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  10418. }
  10419. renderer.autoClear = autoClear;
  10420. }
  10421. /**
  10422. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  10423. * vertically and horizontally, but this breaks down on a cube. Here we apply
  10424. * the blur latitudinally (around the poles), and then longitudinally (towards
  10425. * the poles) to approximate the orthogonally-separable blur. It is least
  10426. * accurate at the poles, but still does a decent job.
  10427. */
  10428. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  10429. const pingPongRenderTarget = this._pingPongRenderTarget;
  10430. this._halfBlur(
  10431. cubeUVRenderTarget,
  10432. pingPongRenderTarget,
  10433. lodIn,
  10434. lodOut,
  10435. sigma,
  10436. 'latitudinal',
  10437. poleAxis );
  10438. this._halfBlur(
  10439. pingPongRenderTarget,
  10440. cubeUVRenderTarget,
  10441. lodOut,
  10442. lodOut,
  10443. sigma,
  10444. 'longitudinal',
  10445. poleAxis );
  10446. }
  10447. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  10448. const renderer = this._renderer;
  10449. const blurMaterial = this._blurMaterial;
  10450. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  10451. console.error(
  10452. 'blur direction must be either latitudinal or longitudinal!' );
  10453. }
  10454. // Number of standard deviations at which to cut off the discrete approximation.
  10455. const STANDARD_DEVIATIONS = 3;
  10456. const blurMesh = new Mesh( _lodPlanes[ lodOut ], blurMaterial );
  10457. const blurUniforms = blurMaterial.uniforms;
  10458. const pixels = _sizeLods[ lodIn ] - 1;
  10459. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  10460. const sigmaPixels = sigmaRadians / radiansPerPixel;
  10461. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  10462. if ( samples > MAX_SAMPLES ) {
  10463. console.warn( `sigmaRadians, ${
  10464. sigmaRadians}, is too large and will clip, as it requested ${
  10465. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  10466. }
  10467. const weights = [];
  10468. let sum = 0;
  10469. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  10470. const x = i / sigmaPixels;
  10471. const weight = Math.exp( - x * x / 2 );
  10472. weights.push( weight );
  10473. if ( i == 0 ) {
  10474. sum += weight;
  10475. } else if ( i < samples ) {
  10476. sum += 2 * weight;
  10477. }
  10478. }
  10479. for ( let i = 0; i < weights.length; i ++ ) {
  10480. weights[ i ] = weights[ i ] / sum;
  10481. }
  10482. blurUniforms[ 'envMap' ].value = targetIn.texture;
  10483. blurUniforms[ 'samples' ].value = samples;
  10484. blurUniforms[ 'weights' ].value = weights;
  10485. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  10486. if ( poleAxis ) {
  10487. blurUniforms[ 'poleAxis' ].value = poleAxis;
  10488. }
  10489. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  10490. blurUniforms[ 'mipInt' ].value = LOD_MAX - lodIn;
  10491. blurUniforms[ 'inputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
  10492. blurUniforms[ 'outputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
  10493. const outputSize = _sizeLods[ lodOut ];
  10494. const x = 3 * Math.max( 0, SIZE_MAX - 2 * outputSize );
  10495. const y = ( lodOut === 0 ? 0 : 2 * SIZE_MAX ) + 2 * outputSize * ( lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0 );
  10496. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  10497. renderer.setRenderTarget( targetOut );
  10498. renderer.render( blurMesh, _flatCamera );
  10499. }
  10500. }
  10501. function _isLDR( texture ) {
  10502. if ( texture === undefined || texture.type !== UnsignedByteType ) return false;
  10503. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  10504. }
  10505. function _createPlanes() {
  10506. const _lodPlanes = [];
  10507. const _sizeLods = [];
  10508. const _sigmas = [];
  10509. let lod = LOD_MAX;
  10510. for ( let i = 0; i < TOTAL_LODS; i ++ ) {
  10511. const sizeLod = Math.pow( 2, lod );
  10512. _sizeLods.push( sizeLod );
  10513. let sigma = 1.0 / sizeLod;
  10514. if ( i > LOD_MAX - LOD_MIN ) {
  10515. sigma = EXTRA_LOD_SIGMA[ i - LOD_MAX + LOD_MIN - 1 ];
  10516. } else if ( i == 0 ) {
  10517. sigma = 0;
  10518. }
  10519. _sigmas.push( sigma );
  10520. const texelSize = 1.0 / ( sizeLod - 1 );
  10521. const min = - texelSize / 2;
  10522. const max = 1 + texelSize / 2;
  10523. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  10524. const cubeFaces = 6;
  10525. const vertices = 6;
  10526. const positionSize = 3;
  10527. const uvSize = 2;
  10528. const faceIndexSize = 1;
  10529. const position = new Float32Array( positionSize * vertices * cubeFaces );
  10530. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  10531. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  10532. for ( let face = 0; face < cubeFaces; face ++ ) {
  10533. const x = ( face % 3 ) * 2 / 3 - 1;
  10534. const y = face > 2 ? 0 : - 1;
  10535. const coordinates = [
  10536. x, y, 0,
  10537. x + 2 / 3, y, 0,
  10538. x + 2 / 3, y + 1, 0,
  10539. x, y, 0,
  10540. x + 2 / 3, y + 1, 0,
  10541. x, y + 1, 0
  10542. ];
  10543. position.set( coordinates, positionSize * vertices * face );
  10544. uv.set( uv1, uvSize * vertices * face );
  10545. const fill = [ face, face, face, face, face, face ];
  10546. faceIndex.set( fill, faceIndexSize * vertices * face );
  10547. }
  10548. const planes = new BufferGeometry();
  10549. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  10550. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  10551. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  10552. _lodPlanes.push( planes );
  10553. if ( lod > LOD_MIN ) {
  10554. lod --;
  10555. }
  10556. }
  10557. return { _lodPlanes, _sizeLods, _sigmas };
  10558. }
  10559. function _createRenderTarget( params ) {
  10560. const cubeUVRenderTarget = new WebGLRenderTarget( 3 * SIZE_MAX, 3 * SIZE_MAX, params );
  10561. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  10562. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  10563. cubeUVRenderTarget.scissorTest = true;
  10564. return cubeUVRenderTarget;
  10565. }
  10566. function _setViewport( target, x, y, width, height ) {
  10567. target.viewport.set( x, y, width, height );
  10568. target.scissor.set( x, y, width, height );
  10569. }
  10570. function _getBlurShader( maxSamples ) {
  10571. const weights = new Float32Array( maxSamples );
  10572. const poleAxis = new Vector3( 0, 1, 0 );
  10573. const shaderMaterial = new RawShaderMaterial( {
  10574. name: 'SphericalGaussianBlur',
  10575. defines: { 'n': maxSamples },
  10576. uniforms: {
  10577. 'envMap': { value: null },
  10578. 'samples': { value: 1 },
  10579. 'weights': { value: weights },
  10580. 'latitudinal': { value: false },
  10581. 'dTheta': { value: 0 },
  10582. 'mipInt': { value: 0 },
  10583. 'poleAxis': { value: poleAxis },
  10584. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  10585. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  10586. },
  10587. vertexShader: _getCommonVertexShader(),
  10588. fragmentShader: /* glsl */`
  10589. precision mediump float;
  10590. precision mediump int;
  10591. varying vec3 vOutputDirection;
  10592. uniform sampler2D envMap;
  10593. uniform int samples;
  10594. uniform float weights[ n ];
  10595. uniform bool latitudinal;
  10596. uniform float dTheta;
  10597. uniform float mipInt;
  10598. uniform vec3 poleAxis;
  10599. ${ _getEncodings() }
  10600. #define ENVMAP_TYPE_CUBE_UV
  10601. #include <cube_uv_reflection_fragment>
  10602. vec3 getSample( float theta, vec3 axis ) {
  10603. float cosTheta = cos( theta );
  10604. // Rodrigues' axis-angle rotation
  10605. vec3 sampleDirection = vOutputDirection * cosTheta
  10606. + cross( axis, vOutputDirection ) * sin( theta )
  10607. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  10608. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  10609. }
  10610. void main() {
  10611. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  10612. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  10613. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  10614. }
  10615. axis = normalize( axis );
  10616. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  10617. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  10618. for ( int i = 1; i < n; i++ ) {
  10619. if ( i >= samples ) {
  10620. break;
  10621. }
  10622. float theta = dTheta * float( i );
  10623. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  10624. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  10625. }
  10626. gl_FragColor = linearToOutputTexel( gl_FragColor );
  10627. }
  10628. `,
  10629. blending: NoBlending,
  10630. depthTest: false,
  10631. depthWrite: false
  10632. } );
  10633. return shaderMaterial;
  10634. }
  10635. function _getEquirectShader() {
  10636. const texelSize = new Vector2( 1, 1 );
  10637. const shaderMaterial = new RawShaderMaterial( {
  10638. name: 'EquirectangularToCubeUV',
  10639. uniforms: {
  10640. 'envMap': { value: null },
  10641. 'texelSize': { value: texelSize },
  10642. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  10643. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  10644. },
  10645. vertexShader: _getCommonVertexShader(),
  10646. fragmentShader: /* glsl */`
  10647. precision mediump float;
  10648. precision mediump int;
  10649. varying vec3 vOutputDirection;
  10650. uniform sampler2D envMap;
  10651. uniform vec2 texelSize;
  10652. ${ _getEncodings() }
  10653. #include <common>
  10654. void main() {
  10655. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  10656. vec3 outputDirection = normalize( vOutputDirection );
  10657. vec2 uv = equirectUv( outputDirection );
  10658. vec2 f = fract( uv / texelSize - 0.5 );
  10659. uv -= f * texelSize;
  10660. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  10661. uv.x += texelSize.x;
  10662. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  10663. uv.y += texelSize.y;
  10664. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  10665. uv.x -= texelSize.x;
  10666. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  10667. vec3 tm = mix( tl, tr, f.x );
  10668. vec3 bm = mix( bl, br, f.x );
  10669. gl_FragColor.rgb = mix( tm, bm, f.y );
  10670. gl_FragColor = linearToOutputTexel( gl_FragColor );
  10671. }
  10672. `,
  10673. blending: NoBlending,
  10674. depthTest: false,
  10675. depthWrite: false
  10676. } );
  10677. return shaderMaterial;
  10678. }
  10679. function _getCubemapShader() {
  10680. const shaderMaterial = new RawShaderMaterial( {
  10681. name: 'CubemapToCubeUV',
  10682. uniforms: {
  10683. 'envMap': { value: null },
  10684. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  10685. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  10686. },
  10687. vertexShader: _getCommonVertexShader(),
  10688. fragmentShader: /* glsl */`
  10689. precision mediump float;
  10690. precision mediump int;
  10691. varying vec3 vOutputDirection;
  10692. uniform samplerCube envMap;
  10693. ${ _getEncodings() }
  10694. void main() {
  10695. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  10696. gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;
  10697. gl_FragColor = linearToOutputTexel( gl_FragColor );
  10698. }
  10699. `,
  10700. blending: NoBlending,
  10701. depthTest: false,
  10702. depthWrite: false
  10703. } );
  10704. return shaderMaterial;
  10705. }
  10706. function _getCommonVertexShader() {
  10707. return /* glsl */`
  10708. precision mediump float;
  10709. precision mediump int;
  10710. attribute vec3 position;
  10711. attribute vec2 uv;
  10712. attribute float faceIndex;
  10713. varying vec3 vOutputDirection;
  10714. // RH coordinate system; PMREM face-indexing convention
  10715. vec3 getDirection( vec2 uv, float face ) {
  10716. uv = 2.0 * uv - 1.0;
  10717. vec3 direction = vec3( uv, 1.0 );
  10718. if ( face == 0.0 ) {
  10719. direction = direction.zyx; // ( 1, v, u ) pos x
  10720. } else if ( face == 1.0 ) {
  10721. direction = direction.xzy;
  10722. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  10723. } else if ( face == 2.0 ) {
  10724. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  10725. } else if ( face == 3.0 ) {
  10726. direction = direction.zyx;
  10727. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  10728. } else if ( face == 4.0 ) {
  10729. direction = direction.xzy;
  10730. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  10731. } else if ( face == 5.0 ) {
  10732. direction.z *= -1.0; // ( u, v, -1 ) neg z
  10733. }
  10734. return direction;
  10735. }
  10736. void main() {
  10737. vOutputDirection = getDirection( uv, faceIndex );
  10738. gl_Position = vec4( position, 1.0 );
  10739. }
  10740. `;
  10741. }
  10742. function _getEncodings() {
  10743. return /* glsl */`
  10744. uniform int inputEncoding;
  10745. uniform int outputEncoding;
  10746. #include <encodings_pars_fragment>
  10747. vec4 inputTexelToLinear( vec4 value ) {
  10748. if ( inputEncoding == 0 ) {
  10749. return value;
  10750. } else if ( inputEncoding == 1 ) {
  10751. return sRGBToLinear( value );
  10752. } else if ( inputEncoding == 2 ) {
  10753. return RGBEToLinear( value );
  10754. } else if ( inputEncoding == 3 ) {
  10755. return RGBMToLinear( value, 7.0 );
  10756. } else if ( inputEncoding == 4 ) {
  10757. return RGBMToLinear( value, 16.0 );
  10758. } else if ( inputEncoding == 5 ) {
  10759. return RGBDToLinear( value, 256.0 );
  10760. } else {
  10761. return GammaToLinear( value, 2.2 );
  10762. }
  10763. }
  10764. vec4 linearToOutputTexel( vec4 value ) {
  10765. if ( outputEncoding == 0 ) {
  10766. return value;
  10767. } else if ( outputEncoding == 1 ) {
  10768. return LinearTosRGB( value );
  10769. } else if ( outputEncoding == 2 ) {
  10770. return LinearToRGBE( value );
  10771. } else if ( outputEncoding == 3 ) {
  10772. return LinearToRGBM( value, 7.0 );
  10773. } else if ( outputEncoding == 4 ) {
  10774. return LinearToRGBM( value, 16.0 );
  10775. } else if ( outputEncoding == 5 ) {
  10776. return LinearToRGBD( value, 256.0 );
  10777. } else {
  10778. return LinearToGamma( value, 2.2 );
  10779. }
  10780. }
  10781. vec4 envMapTexelToLinear( vec4 color ) {
  10782. return inputTexelToLinear( color );
  10783. }
  10784. `;
  10785. }
  10786. function WebGLCubeUVMaps( renderer ) {
  10787. let cubeUVmaps = new WeakMap();
  10788. let pmremGenerator = null;
  10789. function get( texture ) {
  10790. if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
  10791. const mapping = texture.mapping;
  10792. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  10793. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  10794. if ( isEquirectMap || isCubeMap ) {
  10795. // equirect/cube map to cubeUV conversion
  10796. if ( cubeUVmaps.has( texture ) ) {
  10797. return cubeUVmaps.get( texture ).texture;
  10798. } else {
  10799. const image = texture.image;
  10800. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  10801. const currentRenderTarget = renderer.getRenderTarget();
  10802. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  10803. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  10804. cubeUVmaps.set( texture, renderTarget );
  10805. renderer.setRenderTarget( currentRenderTarget );
  10806. texture.addEventListener( 'dispose', onTextureDispose );
  10807. return renderTarget.texture;
  10808. } else {
  10809. // image not yet ready. try the conversion next frame
  10810. return null;
  10811. }
  10812. }
  10813. }
  10814. }
  10815. return texture;
  10816. }
  10817. function isCubeTextureComplete( image ) {
  10818. let count = 0;
  10819. const length = 6;
  10820. for ( let i = 0; i < length; i ++ ) {
  10821. if ( image[ i ] !== undefined ) count ++;
  10822. }
  10823. return count === length;
  10824. }
  10825. function onTextureDispose( event ) {
  10826. const texture = event.target;
  10827. texture.removeEventListener( 'dispose', onTextureDispose );
  10828. const cubemapUV = cubeUVmaps.get( texture );
  10829. if ( cubemapUV !== undefined ) {
  10830. cubeUVmaps.delete( texture );
  10831. cubemapUV.dispose();
  10832. }
  10833. }
  10834. function dispose() {
  10835. cubeUVmaps = new WeakMap();
  10836. if ( pmremGenerator !== null ) {
  10837. pmremGenerator.dispose();
  10838. pmremGenerator = null;
  10839. }
  10840. }
  10841. return {
  10842. get: get,
  10843. dispose: dispose
  10844. };
  10845. }
  10846. function WebGLExtensions( gl ) {
  10847. const extensions = {};
  10848. function getExtension( name ) {
  10849. if ( extensions[ name ] !== undefined ) {
  10850. return extensions[ name ];
  10851. }
  10852. let extension;
  10853. switch ( name ) {
  10854. case 'WEBGL_depth_texture':
  10855. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  10856. break;
  10857. case 'EXT_texture_filter_anisotropic':
  10858. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  10859. break;
  10860. case 'WEBGL_compressed_texture_s3tc':
  10861. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  10862. break;
  10863. case 'WEBGL_compressed_texture_pvrtc':
  10864. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  10865. break;
  10866. default:
  10867. extension = gl.getExtension( name );
  10868. }
  10869. extensions[ name ] = extension;
  10870. return extension;
  10871. }
  10872. return {
  10873. has: function ( name ) {
  10874. return getExtension( name ) !== null;
  10875. },
  10876. init: function ( capabilities ) {
  10877. if ( capabilities.isWebGL2 ) {
  10878. getExtension( 'EXT_color_buffer_float' );
  10879. } else {
  10880. getExtension( 'WEBGL_depth_texture' );
  10881. getExtension( 'OES_texture_float' );
  10882. getExtension( 'OES_texture_half_float' );
  10883. getExtension( 'OES_texture_half_float_linear' );
  10884. getExtension( 'OES_standard_derivatives' );
  10885. getExtension( 'OES_element_index_uint' );
  10886. getExtension( 'OES_vertex_array_object' );
  10887. getExtension( 'ANGLE_instanced_arrays' );
  10888. }
  10889. getExtension( 'OES_texture_float_linear' );
  10890. getExtension( 'EXT_color_buffer_half_float' );
  10891. },
  10892. get: function ( name ) {
  10893. const extension = getExtension( name );
  10894. if ( extension === null ) {
  10895. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  10896. }
  10897. return extension;
  10898. }
  10899. };
  10900. }
  10901. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  10902. const geometries = {};
  10903. const wireframeAttributes = new WeakMap();
  10904. function onGeometryDispose( event ) {
  10905. const geometry = event.target;
  10906. if ( geometry.index !== null ) {
  10907. attributes.remove( geometry.index );
  10908. }
  10909. for ( const name in geometry.attributes ) {
  10910. attributes.remove( geometry.attributes[ name ] );
  10911. }
  10912. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10913. delete geometries[ geometry.id ];
  10914. const attribute = wireframeAttributes.get( geometry );
  10915. if ( attribute ) {
  10916. attributes.remove( attribute );
  10917. wireframeAttributes.delete( geometry );
  10918. }
  10919. bindingStates.releaseStatesOfGeometry( geometry );
  10920. if ( geometry.isInstancedBufferGeometry === true ) {
  10921. delete geometry._maxInstanceCount;
  10922. }
  10923. //
  10924. info.memory.geometries --;
  10925. }
  10926. function get( object, geometry ) {
  10927. if ( geometries[ geometry.id ] === true ) return geometry;
  10928. geometry.addEventListener( 'dispose', onGeometryDispose );
  10929. geometries[ geometry.id ] = true;
  10930. info.memory.geometries ++;
  10931. return geometry;
  10932. }
  10933. function update( geometry ) {
  10934. const geometryAttributes = geometry.attributes;
  10935. // Updating index buffer in VAO now. See WebGLBindingStates.
  10936. for ( const name in geometryAttributes ) {
  10937. attributes.update( geometryAttributes[ name ], 34962 );
  10938. }
  10939. // morph targets
  10940. const morphAttributes = geometry.morphAttributes;
  10941. for ( const name in morphAttributes ) {
  10942. const array = morphAttributes[ name ];
  10943. for ( let i = 0, l = array.length; i < l; i ++ ) {
  10944. attributes.update( array[ i ], 34962 );
  10945. }
  10946. }
  10947. }
  10948. function updateWireframeAttribute( geometry ) {
  10949. const indices = [];
  10950. const geometryIndex = geometry.index;
  10951. const geometryPosition = geometry.attributes.position;
  10952. let version = 0;
  10953. if ( geometryIndex !== null ) {
  10954. const array = geometryIndex.array;
  10955. version = geometryIndex.version;
  10956. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  10957. const a = array[ i + 0 ];
  10958. const b = array[ i + 1 ];
  10959. const c = array[ i + 2 ];
  10960. indices.push( a, b, b, c, c, a );
  10961. }
  10962. } else {
  10963. const array = geometryPosition.array;
  10964. version = geometryPosition.version;
  10965. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  10966. const a = i + 0;
  10967. const b = i + 1;
  10968. const c = i + 2;
  10969. indices.push( a, b, b, c, c, a );
  10970. }
  10971. }
  10972. const attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  10973. attribute.version = version;
  10974. // Updating index buffer in VAO now. See WebGLBindingStates
  10975. //
  10976. const previousAttribute = wireframeAttributes.get( geometry );
  10977. if ( previousAttribute ) attributes.remove( previousAttribute );
  10978. //
  10979. wireframeAttributes.set( geometry, attribute );
  10980. }
  10981. function getWireframeAttribute( geometry ) {
  10982. const currentAttribute = wireframeAttributes.get( geometry );
  10983. if ( currentAttribute ) {
  10984. const geometryIndex = geometry.index;
  10985. if ( geometryIndex !== null ) {
  10986. // if the attribute is obsolete, create a new one
  10987. if ( currentAttribute.version < geometryIndex.version ) {
  10988. updateWireframeAttribute( geometry );
  10989. }
  10990. }
  10991. } else {
  10992. updateWireframeAttribute( geometry );
  10993. }
  10994. return wireframeAttributes.get( geometry );
  10995. }
  10996. return {
  10997. get: get,
  10998. update: update,
  10999. getWireframeAttribute: getWireframeAttribute
  11000. };
  11001. }
  11002. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  11003. const isWebGL2 = capabilities.isWebGL2;
  11004. let mode;
  11005. function setMode( value ) {
  11006. mode = value;
  11007. }
  11008. let type, bytesPerElement;
  11009. function setIndex( value ) {
  11010. type = value.type;
  11011. bytesPerElement = value.bytesPerElement;
  11012. }
  11013. function render( start, count ) {
  11014. gl.drawElements( mode, count, type, start * bytesPerElement );
  11015. info.update( count, mode, 1 );
  11016. }
  11017. function renderInstances( start, count, primcount ) {
  11018. if ( primcount === 0 ) return;
  11019. let extension, methodName;
  11020. if ( isWebGL2 ) {
  11021. extension = gl;
  11022. methodName = 'drawElementsInstanced';
  11023. } else {
  11024. extension = extensions.get( 'ANGLE_instanced_arrays' );
  11025. methodName = 'drawElementsInstancedANGLE';
  11026. if ( extension === null ) {
  11027. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  11028. return;
  11029. }
  11030. }
  11031. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  11032. info.update( count, mode, primcount );
  11033. }
  11034. //
  11035. this.setMode = setMode;
  11036. this.setIndex = setIndex;
  11037. this.render = render;
  11038. this.renderInstances = renderInstances;
  11039. }
  11040. function WebGLInfo( gl ) {
  11041. const memory = {
  11042. geometries: 0,
  11043. textures: 0
  11044. };
  11045. const render = {
  11046. frame: 0,
  11047. calls: 0,
  11048. triangles: 0,
  11049. points: 0,
  11050. lines: 0
  11051. };
  11052. function update( count, mode, instanceCount ) {
  11053. render.calls ++;
  11054. switch ( mode ) {
  11055. case 4:
  11056. render.triangles += instanceCount * ( count / 3 );
  11057. break;
  11058. case 1:
  11059. render.lines += instanceCount * ( count / 2 );
  11060. break;
  11061. case 3:
  11062. render.lines += instanceCount * ( count - 1 );
  11063. break;
  11064. case 2:
  11065. render.lines += instanceCount * count;
  11066. break;
  11067. case 0:
  11068. render.points += instanceCount * count;
  11069. break;
  11070. default:
  11071. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  11072. break;
  11073. }
  11074. }
  11075. function reset() {
  11076. render.frame ++;
  11077. render.calls = 0;
  11078. render.triangles = 0;
  11079. render.points = 0;
  11080. render.lines = 0;
  11081. }
  11082. return {
  11083. memory: memory,
  11084. render: render,
  11085. programs: null,
  11086. autoReset: true,
  11087. reset: reset,
  11088. update: update
  11089. };
  11090. }
  11091. function numericalSort( a, b ) {
  11092. return a[ 0 ] - b[ 0 ];
  11093. }
  11094. function absNumericalSort( a, b ) {
  11095. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  11096. }
  11097. function WebGLMorphtargets( gl ) {
  11098. const influencesList = {};
  11099. const morphInfluences = new Float32Array( 8 );
  11100. const workInfluences = [];
  11101. for ( let i = 0; i < 8; i ++ ) {
  11102. workInfluences[ i ] = [ i, 0 ];
  11103. }
  11104. function update( object, geometry, material, program ) {
  11105. const objectInfluences = object.morphTargetInfluences;
  11106. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  11107. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  11108. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  11109. let influences = influencesList[ geometry.id ];
  11110. if ( influences === undefined || influences.length !== length ) {
  11111. // initialise list
  11112. influences = [];
  11113. for ( let i = 0; i < length; i ++ ) {
  11114. influences[ i ] = [ i, 0 ];
  11115. }
  11116. influencesList[ geometry.id ] = influences;
  11117. }
  11118. // Collect influences
  11119. for ( let i = 0; i < length; i ++ ) {
  11120. const influence = influences[ i ];
  11121. influence[ 0 ] = i;
  11122. influence[ 1 ] = objectInfluences[ i ];
  11123. }
  11124. influences.sort( absNumericalSort );
  11125. for ( let i = 0; i < 8; i ++ ) {
  11126. if ( i < length && influences[ i ][ 1 ] ) {
  11127. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  11128. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  11129. } else {
  11130. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  11131. workInfluences[ i ][ 1 ] = 0;
  11132. }
  11133. }
  11134. workInfluences.sort( numericalSort );
  11135. const morphTargets = geometry.morphAttributes.position;
  11136. const morphNormals = geometry.morphAttributes.normal;
  11137. let morphInfluencesSum = 0;
  11138. for ( let i = 0; i < 8; i ++ ) {
  11139. const influence = workInfluences[ i ];
  11140. const index = influence[ 0 ];
  11141. const value = influence[ 1 ];
  11142. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  11143. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  11144. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  11145. }
  11146. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  11147. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  11148. }
  11149. morphInfluences[ i ] = value;
  11150. morphInfluencesSum += value;
  11151. } else {
  11152. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  11153. geometry.deleteAttribute( 'morphTarget' + i );
  11154. }
  11155. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  11156. geometry.deleteAttribute( 'morphNormal' + i );
  11157. }
  11158. morphInfluences[ i ] = 0;
  11159. }
  11160. }
  11161. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  11162. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  11163. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  11164. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  11165. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  11166. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  11167. }
  11168. return {
  11169. update: update
  11170. };
  11171. }
  11172. function WebGLObjects( gl, geometries, attributes, info ) {
  11173. let updateMap = new WeakMap();
  11174. function update( object ) {
  11175. const frame = info.render.frame;
  11176. const geometry = object.geometry;
  11177. const buffergeometry = geometries.get( object, geometry );
  11178. // Update once per frame
  11179. if ( updateMap.get( buffergeometry ) !== frame ) {
  11180. geometries.update( buffergeometry );
  11181. updateMap.set( buffergeometry, frame );
  11182. }
  11183. if ( object.isInstancedMesh ) {
  11184. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  11185. object.addEventListener( 'dispose', onInstancedMeshDispose );
  11186. }
  11187. attributes.update( object.instanceMatrix, 34962 );
  11188. if ( object.instanceColor !== null ) {
  11189. attributes.update( object.instanceColor, 34962 );
  11190. }
  11191. }
  11192. return buffergeometry;
  11193. }
  11194. function dispose() {
  11195. updateMap = new WeakMap();
  11196. }
  11197. function onInstancedMeshDispose( event ) {
  11198. const instancedMesh = event.target;
  11199. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  11200. attributes.remove( instancedMesh.instanceMatrix );
  11201. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  11202. }
  11203. return {
  11204. update: update,
  11205. dispose: dispose
  11206. };
  11207. }
  11208. class DataTexture2DArray extends Texture {
  11209. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  11210. super( null );
  11211. this.image = { data, width, height, depth };
  11212. this.magFilter = NearestFilter;
  11213. this.minFilter = NearestFilter;
  11214. this.wrapR = ClampToEdgeWrapping;
  11215. this.generateMipmaps = false;
  11216. this.flipY = false;
  11217. this.unpackAlignment = 1;
  11218. this.needsUpdate = true;
  11219. }
  11220. }
  11221. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  11222. class DataTexture3D extends Texture {
  11223. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  11224. // We're going to add .setXXX() methods for setting properties later.
  11225. // Users can still set in DataTexture3D directly.
  11226. //
  11227. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  11228. // texture.anisotropy = 16;
  11229. //
  11230. // See #14839
  11231. super( null );
  11232. this.image = { data, width, height, depth };
  11233. this.magFilter = NearestFilter;
  11234. this.minFilter = NearestFilter;
  11235. this.wrapR = ClampToEdgeWrapping;
  11236. this.generateMipmaps = false;
  11237. this.flipY = false;
  11238. this.unpackAlignment = 1;
  11239. this.needsUpdate = true;
  11240. }
  11241. }
  11242. DataTexture3D.prototype.isDataTexture3D = true;
  11243. /**
  11244. * Uniforms of a program.
  11245. * Those form a tree structure with a special top-level container for the root,
  11246. * which you get by calling 'new WebGLUniforms( gl, program )'.
  11247. *
  11248. *
  11249. * Properties of inner nodes including the top-level container:
  11250. *
  11251. * .seq - array of nested uniforms
  11252. * .map - nested uniforms by name
  11253. *
  11254. *
  11255. * Methods of all nodes except the top-level container:
  11256. *
  11257. * .setValue( gl, value, [textures] )
  11258. *
  11259. * uploads a uniform value(s)
  11260. * the 'textures' parameter is needed for sampler uniforms
  11261. *
  11262. *
  11263. * Static methods of the top-level container (textures factorizations):
  11264. *
  11265. * .upload( gl, seq, values, textures )
  11266. *
  11267. * sets uniforms in 'seq' to 'values[id].value'
  11268. *
  11269. * .seqWithValue( seq, values ) : filteredSeq
  11270. *
  11271. * filters 'seq' entries with corresponding entry in values
  11272. *
  11273. *
  11274. * Methods of the top-level container (textures factorizations):
  11275. *
  11276. * .setValue( gl, name, value, textures )
  11277. *
  11278. * sets uniform with name 'name' to 'value'
  11279. *
  11280. * .setOptional( gl, obj, prop )
  11281. *
  11282. * like .set for an optional property of the object
  11283. *
  11284. */
  11285. const emptyTexture = new Texture();
  11286. const emptyTexture2dArray = new DataTexture2DArray();
  11287. const emptyTexture3d = new DataTexture3D();
  11288. const emptyCubeTexture = new CubeTexture();
  11289. // --- Utilities ---
  11290. // Array Caches (provide typed arrays for temporary by size)
  11291. const arrayCacheF32 = [];
  11292. const arrayCacheI32 = [];
  11293. // Float32Array caches used for uploading Matrix uniforms
  11294. const mat4array = new Float32Array( 16 );
  11295. const mat3array = new Float32Array( 9 );
  11296. const mat2array = new Float32Array( 4 );
  11297. // Flattening for arrays of vectors and matrices
  11298. function flatten( array, nBlocks, blockSize ) {
  11299. const firstElem = array[ 0 ];
  11300. if ( firstElem <= 0 || firstElem > 0 ) return array;
  11301. // unoptimized: ! isNaN( firstElem )
  11302. // see http://jacksondunstan.com/articles/983
  11303. const n = nBlocks * blockSize;
  11304. let r = arrayCacheF32[ n ];
  11305. if ( r === undefined ) {
  11306. r = new Float32Array( n );
  11307. arrayCacheF32[ n ] = r;
  11308. }
  11309. if ( nBlocks !== 0 ) {
  11310. firstElem.toArray( r, 0 );
  11311. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  11312. offset += blockSize;
  11313. array[ i ].toArray( r, offset );
  11314. }
  11315. }
  11316. return r;
  11317. }
  11318. function arraysEqual( a, b ) {
  11319. if ( a.length !== b.length ) return false;
  11320. for ( let i = 0, l = a.length; i < l; i ++ ) {
  11321. if ( a[ i ] !== b[ i ] ) return false;
  11322. }
  11323. return true;
  11324. }
  11325. function copyArray( a, b ) {
  11326. for ( let i = 0, l = b.length; i < l; i ++ ) {
  11327. a[ i ] = b[ i ];
  11328. }
  11329. }
  11330. // Texture unit allocation
  11331. function allocTexUnits( textures, n ) {
  11332. let r = arrayCacheI32[ n ];
  11333. if ( r === undefined ) {
  11334. r = new Int32Array( n );
  11335. arrayCacheI32[ n ] = r;
  11336. }
  11337. for ( let i = 0; i !== n; ++ i ) {
  11338. r[ i ] = textures.allocateTextureUnit();
  11339. }
  11340. return r;
  11341. }
  11342. // --- Setters ---
  11343. // Note: Defining these methods externally, because they come in a bunch
  11344. // and this way their names minify.
  11345. // Single scalar
  11346. function setValueV1f( gl, v ) {
  11347. const cache = this.cache;
  11348. if ( cache[ 0 ] === v ) return;
  11349. gl.uniform1f( this.addr, v );
  11350. cache[ 0 ] = v;
  11351. }
  11352. // Single float vector (from flat array or THREE.VectorN)
  11353. function setValueV2f( gl, v ) {
  11354. const cache = this.cache;
  11355. if ( v.x !== undefined ) {
  11356. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  11357. gl.uniform2f( this.addr, v.x, v.y );
  11358. cache[ 0 ] = v.x;
  11359. cache[ 1 ] = v.y;
  11360. }
  11361. } else {
  11362. if ( arraysEqual( cache, v ) ) return;
  11363. gl.uniform2fv( this.addr, v );
  11364. copyArray( cache, v );
  11365. }
  11366. }
  11367. function setValueV3f( gl, v ) {
  11368. const cache = this.cache;
  11369. if ( v.x !== undefined ) {
  11370. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  11371. gl.uniform3f( this.addr, v.x, v.y, v.z );
  11372. cache[ 0 ] = v.x;
  11373. cache[ 1 ] = v.y;
  11374. cache[ 2 ] = v.z;
  11375. }
  11376. } else if ( v.r !== undefined ) {
  11377. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  11378. gl.uniform3f( this.addr, v.r, v.g, v.b );
  11379. cache[ 0 ] = v.r;
  11380. cache[ 1 ] = v.g;
  11381. cache[ 2 ] = v.b;
  11382. }
  11383. } else {
  11384. if ( arraysEqual( cache, v ) ) return;
  11385. gl.uniform3fv( this.addr, v );
  11386. copyArray( cache, v );
  11387. }
  11388. }
  11389. function setValueV4f( gl, v ) {
  11390. const cache = this.cache;
  11391. if ( v.x !== undefined ) {
  11392. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  11393. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  11394. cache[ 0 ] = v.x;
  11395. cache[ 1 ] = v.y;
  11396. cache[ 2 ] = v.z;
  11397. cache[ 3 ] = v.w;
  11398. }
  11399. } else {
  11400. if ( arraysEqual( cache, v ) ) return;
  11401. gl.uniform4fv( this.addr, v );
  11402. copyArray( cache, v );
  11403. }
  11404. }
  11405. // Single matrix (from flat array or THREE.MatrixN)
  11406. function setValueM2( gl, v ) {
  11407. const cache = this.cache;
  11408. const elements = v.elements;
  11409. if ( elements === undefined ) {
  11410. if ( arraysEqual( cache, v ) ) return;
  11411. gl.uniformMatrix2fv( this.addr, false, v );
  11412. copyArray( cache, v );
  11413. } else {
  11414. if ( arraysEqual( cache, elements ) ) return;
  11415. mat2array.set( elements );
  11416. gl.uniformMatrix2fv( this.addr, false, mat2array );
  11417. copyArray( cache, elements );
  11418. }
  11419. }
  11420. function setValueM3( gl, v ) {
  11421. const cache = this.cache;
  11422. const elements = v.elements;
  11423. if ( elements === undefined ) {
  11424. if ( arraysEqual( cache, v ) ) return;
  11425. gl.uniformMatrix3fv( this.addr, false, v );
  11426. copyArray( cache, v );
  11427. } else {
  11428. if ( arraysEqual( cache, elements ) ) return;
  11429. mat3array.set( elements );
  11430. gl.uniformMatrix3fv( this.addr, false, mat3array );
  11431. copyArray( cache, elements );
  11432. }
  11433. }
  11434. function setValueM4( gl, v ) {
  11435. const cache = this.cache;
  11436. const elements = v.elements;
  11437. if ( elements === undefined ) {
  11438. if ( arraysEqual( cache, v ) ) return;
  11439. gl.uniformMatrix4fv( this.addr, false, v );
  11440. copyArray( cache, v );
  11441. } else {
  11442. if ( arraysEqual( cache, elements ) ) return;
  11443. mat4array.set( elements );
  11444. gl.uniformMatrix4fv( this.addr, false, mat4array );
  11445. copyArray( cache, elements );
  11446. }
  11447. }
  11448. // Single integer / boolean
  11449. function setValueV1i( gl, v ) {
  11450. const cache = this.cache;
  11451. if ( cache[ 0 ] === v ) return;
  11452. gl.uniform1i( this.addr, v );
  11453. cache[ 0 ] = v;
  11454. }
  11455. // Single integer / boolean vector (from flat array)
  11456. function setValueV2i( gl, v ) {
  11457. const cache = this.cache;
  11458. if ( arraysEqual( cache, v ) ) return;
  11459. gl.uniform2iv( this.addr, v );
  11460. copyArray( cache, v );
  11461. }
  11462. function setValueV3i( gl, v ) {
  11463. const cache = this.cache;
  11464. if ( arraysEqual( cache, v ) ) return;
  11465. gl.uniform3iv( this.addr, v );
  11466. copyArray( cache, v );
  11467. }
  11468. function setValueV4i( gl, v ) {
  11469. const cache = this.cache;
  11470. if ( arraysEqual( cache, v ) ) return;
  11471. gl.uniform4iv( this.addr, v );
  11472. copyArray( cache, v );
  11473. }
  11474. // Single unsigned integer
  11475. function setValueV1ui( gl, v ) {
  11476. const cache = this.cache;
  11477. if ( cache[ 0 ] === v ) return;
  11478. gl.uniform1ui( this.addr, v );
  11479. cache[ 0 ] = v;
  11480. }
  11481. // Single unsigned integer vector (from flat array)
  11482. function setValueV2ui( gl, v ) {
  11483. const cache = this.cache;
  11484. if ( arraysEqual( cache, v ) ) return;
  11485. gl.uniform2uiv( this.addr, v );
  11486. copyArray( cache, v );
  11487. }
  11488. function setValueV3ui( gl, v ) {
  11489. const cache = this.cache;
  11490. if ( arraysEqual( cache, v ) ) return;
  11491. gl.uniform3uiv( this.addr, v );
  11492. copyArray( cache, v );
  11493. }
  11494. function setValueV4ui( gl, v ) {
  11495. const cache = this.cache;
  11496. if ( arraysEqual( cache, v ) ) return;
  11497. gl.uniform4uiv( this.addr, v );
  11498. copyArray( cache, v );
  11499. }
  11500. // Single texture (2D / Cube)
  11501. function setValueT1( gl, v, textures ) {
  11502. const cache = this.cache;
  11503. const unit = textures.allocateTextureUnit();
  11504. if ( cache[ 0 ] !== unit ) {
  11505. gl.uniform1i( this.addr, unit );
  11506. cache[ 0 ] = unit;
  11507. }
  11508. textures.safeSetTexture2D( v || emptyTexture, unit );
  11509. }
  11510. function setValueT3D1( gl, v, textures ) {
  11511. const cache = this.cache;
  11512. const unit = textures.allocateTextureUnit();
  11513. if ( cache[ 0 ] !== unit ) {
  11514. gl.uniform1i( this.addr, unit );
  11515. cache[ 0 ] = unit;
  11516. }
  11517. textures.setTexture3D( v || emptyTexture3d, unit );
  11518. }
  11519. function setValueT6( gl, v, textures ) {
  11520. const cache = this.cache;
  11521. const unit = textures.allocateTextureUnit();
  11522. if ( cache[ 0 ] !== unit ) {
  11523. gl.uniform1i( this.addr, unit );
  11524. cache[ 0 ] = unit;
  11525. }
  11526. textures.safeSetTextureCube( v || emptyCubeTexture, unit );
  11527. }
  11528. function setValueT2DArray1( gl, v, textures ) {
  11529. const cache = this.cache;
  11530. const unit = textures.allocateTextureUnit();
  11531. if ( cache[ 0 ] !== unit ) {
  11532. gl.uniform1i( this.addr, unit );
  11533. cache[ 0 ] = unit;
  11534. }
  11535. textures.setTexture2DArray( v || emptyTexture2dArray, unit );
  11536. }
  11537. // Helper to pick the right setter for the singular case
  11538. function getSingularSetter( type ) {
  11539. switch ( type ) {
  11540. case 0x1406: return setValueV1f; // FLOAT
  11541. case 0x8b50: return setValueV2f; // _VEC2
  11542. case 0x8b51: return setValueV3f; // _VEC3
  11543. case 0x8b52: return setValueV4f; // _VEC4
  11544. case 0x8b5a: return setValueM2; // _MAT2
  11545. case 0x8b5b: return setValueM3; // _MAT3
  11546. case 0x8b5c: return setValueM4; // _MAT4
  11547. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  11548. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  11549. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  11550. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  11551. case 0x1405: return setValueV1ui; // UINT
  11552. case 0x8dc6: return setValueV2ui; // _VEC2
  11553. case 0x8dc7: return setValueV3ui; // _VEC3
  11554. case 0x8dc8: return setValueV4ui; // _VEC4
  11555. case 0x8b5e: // SAMPLER_2D
  11556. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11557. case 0x8dca: // INT_SAMPLER_2D
  11558. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11559. case 0x8b62: // SAMPLER_2D_SHADOW
  11560. return setValueT1;
  11561. case 0x8b5f: // SAMPLER_3D
  11562. case 0x8dcb: // INT_SAMPLER_3D
  11563. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  11564. return setValueT3D1;
  11565. case 0x8b60: // SAMPLER_CUBE
  11566. case 0x8dcc: // INT_SAMPLER_CUBE
  11567. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11568. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  11569. return setValueT6;
  11570. case 0x8dc1: // SAMPLER_2D_ARRAY
  11571. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11572. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11573. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  11574. return setValueT2DArray1;
  11575. }
  11576. }
  11577. // Array of scalars
  11578. function setValueV1fArray( gl, v ) {
  11579. gl.uniform1fv( this.addr, v );
  11580. }
  11581. // Array of vectors (from flat array or array of THREE.VectorN)
  11582. function setValueV2fArray( gl, v ) {
  11583. const data = flatten( v, this.size, 2 );
  11584. gl.uniform2fv( this.addr, data );
  11585. }
  11586. function setValueV3fArray( gl, v ) {
  11587. const data = flatten( v, this.size, 3 );
  11588. gl.uniform3fv( this.addr, data );
  11589. }
  11590. function setValueV4fArray( gl, v ) {
  11591. const data = flatten( v, this.size, 4 );
  11592. gl.uniform4fv( this.addr, data );
  11593. }
  11594. // Array of matrices (from flat array or array of THREE.MatrixN)
  11595. function setValueM2Array( gl, v ) {
  11596. const data = flatten( v, this.size, 4 );
  11597. gl.uniformMatrix2fv( this.addr, false, data );
  11598. }
  11599. function setValueM3Array( gl, v ) {
  11600. const data = flatten( v, this.size, 9 );
  11601. gl.uniformMatrix3fv( this.addr, false, data );
  11602. }
  11603. function setValueM4Array( gl, v ) {
  11604. const data = flatten( v, this.size, 16 );
  11605. gl.uniformMatrix4fv( this.addr, false, data );
  11606. }
  11607. // Array of integer / boolean
  11608. function setValueV1iArray( gl, v ) {
  11609. gl.uniform1iv( this.addr, v );
  11610. }
  11611. // Array of integer / boolean vectors (from flat array)
  11612. function setValueV2iArray( gl, v ) {
  11613. gl.uniform2iv( this.addr, v );
  11614. }
  11615. function setValueV3iArray( gl, v ) {
  11616. gl.uniform3iv( this.addr, v );
  11617. }
  11618. function setValueV4iArray( gl, v ) {
  11619. gl.uniform4iv( this.addr, v );
  11620. }
  11621. // Array of unsigned integer
  11622. function setValueV1uiArray( gl, v ) {
  11623. gl.uniform1uiv( this.addr, v );
  11624. }
  11625. // Array of unsigned integer vectors (from flat array)
  11626. function setValueV2uiArray( gl, v ) {
  11627. gl.uniform2uiv( this.addr, v );
  11628. }
  11629. function setValueV3uiArray( gl, v ) {
  11630. gl.uniform3uiv( this.addr, v );
  11631. }
  11632. function setValueV4uiArray( gl, v ) {
  11633. gl.uniform4uiv( this.addr, v );
  11634. }
  11635. // Array of textures (2D / Cube)
  11636. function setValueT1Array( gl, v, textures ) {
  11637. const n = v.length;
  11638. const units = allocTexUnits( textures, n );
  11639. gl.uniform1iv( this.addr, units );
  11640. for ( let i = 0; i !== n; ++ i ) {
  11641. textures.safeSetTexture2D( v[ i ] || emptyTexture, units[ i ] );
  11642. }
  11643. }
  11644. function setValueT6Array( gl, v, textures ) {
  11645. const n = v.length;
  11646. const units = allocTexUnits( textures, n );
  11647. gl.uniform1iv( this.addr, units );
  11648. for ( let i = 0; i !== n; ++ i ) {
  11649. textures.safeSetTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  11650. }
  11651. }
  11652. // Helper to pick the right setter for a pure (bottom-level) array
  11653. function getPureArraySetter( type ) {
  11654. switch ( type ) {
  11655. case 0x1406: return setValueV1fArray; // FLOAT
  11656. case 0x8b50: return setValueV2fArray; // _VEC2
  11657. case 0x8b51: return setValueV3fArray; // _VEC3
  11658. case 0x8b52: return setValueV4fArray; // _VEC4
  11659. case 0x8b5a: return setValueM2Array; // _MAT2
  11660. case 0x8b5b: return setValueM3Array; // _MAT3
  11661. case 0x8b5c: return setValueM4Array; // _MAT4
  11662. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  11663. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  11664. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  11665. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  11666. case 0x1405: return setValueV1uiArray; // UINT
  11667. case 0x8dc6: return setValueV2uiArray; // _VEC2
  11668. case 0x8dc7: return setValueV3uiArray; // _VEC3
  11669. case 0x8dc8: return setValueV4uiArray; // _VEC4
  11670. case 0x8b5e: // SAMPLER_2D
  11671. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11672. case 0x8dca: // INT_SAMPLER_2D
  11673. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11674. case 0x8b62: // SAMPLER_2D_SHADOW
  11675. return setValueT1Array;
  11676. case 0x8b60: // SAMPLER_CUBE
  11677. case 0x8dcc: // INT_SAMPLER_CUBE
  11678. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11679. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  11680. return setValueT6Array;
  11681. }
  11682. }
  11683. // --- Uniform Classes ---
  11684. function SingleUniform( id, activeInfo, addr ) {
  11685. this.id = id;
  11686. this.addr = addr;
  11687. this.cache = [];
  11688. this.setValue = getSingularSetter( activeInfo.type );
  11689. // this.path = activeInfo.name; // DEBUG
  11690. }
  11691. function PureArrayUniform( id, activeInfo, addr ) {
  11692. this.id = id;
  11693. this.addr = addr;
  11694. this.cache = [];
  11695. this.size = activeInfo.size;
  11696. this.setValue = getPureArraySetter( activeInfo.type );
  11697. // this.path = activeInfo.name; // DEBUG
  11698. }
  11699. PureArrayUniform.prototype.updateCache = function ( data ) {
  11700. const cache = this.cache;
  11701. if ( data instanceof Float32Array && cache.length !== data.length ) {
  11702. this.cache = new Float32Array( data.length );
  11703. }
  11704. copyArray( cache, data );
  11705. };
  11706. function StructuredUniform( id ) {
  11707. this.id = id;
  11708. this.seq = [];
  11709. this.map = {};
  11710. }
  11711. StructuredUniform.prototype.setValue = function ( gl, value, textures ) {
  11712. const seq = this.seq;
  11713. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11714. const u = seq[ i ];
  11715. u.setValue( gl, value[ u.id ], textures );
  11716. }
  11717. };
  11718. // --- Top-level ---
  11719. // Parser - builds up the property tree from the path strings
  11720. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  11721. // extracts
  11722. // - the identifier (member name or array index)
  11723. // - followed by an optional right bracket (found when array index)
  11724. // - followed by an optional left bracket or dot (type of subscript)
  11725. //
  11726. // Note: These portions can be read in a non-overlapping fashion and
  11727. // allow straightforward parsing of the hierarchy that WebGL encodes
  11728. // in the uniform names.
  11729. function addUniform( container, uniformObject ) {
  11730. container.seq.push( uniformObject );
  11731. container.map[ uniformObject.id ] = uniformObject;
  11732. }
  11733. function parseUniform( activeInfo, addr, container ) {
  11734. const path = activeInfo.name,
  11735. pathLength = path.length;
  11736. // reset RegExp object, because of the early exit of a previous run
  11737. RePathPart.lastIndex = 0;
  11738. while ( true ) {
  11739. const match = RePathPart.exec( path ),
  11740. matchEnd = RePathPart.lastIndex;
  11741. let id = match[ 1 ];
  11742. const idIsIndex = match[ 2 ] === ']',
  11743. subscript = match[ 3 ];
  11744. if ( idIsIndex ) id = id | 0; // convert to integer
  11745. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  11746. // bare name or "pure" bottom-level array "[0]" suffix
  11747. addUniform( container, subscript === undefined ?
  11748. new SingleUniform( id, activeInfo, addr ) :
  11749. new PureArrayUniform( id, activeInfo, addr ) );
  11750. break;
  11751. } else {
  11752. // step into inner node / create it in case it doesn't exist
  11753. const map = container.map;
  11754. let next = map[ id ];
  11755. if ( next === undefined ) {
  11756. next = new StructuredUniform( id );
  11757. addUniform( container, next );
  11758. }
  11759. container = next;
  11760. }
  11761. }
  11762. }
  11763. // Root Container
  11764. function WebGLUniforms( gl, program ) {
  11765. this.seq = [];
  11766. this.map = {};
  11767. const n = gl.getProgramParameter( program, 35718 );
  11768. for ( let i = 0; i < n; ++ i ) {
  11769. const info = gl.getActiveUniform( program, i ),
  11770. addr = gl.getUniformLocation( program, info.name );
  11771. parseUniform( info, addr, this );
  11772. }
  11773. }
  11774. WebGLUniforms.prototype.setValue = function ( gl, name, value, textures ) {
  11775. const u = this.map[ name ];
  11776. if ( u !== undefined ) u.setValue( gl, value, textures );
  11777. };
  11778. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  11779. const v = object[ name ];
  11780. if ( v !== undefined ) this.setValue( gl, name, v );
  11781. };
  11782. // Static interface
  11783. WebGLUniforms.upload = function ( gl, seq, values, textures ) {
  11784. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11785. const u = seq[ i ],
  11786. v = values[ u.id ];
  11787. if ( v.needsUpdate !== false ) {
  11788. // note: always updating when .needsUpdate is undefined
  11789. u.setValue( gl, v.value, textures );
  11790. }
  11791. }
  11792. };
  11793. WebGLUniforms.seqWithValue = function ( seq, values ) {
  11794. const r = [];
  11795. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11796. const u = seq[ i ];
  11797. if ( u.id in values ) r.push( u );
  11798. }
  11799. return r;
  11800. };
  11801. function WebGLShader( gl, type, string ) {
  11802. const shader = gl.createShader( type );
  11803. gl.shaderSource( shader, string );
  11804. gl.compileShader( shader );
  11805. return shader;
  11806. }
  11807. let programIdCount = 0;
  11808. function addLineNumbers( string ) {
  11809. const lines = string.split( '\n' );
  11810. for ( let i = 0; i < lines.length; i ++ ) {
  11811. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  11812. }
  11813. return lines.join( '\n' );
  11814. }
  11815. function getEncodingComponents( encoding ) {
  11816. switch ( encoding ) {
  11817. case LinearEncoding:
  11818. return [ 'Linear', '( value )' ];
  11819. case sRGBEncoding:
  11820. return [ 'sRGB', '( value )' ];
  11821. case RGBEEncoding:
  11822. return [ 'RGBE', '( value )' ];
  11823. case RGBM7Encoding:
  11824. return [ 'RGBM', '( value, 7.0 )' ];
  11825. case RGBM16Encoding:
  11826. return [ 'RGBM', '( value, 16.0 )' ];
  11827. case RGBDEncoding:
  11828. return [ 'RGBD', '( value, 256.0 )' ];
  11829. case GammaEncoding:
  11830. return [ 'Gamma', '( value, float( GAMMA_FACTOR ) )' ];
  11831. case LogLuvEncoding:
  11832. return [ 'LogLuv', '( value )' ];
  11833. default:
  11834. console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding );
  11835. return [ 'Linear', '( value )' ];
  11836. }
  11837. }
  11838. function getShaderErrors( gl, shader, type ) {
  11839. const status = gl.getShaderParameter( shader, 35713 );
  11840. const errors = gl.getShaderInfoLog( shader ).trim();
  11841. if ( status && errors === '' ) return '';
  11842. // --enable-privileged-webgl-extension
  11843. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11844. return type.toUpperCase() + '\n\n' + errors + '\n\n' + addLineNumbers( gl.getShaderSource( shader ) );
  11845. }
  11846. function getTexelDecodingFunction( functionName, encoding ) {
  11847. const components = getEncodingComponents( encoding );
  11848. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }';
  11849. }
  11850. function getTexelEncodingFunction( functionName, encoding ) {
  11851. const components = getEncodingComponents( encoding );
  11852. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  11853. }
  11854. function getToneMappingFunction( functionName, toneMapping ) {
  11855. let toneMappingName;
  11856. switch ( toneMapping ) {
  11857. case LinearToneMapping:
  11858. toneMappingName = 'Linear';
  11859. break;
  11860. case ReinhardToneMapping:
  11861. toneMappingName = 'Reinhard';
  11862. break;
  11863. case CineonToneMapping:
  11864. toneMappingName = 'OptimizedCineon';
  11865. break;
  11866. case ACESFilmicToneMapping:
  11867. toneMappingName = 'ACESFilmic';
  11868. break;
  11869. case CustomToneMapping:
  11870. toneMappingName = 'Custom';
  11871. break;
  11872. default:
  11873. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  11874. toneMappingName = 'Linear';
  11875. }
  11876. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11877. }
  11878. function generateExtensions( parameters ) {
  11879. const chunks = [
  11880. ( parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  11881. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  11882. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  11883. ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  11884. ];
  11885. return chunks.filter( filterEmptyLine ).join( '\n' );
  11886. }
  11887. function generateDefines( defines ) {
  11888. const chunks = [];
  11889. for ( const name in defines ) {
  11890. const value = defines[ name ];
  11891. if ( value === false ) continue;
  11892. chunks.push( '#define ' + name + ' ' + value );
  11893. }
  11894. return chunks.join( '\n' );
  11895. }
  11896. function fetchAttributeLocations( gl, program ) {
  11897. const attributes = {};
  11898. const n = gl.getProgramParameter( program, 35721 );
  11899. for ( let i = 0; i < n; i ++ ) {
  11900. const info = gl.getActiveAttrib( program, i );
  11901. const name = info.name;
  11902. let locationSize = 1;
  11903. if ( info.type === 35674 ) locationSize = 2;
  11904. if ( info.type === 35675 ) locationSize = 3;
  11905. if ( info.type === 35676 ) locationSize = 4;
  11906. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11907. attributes[ name ] = {
  11908. type: info.type,
  11909. location: gl.getAttribLocation( program, name ),
  11910. locationSize: locationSize
  11911. };
  11912. }
  11913. return attributes;
  11914. }
  11915. function filterEmptyLine( string ) {
  11916. return string !== '';
  11917. }
  11918. function replaceLightNums( string, parameters ) {
  11919. return string
  11920. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  11921. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  11922. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  11923. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  11924. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  11925. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  11926. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  11927. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  11928. }
  11929. function replaceClippingPlaneNums( string, parameters ) {
  11930. return string
  11931. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  11932. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  11933. }
  11934. // Resolve Includes
  11935. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11936. function resolveIncludes( string ) {
  11937. return string.replace( includePattern, includeReplacer );
  11938. }
  11939. function includeReplacer( match, include ) {
  11940. const string = ShaderChunk[ include ];
  11941. if ( string === undefined ) {
  11942. throw new Error( 'Can not resolve #include <' + include + '>' );
  11943. }
  11944. return resolveIncludes( string );
  11945. }
  11946. // Unroll Loops
  11947. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  11948. 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;
  11949. function unrollLoops( string ) {
  11950. return string
  11951. .replace( unrollLoopPattern, loopReplacer )
  11952. .replace( deprecatedUnrollLoopPattern, deprecatedLoopReplacer );
  11953. }
  11954. function deprecatedLoopReplacer( match, start, end, snippet ) {
  11955. console.warn( 'WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.' );
  11956. return loopReplacer( match, start, end, snippet );
  11957. }
  11958. function loopReplacer( match, start, end, snippet ) {
  11959. let string = '';
  11960. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  11961. string += snippet
  11962. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  11963. .replace( /UNROLLED_LOOP_INDEX/g, i );
  11964. }
  11965. return string;
  11966. }
  11967. //
  11968. function generatePrecision( parameters ) {
  11969. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11970. if ( parameters.precision === 'highp' ) {
  11971. precisionstring += '\n#define HIGH_PRECISION';
  11972. } else if ( parameters.precision === 'mediump' ) {
  11973. precisionstring += '\n#define MEDIUM_PRECISION';
  11974. } else if ( parameters.precision === 'lowp' ) {
  11975. precisionstring += '\n#define LOW_PRECISION';
  11976. }
  11977. return precisionstring;
  11978. }
  11979. function generateShadowMapTypeDefine( parameters ) {
  11980. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11981. if ( parameters.shadowMapType === PCFShadowMap ) {
  11982. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11983. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  11984. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11985. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  11986. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11987. }
  11988. return shadowMapTypeDefine;
  11989. }
  11990. function generateEnvMapTypeDefine( parameters ) {
  11991. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11992. if ( parameters.envMap ) {
  11993. switch ( parameters.envMapMode ) {
  11994. case CubeReflectionMapping:
  11995. case CubeRefractionMapping:
  11996. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11997. break;
  11998. case CubeUVReflectionMapping:
  11999. case CubeUVRefractionMapping:
  12000. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  12001. break;
  12002. }
  12003. }
  12004. return envMapTypeDefine;
  12005. }
  12006. function generateEnvMapModeDefine( parameters ) {
  12007. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  12008. if ( parameters.envMap ) {
  12009. switch ( parameters.envMapMode ) {
  12010. case CubeRefractionMapping:
  12011. case CubeUVRefractionMapping:
  12012. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  12013. break;
  12014. }
  12015. }
  12016. return envMapModeDefine;
  12017. }
  12018. function generateEnvMapBlendingDefine( parameters ) {
  12019. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  12020. if ( parameters.envMap ) {
  12021. switch ( parameters.combine ) {
  12022. case MultiplyOperation:
  12023. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  12024. break;
  12025. case MixOperation:
  12026. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  12027. break;
  12028. case AddOperation:
  12029. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  12030. break;
  12031. }
  12032. }
  12033. return envMapBlendingDefine;
  12034. }
  12035. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  12036. // TODO Send this event to Three.js DevTools
  12037. // console.log( 'WebGLProgram', cacheKey );
  12038. const gl = renderer.getContext();
  12039. const defines = parameters.defines;
  12040. let vertexShader = parameters.vertexShader;
  12041. let fragmentShader = parameters.fragmentShader;
  12042. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  12043. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  12044. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  12045. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  12046. const gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  12047. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  12048. const customDefines = generateDefines( defines );
  12049. const program = gl.createProgram();
  12050. let prefixVertex, prefixFragment;
  12051. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  12052. if ( parameters.isRawShaderMaterial ) {
  12053. prefixVertex = [
  12054. customDefines
  12055. ].filter( filterEmptyLine ).join( '\n' );
  12056. if ( prefixVertex.length > 0 ) {
  12057. prefixVertex += '\n';
  12058. }
  12059. prefixFragment = [
  12060. customExtensions,
  12061. customDefines
  12062. ].filter( filterEmptyLine ).join( '\n' );
  12063. if ( prefixFragment.length > 0 ) {
  12064. prefixFragment += '\n';
  12065. }
  12066. } else {
  12067. prefixVertex = [
  12068. generatePrecision( parameters ),
  12069. '#define SHADER_NAME ' + parameters.shaderName,
  12070. customDefines,
  12071. parameters.instancing ? '#define USE_INSTANCING' : '',
  12072. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  12073. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  12074. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  12075. '#define MAX_BONES ' + parameters.maxBones,
  12076. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  12077. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  12078. parameters.map ? '#define USE_MAP' : '',
  12079. parameters.envMap ? '#define USE_ENVMAP' : '',
  12080. parameters.envMap ? '#define ' + envMapModeDefine : '',
  12081. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  12082. parameters.aoMap ? '#define USE_AOMAP' : '',
  12083. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  12084. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  12085. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  12086. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  12087. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  12088. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  12089. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  12090. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  12091. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  12092. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  12093. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  12094. parameters.specularTintMap ? '#define USE_SPECULARTINTMAP' : '',
  12095. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  12096. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  12097. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  12098. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  12099. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  12100. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  12101. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  12102. parameters.vertexColors ? '#define USE_COLOR' : '',
  12103. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  12104. parameters.vertexUvs ? '#define USE_UV' : '',
  12105. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  12106. parameters.flatShading ? '#define FLAT_SHADED' : '',
  12107. parameters.skinning ? '#define USE_SKINNING' : '',
  12108. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  12109. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  12110. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  12111. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  12112. parameters.flipSided ? '#define FLIP_SIDED' : '',
  12113. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  12114. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  12115. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  12116. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  12117. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  12118. 'uniform mat4 modelMatrix;',
  12119. 'uniform mat4 modelViewMatrix;',
  12120. 'uniform mat4 projectionMatrix;',
  12121. 'uniform mat4 viewMatrix;',
  12122. 'uniform mat3 normalMatrix;',
  12123. 'uniform vec3 cameraPosition;',
  12124. 'uniform bool isOrthographic;',
  12125. '#ifdef USE_INSTANCING',
  12126. ' attribute mat4 instanceMatrix;',
  12127. '#endif',
  12128. '#ifdef USE_INSTANCING_COLOR',
  12129. ' attribute vec3 instanceColor;',
  12130. '#endif',
  12131. 'attribute vec3 position;',
  12132. 'attribute vec3 normal;',
  12133. 'attribute vec2 uv;',
  12134. '#ifdef USE_TANGENT',
  12135. ' attribute vec4 tangent;',
  12136. '#endif',
  12137. '#if defined( USE_COLOR_ALPHA )',
  12138. ' attribute vec4 color;',
  12139. '#elif defined( USE_COLOR )',
  12140. ' attribute vec3 color;',
  12141. '#endif',
  12142. '#ifdef USE_MORPHTARGETS',
  12143. ' attribute vec3 morphTarget0;',
  12144. ' attribute vec3 morphTarget1;',
  12145. ' attribute vec3 morphTarget2;',
  12146. ' attribute vec3 morphTarget3;',
  12147. ' #ifdef USE_MORPHNORMALS',
  12148. ' attribute vec3 morphNormal0;',
  12149. ' attribute vec3 morphNormal1;',
  12150. ' attribute vec3 morphNormal2;',
  12151. ' attribute vec3 morphNormal3;',
  12152. ' #else',
  12153. ' attribute vec3 morphTarget4;',
  12154. ' attribute vec3 morphTarget5;',
  12155. ' attribute vec3 morphTarget6;',
  12156. ' attribute vec3 morphTarget7;',
  12157. ' #endif',
  12158. '#endif',
  12159. '#ifdef USE_SKINNING',
  12160. ' attribute vec4 skinIndex;',
  12161. ' attribute vec4 skinWeight;',
  12162. '#endif',
  12163. '\n'
  12164. ].filter( filterEmptyLine ).join( '\n' );
  12165. prefixFragment = [
  12166. customExtensions,
  12167. generatePrecision( parameters ),
  12168. '#define SHADER_NAME ' + parameters.shaderName,
  12169. customDefines,
  12170. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  12171. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  12172. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  12173. parameters.map ? '#define USE_MAP' : '',
  12174. parameters.matcap ? '#define USE_MATCAP' : '',
  12175. parameters.envMap ? '#define USE_ENVMAP' : '',
  12176. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  12177. parameters.envMap ? '#define ' + envMapModeDefine : '',
  12178. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  12179. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  12180. parameters.aoMap ? '#define USE_AOMAP' : '',
  12181. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  12182. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  12183. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  12184. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  12185. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  12186. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  12187. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  12188. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  12189. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  12190. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  12191. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  12192. parameters.specularTintMap ? '#define USE_SPECULARTINTMAP' : '',
  12193. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  12194. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  12195. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  12196. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  12197. parameters.sheenTint ? '#define USE_SHEEN' : '',
  12198. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  12199. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  12200. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  12201. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  12202. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  12203. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  12204. parameters.vertexUvs ? '#define USE_UV' : '',
  12205. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  12206. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  12207. parameters.flatShading ? '#define FLAT_SHADED' : '',
  12208. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  12209. parameters.flipSided ? '#define FLIP_SIDED' : '',
  12210. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  12211. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  12212. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  12213. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  12214. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  12215. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  12216. ( ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ) ? '#define TEXTURE_LOD_EXT' : '',
  12217. 'uniform mat4 viewMatrix;',
  12218. 'uniform vec3 cameraPosition;',
  12219. 'uniform bool isOrthographic;',
  12220. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  12221. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  12222. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  12223. parameters.dithering ? '#define DITHERING' : '',
  12224. parameters.format === RGBFormat ? '#define OPAQUE' : '',
  12225. ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  12226. parameters.map ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  12227. parameters.matcap ? getTexelDecodingFunction( 'matcapTexelToLinear', parameters.matcapEncoding ) : '',
  12228. parameters.envMap ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  12229. parameters.emissiveMap ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  12230. parameters.specularTintMap ? getTexelDecodingFunction( 'specularTintMapTexelToLinear', parameters.specularTintMapEncoding ) : '',
  12231. parameters.lightMap ? getTexelDecodingFunction( 'lightMapTexelToLinear', parameters.lightMapEncoding ) : '',
  12232. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),
  12233. parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  12234. '\n'
  12235. ].filter( filterEmptyLine ).join( '\n' );
  12236. }
  12237. vertexShader = resolveIncludes( vertexShader );
  12238. vertexShader = replaceLightNums( vertexShader, parameters );
  12239. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  12240. fragmentShader = resolveIncludes( fragmentShader );
  12241. fragmentShader = replaceLightNums( fragmentShader, parameters );
  12242. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  12243. vertexShader = unrollLoops( vertexShader );
  12244. fragmentShader = unrollLoops( fragmentShader );
  12245. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  12246. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  12247. versionString = '#version 300 es\n';
  12248. prefixVertex = [
  12249. '#define attribute in',
  12250. '#define varying out',
  12251. '#define texture2D texture'
  12252. ].join( '\n' ) + '\n' + prefixVertex;
  12253. prefixFragment = [
  12254. '#define varying in',
  12255. ( parameters.glslVersion === GLSL3 ) ? '' : 'out highp vec4 pc_fragColor;',
  12256. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  12257. '#define gl_FragDepthEXT gl_FragDepth',
  12258. '#define texture2D texture',
  12259. '#define textureCube texture',
  12260. '#define texture2DProj textureProj',
  12261. '#define texture2DLodEXT textureLod',
  12262. '#define texture2DProjLodEXT textureProjLod',
  12263. '#define textureCubeLodEXT textureLod',
  12264. '#define texture2DGradEXT textureGrad',
  12265. '#define texture2DProjGradEXT textureProjGrad',
  12266. '#define textureCubeGradEXT textureGrad'
  12267. ].join( '\n' ) + '\n' + prefixFragment;
  12268. }
  12269. const vertexGlsl = versionString + prefixVertex + vertexShader;
  12270. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  12271. // console.log( '*VERTEX*', vertexGlsl );
  12272. // console.log( '*FRAGMENT*', fragmentGlsl );
  12273. const glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
  12274. const glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );
  12275. gl.attachShader( program, glVertexShader );
  12276. gl.attachShader( program, glFragmentShader );
  12277. // Force a particular attribute to index 0.
  12278. if ( parameters.index0AttributeName !== undefined ) {
  12279. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  12280. } else if ( parameters.morphTargets === true ) {
  12281. // programs with morphTargets displace position out of attribute 0
  12282. gl.bindAttribLocation( program, 0, 'position' );
  12283. }
  12284. gl.linkProgram( program );
  12285. // check for link errors
  12286. if ( renderer.debug.checkShaderErrors ) {
  12287. const programLog = gl.getProgramInfoLog( program ).trim();
  12288. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  12289. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  12290. let runnable = true;
  12291. let haveDiagnostics = true;
  12292. if ( gl.getProgramParameter( program, 35714 ) === false ) {
  12293. runnable = false;
  12294. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  12295. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  12296. console.error(
  12297. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  12298. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, 35715 ) + '\n\n' +
  12299. 'Program Info Log: ' + programLog + '\n' +
  12300. vertexErrors + '\n' +
  12301. fragmentErrors
  12302. );
  12303. } else if ( programLog !== '' ) {
  12304. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  12305. } else if ( vertexLog === '' || fragmentLog === '' ) {
  12306. haveDiagnostics = false;
  12307. }
  12308. if ( haveDiagnostics ) {
  12309. this.diagnostics = {
  12310. runnable: runnable,
  12311. programLog: programLog,
  12312. vertexShader: {
  12313. log: vertexLog,
  12314. prefix: prefixVertex
  12315. },
  12316. fragmentShader: {
  12317. log: fragmentLog,
  12318. prefix: prefixFragment
  12319. }
  12320. };
  12321. }
  12322. }
  12323. // Clean up
  12324. // Crashes in iOS9 and iOS10. #18402
  12325. // gl.detachShader( program, glVertexShader );
  12326. // gl.detachShader( program, glFragmentShader );
  12327. gl.deleteShader( glVertexShader );
  12328. gl.deleteShader( glFragmentShader );
  12329. // set up caching for uniform locations
  12330. let cachedUniforms;
  12331. this.getUniforms = function () {
  12332. if ( cachedUniforms === undefined ) {
  12333. cachedUniforms = new WebGLUniforms( gl, program );
  12334. }
  12335. return cachedUniforms;
  12336. };
  12337. // set up caching for attribute locations
  12338. let cachedAttributes;
  12339. this.getAttributes = function () {
  12340. if ( cachedAttributes === undefined ) {
  12341. cachedAttributes = fetchAttributeLocations( gl, program );
  12342. }
  12343. return cachedAttributes;
  12344. };
  12345. // free resource
  12346. this.destroy = function () {
  12347. bindingStates.releaseStatesOfProgram( this );
  12348. gl.deleteProgram( program );
  12349. this.program = undefined;
  12350. };
  12351. //
  12352. this.name = parameters.shaderName;
  12353. this.id = programIdCount ++;
  12354. this.cacheKey = cacheKey;
  12355. this.usedTimes = 1;
  12356. this.program = program;
  12357. this.vertexShader = glVertexShader;
  12358. this.fragmentShader = glFragmentShader;
  12359. return this;
  12360. }
  12361. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  12362. const programs = [];
  12363. const isWebGL2 = capabilities.isWebGL2;
  12364. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  12365. const floatVertexTextures = capabilities.floatVertexTextures;
  12366. const maxVertexUniforms = capabilities.maxVertexUniforms;
  12367. const vertexTextures = capabilities.vertexTextures;
  12368. let precision = capabilities.precision;
  12369. const shaderIDs = {
  12370. MeshDepthMaterial: 'depth',
  12371. MeshDistanceMaterial: 'distanceRGBA',
  12372. MeshNormalMaterial: 'normal',
  12373. MeshBasicMaterial: 'basic',
  12374. MeshLambertMaterial: 'lambert',
  12375. MeshPhongMaterial: 'phong',
  12376. MeshToonMaterial: 'toon',
  12377. MeshStandardMaterial: 'physical',
  12378. MeshPhysicalMaterial: 'physical',
  12379. MeshMatcapMaterial: 'matcap',
  12380. LineBasicMaterial: 'basic',
  12381. LineDashedMaterial: 'dashed',
  12382. PointsMaterial: 'points',
  12383. ShadowMaterial: 'shadow',
  12384. SpriteMaterial: 'sprite'
  12385. };
  12386. const parameterNames = [
  12387. 'precision', 'isWebGL2', 'supportsVertexTextures', 'outputEncoding', 'instancing', 'instancingColor',
  12388. 'map', 'mapEncoding', 'matcap', 'matcapEncoding', 'envMap', 'envMapMode', 'envMapEncoding', 'envMapCubeUV',
  12389. 'lightMap', 'lightMapEncoding', 'aoMap', 'emissiveMap', 'emissiveMapEncoding', 'bumpMap', 'normalMap',
  12390. 'objectSpaceNormalMap', 'tangentSpaceNormalMap',
  12391. 'clearcoat', 'clearcoatMap', 'clearcoatRoughnessMap', 'clearcoatNormalMap',
  12392. 'displacementMap',
  12393. 'specularMap', 'specularIntensityMap', 'specularTintMap', 'specularTintMapEncoding', 'roughnessMap', 'metalnessMap', 'gradientMap',
  12394. 'alphaMap', 'alphaTest', 'combine', 'vertexColors', 'vertexAlphas', 'vertexTangents', 'vertexUvs', 'uvsVertexOnly', 'fog', 'useFog', 'fogExp2',
  12395. 'flatShading', 'sizeAttenuation', 'logarithmicDepthBuffer', 'skinning',
  12396. 'maxBones', 'useVertexTexture', 'morphTargets', 'morphNormals', 'premultipliedAlpha',
  12397. 'numDirLights', 'numPointLights', 'numSpotLights', 'numHemiLights', 'numRectAreaLights',
  12398. 'numDirLightShadows', 'numPointLightShadows', 'numSpotLightShadows',
  12399. 'shadowMapEnabled', 'shadowMapType', 'toneMapping', 'physicallyCorrectLights',
  12400. 'doubleSided', 'flipSided', 'numClippingPlanes', 'numClipIntersection', 'depthPacking', 'dithering', 'format',
  12401. 'sheenTint', 'transmission', 'transmissionMap', 'thicknessMap'
  12402. ];
  12403. function getMaxBones( object ) {
  12404. const skeleton = object.skeleton;
  12405. const bones = skeleton.bones;
  12406. if ( floatVertexTextures ) {
  12407. return 1024;
  12408. } else {
  12409. // default for when object is not specified
  12410. // ( for example when prebuilding shader to be used with multiple objects )
  12411. //
  12412. // - leave some extra space for other uniforms
  12413. // - limit here is ANGLE's 254 max uniform vectors
  12414. // (up to 54 should be safe)
  12415. const nVertexUniforms = maxVertexUniforms;
  12416. const nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  12417. const maxBones = Math.min( nVertexMatrices, bones.length );
  12418. if ( maxBones < bones.length ) {
  12419. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  12420. return 0;
  12421. }
  12422. return maxBones;
  12423. }
  12424. }
  12425. function getTextureEncodingFromMap( map ) {
  12426. let encoding;
  12427. if ( map && map.isTexture ) {
  12428. encoding = map.encoding;
  12429. } else if ( map && map.isWebGLRenderTarget ) {
  12430. console.warn( 'THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.' );
  12431. encoding = map.texture.encoding;
  12432. } else {
  12433. encoding = LinearEncoding;
  12434. }
  12435. return encoding;
  12436. }
  12437. function getParameters( material, lights, shadows, scene, object ) {
  12438. const fog = scene.fog;
  12439. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  12440. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  12441. const shaderID = shaderIDs[ material.type ];
  12442. // heuristics to create shader parameters according to lights in the scene
  12443. // (not to blow over maxLights budget)
  12444. const maxBones = object.isSkinnedMesh ? getMaxBones( object ) : 0;
  12445. if ( material.precision !== null ) {
  12446. precision = capabilities.getMaxPrecision( material.precision );
  12447. if ( precision !== material.precision ) {
  12448. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  12449. }
  12450. }
  12451. let vertexShader, fragmentShader;
  12452. if ( shaderID ) {
  12453. const shader = ShaderLib[ shaderID ];
  12454. vertexShader = shader.vertexShader;
  12455. fragmentShader = shader.fragmentShader;
  12456. } else {
  12457. vertexShader = material.vertexShader;
  12458. fragmentShader = material.fragmentShader;
  12459. }
  12460. const currentRenderTarget = renderer.getRenderTarget();
  12461. const useAlphaTest = material.alphaTest > 0;
  12462. const useClearcoat = material.clearcoat > 0;
  12463. const parameters = {
  12464. isWebGL2: isWebGL2,
  12465. shaderID: shaderID,
  12466. shaderName: material.type,
  12467. vertexShader: vertexShader,
  12468. fragmentShader: fragmentShader,
  12469. defines: material.defines,
  12470. isRawShaderMaterial: material.isRawShaderMaterial === true,
  12471. glslVersion: material.glslVersion,
  12472. precision: precision,
  12473. instancing: object.isInstancedMesh === true,
  12474. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  12475. supportsVertexTextures: vertexTextures,
  12476. outputEncoding: ( currentRenderTarget !== null ) ? getTextureEncodingFromMap( currentRenderTarget.texture ) : renderer.outputEncoding,
  12477. map: !! material.map,
  12478. mapEncoding: getTextureEncodingFromMap( material.map ),
  12479. matcap: !! material.matcap,
  12480. matcapEncoding: getTextureEncodingFromMap( material.matcap ),
  12481. envMap: !! envMap,
  12482. envMapMode: envMap && envMap.mapping,
  12483. envMapEncoding: getTextureEncodingFromMap( envMap ),
  12484. envMapCubeUV: ( !! envMap ) && ( ( envMap.mapping === CubeUVReflectionMapping ) || ( envMap.mapping === CubeUVRefractionMapping ) ),
  12485. lightMap: !! material.lightMap,
  12486. lightMapEncoding: getTextureEncodingFromMap( material.lightMap ),
  12487. aoMap: !! material.aoMap,
  12488. emissiveMap: !! material.emissiveMap,
  12489. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap ),
  12490. bumpMap: !! material.bumpMap,
  12491. normalMap: !! material.normalMap,
  12492. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  12493. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  12494. clearcoat: useClearcoat,
  12495. clearcoatMap: useClearcoat && !! material.clearcoatMap,
  12496. clearcoatRoughnessMap: useClearcoat && !! material.clearcoatRoughnessMap,
  12497. clearcoatNormalMap: useClearcoat && !! material.clearcoatNormalMap,
  12498. displacementMap: !! material.displacementMap,
  12499. roughnessMap: !! material.roughnessMap,
  12500. metalnessMap: !! material.metalnessMap,
  12501. specularMap: !! material.specularMap,
  12502. specularIntensityMap: !! material.specularIntensityMap,
  12503. specularTintMap: !! material.specularTintMap,
  12504. specularTintMapEncoding: getTextureEncodingFromMap( material.specularTintMap ),
  12505. alphaMap: !! material.alphaMap,
  12506. alphaTest: useAlphaTest,
  12507. gradientMap: !! material.gradientMap,
  12508. sheenTint: ( !! material.sheenTint && ( material.sheenTint.r > 0 || material.sheenTint.g > 0 || material.sheenTint.b > 0 ) ),
  12509. transmission: material.transmission > 0,
  12510. transmissionMap: !! material.transmissionMap,
  12511. thicknessMap: !! material.thicknessMap,
  12512. combine: material.combine,
  12513. vertexTangents: ( !! material.normalMap && !! object.geometry && !! object.geometry.attributes.tangent ),
  12514. vertexColors: material.vertexColors,
  12515. vertexAlphas: material.vertexColors === true && !! object.geometry && !! object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4,
  12516. vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatMap || !! material.clearcoatRoughnessMap || !! material.clearcoatNormalMap || !! material.displacementMap || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularTintMap,
  12517. uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || material.transmission > 0 || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularTintMap ) && !! material.displacementMap,
  12518. fog: !! fog,
  12519. useFog: material.fog,
  12520. fogExp2: ( fog && fog.isFogExp2 ),
  12521. flatShading: !! material.flatShading,
  12522. sizeAttenuation: material.sizeAttenuation,
  12523. logarithmicDepthBuffer: logarithmicDepthBuffer,
  12524. skinning: object.isSkinnedMesh === true && maxBones > 0,
  12525. maxBones: maxBones,
  12526. useVertexTexture: floatVertexTextures,
  12527. morphTargets: !! object.geometry && !! object.geometry.morphAttributes.position,
  12528. morphNormals: !! object.geometry && !! object.geometry.morphAttributes.normal,
  12529. numDirLights: lights.directional.length,
  12530. numPointLights: lights.point.length,
  12531. numSpotLights: lights.spot.length,
  12532. numRectAreaLights: lights.rectArea.length,
  12533. numHemiLights: lights.hemi.length,
  12534. numDirLightShadows: lights.directionalShadowMap.length,
  12535. numPointLightShadows: lights.pointShadowMap.length,
  12536. numSpotLightShadows: lights.spotShadowMap.length,
  12537. numClippingPlanes: clipping.numPlanes,
  12538. numClipIntersection: clipping.numIntersection,
  12539. format: material.format,
  12540. dithering: material.dithering,
  12541. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  12542. shadowMapType: renderer.shadowMap.type,
  12543. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  12544. physicallyCorrectLights: renderer.physicallyCorrectLights,
  12545. premultipliedAlpha: material.premultipliedAlpha,
  12546. doubleSided: material.side === DoubleSide,
  12547. flipSided: material.side === BackSide,
  12548. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false,
  12549. index0AttributeName: material.index0AttributeName,
  12550. extensionDerivatives: material.extensions && material.extensions.derivatives,
  12551. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  12552. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  12553. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  12554. rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ),
  12555. rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  12556. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  12557. customProgramCacheKey: material.customProgramCacheKey()
  12558. };
  12559. return parameters;
  12560. }
  12561. function getProgramCacheKey( parameters ) {
  12562. const array = [];
  12563. if ( parameters.shaderID ) {
  12564. array.push( parameters.shaderID );
  12565. } else {
  12566. array.push( parameters.fragmentShader );
  12567. array.push( parameters.vertexShader );
  12568. }
  12569. if ( parameters.defines !== undefined ) {
  12570. for ( const name in parameters.defines ) {
  12571. array.push( name );
  12572. array.push( parameters.defines[ name ] );
  12573. }
  12574. }
  12575. if ( parameters.isRawShaderMaterial === false ) {
  12576. for ( let i = 0; i < parameterNames.length; i ++ ) {
  12577. array.push( parameters[ parameterNames[ i ] ] );
  12578. }
  12579. array.push( renderer.outputEncoding );
  12580. array.push( renderer.gammaFactor );
  12581. }
  12582. array.push( parameters.customProgramCacheKey );
  12583. return array.join();
  12584. }
  12585. function getUniforms( material ) {
  12586. const shaderID = shaderIDs[ material.type ];
  12587. let uniforms;
  12588. if ( shaderID ) {
  12589. const shader = ShaderLib[ shaderID ];
  12590. uniforms = UniformsUtils.clone( shader.uniforms );
  12591. } else {
  12592. uniforms = material.uniforms;
  12593. }
  12594. return uniforms;
  12595. }
  12596. function acquireProgram( parameters, cacheKey ) {
  12597. let program;
  12598. // Check if code has been already compiled
  12599. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  12600. const preexistingProgram = programs[ p ];
  12601. if ( preexistingProgram.cacheKey === cacheKey ) {
  12602. program = preexistingProgram;
  12603. ++ program.usedTimes;
  12604. break;
  12605. }
  12606. }
  12607. if ( program === undefined ) {
  12608. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  12609. programs.push( program );
  12610. }
  12611. return program;
  12612. }
  12613. function releaseProgram( program ) {
  12614. if ( -- program.usedTimes === 0 ) {
  12615. // Remove from unordered set
  12616. const i = programs.indexOf( program );
  12617. programs[ i ] = programs[ programs.length - 1 ];
  12618. programs.pop();
  12619. // Free WebGL resources
  12620. program.destroy();
  12621. }
  12622. }
  12623. return {
  12624. getParameters: getParameters,
  12625. getProgramCacheKey: getProgramCacheKey,
  12626. getUniforms: getUniforms,
  12627. acquireProgram: acquireProgram,
  12628. releaseProgram: releaseProgram,
  12629. // Exposed for resource monitoring & error feedback via renderer.info:
  12630. programs: programs
  12631. };
  12632. }
  12633. function WebGLProperties() {
  12634. let properties = new WeakMap();
  12635. function get( object ) {
  12636. let map = properties.get( object );
  12637. if ( map === undefined ) {
  12638. map = {};
  12639. properties.set( object, map );
  12640. }
  12641. return map;
  12642. }
  12643. function remove( object ) {
  12644. properties.delete( object );
  12645. }
  12646. function update( object, key, value ) {
  12647. properties.get( object )[ key ] = value;
  12648. }
  12649. function dispose() {
  12650. properties = new WeakMap();
  12651. }
  12652. return {
  12653. get: get,
  12654. remove: remove,
  12655. update: update,
  12656. dispose: dispose
  12657. };
  12658. }
  12659. function painterSortStable( a, b ) {
  12660. if ( a.groupOrder !== b.groupOrder ) {
  12661. return a.groupOrder - b.groupOrder;
  12662. } else if ( a.renderOrder !== b.renderOrder ) {
  12663. return a.renderOrder - b.renderOrder;
  12664. } else if ( a.program !== b.program ) {
  12665. return a.program.id - b.program.id;
  12666. } else if ( a.material.id !== b.material.id ) {
  12667. return a.material.id - b.material.id;
  12668. } else if ( a.z !== b.z ) {
  12669. return a.z - b.z;
  12670. } else {
  12671. return a.id - b.id;
  12672. }
  12673. }
  12674. function reversePainterSortStable( a, b ) {
  12675. if ( a.groupOrder !== b.groupOrder ) {
  12676. return a.groupOrder - b.groupOrder;
  12677. } else if ( a.renderOrder !== b.renderOrder ) {
  12678. return a.renderOrder - b.renderOrder;
  12679. } else if ( a.z !== b.z ) {
  12680. return b.z - a.z;
  12681. } else {
  12682. return a.id - b.id;
  12683. }
  12684. }
  12685. function WebGLRenderList( properties ) {
  12686. const renderItems = [];
  12687. let renderItemsIndex = 0;
  12688. const opaque = [];
  12689. const transmissive = [];
  12690. const transparent = [];
  12691. const defaultProgram = { id: - 1 };
  12692. function init() {
  12693. renderItemsIndex = 0;
  12694. opaque.length = 0;
  12695. transmissive.length = 0;
  12696. transparent.length = 0;
  12697. }
  12698. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  12699. let renderItem = renderItems[ renderItemsIndex ];
  12700. const materialProperties = properties.get( material );
  12701. if ( renderItem === undefined ) {
  12702. renderItem = {
  12703. id: object.id,
  12704. object: object,
  12705. geometry: geometry,
  12706. material: material,
  12707. program: materialProperties.program || defaultProgram,
  12708. groupOrder: groupOrder,
  12709. renderOrder: object.renderOrder,
  12710. z: z,
  12711. group: group
  12712. };
  12713. renderItems[ renderItemsIndex ] = renderItem;
  12714. } else {
  12715. renderItem.id = object.id;
  12716. renderItem.object = object;
  12717. renderItem.geometry = geometry;
  12718. renderItem.material = material;
  12719. renderItem.program = materialProperties.program || defaultProgram;
  12720. renderItem.groupOrder = groupOrder;
  12721. renderItem.renderOrder = object.renderOrder;
  12722. renderItem.z = z;
  12723. renderItem.group = group;
  12724. }
  12725. renderItemsIndex ++;
  12726. return renderItem;
  12727. }
  12728. function push( object, geometry, material, groupOrder, z, group ) {
  12729. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12730. if ( material.transmission > 0.0 ) {
  12731. transmissive.push( renderItem );
  12732. } else if ( material.transparent === true ) {
  12733. transparent.push( renderItem );
  12734. } else {
  12735. opaque.push( renderItem );
  12736. }
  12737. }
  12738. function unshift( object, geometry, material, groupOrder, z, group ) {
  12739. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12740. if ( material.transmission > 0.0 ) {
  12741. transmissive.unshift( renderItem );
  12742. } else if ( material.transparent === true ) {
  12743. transparent.unshift( renderItem );
  12744. } else {
  12745. opaque.unshift( renderItem );
  12746. }
  12747. }
  12748. function sort( customOpaqueSort, customTransparentSort ) {
  12749. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  12750. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  12751. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  12752. }
  12753. function finish() {
  12754. // Clear references from inactive renderItems in the list
  12755. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  12756. const renderItem = renderItems[ i ];
  12757. if ( renderItem.id === null ) break;
  12758. renderItem.id = null;
  12759. renderItem.object = null;
  12760. renderItem.geometry = null;
  12761. renderItem.material = null;
  12762. renderItem.program = null;
  12763. renderItem.group = null;
  12764. }
  12765. }
  12766. return {
  12767. opaque: opaque,
  12768. transmissive: transmissive,
  12769. transparent: transparent,
  12770. init: init,
  12771. push: push,
  12772. unshift: unshift,
  12773. finish: finish,
  12774. sort: sort
  12775. };
  12776. }
  12777. function WebGLRenderLists( properties ) {
  12778. let lists = new WeakMap();
  12779. function get( scene, renderCallDepth ) {
  12780. let list;
  12781. if ( lists.has( scene ) === false ) {
  12782. list = new WebGLRenderList( properties );
  12783. lists.set( scene, [ list ] );
  12784. } else {
  12785. if ( renderCallDepth >= lists.get( scene ).length ) {
  12786. list = new WebGLRenderList( properties );
  12787. lists.get( scene ).push( list );
  12788. } else {
  12789. list = lists.get( scene )[ renderCallDepth ];
  12790. }
  12791. }
  12792. return list;
  12793. }
  12794. function dispose() {
  12795. lists = new WeakMap();
  12796. }
  12797. return {
  12798. get: get,
  12799. dispose: dispose
  12800. };
  12801. }
  12802. function UniformsCache() {
  12803. const lights = {};
  12804. return {
  12805. get: function ( light ) {
  12806. if ( lights[ light.id ] !== undefined ) {
  12807. return lights[ light.id ];
  12808. }
  12809. let uniforms;
  12810. switch ( light.type ) {
  12811. case 'DirectionalLight':
  12812. uniforms = {
  12813. direction: new Vector3(),
  12814. color: new Color()
  12815. };
  12816. break;
  12817. case 'SpotLight':
  12818. uniforms = {
  12819. position: new Vector3(),
  12820. direction: new Vector3(),
  12821. color: new Color(),
  12822. distance: 0,
  12823. coneCos: 0,
  12824. penumbraCos: 0,
  12825. decay: 0
  12826. };
  12827. break;
  12828. case 'PointLight':
  12829. uniforms = {
  12830. position: new Vector3(),
  12831. color: new Color(),
  12832. distance: 0,
  12833. decay: 0
  12834. };
  12835. break;
  12836. case 'HemisphereLight':
  12837. uniforms = {
  12838. direction: new Vector3(),
  12839. skyColor: new Color(),
  12840. groundColor: new Color()
  12841. };
  12842. break;
  12843. case 'RectAreaLight':
  12844. uniforms = {
  12845. color: new Color(),
  12846. position: new Vector3(),
  12847. halfWidth: new Vector3(),
  12848. halfHeight: new Vector3()
  12849. };
  12850. break;
  12851. }
  12852. lights[ light.id ] = uniforms;
  12853. return uniforms;
  12854. }
  12855. };
  12856. }
  12857. function ShadowUniformsCache() {
  12858. const lights = {};
  12859. return {
  12860. get: function ( light ) {
  12861. if ( lights[ light.id ] !== undefined ) {
  12862. return lights[ light.id ];
  12863. }
  12864. let uniforms;
  12865. switch ( light.type ) {
  12866. case 'DirectionalLight':
  12867. uniforms = {
  12868. shadowBias: 0,
  12869. shadowNormalBias: 0,
  12870. shadowRadius: 1,
  12871. shadowMapSize: new Vector2()
  12872. };
  12873. break;
  12874. case 'SpotLight':
  12875. uniforms = {
  12876. shadowBias: 0,
  12877. shadowNormalBias: 0,
  12878. shadowRadius: 1,
  12879. shadowMapSize: new Vector2()
  12880. };
  12881. break;
  12882. case 'PointLight':
  12883. uniforms = {
  12884. shadowBias: 0,
  12885. shadowNormalBias: 0,
  12886. shadowRadius: 1,
  12887. shadowMapSize: new Vector2(),
  12888. shadowCameraNear: 1,
  12889. shadowCameraFar: 1000
  12890. };
  12891. break;
  12892. // TODO (abelnation): set RectAreaLight shadow uniforms
  12893. }
  12894. lights[ light.id ] = uniforms;
  12895. return uniforms;
  12896. }
  12897. };
  12898. }
  12899. let nextVersion = 0;
  12900. function shadowCastingLightsFirst( lightA, lightB ) {
  12901. return ( lightB.castShadow ? 1 : 0 ) - ( lightA.castShadow ? 1 : 0 );
  12902. }
  12903. function WebGLLights( extensions, capabilities ) {
  12904. const cache = new UniformsCache();
  12905. const shadowCache = ShadowUniformsCache();
  12906. const state = {
  12907. version: 0,
  12908. hash: {
  12909. directionalLength: - 1,
  12910. pointLength: - 1,
  12911. spotLength: - 1,
  12912. rectAreaLength: - 1,
  12913. hemiLength: - 1,
  12914. numDirectionalShadows: - 1,
  12915. numPointShadows: - 1,
  12916. numSpotShadows: - 1
  12917. },
  12918. ambient: [ 0, 0, 0 ],
  12919. probe: [],
  12920. directional: [],
  12921. directionalShadow: [],
  12922. directionalShadowMap: [],
  12923. directionalShadowMatrix: [],
  12924. spot: [],
  12925. spotShadow: [],
  12926. spotShadowMap: [],
  12927. spotShadowMatrix: [],
  12928. rectArea: [],
  12929. rectAreaLTC1: null,
  12930. rectAreaLTC2: null,
  12931. point: [],
  12932. pointShadow: [],
  12933. pointShadowMap: [],
  12934. pointShadowMatrix: [],
  12935. hemi: []
  12936. };
  12937. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  12938. const vector3 = new Vector3();
  12939. const matrix4 = new Matrix4();
  12940. const matrix42 = new Matrix4();
  12941. function setup( lights, physicallyCorrectLights ) {
  12942. let r = 0, g = 0, b = 0;
  12943. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  12944. let directionalLength = 0;
  12945. let pointLength = 0;
  12946. let spotLength = 0;
  12947. let rectAreaLength = 0;
  12948. let hemiLength = 0;
  12949. let numDirectionalShadows = 0;
  12950. let numPointShadows = 0;
  12951. let numSpotShadows = 0;
  12952. lights.sort( shadowCastingLightsFirst );
  12953. // artist-friendly light intensity scaling factor
  12954. const scaleFactor = ( physicallyCorrectLights !== true ) ? Math.PI : 1;
  12955. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12956. const light = lights[ i ];
  12957. const color = light.color;
  12958. const intensity = light.intensity;
  12959. const distance = light.distance;
  12960. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  12961. if ( light.isAmbientLight ) {
  12962. r += color.r * intensity * scaleFactor;
  12963. g += color.g * intensity * scaleFactor;
  12964. b += color.b * intensity * scaleFactor;
  12965. } else if ( light.isLightProbe ) {
  12966. for ( let j = 0; j < 9; j ++ ) {
  12967. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  12968. }
  12969. } else if ( light.isDirectionalLight ) {
  12970. const uniforms = cache.get( light );
  12971. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12972. if ( light.castShadow ) {
  12973. const shadow = light.shadow;
  12974. const shadowUniforms = shadowCache.get( light );
  12975. shadowUniforms.shadowBias = shadow.bias;
  12976. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12977. shadowUniforms.shadowRadius = shadow.radius;
  12978. shadowUniforms.shadowMapSize = shadow.mapSize;
  12979. state.directionalShadow[ directionalLength ] = shadowUniforms;
  12980. state.directionalShadowMap[ directionalLength ] = shadowMap;
  12981. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  12982. numDirectionalShadows ++;
  12983. }
  12984. state.directional[ directionalLength ] = uniforms;
  12985. directionalLength ++;
  12986. } else if ( light.isSpotLight ) {
  12987. const uniforms = cache.get( light );
  12988. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12989. uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor );
  12990. uniforms.distance = distance;
  12991. uniforms.coneCos = Math.cos( light.angle );
  12992. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  12993. uniforms.decay = light.decay;
  12994. if ( light.castShadow ) {
  12995. const shadow = light.shadow;
  12996. const shadowUniforms = shadowCache.get( light );
  12997. shadowUniforms.shadowBias = shadow.bias;
  12998. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12999. shadowUniforms.shadowRadius = shadow.radius;
  13000. shadowUniforms.shadowMapSize = shadow.mapSize;
  13001. state.spotShadow[ spotLength ] = shadowUniforms;
  13002. state.spotShadowMap[ spotLength ] = shadowMap;
  13003. state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  13004. numSpotShadows ++;
  13005. }
  13006. state.spot[ spotLength ] = uniforms;
  13007. spotLength ++;
  13008. } else if ( light.isRectAreaLight ) {
  13009. const uniforms = cache.get( light );
  13010. // (a) intensity is the total visible light emitted
  13011. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  13012. // (b) intensity is the brightness of the light
  13013. uniforms.color.copy( color ).multiplyScalar( intensity );
  13014. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  13015. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  13016. state.rectArea[ rectAreaLength ] = uniforms;
  13017. rectAreaLength ++;
  13018. } else if ( light.isPointLight ) {
  13019. const uniforms = cache.get( light );
  13020. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  13021. uniforms.distance = light.distance;
  13022. uniforms.decay = light.decay;
  13023. if ( light.castShadow ) {
  13024. const shadow = light.shadow;
  13025. const shadowUniforms = shadowCache.get( light );
  13026. shadowUniforms.shadowBias = shadow.bias;
  13027. shadowUniforms.shadowNormalBias = shadow.normalBias;
  13028. shadowUniforms.shadowRadius = shadow.radius;
  13029. shadowUniforms.shadowMapSize = shadow.mapSize;
  13030. shadowUniforms.shadowCameraNear = shadow.camera.near;
  13031. shadowUniforms.shadowCameraFar = shadow.camera.far;
  13032. state.pointShadow[ pointLength ] = shadowUniforms;
  13033. state.pointShadowMap[ pointLength ] = shadowMap;
  13034. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  13035. numPointShadows ++;
  13036. }
  13037. state.point[ pointLength ] = uniforms;
  13038. pointLength ++;
  13039. } else if ( light.isHemisphereLight ) {
  13040. const uniforms = cache.get( light );
  13041. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor );
  13042. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor );
  13043. state.hemi[ hemiLength ] = uniforms;
  13044. hemiLength ++;
  13045. }
  13046. }
  13047. if ( rectAreaLength > 0 ) {
  13048. if ( capabilities.isWebGL2 ) {
  13049. // WebGL 2
  13050. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  13051. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  13052. } else {
  13053. // WebGL 1
  13054. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  13055. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  13056. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  13057. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  13058. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  13059. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  13060. } else {
  13061. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  13062. }
  13063. }
  13064. }
  13065. state.ambient[ 0 ] = r;
  13066. state.ambient[ 1 ] = g;
  13067. state.ambient[ 2 ] = b;
  13068. const hash = state.hash;
  13069. if ( hash.directionalLength !== directionalLength ||
  13070. hash.pointLength !== pointLength ||
  13071. hash.spotLength !== spotLength ||
  13072. hash.rectAreaLength !== rectAreaLength ||
  13073. hash.hemiLength !== hemiLength ||
  13074. hash.numDirectionalShadows !== numDirectionalShadows ||
  13075. hash.numPointShadows !== numPointShadows ||
  13076. hash.numSpotShadows !== numSpotShadows ) {
  13077. state.directional.length = directionalLength;
  13078. state.spot.length = spotLength;
  13079. state.rectArea.length = rectAreaLength;
  13080. state.point.length = pointLength;
  13081. state.hemi.length = hemiLength;
  13082. state.directionalShadow.length = numDirectionalShadows;
  13083. state.directionalShadowMap.length = numDirectionalShadows;
  13084. state.pointShadow.length = numPointShadows;
  13085. state.pointShadowMap.length = numPointShadows;
  13086. state.spotShadow.length = numSpotShadows;
  13087. state.spotShadowMap.length = numSpotShadows;
  13088. state.directionalShadowMatrix.length = numDirectionalShadows;
  13089. state.pointShadowMatrix.length = numPointShadows;
  13090. state.spotShadowMatrix.length = numSpotShadows;
  13091. hash.directionalLength = directionalLength;
  13092. hash.pointLength = pointLength;
  13093. hash.spotLength = spotLength;
  13094. hash.rectAreaLength = rectAreaLength;
  13095. hash.hemiLength = hemiLength;
  13096. hash.numDirectionalShadows = numDirectionalShadows;
  13097. hash.numPointShadows = numPointShadows;
  13098. hash.numSpotShadows = numSpotShadows;
  13099. state.version = nextVersion ++;
  13100. }
  13101. }
  13102. function setupView( lights, camera ) {
  13103. let directionalLength = 0;
  13104. let pointLength = 0;
  13105. let spotLength = 0;
  13106. let rectAreaLength = 0;
  13107. let hemiLength = 0;
  13108. const viewMatrix = camera.matrixWorldInverse;
  13109. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  13110. const light = lights[ i ];
  13111. if ( light.isDirectionalLight ) {
  13112. const uniforms = state.directional[ directionalLength ];
  13113. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13114. vector3.setFromMatrixPosition( light.target.matrixWorld );
  13115. uniforms.direction.sub( vector3 );
  13116. uniforms.direction.transformDirection( viewMatrix );
  13117. directionalLength ++;
  13118. } else if ( light.isSpotLight ) {
  13119. const uniforms = state.spot[ spotLength ];
  13120. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13121. uniforms.position.applyMatrix4( viewMatrix );
  13122. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13123. vector3.setFromMatrixPosition( light.target.matrixWorld );
  13124. uniforms.direction.sub( vector3 );
  13125. uniforms.direction.transformDirection( viewMatrix );
  13126. spotLength ++;
  13127. } else if ( light.isRectAreaLight ) {
  13128. const uniforms = state.rectArea[ rectAreaLength ];
  13129. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13130. uniforms.position.applyMatrix4( viewMatrix );
  13131. // extract local rotation of light to derive width/height half vectors
  13132. matrix42.identity();
  13133. matrix4.copy( light.matrixWorld );
  13134. matrix4.premultiply( viewMatrix );
  13135. matrix42.extractRotation( matrix4 );
  13136. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  13137. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  13138. uniforms.halfWidth.applyMatrix4( matrix42 );
  13139. uniforms.halfHeight.applyMatrix4( matrix42 );
  13140. rectAreaLength ++;
  13141. } else if ( light.isPointLight ) {
  13142. const uniforms = state.point[ pointLength ];
  13143. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13144. uniforms.position.applyMatrix4( viewMatrix );
  13145. pointLength ++;
  13146. } else if ( light.isHemisphereLight ) {
  13147. const uniforms = state.hemi[ hemiLength ];
  13148. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13149. uniforms.direction.transformDirection( viewMatrix );
  13150. uniforms.direction.normalize();
  13151. hemiLength ++;
  13152. }
  13153. }
  13154. }
  13155. return {
  13156. setup: setup,
  13157. setupView: setupView,
  13158. state: state
  13159. };
  13160. }
  13161. function WebGLRenderState( extensions, capabilities ) {
  13162. const lights = new WebGLLights( extensions, capabilities );
  13163. const lightsArray = [];
  13164. const shadowsArray = [];
  13165. function init() {
  13166. lightsArray.length = 0;
  13167. shadowsArray.length = 0;
  13168. }
  13169. function pushLight( light ) {
  13170. lightsArray.push( light );
  13171. }
  13172. function pushShadow( shadowLight ) {
  13173. shadowsArray.push( shadowLight );
  13174. }
  13175. function setupLights( physicallyCorrectLights ) {
  13176. lights.setup( lightsArray, physicallyCorrectLights );
  13177. }
  13178. function setupLightsView( camera ) {
  13179. lights.setupView( lightsArray, camera );
  13180. }
  13181. const state = {
  13182. lightsArray: lightsArray,
  13183. shadowsArray: shadowsArray,
  13184. lights: lights
  13185. };
  13186. return {
  13187. init: init,
  13188. state: state,
  13189. setupLights: setupLights,
  13190. setupLightsView: setupLightsView,
  13191. pushLight: pushLight,
  13192. pushShadow: pushShadow
  13193. };
  13194. }
  13195. function WebGLRenderStates( extensions, capabilities ) {
  13196. let renderStates = new WeakMap();
  13197. function get( scene, renderCallDepth = 0 ) {
  13198. let renderState;
  13199. if ( renderStates.has( scene ) === false ) {
  13200. renderState = new WebGLRenderState( extensions, capabilities );
  13201. renderStates.set( scene, [ renderState ] );
  13202. } else {
  13203. if ( renderCallDepth >= renderStates.get( scene ).length ) {
  13204. renderState = new WebGLRenderState( extensions, capabilities );
  13205. renderStates.get( scene ).push( renderState );
  13206. } else {
  13207. renderState = renderStates.get( scene )[ renderCallDepth ];
  13208. }
  13209. }
  13210. return renderState;
  13211. }
  13212. function dispose() {
  13213. renderStates = new WeakMap();
  13214. }
  13215. return {
  13216. get: get,
  13217. dispose: dispose
  13218. };
  13219. }
  13220. /**
  13221. * parameters = {
  13222. *
  13223. * opacity: <float>,
  13224. *
  13225. * map: new THREE.Texture( <Image> ),
  13226. *
  13227. * alphaMap: new THREE.Texture( <Image> ),
  13228. *
  13229. * displacementMap: new THREE.Texture( <Image> ),
  13230. * displacementScale: <float>,
  13231. * displacementBias: <float>,
  13232. *
  13233. * wireframe: <boolean>,
  13234. * wireframeLinewidth: <float>
  13235. * }
  13236. */
  13237. class MeshDepthMaterial extends Material {
  13238. constructor( parameters ) {
  13239. super();
  13240. this.type = 'MeshDepthMaterial';
  13241. this.depthPacking = BasicDepthPacking;
  13242. this.map = null;
  13243. this.alphaMap = null;
  13244. this.displacementMap = null;
  13245. this.displacementScale = 1;
  13246. this.displacementBias = 0;
  13247. this.wireframe = false;
  13248. this.wireframeLinewidth = 1;
  13249. this.fog = false;
  13250. this.setValues( parameters );
  13251. }
  13252. copy( source ) {
  13253. super.copy( source );
  13254. this.depthPacking = source.depthPacking;
  13255. this.map = source.map;
  13256. this.alphaMap = source.alphaMap;
  13257. this.displacementMap = source.displacementMap;
  13258. this.displacementScale = source.displacementScale;
  13259. this.displacementBias = source.displacementBias;
  13260. this.wireframe = source.wireframe;
  13261. this.wireframeLinewidth = source.wireframeLinewidth;
  13262. return this;
  13263. }
  13264. }
  13265. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  13266. /**
  13267. * parameters = {
  13268. *
  13269. * referencePosition: <float>,
  13270. * nearDistance: <float>,
  13271. * farDistance: <float>,
  13272. *
  13273. * map: new THREE.Texture( <Image> ),
  13274. *
  13275. * alphaMap: new THREE.Texture( <Image> ),
  13276. *
  13277. * displacementMap: new THREE.Texture( <Image> ),
  13278. * displacementScale: <float>,
  13279. * displacementBias: <float>
  13280. *
  13281. * }
  13282. */
  13283. class MeshDistanceMaterial extends Material {
  13284. constructor( parameters ) {
  13285. super();
  13286. this.type = 'MeshDistanceMaterial';
  13287. this.referencePosition = new Vector3();
  13288. this.nearDistance = 1;
  13289. this.farDistance = 1000;
  13290. this.map = null;
  13291. this.alphaMap = null;
  13292. this.displacementMap = null;
  13293. this.displacementScale = 1;
  13294. this.displacementBias = 0;
  13295. this.fog = false;
  13296. this.setValues( parameters );
  13297. }
  13298. copy( source ) {
  13299. super.copy( source );
  13300. this.referencePosition.copy( source.referencePosition );
  13301. this.nearDistance = source.nearDistance;
  13302. this.farDistance = source.farDistance;
  13303. this.map = source.map;
  13304. this.alphaMap = source.alphaMap;
  13305. this.displacementMap = source.displacementMap;
  13306. this.displacementScale = source.displacementScale;
  13307. this.displacementBias = source.displacementBias;
  13308. return this;
  13309. }
  13310. }
  13311. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  13312. var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\nuniform float samples;\n#include <packing>\nvoid main() {\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}";
  13313. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  13314. function WebGLShadowMap( _renderer, _objects, _capabilities ) {
  13315. let _frustum = new Frustum();
  13316. const _shadowMapSize = new Vector2(),
  13317. _viewportSize = new Vector2(),
  13318. _viewport = new Vector4(),
  13319. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  13320. _distanceMaterial = new MeshDistanceMaterial(),
  13321. _materialCache = {},
  13322. _maxTextureSize = _capabilities.maxTextureSize;
  13323. const shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide };
  13324. const shadowMaterialVertical = new ShaderMaterial( {
  13325. uniforms: {
  13326. shadow_pass: { value: null },
  13327. resolution: { value: new Vector2() },
  13328. radius: { value: 4.0 },
  13329. samples: { value: 8.0 }
  13330. },
  13331. vertexShader: vsm_vert,
  13332. fragmentShader: vsm_frag
  13333. } );
  13334. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  13335. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  13336. const fullScreenTri = new BufferGeometry();
  13337. fullScreenTri.setAttribute(
  13338. 'position',
  13339. new BufferAttribute(
  13340. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  13341. 3
  13342. )
  13343. );
  13344. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  13345. const scope = this;
  13346. this.enabled = false;
  13347. this.autoUpdate = true;
  13348. this.needsUpdate = false;
  13349. this.type = PCFShadowMap;
  13350. this.render = function ( lights, scene, camera ) {
  13351. if ( scope.enabled === false ) return;
  13352. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  13353. if ( lights.length === 0 ) return;
  13354. const currentRenderTarget = _renderer.getRenderTarget();
  13355. const activeCubeFace = _renderer.getActiveCubeFace();
  13356. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  13357. const _state = _renderer.state;
  13358. // Set GL state for depth map.
  13359. _state.setBlending( NoBlending );
  13360. _state.buffers.color.setClear( 1, 1, 1, 1 );
  13361. _state.buffers.depth.setTest( true );
  13362. _state.setScissorTest( false );
  13363. // render depth map
  13364. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  13365. const light = lights[ i ];
  13366. const shadow = light.shadow;
  13367. if ( shadow === undefined ) {
  13368. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  13369. continue;
  13370. }
  13371. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  13372. _shadowMapSize.copy( shadow.mapSize );
  13373. const shadowFrameExtents = shadow.getFrameExtents();
  13374. _shadowMapSize.multiply( shadowFrameExtents );
  13375. _viewportSize.copy( shadow.mapSize );
  13376. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  13377. if ( _shadowMapSize.x > _maxTextureSize ) {
  13378. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  13379. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  13380. shadow.mapSize.x = _viewportSize.x;
  13381. }
  13382. if ( _shadowMapSize.y > _maxTextureSize ) {
  13383. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  13384. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  13385. shadow.mapSize.y = _viewportSize.y;
  13386. }
  13387. }
  13388. if ( shadow.map === null && ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  13389. const pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat };
  13390. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  13391. shadow.map.texture.name = light.name + '.shadowMap';
  13392. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  13393. shadow.camera.updateProjectionMatrix();
  13394. }
  13395. if ( shadow.map === null ) {
  13396. const pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  13397. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  13398. shadow.map.texture.name = light.name + '.shadowMap';
  13399. shadow.camera.updateProjectionMatrix();
  13400. }
  13401. _renderer.setRenderTarget( shadow.map );
  13402. _renderer.clear();
  13403. const viewportCount = shadow.getViewportCount();
  13404. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  13405. const viewport = shadow.getViewport( vp );
  13406. _viewport.set(
  13407. _viewportSize.x * viewport.x,
  13408. _viewportSize.y * viewport.y,
  13409. _viewportSize.x * viewport.z,
  13410. _viewportSize.y * viewport.w
  13411. );
  13412. _state.viewport( _viewport );
  13413. shadow.updateMatrices( light, vp );
  13414. _frustum = shadow.getFrustum();
  13415. renderObject( scene, camera, shadow.camera, light, this.type );
  13416. }
  13417. // do blur pass for VSM
  13418. if ( ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  13419. VSMPass( shadow, camera );
  13420. }
  13421. shadow.needsUpdate = false;
  13422. }
  13423. scope.needsUpdate = false;
  13424. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  13425. };
  13426. function VSMPass( shadow, camera ) {
  13427. const geometry = _objects.update( fullScreenMesh );
  13428. // vertical pass
  13429. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  13430. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  13431. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  13432. shadowMaterialVertical.uniforms.samples.value = shadow.blurSamples;
  13433. _renderer.setRenderTarget( shadow.mapPass );
  13434. _renderer.clear();
  13435. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  13436. // horizontal pass
  13437. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  13438. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  13439. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  13440. shadowMaterialHorizontal.uniforms.samples.value = shadow.blurSamples;
  13441. _renderer.setRenderTarget( shadow.map );
  13442. _renderer.clear();
  13443. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  13444. }
  13445. function getDepthMaterial( object, geometry, material, light, shadowCameraNear, shadowCameraFar, type ) {
  13446. let result = null;
  13447. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  13448. if ( customMaterial !== undefined ) {
  13449. result = customMaterial;
  13450. } else {
  13451. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  13452. }
  13453. if ( ( _renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0 ) ||
  13454. ( material.displacementMap && material.displacementScale !== 0 ) ||
  13455. ( material.alphaMap && material.alphaTest > 0 ) ) {
  13456. // in this case we need a unique material instance reflecting the
  13457. // appropriate state
  13458. const keyA = result.uuid, keyB = material.uuid;
  13459. let materialsForVariant = _materialCache[ keyA ];
  13460. if ( materialsForVariant === undefined ) {
  13461. materialsForVariant = {};
  13462. _materialCache[ keyA ] = materialsForVariant;
  13463. }
  13464. let cachedMaterial = materialsForVariant[ keyB ];
  13465. if ( cachedMaterial === undefined ) {
  13466. cachedMaterial = result.clone();
  13467. materialsForVariant[ keyB ] = cachedMaterial;
  13468. }
  13469. result = cachedMaterial;
  13470. }
  13471. result.visible = material.visible;
  13472. result.wireframe = material.wireframe;
  13473. if ( type === VSMShadowMap ) {
  13474. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  13475. } else {
  13476. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  13477. }
  13478. result.alphaMap = material.alphaMap;
  13479. result.alphaTest = material.alphaTest;
  13480. result.clipShadows = material.clipShadows;
  13481. result.clippingPlanes = material.clippingPlanes;
  13482. result.clipIntersection = material.clipIntersection;
  13483. result.displacementMap = material.displacementMap;
  13484. result.displacementScale = material.displacementScale;
  13485. result.displacementBias = material.displacementBias;
  13486. result.wireframeLinewidth = material.wireframeLinewidth;
  13487. result.linewidth = material.linewidth;
  13488. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  13489. result.referencePosition.setFromMatrixPosition( light.matrixWorld );
  13490. result.nearDistance = shadowCameraNear;
  13491. result.farDistance = shadowCameraFar;
  13492. }
  13493. return result;
  13494. }
  13495. function renderObject( object, camera, shadowCamera, light, type ) {
  13496. if ( object.visible === false ) return;
  13497. const visible = object.layers.test( camera.layers );
  13498. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  13499. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  13500. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  13501. const geometry = _objects.update( object );
  13502. const material = object.material;
  13503. if ( Array.isArray( material ) ) {
  13504. const groups = geometry.groups;
  13505. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  13506. const group = groups[ k ];
  13507. const groupMaterial = material[ group.materialIndex ];
  13508. if ( groupMaterial && groupMaterial.visible ) {
  13509. const depthMaterial = getDepthMaterial( object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );
  13510. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  13511. }
  13512. }
  13513. } else if ( material.visible ) {
  13514. const depthMaterial = getDepthMaterial( object, geometry, material, light, shadowCamera.near, shadowCamera.far, type );
  13515. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  13516. }
  13517. }
  13518. }
  13519. const children = object.children;
  13520. for ( let i = 0, l = children.length; i < l; i ++ ) {
  13521. renderObject( children[ i ], camera, shadowCamera, light, type );
  13522. }
  13523. }
  13524. }
  13525. function WebGLState( gl, extensions, capabilities ) {
  13526. const isWebGL2 = capabilities.isWebGL2;
  13527. function ColorBuffer() {
  13528. let locked = false;
  13529. const color = new Vector4();
  13530. let currentColorMask = null;
  13531. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  13532. return {
  13533. setMask: function ( colorMask ) {
  13534. if ( currentColorMask !== colorMask && ! locked ) {
  13535. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  13536. currentColorMask = colorMask;
  13537. }
  13538. },
  13539. setLocked: function ( lock ) {
  13540. locked = lock;
  13541. },
  13542. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  13543. if ( premultipliedAlpha === true ) {
  13544. r *= a; g *= a; b *= a;
  13545. }
  13546. color.set( r, g, b, a );
  13547. if ( currentColorClear.equals( color ) === false ) {
  13548. gl.clearColor( r, g, b, a );
  13549. currentColorClear.copy( color );
  13550. }
  13551. },
  13552. reset: function () {
  13553. locked = false;
  13554. currentColorMask = null;
  13555. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  13556. }
  13557. };
  13558. }
  13559. function DepthBuffer() {
  13560. let locked = false;
  13561. let currentDepthMask = null;
  13562. let currentDepthFunc = null;
  13563. let currentDepthClear = null;
  13564. return {
  13565. setTest: function ( depthTest ) {
  13566. if ( depthTest ) {
  13567. enable( 2929 );
  13568. } else {
  13569. disable( 2929 );
  13570. }
  13571. },
  13572. setMask: function ( depthMask ) {
  13573. if ( currentDepthMask !== depthMask && ! locked ) {
  13574. gl.depthMask( depthMask );
  13575. currentDepthMask = depthMask;
  13576. }
  13577. },
  13578. setFunc: function ( depthFunc ) {
  13579. if ( currentDepthFunc !== depthFunc ) {
  13580. if ( depthFunc ) {
  13581. switch ( depthFunc ) {
  13582. case NeverDepth:
  13583. gl.depthFunc( 512 );
  13584. break;
  13585. case AlwaysDepth:
  13586. gl.depthFunc( 519 );
  13587. break;
  13588. case LessDepth:
  13589. gl.depthFunc( 513 );
  13590. break;
  13591. case LessEqualDepth:
  13592. gl.depthFunc( 515 );
  13593. break;
  13594. case EqualDepth:
  13595. gl.depthFunc( 514 );
  13596. break;
  13597. case GreaterEqualDepth:
  13598. gl.depthFunc( 518 );
  13599. break;
  13600. case GreaterDepth:
  13601. gl.depthFunc( 516 );
  13602. break;
  13603. case NotEqualDepth:
  13604. gl.depthFunc( 517 );
  13605. break;
  13606. default:
  13607. gl.depthFunc( 515 );
  13608. }
  13609. } else {
  13610. gl.depthFunc( 515 );
  13611. }
  13612. currentDepthFunc = depthFunc;
  13613. }
  13614. },
  13615. setLocked: function ( lock ) {
  13616. locked = lock;
  13617. },
  13618. setClear: function ( depth ) {
  13619. if ( currentDepthClear !== depth ) {
  13620. gl.clearDepth( depth );
  13621. currentDepthClear = depth;
  13622. }
  13623. },
  13624. reset: function () {
  13625. locked = false;
  13626. currentDepthMask = null;
  13627. currentDepthFunc = null;
  13628. currentDepthClear = null;
  13629. }
  13630. };
  13631. }
  13632. function StencilBuffer() {
  13633. let locked = false;
  13634. let currentStencilMask = null;
  13635. let currentStencilFunc = null;
  13636. let currentStencilRef = null;
  13637. let currentStencilFuncMask = null;
  13638. let currentStencilFail = null;
  13639. let currentStencilZFail = null;
  13640. let currentStencilZPass = null;
  13641. let currentStencilClear = null;
  13642. return {
  13643. setTest: function ( stencilTest ) {
  13644. if ( ! locked ) {
  13645. if ( stencilTest ) {
  13646. enable( 2960 );
  13647. } else {
  13648. disable( 2960 );
  13649. }
  13650. }
  13651. },
  13652. setMask: function ( stencilMask ) {
  13653. if ( currentStencilMask !== stencilMask && ! locked ) {
  13654. gl.stencilMask( stencilMask );
  13655. currentStencilMask = stencilMask;
  13656. }
  13657. },
  13658. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  13659. if ( currentStencilFunc !== stencilFunc ||
  13660. currentStencilRef !== stencilRef ||
  13661. currentStencilFuncMask !== stencilMask ) {
  13662. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  13663. currentStencilFunc = stencilFunc;
  13664. currentStencilRef = stencilRef;
  13665. currentStencilFuncMask = stencilMask;
  13666. }
  13667. },
  13668. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  13669. if ( currentStencilFail !== stencilFail ||
  13670. currentStencilZFail !== stencilZFail ||
  13671. currentStencilZPass !== stencilZPass ) {
  13672. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  13673. currentStencilFail = stencilFail;
  13674. currentStencilZFail = stencilZFail;
  13675. currentStencilZPass = stencilZPass;
  13676. }
  13677. },
  13678. setLocked: function ( lock ) {
  13679. locked = lock;
  13680. },
  13681. setClear: function ( stencil ) {
  13682. if ( currentStencilClear !== stencil ) {
  13683. gl.clearStencil( stencil );
  13684. currentStencilClear = stencil;
  13685. }
  13686. },
  13687. reset: function () {
  13688. locked = false;
  13689. currentStencilMask = null;
  13690. currentStencilFunc = null;
  13691. currentStencilRef = null;
  13692. currentStencilFuncMask = null;
  13693. currentStencilFail = null;
  13694. currentStencilZFail = null;
  13695. currentStencilZPass = null;
  13696. currentStencilClear = null;
  13697. }
  13698. };
  13699. }
  13700. //
  13701. const colorBuffer = new ColorBuffer();
  13702. const depthBuffer = new DepthBuffer();
  13703. const stencilBuffer = new StencilBuffer();
  13704. let enabledCapabilities = {};
  13705. let xrFramebuffer = null;
  13706. let currentBoundFramebuffers = {};
  13707. let currentProgram = null;
  13708. let currentBlendingEnabled = false;
  13709. let currentBlending = null;
  13710. let currentBlendEquation = null;
  13711. let currentBlendSrc = null;
  13712. let currentBlendDst = null;
  13713. let currentBlendEquationAlpha = null;
  13714. let currentBlendSrcAlpha = null;
  13715. let currentBlendDstAlpha = null;
  13716. let currentPremultipledAlpha = false;
  13717. let currentFlipSided = null;
  13718. let currentCullFace = null;
  13719. let currentLineWidth = null;
  13720. let currentPolygonOffsetFactor = null;
  13721. let currentPolygonOffsetUnits = null;
  13722. const maxTextures = gl.getParameter( 35661 );
  13723. let lineWidthAvailable = false;
  13724. let version = 0;
  13725. const glVersion = gl.getParameter( 7938 );
  13726. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  13727. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  13728. lineWidthAvailable = ( version >= 1.0 );
  13729. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  13730. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  13731. lineWidthAvailable = ( version >= 2.0 );
  13732. }
  13733. let currentTextureSlot = null;
  13734. let currentBoundTextures = {};
  13735. const scissorParam = gl.getParameter( 3088 );
  13736. const viewportParam = gl.getParameter( 2978 );
  13737. const currentScissor = new Vector4().fromArray( scissorParam );
  13738. const currentViewport = new Vector4().fromArray( viewportParam );
  13739. function createTexture( type, target, count ) {
  13740. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  13741. const texture = gl.createTexture();
  13742. gl.bindTexture( type, texture );
  13743. gl.texParameteri( type, 10241, 9728 );
  13744. gl.texParameteri( type, 10240, 9728 );
  13745. for ( let i = 0; i < count; i ++ ) {
  13746. gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );
  13747. }
  13748. return texture;
  13749. }
  13750. const emptyTextures = {};
  13751. emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
  13752. emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );
  13753. // init
  13754. colorBuffer.setClear( 0, 0, 0, 1 );
  13755. depthBuffer.setClear( 1 );
  13756. stencilBuffer.setClear( 0 );
  13757. enable( 2929 );
  13758. depthBuffer.setFunc( LessEqualDepth );
  13759. setFlipSided( false );
  13760. setCullFace( CullFaceBack );
  13761. enable( 2884 );
  13762. setBlending( NoBlending );
  13763. //
  13764. function enable( id ) {
  13765. if ( enabledCapabilities[ id ] !== true ) {
  13766. gl.enable( id );
  13767. enabledCapabilities[ id ] = true;
  13768. }
  13769. }
  13770. function disable( id ) {
  13771. if ( enabledCapabilities[ id ] !== false ) {
  13772. gl.disable( id );
  13773. enabledCapabilities[ id ] = false;
  13774. }
  13775. }
  13776. function bindXRFramebuffer( framebuffer ) {
  13777. if ( framebuffer !== xrFramebuffer ) {
  13778. gl.bindFramebuffer( 36160, framebuffer );
  13779. xrFramebuffer = framebuffer;
  13780. }
  13781. }
  13782. function bindFramebuffer( target, framebuffer ) {
  13783. if ( framebuffer === null && xrFramebuffer !== null ) framebuffer = xrFramebuffer; // use active XR framebuffer if available
  13784. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  13785. gl.bindFramebuffer( target, framebuffer );
  13786. currentBoundFramebuffers[ target ] = framebuffer;
  13787. if ( isWebGL2 ) {
  13788. // 36009 is equivalent to 36160
  13789. if ( target === 36009 ) {
  13790. currentBoundFramebuffers[ 36160 ] = framebuffer;
  13791. }
  13792. if ( target === 36160 ) {
  13793. currentBoundFramebuffers[ 36009 ] = framebuffer;
  13794. }
  13795. }
  13796. return true;
  13797. }
  13798. return false;
  13799. }
  13800. function useProgram( program ) {
  13801. if ( currentProgram !== program ) {
  13802. gl.useProgram( program );
  13803. currentProgram = program;
  13804. return true;
  13805. }
  13806. return false;
  13807. }
  13808. const equationToGL = {
  13809. [ AddEquation ]: 32774,
  13810. [ SubtractEquation ]: 32778,
  13811. [ ReverseSubtractEquation ]: 32779
  13812. };
  13813. if ( isWebGL2 ) {
  13814. equationToGL[ MinEquation ] = 32775;
  13815. equationToGL[ MaxEquation ] = 32776;
  13816. } else {
  13817. const extension = extensions.get( 'EXT_blend_minmax' );
  13818. if ( extension !== null ) {
  13819. equationToGL[ MinEquation ] = extension.MIN_EXT;
  13820. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  13821. }
  13822. }
  13823. const factorToGL = {
  13824. [ ZeroFactor ]: 0,
  13825. [ OneFactor ]: 1,
  13826. [ SrcColorFactor ]: 768,
  13827. [ SrcAlphaFactor ]: 770,
  13828. [ SrcAlphaSaturateFactor ]: 776,
  13829. [ DstColorFactor ]: 774,
  13830. [ DstAlphaFactor ]: 772,
  13831. [ OneMinusSrcColorFactor ]: 769,
  13832. [ OneMinusSrcAlphaFactor ]: 771,
  13833. [ OneMinusDstColorFactor ]: 775,
  13834. [ OneMinusDstAlphaFactor ]: 773
  13835. };
  13836. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  13837. if ( blending === NoBlending ) {
  13838. if ( currentBlendingEnabled === true ) {
  13839. disable( 3042 );
  13840. currentBlendingEnabled = false;
  13841. }
  13842. return;
  13843. }
  13844. if ( currentBlendingEnabled === false ) {
  13845. enable( 3042 );
  13846. currentBlendingEnabled = true;
  13847. }
  13848. if ( blending !== CustomBlending ) {
  13849. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  13850. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  13851. gl.blendEquation( 32774 );
  13852. currentBlendEquation = AddEquation;
  13853. currentBlendEquationAlpha = AddEquation;
  13854. }
  13855. if ( premultipliedAlpha ) {
  13856. switch ( blending ) {
  13857. case NormalBlending:
  13858. gl.blendFuncSeparate( 1, 771, 1, 771 );
  13859. break;
  13860. case AdditiveBlending:
  13861. gl.blendFunc( 1, 1 );
  13862. break;
  13863. case SubtractiveBlending:
  13864. gl.blendFuncSeparate( 0, 0, 769, 771 );
  13865. break;
  13866. case MultiplyBlending:
  13867. gl.blendFuncSeparate( 0, 768, 0, 770 );
  13868. break;
  13869. default:
  13870. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13871. break;
  13872. }
  13873. } else {
  13874. switch ( blending ) {
  13875. case NormalBlending:
  13876. gl.blendFuncSeparate( 770, 771, 1, 771 );
  13877. break;
  13878. case AdditiveBlending:
  13879. gl.blendFunc( 770, 1 );
  13880. break;
  13881. case SubtractiveBlending:
  13882. gl.blendFunc( 0, 769 );
  13883. break;
  13884. case MultiplyBlending:
  13885. gl.blendFunc( 0, 768 );
  13886. break;
  13887. default:
  13888. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13889. break;
  13890. }
  13891. }
  13892. currentBlendSrc = null;
  13893. currentBlendDst = null;
  13894. currentBlendSrcAlpha = null;
  13895. currentBlendDstAlpha = null;
  13896. currentBlending = blending;
  13897. currentPremultipledAlpha = premultipliedAlpha;
  13898. }
  13899. return;
  13900. }
  13901. // custom blending
  13902. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13903. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13904. blendDstAlpha = blendDstAlpha || blendDst;
  13905. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  13906. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  13907. currentBlendEquation = blendEquation;
  13908. currentBlendEquationAlpha = blendEquationAlpha;
  13909. }
  13910. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  13911. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  13912. currentBlendSrc = blendSrc;
  13913. currentBlendDst = blendDst;
  13914. currentBlendSrcAlpha = blendSrcAlpha;
  13915. currentBlendDstAlpha = blendDstAlpha;
  13916. }
  13917. currentBlending = blending;
  13918. currentPremultipledAlpha = null;
  13919. }
  13920. function setMaterial( material, frontFaceCW ) {
  13921. material.side === DoubleSide
  13922. ? disable( 2884 )
  13923. : enable( 2884 );
  13924. let flipSided = ( material.side === BackSide );
  13925. if ( frontFaceCW ) flipSided = ! flipSided;
  13926. setFlipSided( flipSided );
  13927. ( material.blending === NormalBlending && material.transparent === false )
  13928. ? setBlending( NoBlending )
  13929. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  13930. depthBuffer.setFunc( material.depthFunc );
  13931. depthBuffer.setTest( material.depthTest );
  13932. depthBuffer.setMask( material.depthWrite );
  13933. colorBuffer.setMask( material.colorWrite );
  13934. const stencilWrite = material.stencilWrite;
  13935. stencilBuffer.setTest( stencilWrite );
  13936. if ( stencilWrite ) {
  13937. stencilBuffer.setMask( material.stencilWriteMask );
  13938. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  13939. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  13940. }
  13941. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13942. material.alphaToCoverage === true
  13943. ? enable( 32926 )
  13944. : disable( 32926 );
  13945. }
  13946. //
  13947. function setFlipSided( flipSided ) {
  13948. if ( currentFlipSided !== flipSided ) {
  13949. if ( flipSided ) {
  13950. gl.frontFace( 2304 );
  13951. } else {
  13952. gl.frontFace( 2305 );
  13953. }
  13954. currentFlipSided = flipSided;
  13955. }
  13956. }
  13957. function setCullFace( cullFace ) {
  13958. if ( cullFace !== CullFaceNone ) {
  13959. enable( 2884 );
  13960. if ( cullFace !== currentCullFace ) {
  13961. if ( cullFace === CullFaceBack ) {
  13962. gl.cullFace( 1029 );
  13963. } else if ( cullFace === CullFaceFront ) {
  13964. gl.cullFace( 1028 );
  13965. } else {
  13966. gl.cullFace( 1032 );
  13967. }
  13968. }
  13969. } else {
  13970. disable( 2884 );
  13971. }
  13972. currentCullFace = cullFace;
  13973. }
  13974. function setLineWidth( width ) {
  13975. if ( width !== currentLineWidth ) {
  13976. if ( lineWidthAvailable ) gl.lineWidth( width );
  13977. currentLineWidth = width;
  13978. }
  13979. }
  13980. function setPolygonOffset( polygonOffset, factor, units ) {
  13981. if ( polygonOffset ) {
  13982. enable( 32823 );
  13983. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  13984. gl.polygonOffset( factor, units );
  13985. currentPolygonOffsetFactor = factor;
  13986. currentPolygonOffsetUnits = units;
  13987. }
  13988. } else {
  13989. disable( 32823 );
  13990. }
  13991. }
  13992. function setScissorTest( scissorTest ) {
  13993. if ( scissorTest ) {
  13994. enable( 3089 );
  13995. } else {
  13996. disable( 3089 );
  13997. }
  13998. }
  13999. // texture
  14000. function activeTexture( webglSlot ) {
  14001. if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1;
  14002. if ( currentTextureSlot !== webglSlot ) {
  14003. gl.activeTexture( webglSlot );
  14004. currentTextureSlot = webglSlot;
  14005. }
  14006. }
  14007. function bindTexture( webglType, webglTexture ) {
  14008. if ( currentTextureSlot === null ) {
  14009. activeTexture();
  14010. }
  14011. let boundTexture = currentBoundTextures[ currentTextureSlot ];
  14012. if ( boundTexture === undefined ) {
  14013. boundTexture = { type: undefined, texture: undefined };
  14014. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  14015. }
  14016. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  14017. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  14018. boundTexture.type = webglType;
  14019. boundTexture.texture = webglTexture;
  14020. }
  14021. }
  14022. function unbindTexture() {
  14023. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  14024. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  14025. gl.bindTexture( boundTexture.type, null );
  14026. boundTexture.type = undefined;
  14027. boundTexture.texture = undefined;
  14028. }
  14029. }
  14030. function compressedTexImage2D() {
  14031. try {
  14032. gl.compressedTexImage2D.apply( gl, arguments );
  14033. } catch ( error ) {
  14034. console.error( 'THREE.WebGLState:', error );
  14035. }
  14036. }
  14037. function texImage2D() {
  14038. try {
  14039. gl.texImage2D.apply( gl, arguments );
  14040. } catch ( error ) {
  14041. console.error( 'THREE.WebGLState:', error );
  14042. }
  14043. }
  14044. function texImage3D() {
  14045. try {
  14046. gl.texImage3D.apply( gl, arguments );
  14047. } catch ( error ) {
  14048. console.error( 'THREE.WebGLState:', error );
  14049. }
  14050. }
  14051. //
  14052. function scissor( scissor ) {
  14053. if ( currentScissor.equals( scissor ) === false ) {
  14054. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  14055. currentScissor.copy( scissor );
  14056. }
  14057. }
  14058. function viewport( viewport ) {
  14059. if ( currentViewport.equals( viewport ) === false ) {
  14060. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  14061. currentViewport.copy( viewport );
  14062. }
  14063. }
  14064. //
  14065. function reset() {
  14066. // reset state
  14067. gl.disable( 3042 );
  14068. gl.disable( 2884 );
  14069. gl.disable( 2929 );
  14070. gl.disable( 32823 );
  14071. gl.disable( 3089 );
  14072. gl.disable( 2960 );
  14073. gl.disable( 32926 );
  14074. gl.blendEquation( 32774 );
  14075. gl.blendFunc( 1, 0 );
  14076. gl.blendFuncSeparate( 1, 0, 1, 0 );
  14077. gl.colorMask( true, true, true, true );
  14078. gl.clearColor( 0, 0, 0, 0 );
  14079. gl.depthMask( true );
  14080. gl.depthFunc( 513 );
  14081. gl.clearDepth( 1 );
  14082. gl.stencilMask( 0xffffffff );
  14083. gl.stencilFunc( 519, 0, 0xffffffff );
  14084. gl.stencilOp( 7680, 7680, 7680 );
  14085. gl.clearStencil( 0 );
  14086. gl.cullFace( 1029 );
  14087. gl.frontFace( 2305 );
  14088. gl.polygonOffset( 0, 0 );
  14089. gl.activeTexture( 33984 );
  14090. gl.bindFramebuffer( 36160, null );
  14091. if ( isWebGL2 === true ) {
  14092. gl.bindFramebuffer( 36009, null );
  14093. gl.bindFramebuffer( 36008, null );
  14094. }
  14095. gl.useProgram( null );
  14096. gl.lineWidth( 1 );
  14097. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  14098. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  14099. // reset internals
  14100. enabledCapabilities = {};
  14101. currentTextureSlot = null;
  14102. currentBoundTextures = {};
  14103. xrFramebuffer = null;
  14104. currentBoundFramebuffers = {};
  14105. currentProgram = null;
  14106. currentBlendingEnabled = false;
  14107. currentBlending = null;
  14108. currentBlendEquation = null;
  14109. currentBlendSrc = null;
  14110. currentBlendDst = null;
  14111. currentBlendEquationAlpha = null;
  14112. currentBlendSrcAlpha = null;
  14113. currentBlendDstAlpha = null;
  14114. currentPremultipledAlpha = false;
  14115. currentFlipSided = null;
  14116. currentCullFace = null;
  14117. currentLineWidth = null;
  14118. currentPolygonOffsetFactor = null;
  14119. currentPolygonOffsetUnits = null;
  14120. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  14121. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  14122. colorBuffer.reset();
  14123. depthBuffer.reset();
  14124. stencilBuffer.reset();
  14125. }
  14126. return {
  14127. buffers: {
  14128. color: colorBuffer,
  14129. depth: depthBuffer,
  14130. stencil: stencilBuffer
  14131. },
  14132. enable: enable,
  14133. disable: disable,
  14134. bindFramebuffer: bindFramebuffer,
  14135. bindXRFramebuffer: bindXRFramebuffer,
  14136. useProgram: useProgram,
  14137. setBlending: setBlending,
  14138. setMaterial: setMaterial,
  14139. setFlipSided: setFlipSided,
  14140. setCullFace: setCullFace,
  14141. setLineWidth: setLineWidth,
  14142. setPolygonOffset: setPolygonOffset,
  14143. setScissorTest: setScissorTest,
  14144. activeTexture: activeTexture,
  14145. bindTexture: bindTexture,
  14146. unbindTexture: unbindTexture,
  14147. compressedTexImage2D: compressedTexImage2D,
  14148. texImage2D: texImage2D,
  14149. texImage3D: texImage3D,
  14150. scissor: scissor,
  14151. viewport: viewport,
  14152. reset: reset
  14153. };
  14154. }
  14155. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  14156. const isWebGL2 = capabilities.isWebGL2;
  14157. const maxTextures = capabilities.maxTextures;
  14158. const maxCubemapSize = capabilities.maxCubemapSize;
  14159. const maxTextureSize = capabilities.maxTextureSize;
  14160. const maxSamples = capabilities.maxSamples;
  14161. const _videoTextures = new WeakMap();
  14162. let _canvas;
  14163. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  14164. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  14165. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  14166. let useOffscreenCanvas = false;
  14167. try {
  14168. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  14169. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  14170. } catch ( err ) {
  14171. // Ignore any errors
  14172. }
  14173. function createCanvas( width, height ) {
  14174. // Use OffscreenCanvas when available. Specially needed in web workers
  14175. return useOffscreenCanvas ?
  14176. new OffscreenCanvas( width, height ) :
  14177. document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  14178. }
  14179. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  14180. let scale = 1;
  14181. // handle case if texture exceeds max size
  14182. if ( image.width > maxSize || image.height > maxSize ) {
  14183. scale = maxSize / Math.max( image.width, image.height );
  14184. }
  14185. // only perform resize if necessary
  14186. if ( scale < 1 || needsPowerOfTwo === true ) {
  14187. // only perform resize for certain image types
  14188. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  14189. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  14190. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  14191. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  14192. const width = floor( scale * image.width );
  14193. const height = floor( scale * image.height );
  14194. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  14195. // cube textures can't reuse the same canvas
  14196. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  14197. canvas.width = width;
  14198. canvas.height = height;
  14199. const context = canvas.getContext( '2d' );
  14200. context.drawImage( image, 0, 0, width, height );
  14201. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  14202. return canvas;
  14203. } else {
  14204. if ( 'data' in image ) {
  14205. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  14206. }
  14207. return image;
  14208. }
  14209. }
  14210. return image;
  14211. }
  14212. function isPowerOfTwo$1( image ) {
  14213. return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height );
  14214. }
  14215. function textureNeedsPowerOfTwo( texture ) {
  14216. if ( isWebGL2 ) return false;
  14217. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  14218. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  14219. }
  14220. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  14221. return texture.generateMipmaps && supportsMips &&
  14222. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  14223. }
  14224. function generateMipmap( target, texture, width, height, depth = 1 ) {
  14225. _gl.generateMipmap( target );
  14226. const textureProperties = properties.get( texture );
  14227. textureProperties.__maxMipLevel = Math.log2( Math.max( width, height, depth ) );
  14228. }
  14229. function getInternalFormat( internalFormatName, glFormat, glType ) {
  14230. if ( isWebGL2 === false ) return glFormat;
  14231. if ( internalFormatName !== null ) {
  14232. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  14233. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  14234. }
  14235. let internalFormat = glFormat;
  14236. if ( glFormat === 6403 ) {
  14237. if ( glType === 5126 ) internalFormat = 33326;
  14238. if ( glType === 5131 ) internalFormat = 33325;
  14239. if ( glType === 5121 ) internalFormat = 33321;
  14240. }
  14241. if ( glFormat === 6407 ) {
  14242. if ( glType === 5126 ) internalFormat = 34837;
  14243. if ( glType === 5131 ) internalFormat = 34843;
  14244. if ( glType === 5121 ) internalFormat = 32849;
  14245. }
  14246. if ( glFormat === 6408 ) {
  14247. if ( glType === 5126 ) internalFormat = 34836;
  14248. if ( glType === 5131 ) internalFormat = 34842;
  14249. if ( glType === 5121 ) internalFormat = 32856;
  14250. }
  14251. if ( internalFormat === 33325 || internalFormat === 33326 ||
  14252. internalFormat === 34842 || internalFormat === 34836 ) {
  14253. extensions.get( 'EXT_color_buffer_float' );
  14254. }
  14255. return internalFormat;
  14256. }
  14257. // Fallback filters for non-power-of-2 textures
  14258. function filterFallback( f ) {
  14259. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  14260. return 9728;
  14261. }
  14262. return 9729;
  14263. }
  14264. //
  14265. function onTextureDispose( event ) {
  14266. const texture = event.target;
  14267. texture.removeEventListener( 'dispose', onTextureDispose );
  14268. deallocateTexture( texture );
  14269. if ( texture.isVideoTexture ) {
  14270. _videoTextures.delete( texture );
  14271. }
  14272. info.memory.textures --;
  14273. }
  14274. function onRenderTargetDispose( event ) {
  14275. const renderTarget = event.target;
  14276. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  14277. deallocateRenderTarget( renderTarget );
  14278. }
  14279. //
  14280. function deallocateTexture( texture ) {
  14281. const textureProperties = properties.get( texture );
  14282. if ( textureProperties.__webglInit === undefined ) return;
  14283. _gl.deleteTexture( textureProperties.__webglTexture );
  14284. properties.remove( texture );
  14285. }
  14286. function deallocateRenderTarget( renderTarget ) {
  14287. const texture = renderTarget.texture;
  14288. const renderTargetProperties = properties.get( renderTarget );
  14289. const textureProperties = properties.get( texture );
  14290. if ( ! renderTarget ) return;
  14291. if ( textureProperties.__webglTexture !== undefined ) {
  14292. _gl.deleteTexture( textureProperties.__webglTexture );
  14293. info.memory.textures --;
  14294. }
  14295. if ( renderTarget.depthTexture ) {
  14296. renderTarget.depthTexture.dispose();
  14297. }
  14298. if ( renderTarget.isWebGLCubeRenderTarget ) {
  14299. for ( let i = 0; i < 6; i ++ ) {
  14300. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  14301. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  14302. }
  14303. } else {
  14304. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  14305. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  14306. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  14307. if ( renderTargetProperties.__webglColorRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer );
  14308. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  14309. }
  14310. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  14311. for ( let i = 0, il = texture.length; i < il; i ++ ) {
  14312. const attachmentProperties = properties.get( texture[ i ] );
  14313. if ( attachmentProperties.__webglTexture ) {
  14314. _gl.deleteTexture( attachmentProperties.__webglTexture );
  14315. info.memory.textures --;
  14316. }
  14317. properties.remove( texture[ i ] );
  14318. }
  14319. }
  14320. properties.remove( texture );
  14321. properties.remove( renderTarget );
  14322. }
  14323. //
  14324. let textureUnits = 0;
  14325. function resetTextureUnits() {
  14326. textureUnits = 0;
  14327. }
  14328. function allocateTextureUnit() {
  14329. const textureUnit = textureUnits;
  14330. if ( textureUnit >= maxTextures ) {
  14331. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  14332. }
  14333. textureUnits += 1;
  14334. return textureUnit;
  14335. }
  14336. //
  14337. function setTexture2D( texture, slot ) {
  14338. const textureProperties = properties.get( texture );
  14339. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  14340. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14341. const image = texture.image;
  14342. if ( image === undefined ) {
  14343. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' );
  14344. } else if ( image.complete === false ) {
  14345. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  14346. } else {
  14347. uploadTexture( textureProperties, texture, slot );
  14348. return;
  14349. }
  14350. }
  14351. state.activeTexture( 33984 + slot );
  14352. state.bindTexture( 3553, textureProperties.__webglTexture );
  14353. }
  14354. function setTexture2DArray( texture, slot ) {
  14355. const textureProperties = properties.get( texture );
  14356. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14357. uploadTexture( textureProperties, texture, slot );
  14358. return;
  14359. }
  14360. state.activeTexture( 33984 + slot );
  14361. state.bindTexture( 35866, textureProperties.__webglTexture );
  14362. }
  14363. function setTexture3D( texture, slot ) {
  14364. const textureProperties = properties.get( texture );
  14365. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14366. uploadTexture( textureProperties, texture, slot );
  14367. return;
  14368. }
  14369. state.activeTexture( 33984 + slot );
  14370. state.bindTexture( 32879, textureProperties.__webglTexture );
  14371. }
  14372. function setTextureCube( texture, slot ) {
  14373. const textureProperties = properties.get( texture );
  14374. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14375. uploadCubeTexture( textureProperties, texture, slot );
  14376. return;
  14377. }
  14378. state.activeTexture( 33984 + slot );
  14379. state.bindTexture( 34067, textureProperties.__webglTexture );
  14380. }
  14381. const wrappingToGL = {
  14382. [ RepeatWrapping ]: 10497,
  14383. [ ClampToEdgeWrapping ]: 33071,
  14384. [ MirroredRepeatWrapping ]: 33648
  14385. };
  14386. const filterToGL = {
  14387. [ NearestFilter ]: 9728,
  14388. [ NearestMipmapNearestFilter ]: 9984,
  14389. [ NearestMipmapLinearFilter ]: 9986,
  14390. [ LinearFilter ]: 9729,
  14391. [ LinearMipmapNearestFilter ]: 9985,
  14392. [ LinearMipmapLinearFilter ]: 9987
  14393. };
  14394. function setTextureParameters( textureType, texture, supportsMips ) {
  14395. if ( supportsMips ) {
  14396. _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] );
  14397. _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] );
  14398. if ( textureType === 32879 || textureType === 35866 ) {
  14399. _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] );
  14400. }
  14401. _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] );
  14402. _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] );
  14403. } else {
  14404. _gl.texParameteri( textureType, 10242, 33071 );
  14405. _gl.texParameteri( textureType, 10243, 33071 );
  14406. if ( textureType === 32879 || textureType === 35866 ) {
  14407. _gl.texParameteri( textureType, 32882, 33071 );
  14408. }
  14409. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  14410. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  14411. }
  14412. _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
  14413. _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );
  14414. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  14415. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  14416. }
  14417. }
  14418. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  14419. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  14420. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  14421. if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only
  14422. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  14423. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  14424. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  14425. }
  14426. }
  14427. }
  14428. function initTexture( textureProperties, texture ) {
  14429. if ( textureProperties.__webglInit === undefined ) {
  14430. textureProperties.__webglInit = true;
  14431. texture.addEventListener( 'dispose', onTextureDispose );
  14432. textureProperties.__webglTexture = _gl.createTexture();
  14433. info.memory.textures ++;
  14434. }
  14435. }
  14436. function uploadTexture( textureProperties, texture, slot ) {
  14437. let textureType = 3553;
  14438. if ( texture.isDataTexture2DArray ) textureType = 35866;
  14439. if ( texture.isDataTexture3D ) textureType = 32879;
  14440. initTexture( textureProperties, texture );
  14441. state.activeTexture( 33984 + slot );
  14442. state.bindTexture( textureType, textureProperties.__webglTexture );
  14443. _gl.pixelStorei( 37440, texture.flipY );
  14444. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  14445. _gl.pixelStorei( 3317, texture.unpackAlignment );
  14446. _gl.pixelStorei( 37443, 0 );
  14447. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false;
  14448. const image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  14449. const supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14450. glFormat = utils.convert( texture.format );
  14451. let glType = utils.convert( texture.type ),
  14452. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  14453. setTextureParameters( textureType, texture, supportsMips );
  14454. let mipmap;
  14455. const mipmaps = texture.mipmaps;
  14456. if ( texture.isDepthTexture ) {
  14457. // populate depth texture with dummy data
  14458. glInternalFormat = 6402;
  14459. if ( isWebGL2 ) {
  14460. if ( texture.type === FloatType ) {
  14461. glInternalFormat = 36012;
  14462. } else if ( texture.type === UnsignedIntType ) {
  14463. glInternalFormat = 33190;
  14464. } else if ( texture.type === UnsignedInt248Type ) {
  14465. glInternalFormat = 35056;
  14466. } else {
  14467. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  14468. }
  14469. } else {
  14470. if ( texture.type === FloatType ) {
  14471. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  14472. }
  14473. }
  14474. // validation checks for WebGL 1
  14475. if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {
  14476. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14477. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  14478. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14479. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  14480. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  14481. texture.type = UnsignedShortType;
  14482. glType = utils.convert( texture.type );
  14483. }
  14484. }
  14485. if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) {
  14486. // Depth stencil textures need the DEPTH_STENCIL internal format
  14487. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14488. glInternalFormat = 34041;
  14489. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14490. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  14491. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14492. if ( texture.type !== UnsignedInt248Type ) {
  14493. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  14494. texture.type = UnsignedInt248Type;
  14495. glType = utils.convert( texture.type );
  14496. }
  14497. }
  14498. //
  14499. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  14500. } else if ( texture.isDataTexture ) {
  14501. // use manually created mipmaps if available
  14502. // if there are no manual mipmaps
  14503. // set 0 level mipmap and then use GL to generate other mipmap levels
  14504. if ( mipmaps.length > 0 && supportsMips ) {
  14505. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14506. mipmap = mipmaps[ i ];
  14507. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14508. }
  14509. texture.generateMipmaps = false;
  14510. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14511. } else {
  14512. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14513. textureProperties.__maxMipLevel = 0;
  14514. }
  14515. } else if ( texture.isCompressedTexture ) {
  14516. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14517. mipmap = mipmaps[ i ];
  14518. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  14519. if ( glFormat !== null ) {
  14520. state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14521. } else {
  14522. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14523. }
  14524. } else {
  14525. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14526. }
  14527. }
  14528. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14529. } else if ( texture.isDataTexture2DArray ) {
  14530. state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14531. textureProperties.__maxMipLevel = 0;
  14532. } else if ( texture.isDataTexture3D ) {
  14533. state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14534. textureProperties.__maxMipLevel = 0;
  14535. } else {
  14536. // regular Texture (image, video, canvas)
  14537. // use manually created mipmaps if available
  14538. // if there are no manual mipmaps
  14539. // set 0 level mipmap and then use GL to generate other mipmap levels
  14540. if ( mipmaps.length > 0 && supportsMips ) {
  14541. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14542. mipmap = mipmaps[ i ];
  14543. state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );
  14544. }
  14545. texture.generateMipmaps = false;
  14546. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14547. } else {
  14548. state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
  14549. textureProperties.__maxMipLevel = 0;
  14550. }
  14551. }
  14552. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14553. generateMipmap( textureType, texture, image.width, image.height );
  14554. }
  14555. textureProperties.__version = texture.version;
  14556. if ( texture.onUpdate ) texture.onUpdate( texture );
  14557. }
  14558. function uploadCubeTexture( textureProperties, texture, slot ) {
  14559. if ( texture.image.length !== 6 ) return;
  14560. initTexture( textureProperties, texture );
  14561. state.activeTexture( 33984 + slot );
  14562. state.bindTexture( 34067, textureProperties.__webglTexture );
  14563. _gl.pixelStorei( 37440, texture.flipY );
  14564. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  14565. _gl.pixelStorei( 3317, texture.unpackAlignment );
  14566. _gl.pixelStorei( 37443, 0 );
  14567. const isCompressed = ( texture && ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ) );
  14568. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  14569. const cubeImage = [];
  14570. for ( let i = 0; i < 6; i ++ ) {
  14571. if ( ! isCompressed && ! isDataTexture ) {
  14572. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  14573. } else {
  14574. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  14575. }
  14576. }
  14577. const image = cubeImage[ 0 ],
  14578. supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14579. glFormat = utils.convert( texture.format ),
  14580. glType = utils.convert( texture.type ),
  14581. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  14582. setTextureParameters( 34067, texture, supportsMips );
  14583. let mipmaps;
  14584. if ( isCompressed ) {
  14585. for ( let i = 0; i < 6; i ++ ) {
  14586. mipmaps = cubeImage[ i ].mipmaps;
  14587. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14588. const mipmap = mipmaps[ j ];
  14589. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  14590. if ( glFormat !== null ) {
  14591. state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14592. } else {
  14593. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  14594. }
  14595. } else {
  14596. state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14597. }
  14598. }
  14599. }
  14600. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14601. } else {
  14602. mipmaps = texture.mipmaps;
  14603. for ( let i = 0; i < 6; i ++ ) {
  14604. if ( isDataTexture ) {
  14605. state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  14606. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14607. const mipmap = mipmaps[ j ];
  14608. const mipmapImage = mipmap.image[ i ].image;
  14609. state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  14610. }
  14611. } else {
  14612. state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  14613. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14614. const mipmap = mipmaps[ j ];
  14615. state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  14616. }
  14617. }
  14618. }
  14619. textureProperties.__maxMipLevel = mipmaps.length;
  14620. }
  14621. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14622. // We assume images for cube map have the same size.
  14623. generateMipmap( 34067, texture, image.width, image.height );
  14624. }
  14625. textureProperties.__version = texture.version;
  14626. if ( texture.onUpdate ) texture.onUpdate( texture );
  14627. }
  14628. // Render targets
  14629. // Setup storage for target texture and bind it to correct framebuffer
  14630. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) {
  14631. const glFormat = utils.convert( texture.format );
  14632. const glType = utils.convert( texture.type );
  14633. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  14634. if ( textureTarget === 32879 || textureTarget === 35866 ) {
  14635. state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null );
  14636. } else {
  14637. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14638. }
  14639. state.bindFramebuffer( 36160, framebuffer );
  14640. _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 );
  14641. state.bindFramebuffer( 36160, null );
  14642. }
  14643. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14644. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  14645. _gl.bindRenderbuffer( 36161, renderbuffer );
  14646. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14647. let glInternalFormat = 33189;
  14648. if ( isMultisample ) {
  14649. const depthTexture = renderTarget.depthTexture;
  14650. if ( depthTexture && depthTexture.isDepthTexture ) {
  14651. if ( depthTexture.type === FloatType ) {
  14652. glInternalFormat = 36012;
  14653. } else if ( depthTexture.type === UnsignedIntType ) {
  14654. glInternalFormat = 33190;
  14655. }
  14656. }
  14657. const samples = getRenderTargetSamples( renderTarget );
  14658. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14659. } else {
  14660. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  14661. }
  14662. _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );
  14663. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14664. if ( isMultisample ) {
  14665. const samples = getRenderTargetSamples( renderTarget );
  14666. _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  14667. } else {
  14668. _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );
  14669. }
  14670. _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );
  14671. } else {
  14672. // Use the first texture for MRT so far
  14673. const texture = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture[ 0 ] : renderTarget.texture;
  14674. const glFormat = utils.convert( texture.format );
  14675. const glType = utils.convert( texture.type );
  14676. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  14677. if ( isMultisample ) {
  14678. const samples = getRenderTargetSamples( renderTarget );
  14679. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14680. } else {
  14681. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  14682. }
  14683. }
  14684. _gl.bindRenderbuffer( 36161, null );
  14685. }
  14686. // Setup resources for a Depth Texture for a FBO (needs an extension)
  14687. function setupDepthTexture( framebuffer, renderTarget ) {
  14688. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  14689. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  14690. state.bindFramebuffer( 36160, framebuffer );
  14691. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  14692. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  14693. }
  14694. // upload an empty depth texture with framebuffer size
  14695. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  14696. renderTarget.depthTexture.image.width !== renderTarget.width ||
  14697. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  14698. renderTarget.depthTexture.image.width = renderTarget.width;
  14699. renderTarget.depthTexture.image.height = renderTarget.height;
  14700. renderTarget.depthTexture.needsUpdate = true;
  14701. }
  14702. setTexture2D( renderTarget.depthTexture, 0 );
  14703. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  14704. if ( renderTarget.depthTexture.format === DepthFormat ) {
  14705. _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );
  14706. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  14707. _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );
  14708. } else {
  14709. throw new Error( 'Unknown depthTexture format' );
  14710. }
  14711. }
  14712. // Setup GL resources for a non-texture depth buffer
  14713. function setupDepthRenderbuffer( renderTarget ) {
  14714. const renderTargetProperties = properties.get( renderTarget );
  14715. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14716. if ( renderTarget.depthTexture ) {
  14717. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  14718. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  14719. } else {
  14720. if ( isCube ) {
  14721. renderTargetProperties.__webglDepthbuffer = [];
  14722. for ( let i = 0; i < 6; i ++ ) {
  14723. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
  14724. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  14725. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  14726. }
  14727. } else {
  14728. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  14729. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14730. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  14731. }
  14732. }
  14733. state.bindFramebuffer( 36160, null );
  14734. }
  14735. // Set up GL resources for the render target
  14736. function setupRenderTarget( renderTarget ) {
  14737. const texture = renderTarget.texture;
  14738. const renderTargetProperties = properties.get( renderTarget );
  14739. const textureProperties = properties.get( texture );
  14740. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14741. if ( renderTarget.isWebGLMultipleRenderTargets !== true ) {
  14742. textureProperties.__webglTexture = _gl.createTexture();
  14743. textureProperties.__version = texture.version;
  14744. info.memory.textures ++;
  14745. }
  14746. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14747. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  14748. const isMultisample = ( renderTarget.isWebGLMultisampleRenderTarget === true );
  14749. const isRenderTarget3D = texture.isDataTexture3D || texture.isDataTexture2DArray;
  14750. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14751. // Handles WebGL2 RGBFormat fallback - #18858
  14752. if ( isWebGL2 && texture.format === RGBFormat && ( texture.type === FloatType || texture.type === HalfFloatType ) ) {
  14753. texture.format = RGBAFormat;
  14754. console.warn( 'THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.' );
  14755. }
  14756. // Setup framebuffer
  14757. if ( isCube ) {
  14758. renderTargetProperties.__webglFramebuffer = [];
  14759. for ( let i = 0; i < 6; i ++ ) {
  14760. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14761. }
  14762. } else {
  14763. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14764. if ( isMultipleRenderTargets ) {
  14765. if ( capabilities.drawBuffers ) {
  14766. const textures = renderTarget.texture;
  14767. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14768. const attachmentProperties = properties.get( textures[ i ] );
  14769. if ( attachmentProperties.__webglTexture === undefined ) {
  14770. attachmentProperties.__webglTexture = _gl.createTexture();
  14771. info.memory.textures ++;
  14772. }
  14773. }
  14774. } else {
  14775. console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' );
  14776. }
  14777. } else if ( isMultisample ) {
  14778. if ( isWebGL2 ) {
  14779. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14780. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  14781. _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer );
  14782. const glFormat = utils.convert( texture.format );
  14783. const glType = utils.convert( texture.type );
  14784. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  14785. const samples = getRenderTargetSamples( renderTarget );
  14786. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14787. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  14788. _gl.framebufferRenderbuffer( 36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer );
  14789. _gl.bindRenderbuffer( 36161, null );
  14790. if ( renderTarget.depthBuffer ) {
  14791. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14792. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  14793. }
  14794. state.bindFramebuffer( 36160, null );
  14795. } else {
  14796. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  14797. }
  14798. }
  14799. }
  14800. // Setup color buffer
  14801. if ( isCube ) {
  14802. state.bindTexture( 34067, textureProperties.__webglTexture );
  14803. setTextureParameters( 34067, texture, supportsMips );
  14804. for ( let i = 0; i < 6; i ++ ) {
  14805. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, 36064, 34069 + i );
  14806. }
  14807. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14808. generateMipmap( 34067, texture, renderTarget.width, renderTarget.height );
  14809. }
  14810. state.unbindTexture();
  14811. } else if ( isMultipleRenderTargets ) {
  14812. const textures = renderTarget.texture;
  14813. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14814. const attachment = textures[ i ];
  14815. const attachmentProperties = properties.get( attachment );
  14816. state.bindTexture( 3553, attachmentProperties.__webglTexture );
  14817. setTextureParameters( 3553, attachment, supportsMips );
  14818. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, 36064 + i, 3553 );
  14819. if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) {
  14820. generateMipmap( 3553, attachment, renderTarget.width, renderTarget.height );
  14821. }
  14822. }
  14823. state.unbindTexture();
  14824. } else {
  14825. let glTextureType = 3553;
  14826. if ( isRenderTarget3D ) {
  14827. // Render targets containing layers, i.e: Texture 3D and 2d arrays
  14828. if ( isWebGL2 ) {
  14829. const isTexture3D = texture.isDataTexture3D;
  14830. glTextureType = isTexture3D ? 32879 : 35866;
  14831. } else {
  14832. console.warn( 'THREE.DataTexture3D and THREE.DataTexture2DArray only supported with WebGL2.' );
  14833. }
  14834. }
  14835. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  14836. setTextureParameters( glTextureType, texture, supportsMips );
  14837. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, 36064, glTextureType );
  14838. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14839. generateMipmap( glTextureType, texture, renderTarget.width, renderTarget.height, renderTarget.depth );
  14840. }
  14841. state.unbindTexture();
  14842. }
  14843. // Setup depth and stencil buffers
  14844. if ( renderTarget.depthBuffer ) {
  14845. setupDepthRenderbuffer( renderTarget );
  14846. }
  14847. }
  14848. function updateRenderTargetMipmap( renderTarget ) {
  14849. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14850. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14851. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14852. const texture = textures[ i ];
  14853. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14854. const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  14855. const webglTexture = properties.get( texture ).__webglTexture;
  14856. state.bindTexture( target, webglTexture );
  14857. generateMipmap( target, texture, renderTarget.width, renderTarget.height );
  14858. state.unbindTexture();
  14859. }
  14860. }
  14861. }
  14862. function updateMultisampleRenderTarget( renderTarget ) {
  14863. if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  14864. if ( isWebGL2 ) {
  14865. const width = renderTarget.width;
  14866. const height = renderTarget.height;
  14867. let mask = 16384;
  14868. if ( renderTarget.depthBuffer ) mask |= 256;
  14869. if ( renderTarget.stencilBuffer ) mask |= 1024;
  14870. const renderTargetProperties = properties.get( renderTarget );
  14871. state.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
  14872. state.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );
  14873. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );
  14874. state.bindFramebuffer( 36008, null );
  14875. state.bindFramebuffer( 36009, renderTargetProperties.__webglMultisampledFramebuffer );
  14876. } else {
  14877. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  14878. }
  14879. }
  14880. }
  14881. function getRenderTargetSamples( renderTarget ) {
  14882. return ( isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ) ?
  14883. Math.min( maxSamples, renderTarget.samples ) : 0;
  14884. }
  14885. function updateVideoTexture( texture ) {
  14886. const frame = info.render.frame;
  14887. // Check the last frame we updated the VideoTexture
  14888. if ( _videoTextures.get( texture ) !== frame ) {
  14889. _videoTextures.set( texture, frame );
  14890. texture.update();
  14891. }
  14892. }
  14893. // backwards compatibility
  14894. let warnedTexture2D = false;
  14895. let warnedTextureCube = false;
  14896. function safeSetTexture2D( texture, slot ) {
  14897. if ( texture && texture.isWebGLRenderTarget ) {
  14898. if ( warnedTexture2D === false ) {
  14899. console.warn( 'THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.' );
  14900. warnedTexture2D = true;
  14901. }
  14902. texture = texture.texture;
  14903. }
  14904. setTexture2D( texture, slot );
  14905. }
  14906. function safeSetTextureCube( texture, slot ) {
  14907. if ( texture && texture.isWebGLCubeRenderTarget ) {
  14908. if ( warnedTextureCube === false ) {
  14909. console.warn( 'THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.' );
  14910. warnedTextureCube = true;
  14911. }
  14912. texture = texture.texture;
  14913. }
  14914. setTextureCube( texture, slot );
  14915. }
  14916. //
  14917. this.allocateTextureUnit = allocateTextureUnit;
  14918. this.resetTextureUnits = resetTextureUnits;
  14919. this.setTexture2D = setTexture2D;
  14920. this.setTexture2DArray = setTexture2DArray;
  14921. this.setTexture3D = setTexture3D;
  14922. this.setTextureCube = setTextureCube;
  14923. this.setupRenderTarget = setupRenderTarget;
  14924. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14925. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14926. this.safeSetTexture2D = safeSetTexture2D;
  14927. this.safeSetTextureCube = safeSetTextureCube;
  14928. }
  14929. function WebGLUtils( gl, extensions, capabilities ) {
  14930. const isWebGL2 = capabilities.isWebGL2;
  14931. function convert( p ) {
  14932. let extension;
  14933. if ( p === UnsignedByteType ) return 5121;
  14934. if ( p === UnsignedShort4444Type ) return 32819;
  14935. if ( p === UnsignedShort5551Type ) return 32820;
  14936. if ( p === UnsignedShort565Type ) return 33635;
  14937. if ( p === ByteType ) return 5120;
  14938. if ( p === ShortType ) return 5122;
  14939. if ( p === UnsignedShortType ) return 5123;
  14940. if ( p === IntType ) return 5124;
  14941. if ( p === UnsignedIntType ) return 5125;
  14942. if ( p === FloatType ) return 5126;
  14943. if ( p === HalfFloatType ) {
  14944. if ( isWebGL2 ) return 5131;
  14945. extension = extensions.get( 'OES_texture_half_float' );
  14946. if ( extension !== null ) {
  14947. return extension.HALF_FLOAT_OES;
  14948. } else {
  14949. return null;
  14950. }
  14951. }
  14952. if ( p === AlphaFormat ) return 6406;
  14953. if ( p === RGBFormat ) return 6407;
  14954. if ( p === RGBAFormat ) return 6408;
  14955. if ( p === LuminanceFormat ) return 6409;
  14956. if ( p === LuminanceAlphaFormat ) return 6410;
  14957. if ( p === DepthFormat ) return 6402;
  14958. if ( p === DepthStencilFormat ) return 34041;
  14959. if ( p === RedFormat ) return 6403;
  14960. // WebGL2 formats.
  14961. if ( p === RedIntegerFormat ) return 36244;
  14962. if ( p === RGFormat ) return 33319;
  14963. if ( p === RGIntegerFormat ) return 33320;
  14964. if ( p === RGBIntegerFormat ) return 36248;
  14965. if ( p === RGBAIntegerFormat ) return 36249;
  14966. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  14967. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  14968. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  14969. if ( extension !== null ) {
  14970. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14971. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14972. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14973. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14974. } else {
  14975. return null;
  14976. }
  14977. }
  14978. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  14979. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  14980. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  14981. if ( extension !== null ) {
  14982. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14983. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14984. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14985. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14986. } else {
  14987. return null;
  14988. }
  14989. }
  14990. if ( p === RGB_ETC1_Format ) {
  14991. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  14992. if ( extension !== null ) {
  14993. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14994. } else {
  14995. return null;
  14996. }
  14997. }
  14998. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  14999. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  15000. if ( extension !== null ) {
  15001. if ( p === RGB_ETC2_Format ) return extension.COMPRESSED_RGB8_ETC2;
  15002. if ( p === RGBA_ETC2_EAC_Format ) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  15003. }
  15004. }
  15005. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  15006. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  15007. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  15008. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  15009. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ||
  15010. p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format ||
  15011. p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format ||
  15012. p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format ||
  15013. p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format ||
  15014. p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format ) {
  15015. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  15016. if ( extension !== null ) {
  15017. // TODO Complete?
  15018. return p;
  15019. } else {
  15020. return null;
  15021. }
  15022. }
  15023. if ( p === RGBA_BPTC_Format ) {
  15024. extension = extensions.get( 'EXT_texture_compression_bptc' );
  15025. if ( extension !== null ) {
  15026. // TODO Complete?
  15027. return p;
  15028. } else {
  15029. return null;
  15030. }
  15031. }
  15032. if ( p === UnsignedInt248Type ) {
  15033. if ( isWebGL2 ) return 34042;
  15034. extension = extensions.get( 'WEBGL_depth_texture' );
  15035. if ( extension !== null ) {
  15036. return extension.UNSIGNED_INT_24_8_WEBGL;
  15037. } else {
  15038. return null;
  15039. }
  15040. }
  15041. }
  15042. return { convert: convert };
  15043. }
  15044. class ArrayCamera extends PerspectiveCamera {
  15045. constructor( array = [] ) {
  15046. super();
  15047. this.cameras = array;
  15048. }
  15049. }
  15050. ArrayCamera.prototype.isArrayCamera = true;
  15051. class Group extends Object3D {
  15052. constructor() {
  15053. super();
  15054. this.type = 'Group';
  15055. }
  15056. }
  15057. Group.prototype.isGroup = true;
  15058. const _moveEvent = { type: 'move' };
  15059. class WebXRController {
  15060. constructor() {
  15061. this._targetRay = null;
  15062. this._grip = null;
  15063. this._hand = null;
  15064. }
  15065. getHandSpace() {
  15066. if ( this._hand === null ) {
  15067. this._hand = new Group();
  15068. this._hand.matrixAutoUpdate = false;
  15069. this._hand.visible = false;
  15070. this._hand.joints = {};
  15071. this._hand.inputState = { pinching: false };
  15072. }
  15073. return this._hand;
  15074. }
  15075. getTargetRaySpace() {
  15076. if ( this._targetRay === null ) {
  15077. this._targetRay = new Group();
  15078. this._targetRay.matrixAutoUpdate = false;
  15079. this._targetRay.visible = false;
  15080. this._targetRay.hasLinearVelocity = false;
  15081. this._targetRay.linearVelocity = new Vector3();
  15082. this._targetRay.hasAngularVelocity = false;
  15083. this._targetRay.angularVelocity = new Vector3();
  15084. }
  15085. return this._targetRay;
  15086. }
  15087. getGripSpace() {
  15088. if ( this._grip === null ) {
  15089. this._grip = new Group();
  15090. this._grip.matrixAutoUpdate = false;
  15091. this._grip.visible = false;
  15092. this._grip.hasLinearVelocity = false;
  15093. this._grip.linearVelocity = new Vector3();
  15094. this._grip.hasAngularVelocity = false;
  15095. this._grip.angularVelocity = new Vector3();
  15096. }
  15097. return this._grip;
  15098. }
  15099. dispatchEvent( event ) {
  15100. if ( this._targetRay !== null ) {
  15101. this._targetRay.dispatchEvent( event );
  15102. }
  15103. if ( this._grip !== null ) {
  15104. this._grip.dispatchEvent( event );
  15105. }
  15106. if ( this._hand !== null ) {
  15107. this._hand.dispatchEvent( event );
  15108. }
  15109. return this;
  15110. }
  15111. disconnect( inputSource ) {
  15112. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  15113. if ( this._targetRay !== null ) {
  15114. this._targetRay.visible = false;
  15115. }
  15116. if ( this._grip !== null ) {
  15117. this._grip.visible = false;
  15118. }
  15119. if ( this._hand !== null ) {
  15120. this._hand.visible = false;
  15121. }
  15122. return this;
  15123. }
  15124. update( inputSource, frame, referenceSpace ) {
  15125. let inputPose = null;
  15126. let gripPose = null;
  15127. let handPose = null;
  15128. const targetRay = this._targetRay;
  15129. const grip = this._grip;
  15130. const hand = this._hand;
  15131. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  15132. if ( targetRay !== null ) {
  15133. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  15134. if ( inputPose !== null ) {
  15135. targetRay.matrix.fromArray( inputPose.transform.matrix );
  15136. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  15137. if ( inputPose.linearVelocity ) {
  15138. targetRay.hasLinearVelocity = true;
  15139. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  15140. } else {
  15141. targetRay.hasLinearVelocity = false;
  15142. }
  15143. if ( inputPose.angularVelocity ) {
  15144. targetRay.hasAngularVelocity = true;
  15145. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  15146. } else {
  15147. targetRay.hasAngularVelocity = false;
  15148. }
  15149. this.dispatchEvent( _moveEvent );
  15150. }
  15151. }
  15152. if ( hand && inputSource.hand ) {
  15153. handPose = true;
  15154. for ( const inputjoint of inputSource.hand.values() ) {
  15155. // Update the joints groups with the XRJoint poses
  15156. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  15157. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  15158. // The transform of this joint will be updated with the joint pose on each frame
  15159. const joint = new Group();
  15160. joint.matrixAutoUpdate = false;
  15161. joint.visible = false;
  15162. hand.joints[ inputjoint.jointName ] = joint;
  15163. // ??
  15164. hand.add( joint );
  15165. }
  15166. const joint = hand.joints[ inputjoint.jointName ];
  15167. if ( jointPose !== null ) {
  15168. joint.matrix.fromArray( jointPose.transform.matrix );
  15169. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  15170. joint.jointRadius = jointPose.radius;
  15171. }
  15172. joint.visible = jointPose !== null;
  15173. }
  15174. // Custom events
  15175. // Check pinchz
  15176. const indexTip = hand.joints[ 'index-finger-tip' ];
  15177. const thumbTip = hand.joints[ 'thumb-tip' ];
  15178. const distance = indexTip.position.distanceTo( thumbTip.position );
  15179. const distanceToPinch = 0.02;
  15180. const threshold = 0.005;
  15181. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  15182. hand.inputState.pinching = false;
  15183. this.dispatchEvent( {
  15184. type: 'pinchend',
  15185. handedness: inputSource.handedness,
  15186. target: this
  15187. } );
  15188. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  15189. hand.inputState.pinching = true;
  15190. this.dispatchEvent( {
  15191. type: 'pinchstart',
  15192. handedness: inputSource.handedness,
  15193. target: this
  15194. } );
  15195. }
  15196. } else {
  15197. if ( grip !== null && inputSource.gripSpace ) {
  15198. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  15199. if ( gripPose !== null ) {
  15200. grip.matrix.fromArray( gripPose.transform.matrix );
  15201. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  15202. if ( gripPose.linearVelocity ) {
  15203. grip.hasLinearVelocity = true;
  15204. grip.linearVelocity.copy( gripPose.linearVelocity );
  15205. } else {
  15206. grip.hasLinearVelocity = false;
  15207. }
  15208. if ( gripPose.angularVelocity ) {
  15209. grip.hasAngularVelocity = true;
  15210. grip.angularVelocity.copy( gripPose.angularVelocity );
  15211. } else {
  15212. grip.hasAngularVelocity = false;
  15213. }
  15214. }
  15215. }
  15216. }
  15217. }
  15218. if ( targetRay !== null ) {
  15219. targetRay.visible = ( inputPose !== null );
  15220. }
  15221. if ( grip !== null ) {
  15222. grip.visible = ( gripPose !== null );
  15223. }
  15224. if ( hand !== null ) {
  15225. hand.visible = ( handPose !== null );
  15226. }
  15227. return this;
  15228. }
  15229. }
  15230. class WebXRManager extends EventDispatcher {
  15231. constructor( renderer, gl ) {
  15232. super();
  15233. const scope = this;
  15234. const state = renderer.state;
  15235. let session = null;
  15236. let framebufferScaleFactor = 1.0;
  15237. let referenceSpace = null;
  15238. let referenceSpaceType = 'local-floor';
  15239. let pose = null;
  15240. let glBinding = null;
  15241. let glFramebuffer = null;
  15242. let glProjLayer = null;
  15243. let glBaseLayer = null;
  15244. let isMultisample = false;
  15245. let glMultisampledFramebuffer = null;
  15246. let glColorRenderbuffer = null;
  15247. let glDepthRenderbuffer = null;
  15248. let xrFrame = null;
  15249. let depthStyle = null;
  15250. let clearStyle = null;
  15251. const controllers = [];
  15252. const inputSourcesMap = new Map();
  15253. //
  15254. const cameraL = new PerspectiveCamera();
  15255. cameraL.layers.enable( 1 );
  15256. cameraL.viewport = new Vector4();
  15257. const cameraR = new PerspectiveCamera();
  15258. cameraR.layers.enable( 2 );
  15259. cameraR.viewport = new Vector4();
  15260. const cameras = [ cameraL, cameraR ];
  15261. const cameraVR = new ArrayCamera();
  15262. cameraVR.layers.enable( 1 );
  15263. cameraVR.layers.enable( 2 );
  15264. let _currentDepthNear = null;
  15265. let _currentDepthFar = null;
  15266. //
  15267. this.cameraAutoUpdate = true;
  15268. this.enabled = false;
  15269. this.isPresenting = false;
  15270. this.getController = function ( index ) {
  15271. let controller = controllers[ index ];
  15272. if ( controller === undefined ) {
  15273. controller = new WebXRController();
  15274. controllers[ index ] = controller;
  15275. }
  15276. return controller.getTargetRaySpace();
  15277. };
  15278. this.getControllerGrip = function ( index ) {
  15279. let controller = controllers[ index ];
  15280. if ( controller === undefined ) {
  15281. controller = new WebXRController();
  15282. controllers[ index ] = controller;
  15283. }
  15284. return controller.getGripSpace();
  15285. };
  15286. this.getHand = function ( index ) {
  15287. let controller = controllers[ index ];
  15288. if ( controller === undefined ) {
  15289. controller = new WebXRController();
  15290. controllers[ index ] = controller;
  15291. }
  15292. return controller.getHandSpace();
  15293. };
  15294. //
  15295. function onSessionEvent( event ) {
  15296. const controller = inputSourcesMap.get( event.inputSource );
  15297. if ( controller ) {
  15298. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  15299. }
  15300. }
  15301. function onSessionEnd() {
  15302. inputSourcesMap.forEach( function ( controller, inputSource ) {
  15303. controller.disconnect( inputSource );
  15304. } );
  15305. inputSourcesMap.clear();
  15306. _currentDepthNear = null;
  15307. _currentDepthFar = null;
  15308. // restore framebuffer/rendering state
  15309. state.bindXRFramebuffer( null );
  15310. renderer.setRenderTarget( renderer.getRenderTarget() );
  15311. if ( glFramebuffer ) gl.deleteFramebuffer( glFramebuffer );
  15312. if ( glMultisampledFramebuffer ) gl.deleteFramebuffer( glMultisampledFramebuffer );
  15313. if ( glColorRenderbuffer ) gl.deleteRenderbuffer( glColorRenderbuffer );
  15314. if ( glDepthRenderbuffer ) gl.deleteRenderbuffer( glDepthRenderbuffer );
  15315. glFramebuffer = null;
  15316. glMultisampledFramebuffer = null;
  15317. glColorRenderbuffer = null;
  15318. glDepthRenderbuffer = null;
  15319. glBaseLayer = null;
  15320. glProjLayer = null;
  15321. glBinding = null;
  15322. session = null;
  15323. //
  15324. animation.stop();
  15325. scope.isPresenting = false;
  15326. scope.dispatchEvent( { type: 'sessionend' } );
  15327. }
  15328. this.setFramebufferScaleFactor = function ( value ) {
  15329. framebufferScaleFactor = value;
  15330. if ( scope.isPresenting === true ) {
  15331. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  15332. }
  15333. };
  15334. this.setReferenceSpaceType = function ( value ) {
  15335. referenceSpaceType = value;
  15336. if ( scope.isPresenting === true ) {
  15337. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  15338. }
  15339. };
  15340. this.getReferenceSpace = function () {
  15341. return referenceSpace;
  15342. };
  15343. this.getBaseLayer = function () {
  15344. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  15345. };
  15346. this.getBinding = function () {
  15347. return glBinding;
  15348. };
  15349. this.getFrame = function () {
  15350. return xrFrame;
  15351. };
  15352. this.getSession = function () {
  15353. return session;
  15354. };
  15355. this.setSession = async function ( value ) {
  15356. session = value;
  15357. if ( session !== null ) {
  15358. session.addEventListener( 'select', onSessionEvent );
  15359. session.addEventListener( 'selectstart', onSessionEvent );
  15360. session.addEventListener( 'selectend', onSessionEvent );
  15361. session.addEventListener( 'squeeze', onSessionEvent );
  15362. session.addEventListener( 'squeezestart', onSessionEvent );
  15363. session.addEventListener( 'squeezeend', onSessionEvent );
  15364. session.addEventListener( 'end', onSessionEnd );
  15365. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  15366. const attributes = gl.getContextAttributes();
  15367. if ( attributes.xrCompatible !== true ) {
  15368. await gl.makeXRCompatible();
  15369. }
  15370. if ( session.renderState.layers === undefined ) {
  15371. const layerInit = {
  15372. antialias: attributes.antialias,
  15373. alpha: attributes.alpha,
  15374. depth: attributes.depth,
  15375. stencil: attributes.stencil,
  15376. framebufferScaleFactor: framebufferScaleFactor
  15377. };
  15378. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  15379. session.updateRenderState( { baseLayer: glBaseLayer } );
  15380. } else if ( gl instanceof WebGLRenderingContext ) {
  15381. // Use old style webgl layer because we can't use MSAA
  15382. // WebGL2 support.
  15383. const layerInit = {
  15384. antialias: true,
  15385. alpha: attributes.alpha,
  15386. depth: attributes.depth,
  15387. stencil: attributes.stencil,
  15388. framebufferScaleFactor: framebufferScaleFactor
  15389. };
  15390. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  15391. session.updateRenderState( { layers: [ glBaseLayer ] } );
  15392. } else {
  15393. isMultisample = attributes.antialias;
  15394. let depthFormat = null;
  15395. if ( attributes.depth ) {
  15396. clearStyle = 256;
  15397. if ( attributes.stencil ) clearStyle |= 1024;
  15398. depthStyle = attributes.stencil ? 33306 : 36096;
  15399. depthFormat = attributes.stencil ? 35056 : 33190;
  15400. }
  15401. const projectionlayerInit = {
  15402. colorFormat: attributes.alpha ? 32856 : 32849,
  15403. depthFormat: depthFormat,
  15404. scaleFactor: framebufferScaleFactor
  15405. };
  15406. glBinding = new XRWebGLBinding( session, gl );
  15407. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  15408. glFramebuffer = gl.createFramebuffer();
  15409. session.updateRenderState( { layers: [ glProjLayer ] } );
  15410. if ( isMultisample ) {
  15411. glMultisampledFramebuffer = gl.createFramebuffer();
  15412. glColorRenderbuffer = gl.createRenderbuffer();
  15413. gl.bindRenderbuffer( 36161, glColorRenderbuffer );
  15414. gl.renderbufferStorageMultisample(
  15415. 36161,
  15416. 4,
  15417. 32856,
  15418. glProjLayer.textureWidth,
  15419. glProjLayer.textureHeight );
  15420. state.bindFramebuffer( 36160, glMultisampledFramebuffer );
  15421. gl.framebufferRenderbuffer( 36160, 36064, 36161, glColorRenderbuffer );
  15422. gl.bindRenderbuffer( 36161, null );
  15423. if ( depthFormat !== null ) {
  15424. glDepthRenderbuffer = gl.createRenderbuffer();
  15425. gl.bindRenderbuffer( 36161, glDepthRenderbuffer );
  15426. gl.renderbufferStorageMultisample( 36161, 4, depthFormat, glProjLayer.textureWidth, glProjLayer.textureHeight );
  15427. gl.framebufferRenderbuffer( 36160, depthStyle, 36161, glDepthRenderbuffer );
  15428. gl.bindRenderbuffer( 36161, null );
  15429. }
  15430. state.bindFramebuffer( 36160, null );
  15431. }
  15432. }
  15433. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  15434. animation.setContext( session );
  15435. animation.start();
  15436. scope.isPresenting = true;
  15437. scope.dispatchEvent( { type: 'sessionstart' } );
  15438. }
  15439. };
  15440. function onInputSourcesChange( event ) {
  15441. const inputSources = session.inputSources;
  15442. // Assign inputSources to available controllers
  15443. for ( let i = 0; i < controllers.length; i ++ ) {
  15444. inputSourcesMap.set( inputSources[ i ], controllers[ i ] );
  15445. }
  15446. // Notify disconnected
  15447. for ( let i = 0; i < event.removed.length; i ++ ) {
  15448. const inputSource = event.removed[ i ];
  15449. const controller = inputSourcesMap.get( inputSource );
  15450. if ( controller ) {
  15451. controller.dispatchEvent( { type: 'disconnected', data: inputSource } );
  15452. inputSourcesMap.delete( inputSource );
  15453. }
  15454. }
  15455. // Notify connected
  15456. for ( let i = 0; i < event.added.length; i ++ ) {
  15457. const inputSource = event.added[ i ];
  15458. const controller = inputSourcesMap.get( inputSource );
  15459. if ( controller ) {
  15460. controller.dispatchEvent( { type: 'connected', data: inputSource } );
  15461. }
  15462. }
  15463. }
  15464. //
  15465. const cameraLPos = new Vector3();
  15466. const cameraRPos = new Vector3();
  15467. /**
  15468. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15469. * the cameras' projection and world matrices have already been set.
  15470. * And that near and far planes are identical for both cameras.
  15471. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15472. */
  15473. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  15474. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  15475. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  15476. const ipd = cameraLPos.distanceTo( cameraRPos );
  15477. const projL = cameraL.projectionMatrix.elements;
  15478. const projR = cameraR.projectionMatrix.elements;
  15479. // VR systems will have identical far and near planes, and
  15480. // most likely identical top and bottom frustum extents.
  15481. // Use the left camera for these values.
  15482. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  15483. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  15484. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  15485. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  15486. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  15487. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  15488. const left = near * leftFov;
  15489. const right = near * rightFov;
  15490. // Calculate the new camera's position offset from the
  15491. // left camera. xOffset should be roughly half `ipd`.
  15492. const zOffset = ipd / ( - leftFov + rightFov );
  15493. const xOffset = zOffset * - leftFov;
  15494. // TODO: Better way to apply this offset?
  15495. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  15496. camera.translateX( xOffset );
  15497. camera.translateZ( zOffset );
  15498. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  15499. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15500. // Find the union of the frustum values of the cameras and scale
  15501. // the values so that the near plane's position does not change in world space,
  15502. // although must now be relative to the new union camera.
  15503. const near2 = near + zOffset;
  15504. const far2 = far + zOffset;
  15505. const left2 = left - xOffset;
  15506. const right2 = right + ( ipd - xOffset );
  15507. const top2 = topFov * far / far2 * near2;
  15508. const bottom2 = bottomFov * far / far2 * near2;
  15509. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  15510. }
  15511. function updateCamera( camera, parent ) {
  15512. if ( parent === null ) {
  15513. camera.matrixWorld.copy( camera.matrix );
  15514. } else {
  15515. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  15516. }
  15517. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15518. }
  15519. this.updateCamera = function ( camera ) {
  15520. if ( session === null ) return;
  15521. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  15522. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  15523. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  15524. // Note that the new renderState won't apply until the next frame. See #18320
  15525. session.updateRenderState( {
  15526. depthNear: cameraVR.near,
  15527. depthFar: cameraVR.far
  15528. } );
  15529. _currentDepthNear = cameraVR.near;
  15530. _currentDepthFar = cameraVR.far;
  15531. }
  15532. const parent = camera.parent;
  15533. const cameras = cameraVR.cameras;
  15534. updateCamera( cameraVR, parent );
  15535. for ( let i = 0; i < cameras.length; i ++ ) {
  15536. updateCamera( cameras[ i ], parent );
  15537. }
  15538. cameraVR.matrixWorld.decompose( cameraVR.position, cameraVR.quaternion, cameraVR.scale );
  15539. // update user camera and its children
  15540. camera.position.copy( cameraVR.position );
  15541. camera.quaternion.copy( cameraVR.quaternion );
  15542. camera.scale.copy( cameraVR.scale );
  15543. camera.matrix.copy( cameraVR.matrix );
  15544. camera.matrixWorld.copy( cameraVR.matrixWorld );
  15545. const children = camera.children;
  15546. for ( let i = 0, l = children.length; i < l; i ++ ) {
  15547. children[ i ].updateMatrixWorld( true );
  15548. }
  15549. // update projection matrix for proper view frustum culling
  15550. if ( cameras.length === 2 ) {
  15551. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  15552. } else {
  15553. // assume single camera setup (AR)
  15554. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  15555. }
  15556. };
  15557. this.getCamera = function () {
  15558. return cameraVR;
  15559. };
  15560. this.getFoveation = function () {
  15561. if ( glProjLayer !== null ) {
  15562. return glProjLayer.fixedFoveation;
  15563. }
  15564. if ( glBaseLayer !== null ) {
  15565. return glBaseLayer.fixedFoveation;
  15566. }
  15567. return undefined;
  15568. };
  15569. this.setFoveation = function ( foveation ) {
  15570. // 0 = no foveation = full resolution
  15571. // 1 = maximum foveation = the edges render at lower resolution
  15572. if ( glProjLayer !== null ) {
  15573. glProjLayer.fixedFoveation = foveation;
  15574. }
  15575. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  15576. glBaseLayer.fixedFoveation = foveation;
  15577. }
  15578. };
  15579. // Animation Loop
  15580. let onAnimationFrameCallback = null;
  15581. function onAnimationFrame( time, frame ) {
  15582. pose = frame.getViewerPose( referenceSpace );
  15583. xrFrame = frame;
  15584. if ( pose !== null ) {
  15585. const views = pose.views;
  15586. if ( glBaseLayer !== null ) {
  15587. state.bindXRFramebuffer( glBaseLayer.framebuffer );
  15588. }
  15589. let cameraVRNeedsUpdate = false;
  15590. // check if it's necessary to rebuild cameraVR's camera list
  15591. if ( views.length !== cameraVR.cameras.length ) {
  15592. cameraVR.cameras.length = 0;
  15593. cameraVRNeedsUpdate = true;
  15594. }
  15595. for ( let i = 0; i < views.length; i ++ ) {
  15596. const view = views[ i ];
  15597. let viewport = null;
  15598. if ( glBaseLayer !== null ) {
  15599. viewport = glBaseLayer.getViewport( view );
  15600. } else {
  15601. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  15602. state.bindXRFramebuffer( glFramebuffer );
  15603. if ( glSubImage.depthStencilTexture !== undefined ) {
  15604. gl.framebufferTexture2D( 36160, depthStyle, 3553, glSubImage.depthStencilTexture, 0 );
  15605. }
  15606. gl.framebufferTexture2D( 36160, 36064, 3553, glSubImage.colorTexture, 0 );
  15607. viewport = glSubImage.viewport;
  15608. }
  15609. const camera = cameras[ i ];
  15610. camera.matrix.fromArray( view.transform.matrix );
  15611. camera.projectionMatrix.fromArray( view.projectionMatrix );
  15612. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  15613. if ( i === 0 ) {
  15614. cameraVR.matrix.copy( camera.matrix );
  15615. }
  15616. if ( cameraVRNeedsUpdate === true ) {
  15617. cameraVR.cameras.push( camera );
  15618. }
  15619. }
  15620. if ( isMultisample ) {
  15621. state.bindXRFramebuffer( glMultisampledFramebuffer );
  15622. if ( clearStyle !== null ) gl.clear( clearStyle );
  15623. }
  15624. }
  15625. //
  15626. const inputSources = session.inputSources;
  15627. for ( let i = 0; i < controllers.length; i ++ ) {
  15628. const controller = controllers[ i ];
  15629. const inputSource = inputSources[ i ];
  15630. controller.update( inputSource, frame, referenceSpace );
  15631. }
  15632. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  15633. if ( isMultisample ) {
  15634. const width = glProjLayer.textureWidth;
  15635. const height = glProjLayer.textureHeight;
  15636. state.bindFramebuffer( 36008, glMultisampledFramebuffer );
  15637. state.bindFramebuffer( 36009, glFramebuffer );
  15638. // Invalidate the depth here to avoid flush of the depth data to main memory.
  15639. gl.invalidateFramebuffer( 36008, [ depthStyle ] );
  15640. gl.invalidateFramebuffer( 36009, [ depthStyle ] );
  15641. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, 16384, 9728 );
  15642. // Invalidate the MSAA buffer because it's not needed anymore.
  15643. gl.invalidateFramebuffer( 36008, [ 36064 ] );
  15644. state.bindFramebuffer( 36008, null );
  15645. state.bindFramebuffer( 36009, null );
  15646. state.bindFramebuffer( 36160, glMultisampledFramebuffer );
  15647. }
  15648. xrFrame = null;
  15649. }
  15650. const animation = new WebGLAnimation();
  15651. animation.setAnimationLoop( onAnimationFrame );
  15652. this.setAnimationLoop = function ( callback ) {
  15653. onAnimationFrameCallback = callback;
  15654. };
  15655. this.dispose = function () {};
  15656. }
  15657. }
  15658. function WebGLMaterials( properties ) {
  15659. function refreshFogUniforms( uniforms, fog ) {
  15660. uniforms.fogColor.value.copy( fog.color );
  15661. if ( fog.isFog ) {
  15662. uniforms.fogNear.value = fog.near;
  15663. uniforms.fogFar.value = fog.far;
  15664. } else if ( fog.isFogExp2 ) {
  15665. uniforms.fogDensity.value = fog.density;
  15666. }
  15667. }
  15668. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  15669. if ( material.isMeshBasicMaterial ) {
  15670. refreshUniformsCommon( uniforms, material );
  15671. } else if ( material.isMeshLambertMaterial ) {
  15672. refreshUniformsCommon( uniforms, material );
  15673. refreshUniformsLambert( uniforms, material );
  15674. } else if ( material.isMeshToonMaterial ) {
  15675. refreshUniformsCommon( uniforms, material );
  15676. refreshUniformsToon( uniforms, material );
  15677. } else if ( material.isMeshPhongMaterial ) {
  15678. refreshUniformsCommon( uniforms, material );
  15679. refreshUniformsPhong( uniforms, material );
  15680. } else if ( material.isMeshStandardMaterial ) {
  15681. refreshUniformsCommon( uniforms, material );
  15682. if ( material.isMeshPhysicalMaterial ) {
  15683. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  15684. } else {
  15685. refreshUniformsStandard( uniforms, material );
  15686. }
  15687. } else if ( material.isMeshMatcapMaterial ) {
  15688. refreshUniformsCommon( uniforms, material );
  15689. refreshUniformsMatcap( uniforms, material );
  15690. } else if ( material.isMeshDepthMaterial ) {
  15691. refreshUniformsCommon( uniforms, material );
  15692. refreshUniformsDepth( uniforms, material );
  15693. } else if ( material.isMeshDistanceMaterial ) {
  15694. refreshUniformsCommon( uniforms, material );
  15695. refreshUniformsDistance( uniforms, material );
  15696. } else if ( material.isMeshNormalMaterial ) {
  15697. refreshUniformsCommon( uniforms, material );
  15698. refreshUniformsNormal( uniforms, material );
  15699. } else if ( material.isLineBasicMaterial ) {
  15700. refreshUniformsLine( uniforms, material );
  15701. if ( material.isLineDashedMaterial ) {
  15702. refreshUniformsDash( uniforms, material );
  15703. }
  15704. } else if ( material.isPointsMaterial ) {
  15705. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  15706. } else if ( material.isSpriteMaterial ) {
  15707. refreshUniformsSprites( uniforms, material );
  15708. } else if ( material.isShadowMaterial ) {
  15709. uniforms.color.value.copy( material.color );
  15710. uniforms.opacity.value = material.opacity;
  15711. } else if ( material.isShaderMaterial ) {
  15712. material.uniformsNeedUpdate = false; // #15581
  15713. }
  15714. }
  15715. function refreshUniformsCommon( uniforms, material ) {
  15716. uniforms.opacity.value = material.opacity;
  15717. if ( material.color ) {
  15718. uniforms.diffuse.value.copy( material.color );
  15719. }
  15720. if ( material.emissive ) {
  15721. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  15722. }
  15723. if ( material.map ) {
  15724. uniforms.map.value = material.map;
  15725. }
  15726. if ( material.alphaMap ) {
  15727. uniforms.alphaMap.value = material.alphaMap;
  15728. }
  15729. if ( material.specularMap ) {
  15730. uniforms.specularMap.value = material.specularMap;
  15731. }
  15732. if ( material.alphaTest > 0 ) {
  15733. uniforms.alphaTest.value = material.alphaTest;
  15734. }
  15735. const envMap = properties.get( material ).envMap;
  15736. if ( envMap ) {
  15737. uniforms.envMap.value = envMap;
  15738. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  15739. uniforms.reflectivity.value = material.reflectivity;
  15740. uniforms.ior.value = material.ior;
  15741. uniforms.refractionRatio.value = material.refractionRatio;
  15742. const maxMipLevel = properties.get( envMap ).__maxMipLevel;
  15743. if ( maxMipLevel !== undefined ) {
  15744. uniforms.maxMipLevel.value = maxMipLevel;
  15745. }
  15746. }
  15747. if ( material.lightMap ) {
  15748. uniforms.lightMap.value = material.lightMap;
  15749. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  15750. }
  15751. if ( material.aoMap ) {
  15752. uniforms.aoMap.value = material.aoMap;
  15753. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15754. }
  15755. // uv repeat and offset setting priorities
  15756. // 1. color map
  15757. // 2. specular map
  15758. // 3. displacementMap map
  15759. // 4. normal map
  15760. // 5. bump map
  15761. // 6. roughnessMap map
  15762. // 7. metalnessMap map
  15763. // 8. alphaMap map
  15764. // 9. emissiveMap map
  15765. // 10. clearcoat map
  15766. // 11. clearcoat normal map
  15767. // 12. clearcoat roughnessMap map
  15768. // 13. specular intensity map
  15769. // 14. specular tint map
  15770. // 15. transmission map
  15771. // 16. thickness map
  15772. let uvScaleMap;
  15773. if ( material.map ) {
  15774. uvScaleMap = material.map;
  15775. } else if ( material.specularMap ) {
  15776. uvScaleMap = material.specularMap;
  15777. } else if ( material.displacementMap ) {
  15778. uvScaleMap = material.displacementMap;
  15779. } else if ( material.normalMap ) {
  15780. uvScaleMap = material.normalMap;
  15781. } else if ( material.bumpMap ) {
  15782. uvScaleMap = material.bumpMap;
  15783. } else if ( material.roughnessMap ) {
  15784. uvScaleMap = material.roughnessMap;
  15785. } else if ( material.metalnessMap ) {
  15786. uvScaleMap = material.metalnessMap;
  15787. } else if ( material.alphaMap ) {
  15788. uvScaleMap = material.alphaMap;
  15789. } else if ( material.emissiveMap ) {
  15790. uvScaleMap = material.emissiveMap;
  15791. } else if ( material.clearcoatMap ) {
  15792. uvScaleMap = material.clearcoatMap;
  15793. } else if ( material.clearcoatNormalMap ) {
  15794. uvScaleMap = material.clearcoatNormalMap;
  15795. } else if ( material.clearcoatRoughnessMap ) {
  15796. uvScaleMap = material.clearcoatRoughnessMap;
  15797. } else if ( material.specularIntensityMap ) {
  15798. uvScaleMap = material.specularIntensityMap;
  15799. } else if ( material.specularTintMap ) {
  15800. uvScaleMap = material.specularTintMap;
  15801. } else if ( material.transmissionMap ) {
  15802. uvScaleMap = material.transmissionMap;
  15803. } else if ( material.thicknessMap ) {
  15804. uvScaleMap = material.thicknessMap;
  15805. }
  15806. if ( uvScaleMap !== undefined ) {
  15807. // backwards compatibility
  15808. if ( uvScaleMap.isWebGLRenderTarget ) {
  15809. uvScaleMap = uvScaleMap.texture;
  15810. }
  15811. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15812. uvScaleMap.updateMatrix();
  15813. }
  15814. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15815. }
  15816. // uv repeat and offset setting priorities for uv2
  15817. // 1. ao map
  15818. // 2. light map
  15819. let uv2ScaleMap;
  15820. if ( material.aoMap ) {
  15821. uv2ScaleMap = material.aoMap;
  15822. } else if ( material.lightMap ) {
  15823. uv2ScaleMap = material.lightMap;
  15824. }
  15825. if ( uv2ScaleMap !== undefined ) {
  15826. // backwards compatibility
  15827. if ( uv2ScaleMap.isWebGLRenderTarget ) {
  15828. uv2ScaleMap = uv2ScaleMap.texture;
  15829. }
  15830. if ( uv2ScaleMap.matrixAutoUpdate === true ) {
  15831. uv2ScaleMap.updateMatrix();
  15832. }
  15833. uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );
  15834. }
  15835. }
  15836. function refreshUniformsLine( uniforms, material ) {
  15837. uniforms.diffuse.value.copy( material.color );
  15838. uniforms.opacity.value = material.opacity;
  15839. }
  15840. function refreshUniformsDash( uniforms, material ) {
  15841. uniforms.dashSize.value = material.dashSize;
  15842. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15843. uniforms.scale.value = material.scale;
  15844. }
  15845. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  15846. uniforms.diffuse.value.copy( material.color );
  15847. uniforms.opacity.value = material.opacity;
  15848. uniforms.size.value = material.size * pixelRatio;
  15849. uniforms.scale.value = height * 0.5;
  15850. if ( material.map ) {
  15851. uniforms.map.value = material.map;
  15852. }
  15853. if ( material.alphaMap ) {
  15854. uniforms.alphaMap.value = material.alphaMap;
  15855. }
  15856. if ( material.alphaTest > 0 ) {
  15857. uniforms.alphaTest.value = material.alphaTest;
  15858. }
  15859. // uv repeat and offset setting priorities
  15860. // 1. color map
  15861. // 2. alpha map
  15862. let uvScaleMap;
  15863. if ( material.map ) {
  15864. uvScaleMap = material.map;
  15865. } else if ( material.alphaMap ) {
  15866. uvScaleMap = material.alphaMap;
  15867. }
  15868. if ( uvScaleMap !== undefined ) {
  15869. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15870. uvScaleMap.updateMatrix();
  15871. }
  15872. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15873. }
  15874. }
  15875. function refreshUniformsSprites( uniforms, material ) {
  15876. uniforms.diffuse.value.copy( material.color );
  15877. uniforms.opacity.value = material.opacity;
  15878. uniforms.rotation.value = material.rotation;
  15879. if ( material.map ) {
  15880. uniforms.map.value = material.map;
  15881. }
  15882. if ( material.alphaMap ) {
  15883. uniforms.alphaMap.value = material.alphaMap;
  15884. }
  15885. if ( material.alphaTest > 0 ) {
  15886. uniforms.alphaTest.value = material.alphaTest;
  15887. }
  15888. // uv repeat and offset setting priorities
  15889. // 1. color map
  15890. // 2. alpha map
  15891. let uvScaleMap;
  15892. if ( material.map ) {
  15893. uvScaleMap = material.map;
  15894. } else if ( material.alphaMap ) {
  15895. uvScaleMap = material.alphaMap;
  15896. }
  15897. if ( uvScaleMap !== undefined ) {
  15898. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15899. uvScaleMap.updateMatrix();
  15900. }
  15901. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15902. }
  15903. }
  15904. function refreshUniformsLambert( uniforms, material ) {
  15905. if ( material.emissiveMap ) {
  15906. uniforms.emissiveMap.value = material.emissiveMap;
  15907. }
  15908. }
  15909. function refreshUniformsPhong( uniforms, material ) {
  15910. uniforms.specular.value.copy( material.specular );
  15911. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  15912. if ( material.emissiveMap ) {
  15913. uniforms.emissiveMap.value = material.emissiveMap;
  15914. }
  15915. if ( material.bumpMap ) {
  15916. uniforms.bumpMap.value = material.bumpMap;
  15917. uniforms.bumpScale.value = material.bumpScale;
  15918. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  15919. }
  15920. if ( material.normalMap ) {
  15921. uniforms.normalMap.value = material.normalMap;
  15922. uniforms.normalScale.value.copy( material.normalScale );
  15923. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  15924. }
  15925. if ( material.displacementMap ) {
  15926. uniforms.displacementMap.value = material.displacementMap;
  15927. uniforms.displacementScale.value = material.displacementScale;
  15928. uniforms.displacementBias.value = material.displacementBias;
  15929. }
  15930. }
  15931. function refreshUniformsToon( uniforms, material ) {
  15932. if ( material.gradientMap ) {
  15933. uniforms.gradientMap.value = material.gradientMap;
  15934. }
  15935. if ( material.emissiveMap ) {
  15936. uniforms.emissiveMap.value = material.emissiveMap;
  15937. }
  15938. if ( material.bumpMap ) {
  15939. uniforms.bumpMap.value = material.bumpMap;
  15940. uniforms.bumpScale.value = material.bumpScale;
  15941. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  15942. }
  15943. if ( material.normalMap ) {
  15944. uniforms.normalMap.value = material.normalMap;
  15945. uniforms.normalScale.value.copy( material.normalScale );
  15946. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  15947. }
  15948. if ( material.displacementMap ) {
  15949. uniforms.displacementMap.value = material.displacementMap;
  15950. uniforms.displacementScale.value = material.displacementScale;
  15951. uniforms.displacementBias.value = material.displacementBias;
  15952. }
  15953. }
  15954. function refreshUniformsStandard( uniforms, material ) {
  15955. uniforms.roughness.value = material.roughness;
  15956. uniforms.metalness.value = material.metalness;
  15957. if ( material.roughnessMap ) {
  15958. uniforms.roughnessMap.value = material.roughnessMap;
  15959. }
  15960. if ( material.metalnessMap ) {
  15961. uniforms.metalnessMap.value = material.metalnessMap;
  15962. }
  15963. if ( material.emissiveMap ) {
  15964. uniforms.emissiveMap.value = material.emissiveMap;
  15965. }
  15966. if ( material.bumpMap ) {
  15967. uniforms.bumpMap.value = material.bumpMap;
  15968. uniforms.bumpScale.value = material.bumpScale;
  15969. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  15970. }
  15971. if ( material.normalMap ) {
  15972. uniforms.normalMap.value = material.normalMap;
  15973. uniforms.normalScale.value.copy( material.normalScale );
  15974. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  15975. }
  15976. if ( material.displacementMap ) {
  15977. uniforms.displacementMap.value = material.displacementMap;
  15978. uniforms.displacementScale.value = material.displacementScale;
  15979. uniforms.displacementBias.value = material.displacementBias;
  15980. }
  15981. const envMap = properties.get( material ).envMap;
  15982. if ( envMap ) {
  15983. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15984. uniforms.envMapIntensity.value = material.envMapIntensity;
  15985. }
  15986. }
  15987. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  15988. refreshUniformsStandard( uniforms, material );
  15989. uniforms.ior.value = material.ior; // also part of uniforms common
  15990. if ( material.sheenTint ) uniforms.sheenTint.value.copy( material.sheenTint );
  15991. if ( material.clearcoat > 0 ) {
  15992. uniforms.clearcoat.value = material.clearcoat;
  15993. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  15994. if ( material.clearcoatMap ) {
  15995. uniforms.clearcoatMap.value = material.clearcoatMap;
  15996. }
  15997. if ( material.clearcoatRoughnessMap ) {
  15998. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  15999. }
  16000. if ( material.clearcoatNormalMap ) {
  16001. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  16002. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  16003. if ( material.side === BackSide ) {
  16004. uniforms.clearcoatNormalScale.value.negate();
  16005. }
  16006. }
  16007. }
  16008. if ( material.transmission > 0 ) {
  16009. uniforms.transmission.value = material.transmission;
  16010. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  16011. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  16012. if ( material.transmissionMap ) {
  16013. uniforms.transmissionMap.value = material.transmissionMap;
  16014. }
  16015. uniforms.thickness.value = material.thickness;
  16016. if ( material.thicknessMap ) {
  16017. uniforms.thicknessMap.value = material.thicknessMap;
  16018. }
  16019. uniforms.attenuationDistance.value = material.attenuationDistance;
  16020. uniforms.attenuationTint.value.copy( material.attenuationTint );
  16021. }
  16022. uniforms.specularIntensity.value = material.specularIntensity;
  16023. uniforms.specularTint.value.copy( material.specularTint );
  16024. if ( material.specularIntensityMap ) {
  16025. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  16026. }
  16027. if ( material.specularTintMap ) {
  16028. uniforms.specularTintMap.value = material.specularTintMap;
  16029. }
  16030. }
  16031. function refreshUniformsMatcap( uniforms, material ) {
  16032. if ( material.matcap ) {
  16033. uniforms.matcap.value = material.matcap;
  16034. }
  16035. if ( material.bumpMap ) {
  16036. uniforms.bumpMap.value = material.bumpMap;
  16037. uniforms.bumpScale.value = material.bumpScale;
  16038. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  16039. }
  16040. if ( material.normalMap ) {
  16041. uniforms.normalMap.value = material.normalMap;
  16042. uniforms.normalScale.value.copy( material.normalScale );
  16043. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  16044. }
  16045. if ( material.displacementMap ) {
  16046. uniforms.displacementMap.value = material.displacementMap;
  16047. uniforms.displacementScale.value = material.displacementScale;
  16048. uniforms.displacementBias.value = material.displacementBias;
  16049. }
  16050. }
  16051. function refreshUniformsDepth( uniforms, material ) {
  16052. if ( material.displacementMap ) {
  16053. uniforms.displacementMap.value = material.displacementMap;
  16054. uniforms.displacementScale.value = material.displacementScale;
  16055. uniforms.displacementBias.value = material.displacementBias;
  16056. }
  16057. }
  16058. function refreshUniformsDistance( uniforms, material ) {
  16059. if ( material.displacementMap ) {
  16060. uniforms.displacementMap.value = material.displacementMap;
  16061. uniforms.displacementScale.value = material.displacementScale;
  16062. uniforms.displacementBias.value = material.displacementBias;
  16063. }
  16064. uniforms.referencePosition.value.copy( material.referencePosition );
  16065. uniforms.nearDistance.value = material.nearDistance;
  16066. uniforms.farDistance.value = material.farDistance;
  16067. }
  16068. function refreshUniformsNormal( uniforms, material ) {
  16069. if ( material.bumpMap ) {
  16070. uniforms.bumpMap.value = material.bumpMap;
  16071. uniforms.bumpScale.value = material.bumpScale;
  16072. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  16073. }
  16074. if ( material.normalMap ) {
  16075. uniforms.normalMap.value = material.normalMap;
  16076. uniforms.normalScale.value.copy( material.normalScale );
  16077. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  16078. }
  16079. if ( material.displacementMap ) {
  16080. uniforms.displacementMap.value = material.displacementMap;
  16081. uniforms.displacementScale.value = material.displacementScale;
  16082. uniforms.displacementBias.value = material.displacementBias;
  16083. }
  16084. }
  16085. return {
  16086. refreshFogUniforms: refreshFogUniforms,
  16087. refreshMaterialUniforms: refreshMaterialUniforms
  16088. };
  16089. }
  16090. function createCanvasElement() {
  16091. const canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  16092. canvas.style.display = 'block';
  16093. return canvas;
  16094. }
  16095. function WebGLRenderer( parameters = {} ) {
  16096. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  16097. _context = parameters.context !== undefined ? parameters.context : null,
  16098. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  16099. _depth = parameters.depth !== undefined ? parameters.depth : true,
  16100. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  16101. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  16102. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  16103. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  16104. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  16105. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  16106. let currentRenderList = null;
  16107. let currentRenderState = null;
  16108. // render() can be called from within a callback triggered by another render.
  16109. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  16110. const renderListStack = [];
  16111. const renderStateStack = [];
  16112. // public properties
  16113. this.domElement = _canvas;
  16114. // Debug configuration container
  16115. this.debug = {
  16116. /**
  16117. * Enables error checking and reporting when shader programs are being compiled
  16118. * @type {boolean}
  16119. */
  16120. checkShaderErrors: true
  16121. };
  16122. // clearing
  16123. this.autoClear = true;
  16124. this.autoClearColor = true;
  16125. this.autoClearDepth = true;
  16126. this.autoClearStencil = true;
  16127. // scene graph
  16128. this.sortObjects = true;
  16129. // user-defined clipping
  16130. this.clippingPlanes = [];
  16131. this.localClippingEnabled = false;
  16132. // physically based shading
  16133. this.gammaFactor = 2.0; // for backwards compatibility
  16134. this.outputEncoding = LinearEncoding;
  16135. // physical lights
  16136. this.physicallyCorrectLights = false;
  16137. // tone mapping
  16138. this.toneMapping = NoToneMapping;
  16139. this.toneMappingExposure = 1.0;
  16140. // internal properties
  16141. const _this = this;
  16142. let _isContextLost = false;
  16143. // internal state cache
  16144. let _currentActiveCubeFace = 0;
  16145. let _currentActiveMipmapLevel = 0;
  16146. let _currentRenderTarget = null;
  16147. let _currentMaterialId = - 1;
  16148. let _currentCamera = null;
  16149. const _currentViewport = new Vector4();
  16150. const _currentScissor = new Vector4();
  16151. let _currentScissorTest = null;
  16152. //
  16153. let _width = _canvas.width;
  16154. let _height = _canvas.height;
  16155. let _pixelRatio = 1;
  16156. let _opaqueSort = null;
  16157. let _transparentSort = null;
  16158. const _viewport = new Vector4( 0, 0, _width, _height );
  16159. const _scissor = new Vector4( 0, 0, _width, _height );
  16160. let _scissorTest = false;
  16161. //
  16162. const _currentDrawBuffers = [];
  16163. // frustum
  16164. const _frustum = new Frustum();
  16165. // clipping
  16166. let _clippingEnabled = false;
  16167. let _localClippingEnabled = false;
  16168. // transmission
  16169. let _transmissionRenderTarget = null;
  16170. // camera matrices cache
  16171. const _projScreenMatrix = new Matrix4();
  16172. const _vector3 = new Vector3();
  16173. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  16174. function getTargetPixelRatio() {
  16175. return _currentRenderTarget === null ? _pixelRatio : 1;
  16176. }
  16177. // initialize
  16178. let _gl = _context;
  16179. function getContext( contextNames, contextAttributes ) {
  16180. for ( let i = 0; i < contextNames.length; i ++ ) {
  16181. const contextName = contextNames[ i ];
  16182. const context = _canvas.getContext( contextName, contextAttributes );
  16183. if ( context !== null ) return context;
  16184. }
  16185. return null;
  16186. }
  16187. try {
  16188. const contextAttributes = {
  16189. alpha: _alpha,
  16190. depth: _depth,
  16191. stencil: _stencil,
  16192. antialias: _antialias,
  16193. premultipliedAlpha: _premultipliedAlpha,
  16194. preserveDrawingBuffer: _preserveDrawingBuffer,
  16195. powerPreference: _powerPreference,
  16196. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  16197. };
  16198. // event listeners must be registered before WebGL context is created, see #12753
  16199. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  16200. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  16201. if ( _gl === null ) {
  16202. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  16203. if ( _this.isWebGL1Renderer === true ) {
  16204. contextNames.shift();
  16205. }
  16206. _gl = getContext( contextNames, contextAttributes );
  16207. if ( _gl === null ) {
  16208. if ( getContext( contextNames ) ) {
  16209. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  16210. } else {
  16211. throw new Error( 'Error creating WebGL context.' );
  16212. }
  16213. }
  16214. }
  16215. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  16216. if ( _gl.getShaderPrecisionFormat === undefined ) {
  16217. _gl.getShaderPrecisionFormat = function () {
  16218. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  16219. };
  16220. }
  16221. } catch ( error ) {
  16222. console.error( 'THREE.WebGLRenderer: ' + error.message );
  16223. throw error;
  16224. }
  16225. let extensions, capabilities, state, info;
  16226. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  16227. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  16228. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  16229. let utils, bindingStates;
  16230. function initGLContext() {
  16231. extensions = new WebGLExtensions( _gl );
  16232. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  16233. extensions.init( capabilities );
  16234. utils = new WebGLUtils( _gl, extensions, capabilities );
  16235. state = new WebGLState( _gl, extensions, capabilities );
  16236. _currentDrawBuffers[ 0 ] = 1029;
  16237. info = new WebGLInfo( _gl );
  16238. properties = new WebGLProperties();
  16239. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  16240. cubemaps = new WebGLCubeMaps( _this );
  16241. cubeuvmaps = new WebGLCubeUVMaps( _this );
  16242. attributes = new WebGLAttributes( _gl, capabilities );
  16243. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  16244. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  16245. objects = new WebGLObjects( _gl, geometries, attributes, info );
  16246. morphtargets = new WebGLMorphtargets( _gl );
  16247. clipping = new WebGLClipping( properties );
  16248. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  16249. materials = new WebGLMaterials( properties );
  16250. renderLists = new WebGLRenderLists( properties );
  16251. renderStates = new WebGLRenderStates( extensions, capabilities );
  16252. background = new WebGLBackground( _this, cubemaps, state, objects, _premultipliedAlpha );
  16253. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  16254. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  16255. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  16256. info.programs = programCache.programs;
  16257. _this.capabilities = capabilities;
  16258. _this.extensions = extensions;
  16259. _this.properties = properties;
  16260. _this.renderLists = renderLists;
  16261. _this.shadowMap = shadowMap;
  16262. _this.state = state;
  16263. _this.info = info;
  16264. }
  16265. initGLContext();
  16266. // xr
  16267. const xr = new WebXRManager( _this, _gl );
  16268. this.xr = xr;
  16269. // API
  16270. this.getContext = function () {
  16271. return _gl;
  16272. };
  16273. this.getContextAttributes = function () {
  16274. return _gl.getContextAttributes();
  16275. };
  16276. this.forceContextLoss = function () {
  16277. const extension = extensions.get( 'WEBGL_lose_context' );
  16278. if ( extension ) extension.loseContext();
  16279. };
  16280. this.forceContextRestore = function () {
  16281. const extension = extensions.get( 'WEBGL_lose_context' );
  16282. if ( extension ) extension.restoreContext();
  16283. };
  16284. this.getPixelRatio = function () {
  16285. return _pixelRatio;
  16286. };
  16287. this.setPixelRatio = function ( value ) {
  16288. if ( value === undefined ) return;
  16289. _pixelRatio = value;
  16290. this.setSize( _width, _height, false );
  16291. };
  16292. this.getSize = function ( target ) {
  16293. return target.set( _width, _height );
  16294. };
  16295. this.setSize = function ( width, height, updateStyle ) {
  16296. if ( xr.isPresenting ) {
  16297. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  16298. return;
  16299. }
  16300. _width = width;
  16301. _height = height;
  16302. _canvas.width = Math.floor( width * _pixelRatio );
  16303. _canvas.height = Math.floor( height * _pixelRatio );
  16304. if ( updateStyle !== false ) {
  16305. _canvas.style.width = width + 'px';
  16306. _canvas.style.height = height + 'px';
  16307. }
  16308. this.setViewport( 0, 0, width, height );
  16309. };
  16310. this.getDrawingBufferSize = function ( target ) {
  16311. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  16312. };
  16313. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  16314. _width = width;
  16315. _height = height;
  16316. _pixelRatio = pixelRatio;
  16317. _canvas.width = Math.floor( width * pixelRatio );
  16318. _canvas.height = Math.floor( height * pixelRatio );
  16319. this.setViewport( 0, 0, width, height );
  16320. };
  16321. this.getCurrentViewport = function ( target ) {
  16322. return target.copy( _currentViewport );
  16323. };
  16324. this.getViewport = function ( target ) {
  16325. return target.copy( _viewport );
  16326. };
  16327. this.setViewport = function ( x, y, width, height ) {
  16328. if ( x.isVector4 ) {
  16329. _viewport.set( x.x, x.y, x.z, x.w );
  16330. } else {
  16331. _viewport.set( x, y, width, height );
  16332. }
  16333. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  16334. };
  16335. this.getScissor = function ( target ) {
  16336. return target.copy( _scissor );
  16337. };
  16338. this.setScissor = function ( x, y, width, height ) {
  16339. if ( x.isVector4 ) {
  16340. _scissor.set( x.x, x.y, x.z, x.w );
  16341. } else {
  16342. _scissor.set( x, y, width, height );
  16343. }
  16344. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  16345. };
  16346. this.getScissorTest = function () {
  16347. return _scissorTest;
  16348. };
  16349. this.setScissorTest = function ( boolean ) {
  16350. state.setScissorTest( _scissorTest = boolean );
  16351. };
  16352. this.setOpaqueSort = function ( method ) {
  16353. _opaqueSort = method;
  16354. };
  16355. this.setTransparentSort = function ( method ) {
  16356. _transparentSort = method;
  16357. };
  16358. // Clearing
  16359. this.getClearColor = function ( target ) {
  16360. return target.copy( background.getClearColor() );
  16361. };
  16362. this.setClearColor = function () {
  16363. background.setClearColor.apply( background, arguments );
  16364. };
  16365. this.getClearAlpha = function () {
  16366. return background.getClearAlpha();
  16367. };
  16368. this.setClearAlpha = function () {
  16369. background.setClearAlpha.apply( background, arguments );
  16370. };
  16371. this.clear = function ( color, depth, stencil ) {
  16372. let bits = 0;
  16373. if ( color === undefined || color ) bits |= 16384;
  16374. if ( depth === undefined || depth ) bits |= 256;
  16375. if ( stencil === undefined || stencil ) bits |= 1024;
  16376. _gl.clear( bits );
  16377. };
  16378. this.clearColor = function () {
  16379. this.clear( true, false, false );
  16380. };
  16381. this.clearDepth = function () {
  16382. this.clear( false, true, false );
  16383. };
  16384. this.clearStencil = function () {
  16385. this.clear( false, false, true );
  16386. };
  16387. //
  16388. this.dispose = function () {
  16389. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  16390. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  16391. renderLists.dispose();
  16392. renderStates.dispose();
  16393. properties.dispose();
  16394. cubemaps.dispose();
  16395. cubeuvmaps.dispose();
  16396. objects.dispose();
  16397. bindingStates.dispose();
  16398. xr.dispose();
  16399. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  16400. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  16401. if ( _transmissionRenderTarget ) {
  16402. _transmissionRenderTarget.dispose();
  16403. _transmissionRenderTarget = null;
  16404. }
  16405. animation.stop();
  16406. };
  16407. // Events
  16408. function onContextLost( event ) {
  16409. event.preventDefault();
  16410. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  16411. _isContextLost = true;
  16412. }
  16413. function onContextRestore( /* event */ ) {
  16414. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  16415. _isContextLost = false;
  16416. const infoAutoReset = info.autoReset;
  16417. const shadowMapEnabled = shadowMap.enabled;
  16418. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  16419. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  16420. const shadowMapType = shadowMap.type;
  16421. initGLContext();
  16422. info.autoReset = infoAutoReset;
  16423. shadowMap.enabled = shadowMapEnabled;
  16424. shadowMap.autoUpdate = shadowMapAutoUpdate;
  16425. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  16426. shadowMap.type = shadowMapType;
  16427. }
  16428. function onMaterialDispose( event ) {
  16429. const material = event.target;
  16430. material.removeEventListener( 'dispose', onMaterialDispose );
  16431. deallocateMaterial( material );
  16432. }
  16433. // Buffer deallocation
  16434. function deallocateMaterial( material ) {
  16435. releaseMaterialProgramReferences( material );
  16436. properties.remove( material );
  16437. }
  16438. function releaseMaterialProgramReferences( material ) {
  16439. const programs = properties.get( material ).programs;
  16440. if ( programs !== undefined ) {
  16441. programs.forEach( function ( program ) {
  16442. programCache.releaseProgram( program );
  16443. } );
  16444. }
  16445. }
  16446. // Buffer rendering
  16447. function renderObjectImmediate( object, program ) {
  16448. object.render( function ( object ) {
  16449. _this.renderBufferImmediate( object, program );
  16450. } );
  16451. }
  16452. this.renderBufferImmediate = function ( object, program ) {
  16453. bindingStates.initAttributes();
  16454. const buffers = properties.get( object );
  16455. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  16456. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  16457. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  16458. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  16459. const programAttributes = program.getAttributes();
  16460. if ( object.hasPositions ) {
  16461. _gl.bindBuffer( 34962, buffers.position );
  16462. _gl.bufferData( 34962, object.positionArray, 35048 );
  16463. bindingStates.enableAttribute( programAttributes.position.location );
  16464. _gl.vertexAttribPointer( programAttributes.position.location, 3, 5126, false, 0, 0 );
  16465. }
  16466. if ( object.hasNormals ) {
  16467. _gl.bindBuffer( 34962, buffers.normal );
  16468. _gl.bufferData( 34962, object.normalArray, 35048 );
  16469. bindingStates.enableAttribute( programAttributes.normal.location );
  16470. _gl.vertexAttribPointer( programAttributes.normal.location, 3, 5126, false, 0, 0 );
  16471. }
  16472. if ( object.hasUvs ) {
  16473. _gl.bindBuffer( 34962, buffers.uv );
  16474. _gl.bufferData( 34962, object.uvArray, 35048 );
  16475. bindingStates.enableAttribute( programAttributes.uv.location );
  16476. _gl.vertexAttribPointer( programAttributes.uv.location, 2, 5126, false, 0, 0 );
  16477. }
  16478. if ( object.hasColors ) {
  16479. _gl.bindBuffer( 34962, buffers.color );
  16480. _gl.bufferData( 34962, object.colorArray, 35048 );
  16481. bindingStates.enableAttribute( programAttributes.color.location );
  16482. _gl.vertexAttribPointer( programAttributes.color.location, 3, 5126, false, 0, 0 );
  16483. }
  16484. bindingStates.disableUnusedAttributes();
  16485. _gl.drawArrays( 4, 0, object.count );
  16486. object.count = 0;
  16487. };
  16488. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  16489. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  16490. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  16491. const program = setProgram( camera, scene, material, object );
  16492. state.setMaterial( material, frontFaceCW );
  16493. //
  16494. let index = geometry.index;
  16495. const position = geometry.attributes.position;
  16496. //
  16497. if ( index === null ) {
  16498. if ( position === undefined || position.count === 0 ) return;
  16499. } else if ( index.count === 0 ) {
  16500. return;
  16501. }
  16502. //
  16503. let rangeFactor = 1;
  16504. if ( material.wireframe === true ) {
  16505. index = geometries.getWireframeAttribute( geometry );
  16506. rangeFactor = 2;
  16507. }
  16508. if ( geometry.morphAttributes.position !== undefined || geometry.morphAttributes.normal !== undefined ) {
  16509. morphtargets.update( object, geometry, material, program );
  16510. }
  16511. bindingStates.setup( object, material, program, geometry, index );
  16512. let attribute;
  16513. let renderer = bufferRenderer;
  16514. if ( index !== null ) {
  16515. attribute = attributes.get( index );
  16516. renderer = indexedBufferRenderer;
  16517. renderer.setIndex( attribute );
  16518. }
  16519. //
  16520. const dataCount = ( index !== null ) ? index.count : position.count;
  16521. const rangeStart = geometry.drawRange.start * rangeFactor;
  16522. const rangeCount = geometry.drawRange.count * rangeFactor;
  16523. const groupStart = group !== null ? group.start * rangeFactor : 0;
  16524. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  16525. const drawStart = Math.max( rangeStart, groupStart );
  16526. const drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  16527. const drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  16528. if ( drawCount === 0 ) return;
  16529. //
  16530. if ( object.isMesh ) {
  16531. if ( material.wireframe === true ) {
  16532. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  16533. renderer.setMode( 1 );
  16534. } else {
  16535. renderer.setMode( 4 );
  16536. }
  16537. } else if ( object.isLine ) {
  16538. let lineWidth = material.linewidth;
  16539. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  16540. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  16541. if ( object.isLineSegments ) {
  16542. renderer.setMode( 1 );
  16543. } else if ( object.isLineLoop ) {
  16544. renderer.setMode( 2 );
  16545. } else {
  16546. renderer.setMode( 3 );
  16547. }
  16548. } else if ( object.isPoints ) {
  16549. renderer.setMode( 0 );
  16550. } else if ( object.isSprite ) {
  16551. renderer.setMode( 4 );
  16552. }
  16553. if ( object.isInstancedMesh ) {
  16554. renderer.renderInstances( drawStart, drawCount, object.count );
  16555. } else if ( geometry.isInstancedBufferGeometry ) {
  16556. const instanceCount = Math.min( geometry.instanceCount, geometry._maxInstanceCount );
  16557. renderer.renderInstances( drawStart, drawCount, instanceCount );
  16558. } else {
  16559. renderer.render( drawStart, drawCount );
  16560. }
  16561. };
  16562. // Compile
  16563. this.compile = function ( scene, camera ) {
  16564. currentRenderState = renderStates.get( scene );
  16565. currentRenderState.init();
  16566. renderStateStack.push( currentRenderState );
  16567. scene.traverseVisible( function ( object ) {
  16568. if ( object.isLight && object.layers.test( camera.layers ) ) {
  16569. currentRenderState.pushLight( object );
  16570. if ( object.castShadow ) {
  16571. currentRenderState.pushShadow( object );
  16572. }
  16573. }
  16574. } );
  16575. currentRenderState.setupLights( _this.physicallyCorrectLights );
  16576. scene.traverse( function ( object ) {
  16577. const material = object.material;
  16578. if ( material ) {
  16579. if ( Array.isArray( material ) ) {
  16580. for ( let i = 0; i < material.length; i ++ ) {
  16581. const material2 = material[ i ];
  16582. getProgram( material2, scene, object );
  16583. }
  16584. } else {
  16585. getProgram( material, scene, object );
  16586. }
  16587. }
  16588. } );
  16589. renderStateStack.pop();
  16590. currentRenderState = null;
  16591. };
  16592. // Animation Loop
  16593. let onAnimationFrameCallback = null;
  16594. function onAnimationFrame( time ) {
  16595. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  16596. }
  16597. function onXRSessionStart() {
  16598. animation.stop();
  16599. }
  16600. function onXRSessionEnd() {
  16601. animation.start();
  16602. }
  16603. const animation = new WebGLAnimation();
  16604. animation.setAnimationLoop( onAnimationFrame );
  16605. if ( typeof window !== 'undefined' ) animation.setContext( window );
  16606. this.setAnimationLoop = function ( callback ) {
  16607. onAnimationFrameCallback = callback;
  16608. xr.setAnimationLoop( callback );
  16609. ( callback === null ) ? animation.stop() : animation.start();
  16610. };
  16611. xr.addEventListener( 'sessionstart', onXRSessionStart );
  16612. xr.addEventListener( 'sessionend', onXRSessionEnd );
  16613. // Rendering
  16614. this.render = function ( scene, camera ) {
  16615. if ( camera !== undefined && camera.isCamera !== true ) {
  16616. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  16617. return;
  16618. }
  16619. if ( _isContextLost === true ) return;
  16620. // update scene graph
  16621. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  16622. // update camera matrices and frustum
  16623. if ( camera.parent === null ) camera.updateMatrixWorld();
  16624. if ( xr.enabled === true && xr.isPresenting === true ) {
  16625. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  16626. camera = xr.getCamera(); // use XR camera for rendering
  16627. }
  16628. //
  16629. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  16630. currentRenderState = renderStates.get( scene, renderStateStack.length );
  16631. currentRenderState.init();
  16632. renderStateStack.push( currentRenderState );
  16633. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16634. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  16635. _localClippingEnabled = this.localClippingEnabled;
  16636. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  16637. currentRenderList = renderLists.get( scene, renderListStack.length );
  16638. currentRenderList.init();
  16639. renderListStack.push( currentRenderList );
  16640. projectObject( scene, camera, 0, _this.sortObjects );
  16641. currentRenderList.finish();
  16642. if ( _this.sortObjects === true ) {
  16643. currentRenderList.sort( _opaqueSort, _transparentSort );
  16644. }
  16645. //
  16646. if ( _clippingEnabled === true ) clipping.beginShadows();
  16647. const shadowsArray = currentRenderState.state.shadowsArray;
  16648. shadowMap.render( shadowsArray, scene, camera );
  16649. if ( _clippingEnabled === true ) clipping.endShadows();
  16650. //
  16651. if ( this.info.autoReset === true ) this.info.reset();
  16652. //
  16653. background.render( currentRenderList, scene );
  16654. // render scene
  16655. currentRenderState.setupLights( _this.physicallyCorrectLights );
  16656. if ( camera.isArrayCamera ) {
  16657. const cameras = camera.cameras;
  16658. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  16659. const camera2 = cameras[ i ];
  16660. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  16661. }
  16662. } else {
  16663. renderScene( currentRenderList, scene, camera );
  16664. }
  16665. //
  16666. if ( _currentRenderTarget !== null ) {
  16667. // resolve multisample renderbuffers to a single-sample texture if necessary
  16668. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  16669. // Generate mipmap if we're using any kind of mipmap filtering
  16670. textures.updateRenderTargetMipmap( _currentRenderTarget );
  16671. }
  16672. //
  16673. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  16674. // Ensure depth buffer writing is enabled so it can be cleared on next render
  16675. state.buffers.depth.setTest( true );
  16676. state.buffers.depth.setMask( true );
  16677. state.buffers.color.setMask( true );
  16678. state.setPolygonOffset( false );
  16679. // _gl.finish();
  16680. bindingStates.resetDefaultState();
  16681. _currentMaterialId = - 1;
  16682. _currentCamera = null;
  16683. renderStateStack.pop();
  16684. if ( renderStateStack.length > 0 ) {
  16685. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  16686. } else {
  16687. currentRenderState = null;
  16688. }
  16689. renderListStack.pop();
  16690. if ( renderListStack.length > 0 ) {
  16691. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  16692. } else {
  16693. currentRenderList = null;
  16694. }
  16695. };
  16696. function projectObject( object, camera, groupOrder, sortObjects ) {
  16697. if ( object.visible === false ) return;
  16698. const visible = object.layers.test( camera.layers );
  16699. if ( visible ) {
  16700. if ( object.isGroup ) {
  16701. groupOrder = object.renderOrder;
  16702. } else if ( object.isLOD ) {
  16703. if ( object.autoUpdate === true ) object.update( camera );
  16704. } else if ( object.isLight ) {
  16705. currentRenderState.pushLight( object );
  16706. if ( object.castShadow ) {
  16707. currentRenderState.pushShadow( object );
  16708. }
  16709. } else if ( object.isSprite ) {
  16710. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  16711. if ( sortObjects ) {
  16712. _vector3.setFromMatrixPosition( object.matrixWorld )
  16713. .applyMatrix4( _projScreenMatrix );
  16714. }
  16715. const geometry = objects.update( object );
  16716. const material = object.material;
  16717. if ( material.visible ) {
  16718. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  16719. }
  16720. }
  16721. } else if ( object.isImmediateRenderObject ) {
  16722. if ( sortObjects ) {
  16723. _vector3.setFromMatrixPosition( object.matrixWorld )
  16724. .applyMatrix4( _projScreenMatrix );
  16725. }
  16726. currentRenderList.push( object, null, object.material, groupOrder, _vector3.z, null );
  16727. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  16728. if ( object.isSkinnedMesh ) {
  16729. // update skeleton only once in a frame
  16730. if ( object.skeleton.frame !== info.render.frame ) {
  16731. object.skeleton.update();
  16732. object.skeleton.frame = info.render.frame;
  16733. }
  16734. }
  16735. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  16736. if ( sortObjects ) {
  16737. _vector3.setFromMatrixPosition( object.matrixWorld )
  16738. .applyMatrix4( _projScreenMatrix );
  16739. }
  16740. const geometry = objects.update( object );
  16741. const material = object.material;
  16742. if ( Array.isArray( material ) ) {
  16743. const groups = geometry.groups;
  16744. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  16745. const group = groups[ i ];
  16746. const groupMaterial = material[ group.materialIndex ];
  16747. if ( groupMaterial && groupMaterial.visible ) {
  16748. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  16749. }
  16750. }
  16751. } else if ( material.visible ) {
  16752. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  16753. }
  16754. }
  16755. }
  16756. }
  16757. const children = object.children;
  16758. for ( let i = 0, l = children.length; i < l; i ++ ) {
  16759. projectObject( children[ i ], camera, groupOrder, sortObjects );
  16760. }
  16761. }
  16762. function renderScene( currentRenderList, scene, camera, viewport ) {
  16763. const opaqueObjects = currentRenderList.opaque;
  16764. const transmissiveObjects = currentRenderList.transmissive;
  16765. const transparentObjects = currentRenderList.transparent;
  16766. currentRenderState.setupLightsView( camera );
  16767. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, scene, camera );
  16768. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  16769. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  16770. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  16771. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  16772. }
  16773. function renderTransmissionPass( opaqueObjects, scene, camera ) {
  16774. if ( _transmissionRenderTarget === null ) {
  16775. const needsAntialias = _antialias === true && capabilities.isWebGL2 === true;
  16776. const renderTargetType = needsAntialias ? WebGLMultisampleRenderTarget : WebGLRenderTarget;
  16777. _transmissionRenderTarget = new renderTargetType( 1024, 1024, {
  16778. generateMipmaps: true,
  16779. type: utils.convert( HalfFloatType ) !== null ? HalfFloatType : UnsignedByteType,
  16780. minFilter: LinearMipmapLinearFilter,
  16781. magFilter: NearestFilter,
  16782. wrapS: ClampToEdgeWrapping,
  16783. wrapT: ClampToEdgeWrapping
  16784. } );
  16785. }
  16786. const currentRenderTarget = _this.getRenderTarget();
  16787. _this.setRenderTarget( _transmissionRenderTarget );
  16788. _this.clear();
  16789. // Turn off the features which can affect the frag color for opaque objects pass.
  16790. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  16791. const currentToneMapping = _this.toneMapping;
  16792. _this.toneMapping = NoToneMapping;
  16793. renderObjects( opaqueObjects, scene, camera );
  16794. _this.toneMapping = currentToneMapping;
  16795. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  16796. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  16797. _this.setRenderTarget( currentRenderTarget );
  16798. }
  16799. function renderObjects( renderList, scene, camera ) {
  16800. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  16801. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  16802. const renderItem = renderList[ i ];
  16803. const object = renderItem.object;
  16804. const geometry = renderItem.geometry;
  16805. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  16806. const group = renderItem.group;
  16807. if ( object.layers.test( camera.layers ) ) {
  16808. renderObject( object, scene, camera, geometry, material, group );
  16809. }
  16810. }
  16811. }
  16812. function renderObject( object, scene, camera, geometry, material, group ) {
  16813. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  16814. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  16815. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  16816. if ( object.isImmediateRenderObject ) {
  16817. const program = setProgram( camera, scene, material, object );
  16818. state.setMaterial( material );
  16819. bindingStates.reset();
  16820. renderObjectImmediate( object, program );
  16821. } else {
  16822. if ( material.transparent === true && material.side === DoubleSide ) {
  16823. material.side = BackSide;
  16824. material.needsUpdate = true;
  16825. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16826. material.side = FrontSide;
  16827. material.needsUpdate = true;
  16828. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16829. material.side = DoubleSide;
  16830. } else {
  16831. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16832. }
  16833. }
  16834. object.onAfterRender( _this, scene, camera, geometry, material, group );
  16835. }
  16836. function getProgram( material, scene, object ) {
  16837. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16838. const materialProperties = properties.get( material );
  16839. const lights = currentRenderState.state.lights;
  16840. const shadowsArray = currentRenderState.state.shadowsArray;
  16841. const lightsStateVersion = lights.state.version;
  16842. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  16843. const programCacheKey = programCache.getProgramCacheKey( parameters );
  16844. let programs = materialProperties.programs;
  16845. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  16846. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  16847. materialProperties.fog = scene.fog;
  16848. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  16849. if ( programs === undefined ) {
  16850. // new material
  16851. material.addEventListener( 'dispose', onMaterialDispose );
  16852. programs = new Map();
  16853. materialProperties.programs = programs;
  16854. }
  16855. let program = programs.get( programCacheKey );
  16856. if ( program !== undefined ) {
  16857. // early out if program and light state is identical
  16858. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  16859. updateCommonMaterialProperties( material, parameters );
  16860. return program;
  16861. }
  16862. } else {
  16863. parameters.uniforms = programCache.getUniforms( material );
  16864. material.onBuild( parameters, _this );
  16865. material.onBeforeCompile( parameters, _this );
  16866. program = programCache.acquireProgram( parameters, programCacheKey );
  16867. programs.set( programCacheKey, program );
  16868. materialProperties.uniforms = parameters.uniforms;
  16869. }
  16870. const uniforms = materialProperties.uniforms;
  16871. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  16872. uniforms.clippingPlanes = clipping.uniform;
  16873. }
  16874. updateCommonMaterialProperties( material, parameters );
  16875. // store the light setup it was created for
  16876. materialProperties.needsLights = materialNeedsLights( material );
  16877. materialProperties.lightsStateVersion = lightsStateVersion;
  16878. if ( materialProperties.needsLights ) {
  16879. // wire up the material to this renderer's lighting state
  16880. uniforms.ambientLightColor.value = lights.state.ambient;
  16881. uniforms.lightProbe.value = lights.state.probe;
  16882. uniforms.directionalLights.value = lights.state.directional;
  16883. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  16884. uniforms.spotLights.value = lights.state.spot;
  16885. uniforms.spotLightShadows.value = lights.state.spotShadow;
  16886. uniforms.rectAreaLights.value = lights.state.rectArea;
  16887. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  16888. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  16889. uniforms.pointLights.value = lights.state.point;
  16890. uniforms.pointLightShadows.value = lights.state.pointShadow;
  16891. uniforms.hemisphereLights.value = lights.state.hemi;
  16892. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  16893. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  16894. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  16895. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  16896. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  16897. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  16898. // TODO (abelnation): add area lights shadow info to uniforms
  16899. }
  16900. const progUniforms = program.getUniforms();
  16901. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  16902. materialProperties.currentProgram = program;
  16903. materialProperties.uniformsList = uniformsList;
  16904. return program;
  16905. }
  16906. function updateCommonMaterialProperties( material, parameters ) {
  16907. const materialProperties = properties.get( material );
  16908. materialProperties.outputEncoding = parameters.outputEncoding;
  16909. materialProperties.instancing = parameters.instancing;
  16910. materialProperties.skinning = parameters.skinning;
  16911. materialProperties.morphTargets = parameters.morphTargets;
  16912. materialProperties.morphNormals = parameters.morphNormals;
  16913. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  16914. materialProperties.numIntersection = parameters.numClipIntersection;
  16915. materialProperties.vertexAlphas = parameters.vertexAlphas;
  16916. materialProperties.vertexTangents = parameters.vertexTangents;
  16917. }
  16918. function setProgram( camera, scene, material, object ) {
  16919. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16920. textures.resetTextureUnits();
  16921. const fog = scene.fog;
  16922. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  16923. const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  16924. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  16925. const vertexAlphas = material.vertexColors === true && !! object.geometry && !! object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4;
  16926. const vertexTangents = !! object.geometry && !! object.geometry.attributes.tangent;
  16927. const morphTargets = !! object.geometry && !! object.geometry.morphAttributes.position;
  16928. const morphNormals = !! object.geometry && !! object.geometry.morphAttributes.normal;
  16929. const materialProperties = properties.get( material );
  16930. const lights = currentRenderState.state.lights;
  16931. if ( _clippingEnabled === true ) {
  16932. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  16933. const useCache =
  16934. camera === _currentCamera &&
  16935. material.id === _currentMaterialId;
  16936. // we might want to call this function with some ClippingGroup
  16937. // object instead of the material, once it becomes feasible
  16938. // (#8465, #8379)
  16939. clipping.setState( material, camera, useCache );
  16940. }
  16941. }
  16942. //
  16943. let needsProgramChange = false;
  16944. if ( material.version === materialProperties.__version ) {
  16945. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  16946. needsProgramChange = true;
  16947. } else if ( materialProperties.outputEncoding !== encoding ) {
  16948. needsProgramChange = true;
  16949. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  16950. needsProgramChange = true;
  16951. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  16952. needsProgramChange = true;
  16953. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  16954. needsProgramChange = true;
  16955. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  16956. needsProgramChange = true;
  16957. } else if ( materialProperties.envMap !== envMap ) {
  16958. needsProgramChange = true;
  16959. } else if ( material.fog && materialProperties.fog !== fog ) {
  16960. needsProgramChange = true;
  16961. } else if ( materialProperties.numClippingPlanes !== undefined &&
  16962. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  16963. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  16964. needsProgramChange = true;
  16965. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  16966. needsProgramChange = true;
  16967. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  16968. needsProgramChange = true;
  16969. } else if ( materialProperties.morphTargets !== morphTargets ) {
  16970. needsProgramChange = true;
  16971. } else if ( materialProperties.morphNormals !== morphNormals ) {
  16972. needsProgramChange = true;
  16973. }
  16974. } else {
  16975. needsProgramChange = true;
  16976. materialProperties.__version = material.version;
  16977. }
  16978. //
  16979. let program = materialProperties.currentProgram;
  16980. if ( needsProgramChange === true ) {
  16981. program = getProgram( material, scene, object );
  16982. }
  16983. let refreshProgram = false;
  16984. let refreshMaterial = false;
  16985. let refreshLights = false;
  16986. const p_uniforms = program.getUniforms(),
  16987. m_uniforms = materialProperties.uniforms;
  16988. if ( state.useProgram( program.program ) ) {
  16989. refreshProgram = true;
  16990. refreshMaterial = true;
  16991. refreshLights = true;
  16992. }
  16993. if ( material.id !== _currentMaterialId ) {
  16994. _currentMaterialId = material.id;
  16995. refreshMaterial = true;
  16996. }
  16997. if ( refreshProgram || _currentCamera !== camera ) {
  16998. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  16999. if ( capabilities.logarithmicDepthBuffer ) {
  17000. p_uniforms.setValue( _gl, 'logDepthBufFC',
  17001. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  17002. }
  17003. if ( _currentCamera !== camera ) {
  17004. _currentCamera = camera;
  17005. // lighting uniforms depend on the camera so enforce an update
  17006. // now, in case this material supports lights - or later, when
  17007. // the next material that does gets activated:
  17008. refreshMaterial = true; // set to true on material change
  17009. refreshLights = true; // remains set until update done
  17010. }
  17011. // load material specific uniforms
  17012. // (shader material also gets them for the sake of genericity)
  17013. if ( material.isShaderMaterial ||
  17014. material.isMeshPhongMaterial ||
  17015. material.isMeshToonMaterial ||
  17016. material.isMeshStandardMaterial ||
  17017. material.envMap ) {
  17018. const uCamPos = p_uniforms.map.cameraPosition;
  17019. if ( uCamPos !== undefined ) {
  17020. uCamPos.setValue( _gl,
  17021. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  17022. }
  17023. }
  17024. if ( material.isMeshPhongMaterial ||
  17025. material.isMeshToonMaterial ||
  17026. material.isMeshLambertMaterial ||
  17027. material.isMeshBasicMaterial ||
  17028. material.isMeshStandardMaterial ||
  17029. material.isShaderMaterial ) {
  17030. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  17031. }
  17032. if ( material.isMeshPhongMaterial ||
  17033. material.isMeshToonMaterial ||
  17034. material.isMeshLambertMaterial ||
  17035. material.isMeshBasicMaterial ||
  17036. material.isMeshStandardMaterial ||
  17037. material.isShaderMaterial ||
  17038. material.isShadowMaterial ||
  17039. object.isSkinnedMesh ) {
  17040. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  17041. }
  17042. }
  17043. // skinning uniforms must be set even if material didn't change
  17044. // auto-setting of texture unit for bone texture must go before other textures
  17045. // otherwise textures used for skinning can take over texture units reserved for other material textures
  17046. if ( object.isSkinnedMesh ) {
  17047. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  17048. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  17049. const skeleton = object.skeleton;
  17050. if ( skeleton ) {
  17051. if ( capabilities.floatVertexTextures ) {
  17052. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  17053. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  17054. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  17055. } else {
  17056. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  17057. }
  17058. }
  17059. }
  17060. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  17061. materialProperties.receiveShadow = object.receiveShadow;
  17062. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  17063. }
  17064. if ( refreshMaterial ) {
  17065. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  17066. if ( materialProperties.needsLights ) {
  17067. // the current material requires lighting info
  17068. // note: all lighting uniforms are always set correctly
  17069. // they simply reference the renderer's state for their
  17070. // values
  17071. //
  17072. // use the current material's .needsUpdate flags to set
  17073. // the GL state when required
  17074. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  17075. }
  17076. // refresh uniforms common to several materials
  17077. if ( fog && material.fog ) {
  17078. materials.refreshFogUniforms( m_uniforms, fog );
  17079. }
  17080. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget );
  17081. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17082. }
  17083. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  17084. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17085. material.uniformsNeedUpdate = false;
  17086. }
  17087. if ( material.isSpriteMaterial ) {
  17088. p_uniforms.setValue( _gl, 'center', object.center );
  17089. }
  17090. // common matrices
  17091. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  17092. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  17093. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  17094. return program;
  17095. }
  17096. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  17097. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  17098. uniforms.ambientLightColor.needsUpdate = value;
  17099. uniforms.lightProbe.needsUpdate = value;
  17100. uniforms.directionalLights.needsUpdate = value;
  17101. uniforms.directionalLightShadows.needsUpdate = value;
  17102. uniforms.pointLights.needsUpdate = value;
  17103. uniforms.pointLightShadows.needsUpdate = value;
  17104. uniforms.spotLights.needsUpdate = value;
  17105. uniforms.spotLightShadows.needsUpdate = value;
  17106. uniforms.rectAreaLights.needsUpdate = value;
  17107. uniforms.hemisphereLights.needsUpdate = value;
  17108. }
  17109. function materialNeedsLights( material ) {
  17110. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  17111. material.isMeshStandardMaterial || material.isShadowMaterial ||
  17112. ( material.isShaderMaterial && material.lights === true );
  17113. }
  17114. this.getActiveCubeFace = function () {
  17115. return _currentActiveCubeFace;
  17116. };
  17117. this.getActiveMipmapLevel = function () {
  17118. return _currentActiveMipmapLevel;
  17119. };
  17120. this.getRenderTarget = function () {
  17121. return _currentRenderTarget;
  17122. };
  17123. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  17124. _currentRenderTarget = renderTarget;
  17125. _currentActiveCubeFace = activeCubeFace;
  17126. _currentActiveMipmapLevel = activeMipmapLevel;
  17127. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  17128. textures.setupRenderTarget( renderTarget );
  17129. }
  17130. let framebuffer = null;
  17131. let isCube = false;
  17132. let isRenderTarget3D = false;
  17133. if ( renderTarget ) {
  17134. const texture = renderTarget.texture;
  17135. if ( texture.isDataTexture3D || texture.isDataTexture2DArray ) {
  17136. isRenderTarget3D = true;
  17137. }
  17138. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17139. if ( renderTarget.isWebGLCubeRenderTarget ) {
  17140. framebuffer = __webglFramebuffer[ activeCubeFace ];
  17141. isCube = true;
  17142. } else if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  17143. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  17144. } else {
  17145. framebuffer = __webglFramebuffer;
  17146. }
  17147. _currentViewport.copy( renderTarget.viewport );
  17148. _currentScissor.copy( renderTarget.scissor );
  17149. _currentScissorTest = renderTarget.scissorTest;
  17150. } else {
  17151. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  17152. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  17153. _currentScissorTest = _scissorTest;
  17154. }
  17155. const framebufferBound = state.bindFramebuffer( 36160, framebuffer );
  17156. if ( framebufferBound && capabilities.drawBuffers ) {
  17157. let needsUpdate = false;
  17158. if ( renderTarget ) {
  17159. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  17160. const textures = renderTarget.texture;
  17161. if ( _currentDrawBuffers.length !== textures.length || _currentDrawBuffers[ 0 ] !== 36064 ) {
  17162. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  17163. _currentDrawBuffers[ i ] = 36064 + i;
  17164. }
  17165. _currentDrawBuffers.length = textures.length;
  17166. needsUpdate = true;
  17167. }
  17168. } else {
  17169. if ( _currentDrawBuffers.length !== 1 || _currentDrawBuffers[ 0 ] !== 36064 ) {
  17170. _currentDrawBuffers[ 0 ] = 36064;
  17171. _currentDrawBuffers.length = 1;
  17172. needsUpdate = true;
  17173. }
  17174. }
  17175. } else {
  17176. if ( _currentDrawBuffers.length !== 1 || _currentDrawBuffers[ 0 ] !== 1029 ) {
  17177. _currentDrawBuffers[ 0 ] = 1029;
  17178. _currentDrawBuffers.length = 1;
  17179. needsUpdate = true;
  17180. }
  17181. }
  17182. if ( needsUpdate ) {
  17183. if ( capabilities.isWebGL2 ) {
  17184. _gl.drawBuffers( _currentDrawBuffers );
  17185. } else {
  17186. extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( _currentDrawBuffers );
  17187. }
  17188. }
  17189. }
  17190. state.viewport( _currentViewport );
  17191. state.scissor( _currentScissor );
  17192. state.setScissorTest( _currentScissorTest );
  17193. if ( isCube ) {
  17194. const textureProperties = properties.get( renderTarget.texture );
  17195. _gl.framebufferTexture2D( 36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  17196. } else if ( isRenderTarget3D ) {
  17197. const textureProperties = properties.get( renderTarget.texture );
  17198. const layer = activeCubeFace || 0;
  17199. _gl.framebufferTextureLayer( 36160, 36064, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  17200. }
  17201. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  17202. };
  17203. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  17204. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  17205. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  17206. return;
  17207. }
  17208. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17209. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  17210. framebuffer = framebuffer[ activeCubeFaceIndex ];
  17211. }
  17212. if ( framebuffer ) {
  17213. state.bindFramebuffer( 36160, framebuffer );
  17214. try {
  17215. const texture = renderTarget.texture;
  17216. const textureFormat = texture.format;
  17217. const textureType = texture.type;
  17218. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {
  17219. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  17220. return;
  17221. }
  17222. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) );
  17223. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // Edge and Chrome Mac < 52 (#9513)
  17224. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  17225. ! halfFloatSupportedByExt ) {
  17226. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  17227. return;
  17228. }
  17229. if ( _gl.checkFramebufferStatus( 36160 ) === 36053 ) {
  17230. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  17231. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  17232. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  17233. }
  17234. } else {
  17235. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  17236. }
  17237. } finally {
  17238. // restore framebuffer of current render target if necessary
  17239. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  17240. state.bindFramebuffer( 36160, framebuffer );
  17241. }
  17242. }
  17243. };
  17244. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  17245. const levelScale = Math.pow( 2, - level );
  17246. const width = Math.floor( texture.image.width * levelScale );
  17247. const height = Math.floor( texture.image.height * levelScale );
  17248. let glFormat = utils.convert( texture.format );
  17249. if ( capabilities.isWebGL2 ) {
  17250. // Workaround for https://bugs.chromium.org/p/chromium/issues/detail?id=1120100
  17251. // Not needed in Chrome 93+
  17252. if ( glFormat === 6407 ) glFormat = 32849;
  17253. if ( glFormat === 6408 ) glFormat = 32856;
  17254. }
  17255. textures.setTexture2D( texture, 0 );
  17256. _gl.copyTexImage2D( 3553, level, glFormat, position.x, position.y, width, height, 0 );
  17257. state.unbindTexture();
  17258. };
  17259. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  17260. const width = srcTexture.image.width;
  17261. const height = srcTexture.image.height;
  17262. const glFormat = utils.convert( dstTexture.format );
  17263. const glType = utils.convert( dstTexture.type );
  17264. textures.setTexture2D( dstTexture, 0 );
  17265. // As another texture upload may have changed pixelStorei
  17266. // parameters, make sure they are correct for the dstTexture
  17267. _gl.pixelStorei( 37440, dstTexture.flipY );
  17268. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  17269. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  17270. if ( srcTexture.isDataTexture ) {
  17271. _gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  17272. } else {
  17273. if ( srcTexture.isCompressedTexture ) {
  17274. _gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  17275. } else {
  17276. _gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image );
  17277. }
  17278. }
  17279. // Generate mipmaps only when copying level 0
  17280. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 );
  17281. state.unbindTexture();
  17282. };
  17283. this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {
  17284. if ( _this.isWebGL1Renderer ) {
  17285. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' );
  17286. return;
  17287. }
  17288. const width = sourceBox.max.x - sourceBox.min.x + 1;
  17289. const height = sourceBox.max.y - sourceBox.min.y + 1;
  17290. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  17291. const glFormat = utils.convert( dstTexture.format );
  17292. const glType = utils.convert( dstTexture.type );
  17293. let glTarget;
  17294. if ( dstTexture.isDataTexture3D ) {
  17295. textures.setTexture3D( dstTexture, 0 );
  17296. glTarget = 32879;
  17297. } else if ( dstTexture.isDataTexture2DArray ) {
  17298. textures.setTexture2DArray( dstTexture, 0 );
  17299. glTarget = 35866;
  17300. } else {
  17301. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  17302. return;
  17303. }
  17304. _gl.pixelStorei( 37440, dstTexture.flipY );
  17305. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  17306. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  17307. const unpackRowLen = _gl.getParameter( 3314 );
  17308. const unpackImageHeight = _gl.getParameter( 32878 );
  17309. const unpackSkipPixels = _gl.getParameter( 3316 );
  17310. const unpackSkipRows = _gl.getParameter( 3315 );
  17311. const unpackSkipImages = _gl.getParameter( 32877 );
  17312. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image;
  17313. _gl.pixelStorei( 3314, image.width );
  17314. _gl.pixelStorei( 32878, image.height );
  17315. _gl.pixelStorei( 3316, sourceBox.min.x );
  17316. _gl.pixelStorei( 3315, sourceBox.min.y );
  17317. _gl.pixelStorei( 32877, sourceBox.min.z );
  17318. if ( srcTexture.isDataTexture || srcTexture.isDataTexture3D ) {
  17319. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data );
  17320. } else {
  17321. if ( srcTexture.isCompressedTexture ) {
  17322. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' );
  17323. _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data );
  17324. } else {
  17325. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image );
  17326. }
  17327. }
  17328. _gl.pixelStorei( 3314, unpackRowLen );
  17329. _gl.pixelStorei( 32878, unpackImageHeight );
  17330. _gl.pixelStorei( 3316, unpackSkipPixels );
  17331. _gl.pixelStorei( 3315, unpackSkipRows );
  17332. _gl.pixelStorei( 32877, unpackSkipImages );
  17333. // Generate mipmaps only when copying level 0
  17334. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  17335. state.unbindTexture();
  17336. };
  17337. this.initTexture = function ( texture ) {
  17338. textures.setTexture2D( texture, 0 );
  17339. state.unbindTexture();
  17340. };
  17341. this.resetState = function () {
  17342. _currentActiveCubeFace = 0;
  17343. _currentActiveMipmapLevel = 0;
  17344. _currentRenderTarget = null;
  17345. state.reset();
  17346. bindingStates.reset();
  17347. };
  17348. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17349. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  17350. }
  17351. }
  17352. class WebGL1Renderer extends WebGLRenderer {}
  17353. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  17354. class FogExp2 {
  17355. constructor( color, density = 0.00025 ) {
  17356. this.name = '';
  17357. this.color = new Color( color );
  17358. this.density = density;
  17359. }
  17360. clone() {
  17361. return new FogExp2( this.color, this.density );
  17362. }
  17363. toJSON( /* meta */ ) {
  17364. return {
  17365. type: 'FogExp2',
  17366. color: this.color.getHex(),
  17367. density: this.density
  17368. };
  17369. }
  17370. }
  17371. FogExp2.prototype.isFogExp2 = true;
  17372. class Fog {
  17373. constructor( color, near = 1, far = 1000 ) {
  17374. this.name = '';
  17375. this.color = new Color( color );
  17376. this.near = near;
  17377. this.far = far;
  17378. }
  17379. clone() {
  17380. return new Fog( this.color, this.near, this.far );
  17381. }
  17382. toJSON( /* meta */ ) {
  17383. return {
  17384. type: 'Fog',
  17385. color: this.color.getHex(),
  17386. near: this.near,
  17387. far: this.far
  17388. };
  17389. }
  17390. }
  17391. Fog.prototype.isFog = true;
  17392. class Scene extends Object3D {
  17393. constructor() {
  17394. super();
  17395. this.type = 'Scene';
  17396. this.background = null;
  17397. this.environment = null;
  17398. this.fog = null;
  17399. this.overrideMaterial = null;
  17400. this.autoUpdate = true; // checked by the renderer
  17401. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17402. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  17403. }
  17404. }
  17405. copy( source, recursive ) {
  17406. super.copy( source, recursive );
  17407. if ( source.background !== null ) this.background = source.background.clone();
  17408. if ( source.environment !== null ) this.environment = source.environment.clone();
  17409. if ( source.fog !== null ) this.fog = source.fog.clone();
  17410. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17411. this.autoUpdate = source.autoUpdate;
  17412. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17413. return this;
  17414. }
  17415. toJSON( meta ) {
  17416. const data = super.toJSON( meta );
  17417. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17418. return data;
  17419. }
  17420. }
  17421. Scene.prototype.isScene = true;
  17422. class InterleavedBuffer {
  17423. constructor( array, stride ) {
  17424. this.array = array;
  17425. this.stride = stride;
  17426. this.count = array !== undefined ? array.length / stride : 0;
  17427. this.usage = StaticDrawUsage;
  17428. this.updateRange = { offset: 0, count: - 1 };
  17429. this.version = 0;
  17430. this.uuid = generateUUID();
  17431. }
  17432. onUploadCallback() {}
  17433. set needsUpdate( value ) {
  17434. if ( value === true ) this.version ++;
  17435. }
  17436. setUsage( value ) {
  17437. this.usage = value;
  17438. return this;
  17439. }
  17440. copy( source ) {
  17441. this.array = new source.array.constructor( source.array );
  17442. this.count = source.count;
  17443. this.stride = source.stride;
  17444. this.usage = source.usage;
  17445. return this;
  17446. }
  17447. copyAt( index1, attribute, index2 ) {
  17448. index1 *= this.stride;
  17449. index2 *= attribute.stride;
  17450. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17451. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  17452. }
  17453. return this;
  17454. }
  17455. set( value, offset = 0 ) {
  17456. this.array.set( value, offset );
  17457. return this;
  17458. }
  17459. clone( data ) {
  17460. if ( data.arrayBuffers === undefined ) {
  17461. data.arrayBuffers = {};
  17462. }
  17463. if ( this.array.buffer._uuid === undefined ) {
  17464. this.array.buffer._uuid = generateUUID();
  17465. }
  17466. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17467. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17468. }
  17469. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17470. const ib = new this.constructor( array, this.stride );
  17471. ib.setUsage( this.usage );
  17472. return ib;
  17473. }
  17474. onUpload( callback ) {
  17475. this.onUploadCallback = callback;
  17476. return this;
  17477. }
  17478. toJSON( data ) {
  17479. if ( data.arrayBuffers === undefined ) {
  17480. data.arrayBuffers = {};
  17481. }
  17482. // generate UUID for array buffer if necessary
  17483. if ( this.array.buffer._uuid === undefined ) {
  17484. this.array.buffer._uuid = generateUUID();
  17485. }
  17486. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17487. data.arrayBuffers[ this.array.buffer._uuid ] = Array.prototype.slice.call( new Uint32Array( this.array.buffer ) );
  17488. }
  17489. //
  17490. return {
  17491. uuid: this.uuid,
  17492. buffer: this.array.buffer._uuid,
  17493. type: this.array.constructor.name,
  17494. stride: this.stride
  17495. };
  17496. }
  17497. }
  17498. InterleavedBuffer.prototype.isInterleavedBuffer = true;
  17499. const _vector$6 = /*@__PURE__*/ new Vector3();
  17500. class InterleavedBufferAttribute {
  17501. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17502. this.name = '';
  17503. this.data = interleavedBuffer;
  17504. this.itemSize = itemSize;
  17505. this.offset = offset;
  17506. this.normalized = normalized === true;
  17507. }
  17508. get count() {
  17509. return this.data.count;
  17510. }
  17511. get array() {
  17512. return this.data.array;
  17513. }
  17514. set needsUpdate( value ) {
  17515. this.data.needsUpdate = value;
  17516. }
  17517. applyMatrix4( m ) {
  17518. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17519. _vector$6.x = this.getX( i );
  17520. _vector$6.y = this.getY( i );
  17521. _vector$6.z = this.getZ( i );
  17522. _vector$6.applyMatrix4( m );
  17523. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17524. }
  17525. return this;
  17526. }
  17527. applyNormalMatrix( m ) {
  17528. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17529. _vector$6.x = this.getX( i );
  17530. _vector$6.y = this.getY( i );
  17531. _vector$6.z = this.getZ( i );
  17532. _vector$6.applyNormalMatrix( m );
  17533. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17534. }
  17535. return this;
  17536. }
  17537. transformDirection( m ) {
  17538. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17539. _vector$6.x = this.getX( i );
  17540. _vector$6.y = this.getY( i );
  17541. _vector$6.z = this.getZ( i );
  17542. _vector$6.transformDirection( m );
  17543. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17544. }
  17545. return this;
  17546. }
  17547. setX( index, x ) {
  17548. this.data.array[ index * this.data.stride + this.offset ] = x;
  17549. return this;
  17550. }
  17551. setY( index, y ) {
  17552. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17553. return this;
  17554. }
  17555. setZ( index, z ) {
  17556. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17557. return this;
  17558. }
  17559. setW( index, w ) {
  17560. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17561. return this;
  17562. }
  17563. getX( index ) {
  17564. return this.data.array[ index * this.data.stride + this.offset ];
  17565. }
  17566. getY( index ) {
  17567. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  17568. }
  17569. getZ( index ) {
  17570. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  17571. }
  17572. getW( index ) {
  17573. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  17574. }
  17575. setXY( index, x, y ) {
  17576. index = index * this.data.stride + this.offset;
  17577. this.data.array[ index + 0 ] = x;
  17578. this.data.array[ index + 1 ] = y;
  17579. return this;
  17580. }
  17581. setXYZ( index, x, y, z ) {
  17582. index = index * this.data.stride + this.offset;
  17583. this.data.array[ index + 0 ] = x;
  17584. this.data.array[ index + 1 ] = y;
  17585. this.data.array[ index + 2 ] = z;
  17586. return this;
  17587. }
  17588. setXYZW( index, x, y, z, w ) {
  17589. index = index * this.data.stride + this.offset;
  17590. this.data.array[ index + 0 ] = x;
  17591. this.data.array[ index + 1 ] = y;
  17592. this.data.array[ index + 2 ] = z;
  17593. this.data.array[ index + 3 ] = w;
  17594. return this;
  17595. }
  17596. clone( data ) {
  17597. if ( data === undefined ) {
  17598. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.' );
  17599. const array = [];
  17600. for ( let i = 0; i < this.count; i ++ ) {
  17601. const index = i * this.data.stride + this.offset;
  17602. for ( let j = 0; j < this.itemSize; j ++ ) {
  17603. array.push( this.data.array[ index + j ] );
  17604. }
  17605. }
  17606. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17607. } else {
  17608. if ( data.interleavedBuffers === undefined ) {
  17609. data.interleavedBuffers = {};
  17610. }
  17611. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17612. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17613. }
  17614. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17615. }
  17616. }
  17617. toJSON( data ) {
  17618. if ( data === undefined ) {
  17619. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.' );
  17620. const array = [];
  17621. for ( let i = 0; i < this.count; i ++ ) {
  17622. const index = i * this.data.stride + this.offset;
  17623. for ( let j = 0; j < this.itemSize; j ++ ) {
  17624. array.push( this.data.array[ index + j ] );
  17625. }
  17626. }
  17627. // deinterleave data and save it as an ordinary buffer attribute for now
  17628. return {
  17629. itemSize: this.itemSize,
  17630. type: this.array.constructor.name,
  17631. array: array,
  17632. normalized: this.normalized
  17633. };
  17634. } else {
  17635. // save as true interlaved attribtue
  17636. if ( data.interleavedBuffers === undefined ) {
  17637. data.interleavedBuffers = {};
  17638. }
  17639. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17640. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17641. }
  17642. return {
  17643. isInterleavedBufferAttribute: true,
  17644. itemSize: this.itemSize,
  17645. data: this.data.uuid,
  17646. offset: this.offset,
  17647. normalized: this.normalized
  17648. };
  17649. }
  17650. }
  17651. }
  17652. InterleavedBufferAttribute.prototype.isInterleavedBufferAttribute = true;
  17653. /**
  17654. * parameters = {
  17655. * color: <hex>,
  17656. * map: new THREE.Texture( <Image> ),
  17657. * alphaMap: new THREE.Texture( <Image> ),
  17658. * rotation: <float>,
  17659. * sizeAttenuation: <bool>
  17660. * }
  17661. */
  17662. class SpriteMaterial extends Material {
  17663. constructor( parameters ) {
  17664. super();
  17665. this.type = 'SpriteMaterial';
  17666. this.color = new Color( 0xffffff );
  17667. this.map = null;
  17668. this.alphaMap = null;
  17669. this.rotation = 0;
  17670. this.sizeAttenuation = true;
  17671. this.transparent = true;
  17672. this.setValues( parameters );
  17673. }
  17674. copy( source ) {
  17675. super.copy( source );
  17676. this.color.copy( source.color );
  17677. this.map = source.map;
  17678. this.alphaMap = source.alphaMap;
  17679. this.rotation = source.rotation;
  17680. this.sizeAttenuation = source.sizeAttenuation;
  17681. return this;
  17682. }
  17683. }
  17684. SpriteMaterial.prototype.isSpriteMaterial = true;
  17685. let _geometry;
  17686. const _intersectPoint = /*@__PURE__*/ new Vector3();
  17687. const _worldScale = /*@__PURE__*/ new Vector3();
  17688. const _mvPosition = /*@__PURE__*/ new Vector3();
  17689. const _alignedPosition = /*@__PURE__*/ new Vector2();
  17690. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  17691. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  17692. const _vA = /*@__PURE__*/ new Vector3();
  17693. const _vB = /*@__PURE__*/ new Vector3();
  17694. const _vC = /*@__PURE__*/ new Vector3();
  17695. const _uvA = /*@__PURE__*/ new Vector2();
  17696. const _uvB = /*@__PURE__*/ new Vector2();
  17697. const _uvC = /*@__PURE__*/ new Vector2();
  17698. class Sprite extends Object3D {
  17699. constructor( material ) {
  17700. super();
  17701. this.type = 'Sprite';
  17702. if ( _geometry === undefined ) {
  17703. _geometry = new BufferGeometry();
  17704. const float32Array = new Float32Array( [
  17705. - 0.5, - 0.5, 0, 0, 0,
  17706. 0.5, - 0.5, 0, 1, 0,
  17707. 0.5, 0.5, 0, 1, 1,
  17708. - 0.5, 0.5, 0, 0, 1
  17709. ] );
  17710. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  17711. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  17712. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  17713. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  17714. }
  17715. this.geometry = _geometry;
  17716. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  17717. this.center = new Vector2( 0.5, 0.5 );
  17718. }
  17719. raycast( raycaster, intersects ) {
  17720. if ( raycaster.camera === null ) {
  17721. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  17722. }
  17723. _worldScale.setFromMatrixScale( this.matrixWorld );
  17724. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  17725. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  17726. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  17727. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  17728. _worldScale.multiplyScalar( - _mvPosition.z );
  17729. }
  17730. const rotation = this.material.rotation;
  17731. let sin, cos;
  17732. if ( rotation !== 0 ) {
  17733. cos = Math.cos( rotation );
  17734. sin = Math.sin( rotation );
  17735. }
  17736. const center = this.center;
  17737. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17738. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17739. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17740. _uvA.set( 0, 0 );
  17741. _uvB.set( 1, 0 );
  17742. _uvC.set( 1, 1 );
  17743. // check first triangle
  17744. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  17745. if ( intersect === null ) {
  17746. // check second triangle
  17747. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17748. _uvB.set( 0, 1 );
  17749. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  17750. if ( intersect === null ) {
  17751. return;
  17752. }
  17753. }
  17754. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  17755. if ( distance < raycaster.near || distance > raycaster.far ) return;
  17756. intersects.push( {
  17757. distance: distance,
  17758. point: _intersectPoint.clone(),
  17759. uv: Triangle.getUV( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  17760. face: null,
  17761. object: this
  17762. } );
  17763. }
  17764. copy( source ) {
  17765. super.copy( source );
  17766. if ( source.center !== undefined ) this.center.copy( source.center );
  17767. this.material = source.material;
  17768. return this;
  17769. }
  17770. }
  17771. Sprite.prototype.isSprite = true;
  17772. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  17773. // compute position in camera space
  17774. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  17775. // to check if rotation is not zero
  17776. if ( sin !== undefined ) {
  17777. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  17778. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  17779. } else {
  17780. _rotatedPosition.copy( _alignedPosition );
  17781. }
  17782. vertexPosition.copy( mvPosition );
  17783. vertexPosition.x += _rotatedPosition.x;
  17784. vertexPosition.y += _rotatedPosition.y;
  17785. // transform to world space
  17786. vertexPosition.applyMatrix4( _viewWorldMatrix );
  17787. }
  17788. const _v1$2 = /*@__PURE__*/ new Vector3();
  17789. const _v2$1 = /*@__PURE__*/ new Vector3();
  17790. class LOD extends Object3D {
  17791. constructor() {
  17792. super();
  17793. this._currentLevel = 0;
  17794. this.type = 'LOD';
  17795. Object.defineProperties( this, {
  17796. levels: {
  17797. enumerable: true,
  17798. value: []
  17799. },
  17800. isLOD: {
  17801. value: true,
  17802. }
  17803. } );
  17804. this.autoUpdate = true;
  17805. }
  17806. copy( source ) {
  17807. super.copy( source, false );
  17808. const levels = source.levels;
  17809. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  17810. const level = levels[ i ];
  17811. this.addLevel( level.object.clone(), level.distance );
  17812. }
  17813. this.autoUpdate = source.autoUpdate;
  17814. return this;
  17815. }
  17816. addLevel( object, distance = 0 ) {
  17817. distance = Math.abs( distance );
  17818. const levels = this.levels;
  17819. let l;
  17820. for ( l = 0; l < levels.length; l ++ ) {
  17821. if ( distance < levels[ l ].distance ) {
  17822. break;
  17823. }
  17824. }
  17825. levels.splice( l, 0, { distance: distance, object: object } );
  17826. this.add( object );
  17827. return this;
  17828. }
  17829. getCurrentLevel() {
  17830. return this._currentLevel;
  17831. }
  17832. getObjectForDistance( distance ) {
  17833. const levels = this.levels;
  17834. if ( levels.length > 0 ) {
  17835. let i, l;
  17836. for ( i = 1, l = levels.length; i < l; i ++ ) {
  17837. if ( distance < levels[ i ].distance ) {
  17838. break;
  17839. }
  17840. }
  17841. return levels[ i - 1 ].object;
  17842. }
  17843. return null;
  17844. }
  17845. raycast( raycaster, intersects ) {
  17846. const levels = this.levels;
  17847. if ( levels.length > 0 ) {
  17848. _v1$2.setFromMatrixPosition( this.matrixWorld );
  17849. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  17850. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  17851. }
  17852. }
  17853. update( camera ) {
  17854. const levels = this.levels;
  17855. if ( levels.length > 1 ) {
  17856. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  17857. _v2$1.setFromMatrixPosition( this.matrixWorld );
  17858. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  17859. levels[ 0 ].object.visible = true;
  17860. let i, l;
  17861. for ( i = 1, l = levels.length; i < l; i ++ ) {
  17862. if ( distance >= levels[ i ].distance ) {
  17863. levels[ i - 1 ].object.visible = false;
  17864. levels[ i ].object.visible = true;
  17865. } else {
  17866. break;
  17867. }
  17868. }
  17869. this._currentLevel = i - 1;
  17870. for ( ; i < l; i ++ ) {
  17871. levels[ i ].object.visible = false;
  17872. }
  17873. }
  17874. }
  17875. toJSON( meta ) {
  17876. const data = super.toJSON( meta );
  17877. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  17878. data.object.levels = [];
  17879. const levels = this.levels;
  17880. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  17881. const level = levels[ i ];
  17882. data.object.levels.push( {
  17883. object: level.object.uuid,
  17884. distance: level.distance
  17885. } );
  17886. }
  17887. return data;
  17888. }
  17889. }
  17890. const _basePosition = /*@__PURE__*/ new Vector3();
  17891. const _skinIndex = /*@__PURE__*/ new Vector4();
  17892. const _skinWeight = /*@__PURE__*/ new Vector4();
  17893. const _vector$5 = /*@__PURE__*/ new Vector3();
  17894. const _matrix = /*@__PURE__*/ new Matrix4();
  17895. class SkinnedMesh extends Mesh {
  17896. constructor( geometry, material ) {
  17897. super( geometry, material );
  17898. this.type = 'SkinnedMesh';
  17899. this.bindMode = 'attached';
  17900. this.bindMatrix = new Matrix4();
  17901. this.bindMatrixInverse = new Matrix4();
  17902. }
  17903. copy( source ) {
  17904. super.copy( source );
  17905. this.bindMode = source.bindMode;
  17906. this.bindMatrix.copy( source.bindMatrix );
  17907. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  17908. this.skeleton = source.skeleton;
  17909. return this;
  17910. }
  17911. bind( skeleton, bindMatrix ) {
  17912. this.skeleton = skeleton;
  17913. if ( bindMatrix === undefined ) {
  17914. this.updateMatrixWorld( true );
  17915. this.skeleton.calculateInverses();
  17916. bindMatrix = this.matrixWorld;
  17917. }
  17918. this.bindMatrix.copy( bindMatrix );
  17919. this.bindMatrixInverse.copy( bindMatrix ).invert();
  17920. }
  17921. pose() {
  17922. this.skeleton.pose();
  17923. }
  17924. normalizeSkinWeights() {
  17925. const vector = new Vector4();
  17926. const skinWeight = this.geometry.attributes.skinWeight;
  17927. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  17928. vector.x = skinWeight.getX( i );
  17929. vector.y = skinWeight.getY( i );
  17930. vector.z = skinWeight.getZ( i );
  17931. vector.w = skinWeight.getW( i );
  17932. const scale = 1.0 / vector.manhattanLength();
  17933. if ( scale !== Infinity ) {
  17934. vector.multiplyScalar( scale );
  17935. } else {
  17936. vector.set( 1, 0, 0, 0 ); // do something reasonable
  17937. }
  17938. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  17939. }
  17940. }
  17941. updateMatrixWorld( force ) {
  17942. super.updateMatrixWorld( force );
  17943. if ( this.bindMode === 'attached' ) {
  17944. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  17945. } else if ( this.bindMode === 'detached' ) {
  17946. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  17947. } else {
  17948. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  17949. }
  17950. }
  17951. boneTransform( index, target ) {
  17952. const skeleton = this.skeleton;
  17953. const geometry = this.geometry;
  17954. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  17955. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  17956. _basePosition.fromBufferAttribute( geometry.attributes.position, index ).applyMatrix4( this.bindMatrix );
  17957. target.set( 0, 0, 0 );
  17958. for ( let i = 0; i < 4; i ++ ) {
  17959. const weight = _skinWeight.getComponent( i );
  17960. if ( weight !== 0 ) {
  17961. const boneIndex = _skinIndex.getComponent( i );
  17962. _matrix.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  17963. target.addScaledVector( _vector$5.copy( _basePosition ).applyMatrix4( _matrix ), weight );
  17964. }
  17965. }
  17966. return target.applyMatrix4( this.bindMatrixInverse );
  17967. }
  17968. }
  17969. SkinnedMesh.prototype.isSkinnedMesh = true;
  17970. class Bone extends Object3D {
  17971. constructor() {
  17972. super();
  17973. this.type = 'Bone';
  17974. }
  17975. }
  17976. Bone.prototype.isBone = true;
  17977. class DataTexture extends Texture {
  17978. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding ) {
  17979. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  17980. this.image = { data: data, width: width, height: height };
  17981. this.magFilter = magFilter;
  17982. this.minFilter = minFilter;
  17983. this.generateMipmaps = false;
  17984. this.flipY = false;
  17985. this.unpackAlignment = 1;
  17986. this.needsUpdate = true;
  17987. }
  17988. }
  17989. DataTexture.prototype.isDataTexture = true;
  17990. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  17991. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  17992. class Skeleton {
  17993. constructor( bones = [], boneInverses = [] ) {
  17994. this.uuid = generateUUID();
  17995. this.bones = bones.slice( 0 );
  17996. this.boneInverses = boneInverses;
  17997. this.boneMatrices = null;
  17998. this.boneTexture = null;
  17999. this.boneTextureSize = 0;
  18000. this.frame = - 1;
  18001. this.init();
  18002. }
  18003. init() {
  18004. const bones = this.bones;
  18005. const boneInverses = this.boneInverses;
  18006. this.boneMatrices = new Float32Array( bones.length * 16 );
  18007. // calculate inverse bone matrices if necessary
  18008. if ( boneInverses.length === 0 ) {
  18009. this.calculateInverses();
  18010. } else {
  18011. // handle special case
  18012. if ( bones.length !== boneInverses.length ) {
  18013. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18014. this.boneInverses = [];
  18015. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18016. this.boneInverses.push( new Matrix4() );
  18017. }
  18018. }
  18019. }
  18020. }
  18021. calculateInverses() {
  18022. this.boneInverses.length = 0;
  18023. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18024. const inverse = new Matrix4();
  18025. if ( this.bones[ i ] ) {
  18026. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18027. }
  18028. this.boneInverses.push( inverse );
  18029. }
  18030. }
  18031. pose() {
  18032. // recover the bind-time world matrices
  18033. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18034. const bone = this.bones[ i ];
  18035. if ( bone ) {
  18036. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18037. }
  18038. }
  18039. // compute the local matrices, positions, rotations and scales
  18040. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18041. const bone = this.bones[ i ];
  18042. if ( bone ) {
  18043. if ( bone.parent && bone.parent.isBone ) {
  18044. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18045. bone.matrix.multiply( bone.matrixWorld );
  18046. } else {
  18047. bone.matrix.copy( bone.matrixWorld );
  18048. }
  18049. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18050. }
  18051. }
  18052. }
  18053. update() {
  18054. const bones = this.bones;
  18055. const boneInverses = this.boneInverses;
  18056. const boneMatrices = this.boneMatrices;
  18057. const boneTexture = this.boneTexture;
  18058. // flatten bone matrices to array
  18059. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18060. // compute the offset between the current and the original transform
  18061. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18062. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18063. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18064. }
  18065. if ( boneTexture !== null ) {
  18066. boneTexture.needsUpdate = true;
  18067. }
  18068. }
  18069. clone() {
  18070. return new Skeleton( this.bones, this.boneInverses );
  18071. }
  18072. computeBoneTexture() {
  18073. // layout (1 matrix = 4 pixels)
  18074. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18075. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18076. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18077. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18078. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18079. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18080. size = ceilPowerOfTwo( size );
  18081. size = Math.max( size, 4 );
  18082. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18083. boneMatrices.set( this.boneMatrices ); // copy current values
  18084. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18085. this.boneMatrices = boneMatrices;
  18086. this.boneTexture = boneTexture;
  18087. this.boneTextureSize = size;
  18088. return this;
  18089. }
  18090. getBoneByName( name ) {
  18091. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18092. const bone = this.bones[ i ];
  18093. if ( bone.name === name ) {
  18094. return bone;
  18095. }
  18096. }
  18097. return undefined;
  18098. }
  18099. dispose( ) {
  18100. if ( this.boneTexture !== null ) {
  18101. this.boneTexture.dispose();
  18102. this.boneTexture = null;
  18103. }
  18104. }
  18105. fromJSON( json, bones ) {
  18106. this.uuid = json.uuid;
  18107. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18108. const uuid = json.bones[ i ];
  18109. let bone = bones[ uuid ];
  18110. if ( bone === undefined ) {
  18111. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  18112. bone = new Bone();
  18113. }
  18114. this.bones.push( bone );
  18115. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18116. }
  18117. this.init();
  18118. return this;
  18119. }
  18120. toJSON() {
  18121. const data = {
  18122. metadata: {
  18123. version: 4.5,
  18124. type: 'Skeleton',
  18125. generator: 'Skeleton.toJSON'
  18126. },
  18127. bones: [],
  18128. boneInverses: []
  18129. };
  18130. data.uuid = this.uuid;
  18131. const bones = this.bones;
  18132. const boneInverses = this.boneInverses;
  18133. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18134. const bone = bones[ i ];
  18135. data.bones.push( bone.uuid );
  18136. const boneInverse = boneInverses[ i ];
  18137. data.boneInverses.push( boneInverse.toArray() );
  18138. }
  18139. return data;
  18140. }
  18141. }
  18142. class InstancedBufferAttribute extends BufferAttribute {
  18143. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18144. if ( typeof normalized === 'number' ) {
  18145. meshPerAttribute = normalized;
  18146. normalized = false;
  18147. console.error( 'THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.' );
  18148. }
  18149. super( array, itemSize, normalized );
  18150. this.meshPerAttribute = meshPerAttribute;
  18151. }
  18152. copy( source ) {
  18153. super.copy( source );
  18154. this.meshPerAttribute = source.meshPerAttribute;
  18155. return this;
  18156. }
  18157. toJSON() {
  18158. const data = super.toJSON();
  18159. data.meshPerAttribute = this.meshPerAttribute;
  18160. data.isInstancedBufferAttribute = true;
  18161. return data;
  18162. }
  18163. }
  18164. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  18165. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18166. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18167. const _instanceIntersects = [];
  18168. const _mesh = /*@__PURE__*/ new Mesh();
  18169. class InstancedMesh extends Mesh {
  18170. constructor( geometry, material, count ) {
  18171. super( geometry, material );
  18172. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18173. this.instanceColor = null;
  18174. this.count = count;
  18175. this.frustumCulled = false;
  18176. }
  18177. copy( source ) {
  18178. super.copy( source );
  18179. this.instanceMatrix.copy( source.instanceMatrix );
  18180. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  18181. this.count = source.count;
  18182. return this;
  18183. }
  18184. getColorAt( index, color ) {
  18185. color.fromArray( this.instanceColor.array, index * 3 );
  18186. }
  18187. getMatrixAt( index, matrix ) {
  18188. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  18189. }
  18190. raycast( raycaster, intersects ) {
  18191. const matrixWorld = this.matrixWorld;
  18192. const raycastTimes = this.count;
  18193. _mesh.geometry = this.geometry;
  18194. _mesh.material = this.material;
  18195. if ( _mesh.material === undefined ) return;
  18196. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  18197. // calculate the world matrix for each instance
  18198. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  18199. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  18200. // the mesh represents this single instance
  18201. _mesh.matrixWorld = _instanceWorldMatrix;
  18202. _mesh.raycast( raycaster, _instanceIntersects );
  18203. // process the result of raycast
  18204. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  18205. const intersect = _instanceIntersects[ i ];
  18206. intersect.instanceId = instanceId;
  18207. intersect.object = this;
  18208. intersects.push( intersect );
  18209. }
  18210. _instanceIntersects.length = 0;
  18211. }
  18212. }
  18213. setColorAt( index, color ) {
  18214. if ( this.instanceColor === null ) {
  18215. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  18216. }
  18217. color.toArray( this.instanceColor.array, index * 3 );
  18218. }
  18219. setMatrixAt( index, matrix ) {
  18220. matrix.toArray( this.instanceMatrix.array, index * 16 );
  18221. }
  18222. updateMorphTargets() {
  18223. }
  18224. dispose() {
  18225. this.dispatchEvent( { type: 'dispose' } );
  18226. }
  18227. }
  18228. InstancedMesh.prototype.isInstancedMesh = true;
  18229. /**
  18230. * parameters = {
  18231. * color: <hex>,
  18232. * opacity: <float>,
  18233. *
  18234. * linewidth: <float>,
  18235. * linecap: "round",
  18236. * linejoin: "round"
  18237. * }
  18238. */
  18239. class LineBasicMaterial extends Material {
  18240. constructor( parameters ) {
  18241. super();
  18242. this.type = 'LineBasicMaterial';
  18243. this.color = new Color( 0xffffff );
  18244. this.linewidth = 1;
  18245. this.linecap = 'round';
  18246. this.linejoin = 'round';
  18247. this.setValues( parameters );
  18248. }
  18249. copy( source ) {
  18250. super.copy( source );
  18251. this.color.copy( source.color );
  18252. this.linewidth = source.linewidth;
  18253. this.linecap = source.linecap;
  18254. this.linejoin = source.linejoin;
  18255. return this;
  18256. }
  18257. }
  18258. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  18259. const _start$1 = /*@__PURE__*/ new Vector3();
  18260. const _end$1 = /*@__PURE__*/ new Vector3();
  18261. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  18262. const _ray$1 = /*@__PURE__*/ new Ray();
  18263. const _sphere$1 = /*@__PURE__*/ new Sphere();
  18264. class Line extends Object3D {
  18265. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  18266. super();
  18267. this.type = 'Line';
  18268. this.geometry = geometry;
  18269. this.material = material;
  18270. this.updateMorphTargets();
  18271. }
  18272. copy( source ) {
  18273. super.copy( source );
  18274. this.material = source.material;
  18275. this.geometry = source.geometry;
  18276. return this;
  18277. }
  18278. computeLineDistances() {
  18279. const geometry = this.geometry;
  18280. if ( geometry.isBufferGeometry ) {
  18281. // we assume non-indexed geometry
  18282. if ( geometry.index === null ) {
  18283. const positionAttribute = geometry.attributes.position;
  18284. const lineDistances = [ 0 ];
  18285. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  18286. _start$1.fromBufferAttribute( positionAttribute, i - 1 );
  18287. _end$1.fromBufferAttribute( positionAttribute, i );
  18288. lineDistances[ i ] = lineDistances[ i - 1 ];
  18289. lineDistances[ i ] += _start$1.distanceTo( _end$1 );
  18290. }
  18291. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  18292. } else {
  18293. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  18294. }
  18295. } else if ( geometry.isGeometry ) {
  18296. console.error( 'THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  18297. }
  18298. return this;
  18299. }
  18300. raycast( raycaster, intersects ) {
  18301. const geometry = this.geometry;
  18302. const matrixWorld = this.matrixWorld;
  18303. const threshold = raycaster.params.Line.threshold;
  18304. const drawRange = geometry.drawRange;
  18305. // Checking boundingSphere distance to ray
  18306. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18307. _sphere$1.copy( geometry.boundingSphere );
  18308. _sphere$1.applyMatrix4( matrixWorld );
  18309. _sphere$1.radius += threshold;
  18310. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  18311. //
  18312. _inverseMatrix$1.copy( matrixWorld ).invert();
  18313. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  18314. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18315. const localThresholdSq = localThreshold * localThreshold;
  18316. const vStart = new Vector3();
  18317. const vEnd = new Vector3();
  18318. const interSegment = new Vector3();
  18319. const interRay = new Vector3();
  18320. const step = this.isLineSegments ? 2 : 1;
  18321. if ( geometry.isBufferGeometry ) {
  18322. const index = geometry.index;
  18323. const attributes = geometry.attributes;
  18324. const positionAttribute = attributes.position;
  18325. if ( index !== null ) {
  18326. const start = Math.max( 0, drawRange.start );
  18327. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  18328. for ( let i = start, l = end - 1; i < l; i += step ) {
  18329. const a = index.getX( i );
  18330. const b = index.getX( i + 1 );
  18331. vStart.fromBufferAttribute( positionAttribute, a );
  18332. vEnd.fromBufferAttribute( positionAttribute, b );
  18333. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18334. if ( distSq > localThresholdSq ) continue;
  18335. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18336. const distance = raycaster.ray.origin.distanceTo( interRay );
  18337. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18338. intersects.push( {
  18339. distance: distance,
  18340. // What do we want? intersection point on the ray or on the segment??
  18341. // point: raycaster.ray.at( distance ),
  18342. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18343. index: i,
  18344. face: null,
  18345. faceIndex: null,
  18346. object: this
  18347. } );
  18348. }
  18349. } else {
  18350. const start = Math.max( 0, drawRange.start );
  18351. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  18352. for ( let i = start, l = end - 1; i < l; i += step ) {
  18353. vStart.fromBufferAttribute( positionAttribute, i );
  18354. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  18355. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18356. if ( distSq > localThresholdSq ) continue;
  18357. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18358. const distance = raycaster.ray.origin.distanceTo( interRay );
  18359. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18360. intersects.push( {
  18361. distance: distance,
  18362. // What do we want? intersection point on the ray or on the segment??
  18363. // point: raycaster.ray.at( distance ),
  18364. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18365. index: i,
  18366. face: null,
  18367. faceIndex: null,
  18368. object: this
  18369. } );
  18370. }
  18371. }
  18372. } else if ( geometry.isGeometry ) {
  18373. console.error( 'THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  18374. }
  18375. }
  18376. updateMorphTargets() {
  18377. const geometry = this.geometry;
  18378. if ( geometry.isBufferGeometry ) {
  18379. const morphAttributes = geometry.morphAttributes;
  18380. const keys = Object.keys( morphAttributes );
  18381. if ( keys.length > 0 ) {
  18382. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  18383. if ( morphAttribute !== undefined ) {
  18384. this.morphTargetInfluences = [];
  18385. this.morphTargetDictionary = {};
  18386. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  18387. const name = morphAttribute[ m ].name || String( m );
  18388. this.morphTargetInfluences.push( 0 );
  18389. this.morphTargetDictionary[ name ] = m;
  18390. }
  18391. }
  18392. }
  18393. } else {
  18394. const morphTargets = geometry.morphTargets;
  18395. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  18396. console.error( 'THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  18397. }
  18398. }
  18399. }
  18400. }
  18401. Line.prototype.isLine = true;
  18402. const _start = /*@__PURE__*/ new Vector3();
  18403. const _end = /*@__PURE__*/ new Vector3();
  18404. class LineSegments extends Line {
  18405. constructor( geometry, material ) {
  18406. super( geometry, material );
  18407. this.type = 'LineSegments';
  18408. }
  18409. computeLineDistances() {
  18410. const geometry = this.geometry;
  18411. if ( geometry.isBufferGeometry ) {
  18412. // we assume non-indexed geometry
  18413. if ( geometry.index === null ) {
  18414. const positionAttribute = geometry.attributes.position;
  18415. const lineDistances = [];
  18416. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  18417. _start.fromBufferAttribute( positionAttribute, i );
  18418. _end.fromBufferAttribute( positionAttribute, i + 1 );
  18419. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  18420. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  18421. }
  18422. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  18423. } else {
  18424. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  18425. }
  18426. } else if ( geometry.isGeometry ) {
  18427. console.error( 'THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  18428. }
  18429. return this;
  18430. }
  18431. }
  18432. LineSegments.prototype.isLineSegments = true;
  18433. class LineLoop extends Line {
  18434. constructor( geometry, material ) {
  18435. super( geometry, material );
  18436. this.type = 'LineLoop';
  18437. }
  18438. }
  18439. LineLoop.prototype.isLineLoop = true;
  18440. /**
  18441. * parameters = {
  18442. * color: <hex>,
  18443. * opacity: <float>,
  18444. * map: new THREE.Texture( <Image> ),
  18445. * alphaMap: new THREE.Texture( <Image> ),
  18446. *
  18447. * size: <float>,
  18448. * sizeAttenuation: <bool>
  18449. *
  18450. * }
  18451. */
  18452. class PointsMaterial extends Material {
  18453. constructor( parameters ) {
  18454. super();
  18455. this.type = 'PointsMaterial';
  18456. this.color = new Color( 0xffffff );
  18457. this.map = null;
  18458. this.alphaMap = null;
  18459. this.size = 1;
  18460. this.sizeAttenuation = true;
  18461. this.setValues( parameters );
  18462. }
  18463. copy( source ) {
  18464. super.copy( source );
  18465. this.color.copy( source.color );
  18466. this.map = source.map;
  18467. this.alphaMap = source.alphaMap;
  18468. this.size = source.size;
  18469. this.sizeAttenuation = source.sizeAttenuation;
  18470. return this;
  18471. }
  18472. }
  18473. PointsMaterial.prototype.isPointsMaterial = true;
  18474. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  18475. const _ray = /*@__PURE__*/ new Ray();
  18476. const _sphere = /*@__PURE__*/ new Sphere();
  18477. const _position$2 = /*@__PURE__*/ new Vector3();
  18478. class Points extends Object3D {
  18479. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  18480. super();
  18481. this.type = 'Points';
  18482. this.geometry = geometry;
  18483. this.material = material;
  18484. this.updateMorphTargets();
  18485. }
  18486. copy( source ) {
  18487. super.copy( source );
  18488. this.material = source.material;
  18489. this.geometry = source.geometry;
  18490. return this;
  18491. }
  18492. raycast( raycaster, intersects ) {
  18493. const geometry = this.geometry;
  18494. const matrixWorld = this.matrixWorld;
  18495. const threshold = raycaster.params.Points.threshold;
  18496. const drawRange = geometry.drawRange;
  18497. // Checking boundingSphere distance to ray
  18498. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18499. _sphere.copy( geometry.boundingSphere );
  18500. _sphere.applyMatrix4( matrixWorld );
  18501. _sphere.radius += threshold;
  18502. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  18503. //
  18504. _inverseMatrix.copy( matrixWorld ).invert();
  18505. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  18506. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18507. const localThresholdSq = localThreshold * localThreshold;
  18508. if ( geometry.isBufferGeometry ) {
  18509. const index = geometry.index;
  18510. const attributes = geometry.attributes;
  18511. const positionAttribute = attributes.position;
  18512. if ( index !== null ) {
  18513. const start = Math.max( 0, drawRange.start );
  18514. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  18515. for ( let i = start, il = end; i < il; i ++ ) {
  18516. const a = index.getX( i );
  18517. _position$2.fromBufferAttribute( positionAttribute, a );
  18518. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  18519. }
  18520. } else {
  18521. const start = Math.max( 0, drawRange.start );
  18522. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  18523. for ( let i = start, l = end; i < l; i ++ ) {
  18524. _position$2.fromBufferAttribute( positionAttribute, i );
  18525. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  18526. }
  18527. }
  18528. } else {
  18529. console.error( 'THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  18530. }
  18531. }
  18532. updateMorphTargets() {
  18533. const geometry = this.geometry;
  18534. if ( geometry.isBufferGeometry ) {
  18535. const morphAttributes = geometry.morphAttributes;
  18536. const keys = Object.keys( morphAttributes );
  18537. if ( keys.length > 0 ) {
  18538. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  18539. if ( morphAttribute !== undefined ) {
  18540. this.morphTargetInfluences = [];
  18541. this.morphTargetDictionary = {};
  18542. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  18543. const name = morphAttribute[ m ].name || String( m );
  18544. this.morphTargetInfluences.push( 0 );
  18545. this.morphTargetDictionary[ name ] = m;
  18546. }
  18547. }
  18548. }
  18549. } else {
  18550. const morphTargets = geometry.morphTargets;
  18551. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  18552. console.error( 'THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  18553. }
  18554. }
  18555. }
  18556. }
  18557. Points.prototype.isPoints = true;
  18558. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  18559. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  18560. if ( rayPointDistanceSq < localThresholdSq ) {
  18561. const intersectPoint = new Vector3();
  18562. _ray.closestPointToPoint( point, intersectPoint );
  18563. intersectPoint.applyMatrix4( matrixWorld );
  18564. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  18565. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18566. intersects.push( {
  18567. distance: distance,
  18568. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  18569. point: intersectPoint,
  18570. index: index,
  18571. face: null,
  18572. object: object
  18573. } );
  18574. }
  18575. }
  18576. class VideoTexture extends Texture {
  18577. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18578. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18579. this.format = format !== undefined ? format : RGBFormat;
  18580. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  18581. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  18582. this.generateMipmaps = false;
  18583. const scope = this;
  18584. function updateVideo() {
  18585. scope.needsUpdate = true;
  18586. video.requestVideoFrameCallback( updateVideo );
  18587. }
  18588. if ( 'requestVideoFrameCallback' in video ) {
  18589. video.requestVideoFrameCallback( updateVideo );
  18590. }
  18591. }
  18592. clone() {
  18593. return new this.constructor( this.image ).copy( this );
  18594. }
  18595. update() {
  18596. const video = this.image;
  18597. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  18598. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  18599. this.needsUpdate = true;
  18600. }
  18601. }
  18602. }
  18603. VideoTexture.prototype.isVideoTexture = true;
  18604. class CompressedTexture extends Texture {
  18605. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  18606. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  18607. this.image = { width: width, height: height };
  18608. this.mipmaps = mipmaps;
  18609. // no flipping for cube textures
  18610. // (also flipping doesn't work for compressed textures )
  18611. this.flipY = false;
  18612. // can't generate mipmaps for compressed textures
  18613. // mips must be embedded in DDS files
  18614. this.generateMipmaps = false;
  18615. }
  18616. }
  18617. CompressedTexture.prototype.isCompressedTexture = true;
  18618. class CanvasTexture extends Texture {
  18619. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18620. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18621. this.needsUpdate = true;
  18622. }
  18623. }
  18624. CanvasTexture.prototype.isCanvasTexture = true;
  18625. class DepthTexture extends Texture {
  18626. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  18627. format = format !== undefined ? format : DepthFormat;
  18628. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  18629. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  18630. }
  18631. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  18632. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  18633. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18634. this.image = { width: width, height: height };
  18635. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  18636. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  18637. this.flipY = false;
  18638. this.generateMipmaps = false;
  18639. }
  18640. }
  18641. DepthTexture.prototype.isDepthTexture = true;
  18642. class CircleGeometry extends BufferGeometry {
  18643. constructor( radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  18644. super();
  18645. this.type = 'CircleGeometry';
  18646. this.parameters = {
  18647. radius: radius,
  18648. segments: segments,
  18649. thetaStart: thetaStart,
  18650. thetaLength: thetaLength
  18651. };
  18652. segments = Math.max( 3, segments );
  18653. // buffers
  18654. const indices = [];
  18655. const vertices = [];
  18656. const normals = [];
  18657. const uvs = [];
  18658. // helper variables
  18659. const vertex = new Vector3();
  18660. const uv = new Vector2();
  18661. // center point
  18662. vertices.push( 0, 0, 0 );
  18663. normals.push( 0, 0, 1 );
  18664. uvs.push( 0.5, 0.5 );
  18665. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  18666. const segment = thetaStart + s / segments * thetaLength;
  18667. // vertex
  18668. vertex.x = radius * Math.cos( segment );
  18669. vertex.y = radius * Math.sin( segment );
  18670. vertices.push( vertex.x, vertex.y, vertex.z );
  18671. // normal
  18672. normals.push( 0, 0, 1 );
  18673. // uvs
  18674. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  18675. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  18676. uvs.push( uv.x, uv.y );
  18677. }
  18678. // indices
  18679. for ( let i = 1; i <= segments; i ++ ) {
  18680. indices.push( i, i + 1, 0 );
  18681. }
  18682. // build geometry
  18683. this.setIndex( indices );
  18684. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18685. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  18686. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18687. }
  18688. static fromJSON( data ) {
  18689. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  18690. }
  18691. }
  18692. class CylinderGeometry extends BufferGeometry {
  18693. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  18694. super();
  18695. this.type = 'CylinderGeometry';
  18696. this.parameters = {
  18697. radiusTop: radiusTop,
  18698. radiusBottom: radiusBottom,
  18699. height: height,
  18700. radialSegments: radialSegments,
  18701. heightSegments: heightSegments,
  18702. openEnded: openEnded,
  18703. thetaStart: thetaStart,
  18704. thetaLength: thetaLength
  18705. };
  18706. const scope = this;
  18707. radialSegments = Math.floor( radialSegments );
  18708. heightSegments = Math.floor( heightSegments );
  18709. // buffers
  18710. const indices = [];
  18711. const vertices = [];
  18712. const normals = [];
  18713. const uvs = [];
  18714. // helper variables
  18715. let index = 0;
  18716. const indexArray = [];
  18717. const halfHeight = height / 2;
  18718. let groupStart = 0;
  18719. // generate geometry
  18720. generateTorso();
  18721. if ( openEnded === false ) {
  18722. if ( radiusTop > 0 ) generateCap( true );
  18723. if ( radiusBottom > 0 ) generateCap( false );
  18724. }
  18725. // build geometry
  18726. this.setIndex( indices );
  18727. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18728. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  18729. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18730. function generateTorso() {
  18731. const normal = new Vector3();
  18732. const vertex = new Vector3();
  18733. let groupCount = 0;
  18734. // this will be used to calculate the normal
  18735. const slope = ( radiusBottom - radiusTop ) / height;
  18736. // generate vertices, normals and uvs
  18737. for ( let y = 0; y <= heightSegments; y ++ ) {
  18738. const indexRow = [];
  18739. const v = y / heightSegments;
  18740. // calculate the radius of the current row
  18741. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18742. for ( let x = 0; x <= radialSegments; x ++ ) {
  18743. const u = x / radialSegments;
  18744. const theta = u * thetaLength + thetaStart;
  18745. const sinTheta = Math.sin( theta );
  18746. const cosTheta = Math.cos( theta );
  18747. // vertex
  18748. vertex.x = radius * sinTheta;
  18749. vertex.y = - v * height + halfHeight;
  18750. vertex.z = radius * cosTheta;
  18751. vertices.push( vertex.x, vertex.y, vertex.z );
  18752. // normal
  18753. normal.set( sinTheta, slope, cosTheta ).normalize();
  18754. normals.push( normal.x, normal.y, normal.z );
  18755. // uv
  18756. uvs.push( u, 1 - v );
  18757. // save index of vertex in respective row
  18758. indexRow.push( index ++ );
  18759. }
  18760. // now save vertices of the row in our index array
  18761. indexArray.push( indexRow );
  18762. }
  18763. // generate indices
  18764. for ( let x = 0; x < radialSegments; x ++ ) {
  18765. for ( let y = 0; y < heightSegments; y ++ ) {
  18766. // we use the index array to access the correct indices
  18767. const a = indexArray[ y ][ x ];
  18768. const b = indexArray[ y + 1 ][ x ];
  18769. const c = indexArray[ y + 1 ][ x + 1 ];
  18770. const d = indexArray[ y ][ x + 1 ];
  18771. // faces
  18772. indices.push( a, b, d );
  18773. indices.push( b, c, d );
  18774. // update group counter
  18775. groupCount += 6;
  18776. }
  18777. }
  18778. // add a group to the geometry. this will ensure multi material support
  18779. scope.addGroup( groupStart, groupCount, 0 );
  18780. // calculate new start value for groups
  18781. groupStart += groupCount;
  18782. }
  18783. function generateCap( top ) {
  18784. // save the index of the first center vertex
  18785. const centerIndexStart = index;
  18786. const uv = new Vector2();
  18787. const vertex = new Vector3();
  18788. let groupCount = 0;
  18789. const radius = ( top === true ) ? radiusTop : radiusBottom;
  18790. const sign = ( top === true ) ? 1 : - 1;
  18791. // first we generate the center vertex data of the cap.
  18792. // because the geometry needs one set of uvs per face,
  18793. // we must generate a center vertex per face/segment
  18794. for ( let x = 1; x <= radialSegments; x ++ ) {
  18795. // vertex
  18796. vertices.push( 0, halfHeight * sign, 0 );
  18797. // normal
  18798. normals.push( 0, sign, 0 );
  18799. // uv
  18800. uvs.push( 0.5, 0.5 );
  18801. // increase index
  18802. index ++;
  18803. }
  18804. // save the index of the last center vertex
  18805. const centerIndexEnd = index;
  18806. // now we generate the surrounding vertices, normals and uvs
  18807. for ( let x = 0; x <= radialSegments; x ++ ) {
  18808. const u = x / radialSegments;
  18809. const theta = u * thetaLength + thetaStart;
  18810. const cosTheta = Math.cos( theta );
  18811. const sinTheta = Math.sin( theta );
  18812. // vertex
  18813. vertex.x = radius * sinTheta;
  18814. vertex.y = halfHeight * sign;
  18815. vertex.z = radius * cosTheta;
  18816. vertices.push( vertex.x, vertex.y, vertex.z );
  18817. // normal
  18818. normals.push( 0, sign, 0 );
  18819. // uv
  18820. uv.x = ( cosTheta * 0.5 ) + 0.5;
  18821. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  18822. uvs.push( uv.x, uv.y );
  18823. // increase index
  18824. index ++;
  18825. }
  18826. // generate indices
  18827. for ( let x = 0; x < radialSegments; x ++ ) {
  18828. const c = centerIndexStart + x;
  18829. const i = centerIndexEnd + x;
  18830. if ( top === true ) {
  18831. // face top
  18832. indices.push( i, i + 1, c );
  18833. } else {
  18834. // face bottom
  18835. indices.push( i + 1, i, c );
  18836. }
  18837. groupCount += 3;
  18838. }
  18839. // add a group to the geometry. this will ensure multi material support
  18840. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  18841. // calculate new start value for groups
  18842. groupStart += groupCount;
  18843. }
  18844. }
  18845. static fromJSON( data ) {
  18846. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  18847. }
  18848. }
  18849. class ConeGeometry extends CylinderGeometry {
  18850. constructor( radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  18851. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  18852. this.type = 'ConeGeometry';
  18853. this.parameters = {
  18854. radius: radius,
  18855. height: height,
  18856. radialSegments: radialSegments,
  18857. heightSegments: heightSegments,
  18858. openEnded: openEnded,
  18859. thetaStart: thetaStart,
  18860. thetaLength: thetaLength
  18861. };
  18862. }
  18863. static fromJSON( data ) {
  18864. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  18865. }
  18866. }
  18867. class PolyhedronGeometry extends BufferGeometry {
  18868. constructor( vertices, indices, radius = 1, detail = 0 ) {
  18869. super();
  18870. this.type = 'PolyhedronGeometry';
  18871. this.parameters = {
  18872. vertices: vertices,
  18873. indices: indices,
  18874. radius: radius,
  18875. detail: detail
  18876. };
  18877. // default buffer data
  18878. const vertexBuffer = [];
  18879. const uvBuffer = [];
  18880. // the subdivision creates the vertex buffer data
  18881. subdivide( detail );
  18882. // all vertices should lie on a conceptual sphere with a given radius
  18883. applyRadius( radius );
  18884. // finally, create the uv data
  18885. generateUVs();
  18886. // build non-indexed geometry
  18887. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  18888. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  18889. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  18890. if ( detail === 0 ) {
  18891. this.computeVertexNormals(); // flat normals
  18892. } else {
  18893. this.normalizeNormals(); // smooth normals
  18894. }
  18895. // helper functions
  18896. function subdivide( detail ) {
  18897. const a = new Vector3();
  18898. const b = new Vector3();
  18899. const c = new Vector3();
  18900. // iterate over all faces and apply a subdivison with the given detail value
  18901. for ( let i = 0; i < indices.length; i += 3 ) {
  18902. // get the vertices of the face
  18903. getVertexByIndex( indices[ i + 0 ], a );
  18904. getVertexByIndex( indices[ i + 1 ], b );
  18905. getVertexByIndex( indices[ i + 2 ], c );
  18906. // perform subdivision
  18907. subdivideFace( a, b, c, detail );
  18908. }
  18909. }
  18910. function subdivideFace( a, b, c, detail ) {
  18911. const cols = detail + 1;
  18912. // we use this multidimensional array as a data structure for creating the subdivision
  18913. const v = [];
  18914. // construct all of the vertices for this subdivision
  18915. for ( let i = 0; i <= cols; i ++ ) {
  18916. v[ i ] = [];
  18917. const aj = a.clone().lerp( c, i / cols );
  18918. const bj = b.clone().lerp( c, i / cols );
  18919. const rows = cols - i;
  18920. for ( let j = 0; j <= rows; j ++ ) {
  18921. if ( j === 0 && i === cols ) {
  18922. v[ i ][ j ] = aj;
  18923. } else {
  18924. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  18925. }
  18926. }
  18927. }
  18928. // construct all of the faces
  18929. for ( let i = 0; i < cols; i ++ ) {
  18930. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  18931. const k = Math.floor( j / 2 );
  18932. if ( j % 2 === 0 ) {
  18933. pushVertex( v[ i ][ k + 1 ] );
  18934. pushVertex( v[ i + 1 ][ k ] );
  18935. pushVertex( v[ i ][ k ] );
  18936. } else {
  18937. pushVertex( v[ i ][ k + 1 ] );
  18938. pushVertex( v[ i + 1 ][ k + 1 ] );
  18939. pushVertex( v[ i + 1 ][ k ] );
  18940. }
  18941. }
  18942. }
  18943. }
  18944. function applyRadius( radius ) {
  18945. const vertex = new Vector3();
  18946. // iterate over the entire buffer and apply the radius to each vertex
  18947. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  18948. vertex.x = vertexBuffer[ i + 0 ];
  18949. vertex.y = vertexBuffer[ i + 1 ];
  18950. vertex.z = vertexBuffer[ i + 2 ];
  18951. vertex.normalize().multiplyScalar( radius );
  18952. vertexBuffer[ i + 0 ] = vertex.x;
  18953. vertexBuffer[ i + 1 ] = vertex.y;
  18954. vertexBuffer[ i + 2 ] = vertex.z;
  18955. }
  18956. }
  18957. function generateUVs() {
  18958. const vertex = new Vector3();
  18959. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  18960. vertex.x = vertexBuffer[ i + 0 ];
  18961. vertex.y = vertexBuffer[ i + 1 ];
  18962. vertex.z = vertexBuffer[ i + 2 ];
  18963. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  18964. const v = inclination( vertex ) / Math.PI + 0.5;
  18965. uvBuffer.push( u, 1 - v );
  18966. }
  18967. correctUVs();
  18968. correctSeam();
  18969. }
  18970. function correctSeam() {
  18971. // handle case when face straddles the seam, see #3269
  18972. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  18973. // uv data of a single face
  18974. const x0 = uvBuffer[ i + 0 ];
  18975. const x1 = uvBuffer[ i + 2 ];
  18976. const x2 = uvBuffer[ i + 4 ];
  18977. const max = Math.max( x0, x1, x2 );
  18978. const min = Math.min( x0, x1, x2 );
  18979. // 0.9 is somewhat arbitrary
  18980. if ( max > 0.9 && min < 0.1 ) {
  18981. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  18982. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  18983. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  18984. }
  18985. }
  18986. }
  18987. function pushVertex( vertex ) {
  18988. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  18989. }
  18990. function getVertexByIndex( index, vertex ) {
  18991. const stride = index * 3;
  18992. vertex.x = vertices[ stride + 0 ];
  18993. vertex.y = vertices[ stride + 1 ];
  18994. vertex.z = vertices[ stride + 2 ];
  18995. }
  18996. function correctUVs() {
  18997. const a = new Vector3();
  18998. const b = new Vector3();
  18999. const c = new Vector3();
  19000. const centroid = new Vector3();
  19001. const uvA = new Vector2();
  19002. const uvB = new Vector2();
  19003. const uvC = new Vector2();
  19004. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  19005. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  19006. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  19007. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  19008. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  19009. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  19010. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  19011. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  19012. const azi = azimuth( centroid );
  19013. correctUV( uvA, j + 0, a, azi );
  19014. correctUV( uvB, j + 2, b, azi );
  19015. correctUV( uvC, j + 4, c, azi );
  19016. }
  19017. }
  19018. function correctUV( uv, stride, vector, azimuth ) {
  19019. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  19020. uvBuffer[ stride ] = uv.x - 1;
  19021. }
  19022. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  19023. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  19024. }
  19025. }
  19026. // Angle around the Y axis, counter-clockwise when looking from above.
  19027. function azimuth( vector ) {
  19028. return Math.atan2( vector.z, - vector.x );
  19029. }
  19030. // Angle above the XZ plane.
  19031. function inclination( vector ) {
  19032. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19033. }
  19034. }
  19035. static fromJSON( data ) {
  19036. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  19037. }
  19038. }
  19039. class DodecahedronGeometry extends PolyhedronGeometry {
  19040. constructor( radius = 1, detail = 0 ) {
  19041. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19042. const r = 1 / t;
  19043. const vertices = [
  19044. // (±1, ±1, ±1)
  19045. - 1, - 1, - 1, - 1, - 1, 1,
  19046. - 1, 1, - 1, - 1, 1, 1,
  19047. 1, - 1, - 1, 1, - 1, 1,
  19048. 1, 1, - 1, 1, 1, 1,
  19049. // (0, ±1/φ, ±φ)
  19050. 0, - r, - t, 0, - r, t,
  19051. 0, r, - t, 0, r, t,
  19052. // (±1/φ, ±φ, 0)
  19053. - r, - t, 0, - r, t, 0,
  19054. r, - t, 0, r, t, 0,
  19055. // (±φ, 0, ±1/φ)
  19056. - t, 0, - r, t, 0, - r,
  19057. - t, 0, r, t, 0, r
  19058. ];
  19059. const indices = [
  19060. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  19061. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  19062. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  19063. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  19064. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  19065. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  19066. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  19067. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  19068. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  19069. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  19070. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  19071. 1, 12, 14, 1, 14, 5, 1, 5, 9
  19072. ];
  19073. super( vertices, indices, radius, detail );
  19074. this.type = 'DodecahedronGeometry';
  19075. this.parameters = {
  19076. radius: radius,
  19077. detail: detail
  19078. };
  19079. }
  19080. static fromJSON( data ) {
  19081. return new DodecahedronGeometry( data.radius, data.detail );
  19082. }
  19083. }
  19084. const _v0 = new Vector3();
  19085. const _v1$1 = new Vector3();
  19086. const _normal = new Vector3();
  19087. const _triangle = new Triangle();
  19088. class EdgesGeometry extends BufferGeometry {
  19089. constructor( geometry, thresholdAngle ) {
  19090. super();
  19091. this.type = 'EdgesGeometry';
  19092. this.parameters = {
  19093. thresholdAngle: thresholdAngle
  19094. };
  19095. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  19096. if ( geometry.isGeometry === true ) {
  19097. console.error( 'THREE.EdgesGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  19098. return;
  19099. }
  19100. const precisionPoints = 4;
  19101. const precision = Math.pow( 10, precisionPoints );
  19102. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  19103. const indexAttr = geometry.getIndex();
  19104. const positionAttr = geometry.getAttribute( 'position' );
  19105. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  19106. const indexArr = [ 0, 0, 0 ];
  19107. const vertKeys = [ 'a', 'b', 'c' ];
  19108. const hashes = new Array( 3 );
  19109. const edgeData = {};
  19110. const vertices = [];
  19111. for ( let i = 0; i < indexCount; i += 3 ) {
  19112. if ( indexAttr ) {
  19113. indexArr[ 0 ] = indexAttr.getX( i );
  19114. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  19115. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  19116. } else {
  19117. indexArr[ 0 ] = i;
  19118. indexArr[ 1 ] = i + 1;
  19119. indexArr[ 2 ] = i + 2;
  19120. }
  19121. const { a, b, c } = _triangle;
  19122. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  19123. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  19124. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  19125. _triangle.getNormal( _normal );
  19126. // create hashes for the edge from the vertices
  19127. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  19128. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  19129. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  19130. // skip degenerate triangles
  19131. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  19132. continue;
  19133. }
  19134. // iterate over every edge
  19135. for ( let j = 0; j < 3; j ++ ) {
  19136. // get the first and next vertex making up the edge
  19137. const jNext = ( j + 1 ) % 3;
  19138. const vecHash0 = hashes[ j ];
  19139. const vecHash1 = hashes[ jNext ];
  19140. const v0 = _triangle[ vertKeys[ j ] ];
  19141. const v1 = _triangle[ vertKeys[ jNext ] ];
  19142. const hash = `${ vecHash0 }_${ vecHash1 }`;
  19143. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  19144. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  19145. // if we found a sibling edge add it into the vertex array if
  19146. // it meets the angle threshold and delete the edge from the map.
  19147. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  19148. vertices.push( v0.x, v0.y, v0.z );
  19149. vertices.push( v1.x, v1.y, v1.z );
  19150. }
  19151. edgeData[ reverseHash ] = null;
  19152. } else if ( ! ( hash in edgeData ) ) {
  19153. // if we've already got an edge here then skip adding a new one
  19154. edgeData[ hash ] = {
  19155. index0: indexArr[ j ],
  19156. index1: indexArr[ jNext ],
  19157. normal: _normal.clone(),
  19158. };
  19159. }
  19160. }
  19161. }
  19162. // iterate over all remaining, unmatched edges and add them to the vertex array
  19163. for ( const key in edgeData ) {
  19164. if ( edgeData[ key ] ) {
  19165. const { index0, index1 } = edgeData[ key ];
  19166. _v0.fromBufferAttribute( positionAttr, index0 );
  19167. _v1$1.fromBufferAttribute( positionAttr, index1 );
  19168. vertices.push( _v0.x, _v0.y, _v0.z );
  19169. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  19170. }
  19171. }
  19172. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19173. }
  19174. }
  19175. /**
  19176. * Extensible curve object.
  19177. *
  19178. * Some common of curve methods:
  19179. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  19180. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  19181. * .getPoints(), .getSpacedPoints()
  19182. * .getLength()
  19183. * .updateArcLengths()
  19184. *
  19185. * This following curves inherit from THREE.Curve:
  19186. *
  19187. * -- 2D curves --
  19188. * THREE.ArcCurve
  19189. * THREE.CubicBezierCurve
  19190. * THREE.EllipseCurve
  19191. * THREE.LineCurve
  19192. * THREE.QuadraticBezierCurve
  19193. * THREE.SplineCurve
  19194. *
  19195. * -- 3D curves --
  19196. * THREE.CatmullRomCurve3
  19197. * THREE.CubicBezierCurve3
  19198. * THREE.LineCurve3
  19199. * THREE.QuadraticBezierCurve3
  19200. *
  19201. * A series of curves can be represented as a THREE.CurvePath.
  19202. *
  19203. **/
  19204. class Curve {
  19205. constructor() {
  19206. this.type = 'Curve';
  19207. this.arcLengthDivisions = 200;
  19208. }
  19209. // Virtual base class method to overwrite and implement in subclasses
  19210. // - t [0 .. 1]
  19211. getPoint( /* t, optionalTarget */ ) {
  19212. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  19213. return null;
  19214. }
  19215. // Get point at relative position in curve according to arc length
  19216. // - u [0 .. 1]
  19217. getPointAt( u, optionalTarget ) {
  19218. const t = this.getUtoTmapping( u );
  19219. return this.getPoint( t, optionalTarget );
  19220. }
  19221. // Get sequence of points using getPoint( t )
  19222. getPoints( divisions = 5 ) {
  19223. const points = [];
  19224. for ( let d = 0; d <= divisions; d ++ ) {
  19225. points.push( this.getPoint( d / divisions ) );
  19226. }
  19227. return points;
  19228. }
  19229. // Get sequence of points using getPointAt( u )
  19230. getSpacedPoints( divisions = 5 ) {
  19231. const points = [];
  19232. for ( let d = 0; d <= divisions; d ++ ) {
  19233. points.push( this.getPointAt( d / divisions ) );
  19234. }
  19235. return points;
  19236. }
  19237. // Get total curve arc length
  19238. getLength() {
  19239. const lengths = this.getLengths();
  19240. return lengths[ lengths.length - 1 ];
  19241. }
  19242. // Get list of cumulative segment lengths
  19243. getLengths( divisions = this.arcLengthDivisions ) {
  19244. if ( this.cacheArcLengths &&
  19245. ( this.cacheArcLengths.length === divisions + 1 ) &&
  19246. ! this.needsUpdate ) {
  19247. return this.cacheArcLengths;
  19248. }
  19249. this.needsUpdate = false;
  19250. const cache = [];
  19251. let current, last = this.getPoint( 0 );
  19252. let sum = 0;
  19253. cache.push( 0 );
  19254. for ( let p = 1; p <= divisions; p ++ ) {
  19255. current = this.getPoint( p / divisions );
  19256. sum += current.distanceTo( last );
  19257. cache.push( sum );
  19258. last = current;
  19259. }
  19260. this.cacheArcLengths = cache;
  19261. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  19262. }
  19263. updateArcLengths() {
  19264. this.needsUpdate = true;
  19265. this.getLengths();
  19266. }
  19267. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  19268. getUtoTmapping( u, distance ) {
  19269. const arcLengths = this.getLengths();
  19270. let i = 0;
  19271. const il = arcLengths.length;
  19272. let targetArcLength; // The targeted u distance value to get
  19273. if ( distance ) {
  19274. targetArcLength = distance;
  19275. } else {
  19276. targetArcLength = u * arcLengths[ il - 1 ];
  19277. }
  19278. // binary search for the index with largest value smaller than target u distance
  19279. let low = 0, high = il - 1, comparison;
  19280. while ( low <= high ) {
  19281. 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
  19282. comparison = arcLengths[ i ] - targetArcLength;
  19283. if ( comparison < 0 ) {
  19284. low = i + 1;
  19285. } else if ( comparison > 0 ) {
  19286. high = i - 1;
  19287. } else {
  19288. high = i;
  19289. break;
  19290. // DONE
  19291. }
  19292. }
  19293. i = high;
  19294. if ( arcLengths[ i ] === targetArcLength ) {
  19295. return i / ( il - 1 );
  19296. }
  19297. // we could get finer grain at lengths, or use simple interpolation between two points
  19298. const lengthBefore = arcLengths[ i ];
  19299. const lengthAfter = arcLengths[ i + 1 ];
  19300. const segmentLength = lengthAfter - lengthBefore;
  19301. // determine where we are between the 'before' and 'after' points
  19302. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  19303. // add that fractional amount to t
  19304. const t = ( i + segmentFraction ) / ( il - 1 );
  19305. return t;
  19306. }
  19307. // Returns a unit vector tangent at t
  19308. // In case any sub curve does not implement its tangent derivation,
  19309. // 2 points a small delta apart will be used to find its gradient
  19310. // which seems to give a reasonable approximation
  19311. getTangent( t, optionalTarget ) {
  19312. const delta = 0.0001;
  19313. let t1 = t - delta;
  19314. let t2 = t + delta;
  19315. // Capping in case of danger
  19316. if ( t1 < 0 ) t1 = 0;
  19317. if ( t2 > 1 ) t2 = 1;
  19318. const pt1 = this.getPoint( t1 );
  19319. const pt2 = this.getPoint( t2 );
  19320. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  19321. tangent.copy( pt2 ).sub( pt1 ).normalize();
  19322. return tangent;
  19323. }
  19324. getTangentAt( u, optionalTarget ) {
  19325. const t = this.getUtoTmapping( u );
  19326. return this.getTangent( t, optionalTarget );
  19327. }
  19328. computeFrenetFrames( segments, closed ) {
  19329. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19330. const normal = new Vector3();
  19331. const tangents = [];
  19332. const normals = [];
  19333. const binormals = [];
  19334. const vec = new Vector3();
  19335. const mat = new Matrix4();
  19336. // compute the tangent vectors for each segment on the curve
  19337. for ( let i = 0; i <= segments; i ++ ) {
  19338. const u = i / segments;
  19339. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  19340. tangents[ i ].normalize();
  19341. }
  19342. // select an initial normal vector perpendicular to the first tangent vector,
  19343. // and in the direction of the minimum tangent xyz component
  19344. normals[ 0 ] = new Vector3();
  19345. binormals[ 0 ] = new Vector3();
  19346. let min = Number.MAX_VALUE;
  19347. const tx = Math.abs( tangents[ 0 ].x );
  19348. const ty = Math.abs( tangents[ 0 ].y );
  19349. const tz = Math.abs( tangents[ 0 ].z );
  19350. if ( tx <= min ) {
  19351. min = tx;
  19352. normal.set( 1, 0, 0 );
  19353. }
  19354. if ( ty <= min ) {
  19355. min = ty;
  19356. normal.set( 0, 1, 0 );
  19357. }
  19358. if ( tz <= min ) {
  19359. normal.set( 0, 0, 1 );
  19360. }
  19361. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19362. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19363. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19364. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  19365. for ( let i = 1; i <= segments; i ++ ) {
  19366. normals[ i ] = normals[ i - 1 ].clone();
  19367. binormals[ i ] = binormals[ i - 1 ].clone();
  19368. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  19369. if ( vec.length() > Number.EPSILON ) {
  19370. vec.normalize();
  19371. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  19372. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19373. }
  19374. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19375. }
  19376. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19377. if ( closed === true ) {
  19378. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  19379. theta /= segments;
  19380. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  19381. theta = - theta;
  19382. }
  19383. for ( let i = 1; i <= segments; i ++ ) {
  19384. // twist a little...
  19385. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19386. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19387. }
  19388. }
  19389. return {
  19390. tangents: tangents,
  19391. normals: normals,
  19392. binormals: binormals
  19393. };
  19394. }
  19395. clone() {
  19396. return new this.constructor().copy( this );
  19397. }
  19398. copy( source ) {
  19399. this.arcLengthDivisions = source.arcLengthDivisions;
  19400. return this;
  19401. }
  19402. toJSON() {
  19403. const data = {
  19404. metadata: {
  19405. version: 4.5,
  19406. type: 'Curve',
  19407. generator: 'Curve.toJSON'
  19408. }
  19409. };
  19410. data.arcLengthDivisions = this.arcLengthDivisions;
  19411. data.type = this.type;
  19412. return data;
  19413. }
  19414. fromJSON( json ) {
  19415. this.arcLengthDivisions = json.arcLengthDivisions;
  19416. return this;
  19417. }
  19418. }
  19419. class EllipseCurve extends Curve {
  19420. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  19421. super();
  19422. this.type = 'EllipseCurve';
  19423. this.aX = aX;
  19424. this.aY = aY;
  19425. this.xRadius = xRadius;
  19426. this.yRadius = yRadius;
  19427. this.aStartAngle = aStartAngle;
  19428. this.aEndAngle = aEndAngle;
  19429. this.aClockwise = aClockwise;
  19430. this.aRotation = aRotation;
  19431. }
  19432. getPoint( t, optionalTarget ) {
  19433. const point = optionalTarget || new Vector2();
  19434. const twoPi = Math.PI * 2;
  19435. let deltaAngle = this.aEndAngle - this.aStartAngle;
  19436. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  19437. // ensures that deltaAngle is 0 .. 2 PI
  19438. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  19439. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  19440. if ( deltaAngle < Number.EPSILON ) {
  19441. if ( samePoints ) {
  19442. deltaAngle = 0;
  19443. } else {
  19444. deltaAngle = twoPi;
  19445. }
  19446. }
  19447. if ( this.aClockwise === true && ! samePoints ) {
  19448. if ( deltaAngle === twoPi ) {
  19449. deltaAngle = - twoPi;
  19450. } else {
  19451. deltaAngle = deltaAngle - twoPi;
  19452. }
  19453. }
  19454. const angle = this.aStartAngle + t * deltaAngle;
  19455. let x = this.aX + this.xRadius * Math.cos( angle );
  19456. let y = this.aY + this.yRadius * Math.sin( angle );
  19457. if ( this.aRotation !== 0 ) {
  19458. const cos = Math.cos( this.aRotation );
  19459. const sin = Math.sin( this.aRotation );
  19460. const tx = x - this.aX;
  19461. const ty = y - this.aY;
  19462. // Rotate the point about the center of the ellipse.
  19463. x = tx * cos - ty * sin + this.aX;
  19464. y = tx * sin + ty * cos + this.aY;
  19465. }
  19466. return point.set( x, y );
  19467. }
  19468. copy( source ) {
  19469. super.copy( source );
  19470. this.aX = source.aX;
  19471. this.aY = source.aY;
  19472. this.xRadius = source.xRadius;
  19473. this.yRadius = source.yRadius;
  19474. this.aStartAngle = source.aStartAngle;
  19475. this.aEndAngle = source.aEndAngle;
  19476. this.aClockwise = source.aClockwise;
  19477. this.aRotation = source.aRotation;
  19478. return this;
  19479. }
  19480. toJSON() {
  19481. const data = super.toJSON();
  19482. data.aX = this.aX;
  19483. data.aY = this.aY;
  19484. data.xRadius = this.xRadius;
  19485. data.yRadius = this.yRadius;
  19486. data.aStartAngle = this.aStartAngle;
  19487. data.aEndAngle = this.aEndAngle;
  19488. data.aClockwise = this.aClockwise;
  19489. data.aRotation = this.aRotation;
  19490. return data;
  19491. }
  19492. fromJSON( json ) {
  19493. super.fromJSON( json );
  19494. this.aX = json.aX;
  19495. this.aY = json.aY;
  19496. this.xRadius = json.xRadius;
  19497. this.yRadius = json.yRadius;
  19498. this.aStartAngle = json.aStartAngle;
  19499. this.aEndAngle = json.aEndAngle;
  19500. this.aClockwise = json.aClockwise;
  19501. this.aRotation = json.aRotation;
  19502. return this;
  19503. }
  19504. }
  19505. EllipseCurve.prototype.isEllipseCurve = true;
  19506. class ArcCurve extends EllipseCurve {
  19507. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19508. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  19509. this.type = 'ArcCurve';
  19510. }
  19511. }
  19512. ArcCurve.prototype.isArcCurve = true;
  19513. /**
  19514. * Centripetal CatmullRom Curve - which is useful for avoiding
  19515. * cusps and self-intersections in non-uniform catmull rom curves.
  19516. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  19517. *
  19518. * curve.type accepts centripetal(default), chordal and catmullrom
  19519. * curve.tension is used for catmullrom which defaults to 0.5
  19520. */
  19521. /*
  19522. Based on an optimized c++ solution in
  19523. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  19524. - http://ideone.com/NoEbVM
  19525. This CubicPoly class could be used for reusing some variables and calculations,
  19526. but for three.js curve use, it could be possible inlined and flatten into a single function call
  19527. which can be placed in CurveUtils.
  19528. */
  19529. function CubicPoly() {
  19530. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  19531. /*
  19532. * Compute coefficients for a cubic polynomial
  19533. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  19534. * such that
  19535. * p(0) = x0, p(1) = x1
  19536. * and
  19537. * p'(0) = t0, p'(1) = t1.
  19538. */
  19539. function init( x0, x1, t0, t1 ) {
  19540. c0 = x0;
  19541. c1 = t0;
  19542. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  19543. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  19544. }
  19545. return {
  19546. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  19547. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  19548. },
  19549. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  19550. // compute tangents when parameterized in [t1,t2]
  19551. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  19552. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  19553. // rescale tangents for parametrization in [0,1]
  19554. t1 *= dt1;
  19555. t2 *= dt1;
  19556. init( x1, x2, t1, t2 );
  19557. },
  19558. calc: function ( t ) {
  19559. const t2 = t * t;
  19560. const t3 = t2 * t;
  19561. return c0 + c1 * t + c2 * t2 + c3 * t3;
  19562. }
  19563. };
  19564. }
  19565. //
  19566. const tmp = new Vector3();
  19567. const px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly();
  19568. class CatmullRomCurve3 extends Curve {
  19569. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  19570. super();
  19571. this.type = 'CatmullRomCurve3';
  19572. this.points = points;
  19573. this.closed = closed;
  19574. this.curveType = curveType;
  19575. this.tension = tension;
  19576. }
  19577. getPoint( t, optionalTarget = new Vector3() ) {
  19578. const point = optionalTarget;
  19579. const points = this.points;
  19580. const l = points.length;
  19581. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  19582. let intPoint = Math.floor( p );
  19583. let weight = p - intPoint;
  19584. if ( this.closed ) {
  19585. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  19586. } else if ( weight === 0 && intPoint === l - 1 ) {
  19587. intPoint = l - 2;
  19588. weight = 1;
  19589. }
  19590. let p0, p3; // 4 points (p1 & p2 defined below)
  19591. if ( this.closed || intPoint > 0 ) {
  19592. p0 = points[ ( intPoint - 1 ) % l ];
  19593. } else {
  19594. // extrapolate first point
  19595. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  19596. p0 = tmp;
  19597. }
  19598. const p1 = points[ intPoint % l ];
  19599. const p2 = points[ ( intPoint + 1 ) % l ];
  19600. if ( this.closed || intPoint + 2 < l ) {
  19601. p3 = points[ ( intPoint + 2 ) % l ];
  19602. } else {
  19603. // extrapolate last point
  19604. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  19605. p3 = tmp;
  19606. }
  19607. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  19608. // init Centripetal / Chordal Catmull-Rom
  19609. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  19610. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  19611. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  19612. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  19613. // safety check for repeated points
  19614. if ( dt1 < 1e-4 ) dt1 = 1.0;
  19615. if ( dt0 < 1e-4 ) dt0 = dt1;
  19616. if ( dt2 < 1e-4 ) dt2 = dt1;
  19617. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  19618. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  19619. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  19620. } else if ( this.curveType === 'catmullrom' ) {
  19621. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  19622. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  19623. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  19624. }
  19625. point.set(
  19626. px.calc( weight ),
  19627. py.calc( weight ),
  19628. pz.calc( weight )
  19629. );
  19630. return point;
  19631. }
  19632. copy( source ) {
  19633. super.copy( source );
  19634. this.points = [];
  19635. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19636. const point = source.points[ i ];
  19637. this.points.push( point.clone() );
  19638. }
  19639. this.closed = source.closed;
  19640. this.curveType = source.curveType;
  19641. this.tension = source.tension;
  19642. return this;
  19643. }
  19644. toJSON() {
  19645. const data = super.toJSON();
  19646. data.points = [];
  19647. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19648. const point = this.points[ i ];
  19649. data.points.push( point.toArray() );
  19650. }
  19651. data.closed = this.closed;
  19652. data.curveType = this.curveType;
  19653. data.tension = this.tension;
  19654. return data;
  19655. }
  19656. fromJSON( json ) {
  19657. super.fromJSON( json );
  19658. this.points = [];
  19659. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  19660. const point = json.points[ i ];
  19661. this.points.push( new Vector3().fromArray( point ) );
  19662. }
  19663. this.closed = json.closed;
  19664. this.curveType = json.curveType;
  19665. this.tension = json.tension;
  19666. return this;
  19667. }
  19668. }
  19669. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  19670. /**
  19671. * Bezier Curves formulas obtained from
  19672. * http://en.wikipedia.org/wiki/Bézier_curve
  19673. */
  19674. function CatmullRom( t, p0, p1, p2, p3 ) {
  19675. const v0 = ( p2 - p0 ) * 0.5;
  19676. const v1 = ( p3 - p1 ) * 0.5;
  19677. const t2 = t * t;
  19678. const t3 = t * t2;
  19679. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  19680. }
  19681. //
  19682. function QuadraticBezierP0( t, p ) {
  19683. const k = 1 - t;
  19684. return k * k * p;
  19685. }
  19686. function QuadraticBezierP1( t, p ) {
  19687. return 2 * ( 1 - t ) * t * p;
  19688. }
  19689. function QuadraticBezierP2( t, p ) {
  19690. return t * t * p;
  19691. }
  19692. function QuadraticBezier( t, p0, p1, p2 ) {
  19693. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  19694. QuadraticBezierP2( t, p2 );
  19695. }
  19696. //
  19697. function CubicBezierP0( t, p ) {
  19698. const k = 1 - t;
  19699. return k * k * k * p;
  19700. }
  19701. function CubicBezierP1( t, p ) {
  19702. const k = 1 - t;
  19703. return 3 * k * k * t * p;
  19704. }
  19705. function CubicBezierP2( t, p ) {
  19706. return 3 * ( 1 - t ) * t * t * p;
  19707. }
  19708. function CubicBezierP3( t, p ) {
  19709. return t * t * t * p;
  19710. }
  19711. function CubicBezier( t, p0, p1, p2, p3 ) {
  19712. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  19713. CubicBezierP3( t, p3 );
  19714. }
  19715. class CubicBezierCurve extends Curve {
  19716. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  19717. super();
  19718. this.type = 'CubicBezierCurve';
  19719. this.v0 = v0;
  19720. this.v1 = v1;
  19721. this.v2 = v2;
  19722. this.v3 = v3;
  19723. }
  19724. getPoint( t, optionalTarget = new Vector2() ) {
  19725. const point = optionalTarget;
  19726. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19727. point.set(
  19728. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19729. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  19730. );
  19731. return point;
  19732. }
  19733. copy( source ) {
  19734. super.copy( source );
  19735. this.v0.copy( source.v0 );
  19736. this.v1.copy( source.v1 );
  19737. this.v2.copy( source.v2 );
  19738. this.v3.copy( source.v3 );
  19739. return this;
  19740. }
  19741. toJSON() {
  19742. const data = super.toJSON();
  19743. data.v0 = this.v0.toArray();
  19744. data.v1 = this.v1.toArray();
  19745. data.v2 = this.v2.toArray();
  19746. data.v3 = this.v3.toArray();
  19747. return data;
  19748. }
  19749. fromJSON( json ) {
  19750. super.fromJSON( json );
  19751. this.v0.fromArray( json.v0 );
  19752. this.v1.fromArray( json.v1 );
  19753. this.v2.fromArray( json.v2 );
  19754. this.v3.fromArray( json.v3 );
  19755. return this;
  19756. }
  19757. }
  19758. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  19759. class CubicBezierCurve3 extends Curve {
  19760. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  19761. super();
  19762. this.type = 'CubicBezierCurve3';
  19763. this.v0 = v0;
  19764. this.v1 = v1;
  19765. this.v2 = v2;
  19766. this.v3 = v3;
  19767. }
  19768. getPoint( t, optionalTarget = new Vector3() ) {
  19769. const point = optionalTarget;
  19770. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19771. point.set(
  19772. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19773. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  19774. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  19775. );
  19776. return point;
  19777. }
  19778. copy( source ) {
  19779. super.copy( source );
  19780. this.v0.copy( source.v0 );
  19781. this.v1.copy( source.v1 );
  19782. this.v2.copy( source.v2 );
  19783. this.v3.copy( source.v3 );
  19784. return this;
  19785. }
  19786. toJSON() {
  19787. const data = super.toJSON();
  19788. data.v0 = this.v0.toArray();
  19789. data.v1 = this.v1.toArray();
  19790. data.v2 = this.v2.toArray();
  19791. data.v3 = this.v3.toArray();
  19792. return data;
  19793. }
  19794. fromJSON( json ) {
  19795. super.fromJSON( json );
  19796. this.v0.fromArray( json.v0 );
  19797. this.v1.fromArray( json.v1 );
  19798. this.v2.fromArray( json.v2 );
  19799. this.v3.fromArray( json.v3 );
  19800. return this;
  19801. }
  19802. }
  19803. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  19804. class LineCurve extends Curve {
  19805. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  19806. super();
  19807. this.type = 'LineCurve';
  19808. this.v1 = v1;
  19809. this.v2 = v2;
  19810. }
  19811. getPoint( t, optionalTarget = new Vector2() ) {
  19812. const point = optionalTarget;
  19813. if ( t === 1 ) {
  19814. point.copy( this.v2 );
  19815. } else {
  19816. point.copy( this.v2 ).sub( this.v1 );
  19817. point.multiplyScalar( t ).add( this.v1 );
  19818. }
  19819. return point;
  19820. }
  19821. // Line curve is linear, so we can overwrite default getPointAt
  19822. getPointAt( u, optionalTarget ) {
  19823. return this.getPoint( u, optionalTarget );
  19824. }
  19825. getTangent( t, optionalTarget ) {
  19826. const tangent = optionalTarget || new Vector2();
  19827. tangent.copy( this.v2 ).sub( this.v1 ).normalize();
  19828. return tangent;
  19829. }
  19830. copy( source ) {
  19831. super.copy( source );
  19832. this.v1.copy( source.v1 );
  19833. this.v2.copy( source.v2 );
  19834. return this;
  19835. }
  19836. toJSON() {
  19837. const data = super.toJSON();
  19838. data.v1 = this.v1.toArray();
  19839. data.v2 = this.v2.toArray();
  19840. return data;
  19841. }
  19842. fromJSON( json ) {
  19843. super.fromJSON( json );
  19844. this.v1.fromArray( json.v1 );
  19845. this.v2.fromArray( json.v2 );
  19846. return this;
  19847. }
  19848. }
  19849. LineCurve.prototype.isLineCurve = true;
  19850. class LineCurve3 extends Curve {
  19851. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  19852. super();
  19853. this.type = 'LineCurve3';
  19854. this.isLineCurve3 = true;
  19855. this.v1 = v1;
  19856. this.v2 = v2;
  19857. }
  19858. getPoint( t, optionalTarget = new Vector3() ) {
  19859. const point = optionalTarget;
  19860. if ( t === 1 ) {
  19861. point.copy( this.v2 );
  19862. } else {
  19863. point.copy( this.v2 ).sub( this.v1 );
  19864. point.multiplyScalar( t ).add( this.v1 );
  19865. }
  19866. return point;
  19867. }
  19868. // Line curve is linear, so we can overwrite default getPointAt
  19869. getPointAt( u, optionalTarget ) {
  19870. return this.getPoint( u, optionalTarget );
  19871. }
  19872. copy( source ) {
  19873. super.copy( source );
  19874. this.v1.copy( source.v1 );
  19875. this.v2.copy( source.v2 );
  19876. return this;
  19877. }
  19878. toJSON() {
  19879. const data = super.toJSON();
  19880. data.v1 = this.v1.toArray();
  19881. data.v2 = this.v2.toArray();
  19882. return data;
  19883. }
  19884. fromJSON( json ) {
  19885. super.fromJSON( json );
  19886. this.v1.fromArray( json.v1 );
  19887. this.v2.fromArray( json.v2 );
  19888. return this;
  19889. }
  19890. }
  19891. class QuadraticBezierCurve extends Curve {
  19892. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  19893. super();
  19894. this.type = 'QuadraticBezierCurve';
  19895. this.v0 = v0;
  19896. this.v1 = v1;
  19897. this.v2 = v2;
  19898. }
  19899. getPoint( t, optionalTarget = new Vector2() ) {
  19900. const point = optionalTarget;
  19901. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19902. point.set(
  19903. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19904. QuadraticBezier( t, v0.y, v1.y, v2.y )
  19905. );
  19906. return point;
  19907. }
  19908. copy( source ) {
  19909. super.copy( source );
  19910. this.v0.copy( source.v0 );
  19911. this.v1.copy( source.v1 );
  19912. this.v2.copy( source.v2 );
  19913. return this;
  19914. }
  19915. toJSON() {
  19916. const data = super.toJSON();
  19917. data.v0 = this.v0.toArray();
  19918. data.v1 = this.v1.toArray();
  19919. data.v2 = this.v2.toArray();
  19920. return data;
  19921. }
  19922. fromJSON( json ) {
  19923. super.fromJSON( json );
  19924. this.v0.fromArray( json.v0 );
  19925. this.v1.fromArray( json.v1 );
  19926. this.v2.fromArray( json.v2 );
  19927. return this;
  19928. }
  19929. }
  19930. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  19931. class QuadraticBezierCurve3 extends Curve {
  19932. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  19933. super();
  19934. this.type = 'QuadraticBezierCurve3';
  19935. this.v0 = v0;
  19936. this.v1 = v1;
  19937. this.v2 = v2;
  19938. }
  19939. getPoint( t, optionalTarget = new Vector3() ) {
  19940. const point = optionalTarget;
  19941. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19942. point.set(
  19943. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19944. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  19945. QuadraticBezier( t, v0.z, v1.z, v2.z )
  19946. );
  19947. return point;
  19948. }
  19949. copy( source ) {
  19950. super.copy( source );
  19951. this.v0.copy( source.v0 );
  19952. this.v1.copy( source.v1 );
  19953. this.v2.copy( source.v2 );
  19954. return this;
  19955. }
  19956. toJSON() {
  19957. const data = super.toJSON();
  19958. data.v0 = this.v0.toArray();
  19959. data.v1 = this.v1.toArray();
  19960. data.v2 = this.v2.toArray();
  19961. return data;
  19962. }
  19963. fromJSON( json ) {
  19964. super.fromJSON( json );
  19965. this.v0.fromArray( json.v0 );
  19966. this.v1.fromArray( json.v1 );
  19967. this.v2.fromArray( json.v2 );
  19968. return this;
  19969. }
  19970. }
  19971. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  19972. class SplineCurve extends Curve {
  19973. constructor( points = [] ) {
  19974. super();
  19975. this.type = 'SplineCurve';
  19976. this.points = points;
  19977. }
  19978. getPoint( t, optionalTarget = new Vector2() ) {
  19979. const point = optionalTarget;
  19980. const points = this.points;
  19981. const p = ( points.length - 1 ) * t;
  19982. const intPoint = Math.floor( p );
  19983. const weight = p - intPoint;
  19984. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  19985. const p1 = points[ intPoint ];
  19986. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  19987. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  19988. point.set(
  19989. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  19990. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  19991. );
  19992. return point;
  19993. }
  19994. copy( source ) {
  19995. super.copy( source );
  19996. this.points = [];
  19997. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19998. const point = source.points[ i ];
  19999. this.points.push( point.clone() );
  20000. }
  20001. return this;
  20002. }
  20003. toJSON() {
  20004. const data = super.toJSON();
  20005. data.points = [];
  20006. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  20007. const point = this.points[ i ];
  20008. data.points.push( point.toArray() );
  20009. }
  20010. return data;
  20011. }
  20012. fromJSON( json ) {
  20013. super.fromJSON( json );
  20014. this.points = [];
  20015. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  20016. const point = json.points[ i ];
  20017. this.points.push( new Vector2().fromArray( point ) );
  20018. }
  20019. return this;
  20020. }
  20021. }
  20022. SplineCurve.prototype.isSplineCurve = true;
  20023. var Curves = /*#__PURE__*/Object.freeze({
  20024. __proto__: null,
  20025. ArcCurve: ArcCurve,
  20026. CatmullRomCurve3: CatmullRomCurve3,
  20027. CubicBezierCurve: CubicBezierCurve,
  20028. CubicBezierCurve3: CubicBezierCurve3,
  20029. EllipseCurve: EllipseCurve,
  20030. LineCurve: LineCurve,
  20031. LineCurve3: LineCurve3,
  20032. QuadraticBezierCurve: QuadraticBezierCurve,
  20033. QuadraticBezierCurve3: QuadraticBezierCurve3,
  20034. SplineCurve: SplineCurve
  20035. });
  20036. /**
  20037. * Port from https://github.com/mapbox/earcut (v2.2.2)
  20038. */
  20039. const Earcut = {
  20040. triangulate: function ( data, holeIndices, dim = 2 ) {
  20041. const hasHoles = holeIndices && holeIndices.length;
  20042. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  20043. let outerNode = linkedList( data, 0, outerLen, dim, true );
  20044. const triangles = [];
  20045. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  20046. let minX, minY, maxX, maxY, x, y, invSize;
  20047. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  20048. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  20049. if ( data.length > 80 * dim ) {
  20050. minX = maxX = data[ 0 ];
  20051. minY = maxY = data[ 1 ];
  20052. for ( let i = dim; i < outerLen; i += dim ) {
  20053. x = data[ i ];
  20054. y = data[ i + 1 ];
  20055. if ( x < minX ) minX = x;
  20056. if ( y < minY ) minY = y;
  20057. if ( x > maxX ) maxX = x;
  20058. if ( y > maxY ) maxY = y;
  20059. }
  20060. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  20061. invSize = Math.max( maxX - minX, maxY - minY );
  20062. invSize = invSize !== 0 ? 1 / invSize : 0;
  20063. }
  20064. earcutLinked( outerNode, triangles, dim, minX, minY, invSize );
  20065. return triangles;
  20066. }
  20067. };
  20068. // create a circular doubly linked list from polygon points in the specified winding order
  20069. function linkedList( data, start, end, dim, clockwise ) {
  20070. let i, last;
  20071. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  20072. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20073. } else {
  20074. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20075. }
  20076. if ( last && equals( last, last.next ) ) {
  20077. removeNode( last );
  20078. last = last.next;
  20079. }
  20080. return last;
  20081. }
  20082. // eliminate colinear or duplicate points
  20083. function filterPoints( start, end ) {
  20084. if ( ! start ) return start;
  20085. if ( ! end ) end = start;
  20086. let p = start,
  20087. again;
  20088. do {
  20089. again = false;
  20090. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  20091. removeNode( p );
  20092. p = end = p.prev;
  20093. if ( p === p.next ) break;
  20094. again = true;
  20095. } else {
  20096. p = p.next;
  20097. }
  20098. } while ( again || p !== end );
  20099. return end;
  20100. }
  20101. // main ear slicing loop which triangulates a polygon (given as a linked list)
  20102. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  20103. if ( ! ear ) return;
  20104. // interlink polygon nodes in z-order
  20105. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  20106. let stop = ear,
  20107. prev, next;
  20108. // iterate through ears, slicing them one by one
  20109. while ( ear.prev !== ear.next ) {
  20110. prev = ear.prev;
  20111. next = ear.next;
  20112. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  20113. // cut off the triangle
  20114. triangles.push( prev.i / dim );
  20115. triangles.push( ear.i / dim );
  20116. triangles.push( next.i / dim );
  20117. removeNode( ear );
  20118. // skipping the next vertex leads to less sliver triangles
  20119. ear = next.next;
  20120. stop = next.next;
  20121. continue;
  20122. }
  20123. ear = next;
  20124. // if we looped through the whole remaining polygon and can't find any more ears
  20125. if ( ear === stop ) {
  20126. // try filtering points and slicing again
  20127. if ( ! pass ) {
  20128. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  20129. // if this didn't work, try curing all small self-intersections locally
  20130. } else if ( pass === 1 ) {
  20131. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  20132. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  20133. // as a last resort, try splitting the remaining polygon into two
  20134. } else if ( pass === 2 ) {
  20135. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  20136. }
  20137. break;
  20138. }
  20139. }
  20140. }
  20141. // check whether a polygon node forms a valid ear with adjacent nodes
  20142. function isEar( ear ) {
  20143. const a = ear.prev,
  20144. b = ear,
  20145. c = ear.next;
  20146. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20147. // now make sure we don't have other points inside the potential ear
  20148. let p = ear.next.next;
  20149. while ( p !== ear.prev ) {
  20150. if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  20151. area( p.prev, p, p.next ) >= 0 ) return false;
  20152. p = p.next;
  20153. }
  20154. return true;
  20155. }
  20156. function isEarHashed( ear, minX, minY, invSize ) {
  20157. const a = ear.prev,
  20158. b = ear,
  20159. c = ear.next;
  20160. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20161. // triangle bbox; min & max are calculated like this for speed
  20162. const minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ),
  20163. minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ),
  20164. maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ),
  20165. maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y );
  20166. // z-order range for the current triangle bbox;
  20167. const minZ = zOrder( minTX, minTY, minX, minY, invSize ),
  20168. maxZ = zOrder( maxTX, maxTY, minX, minY, invSize );
  20169. let p = ear.prevZ,
  20170. n = ear.nextZ;
  20171. // look for points inside the triangle in both directions
  20172. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  20173. if ( p !== ear.prev && p !== ear.next &&
  20174. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  20175. area( p.prev, p, p.next ) >= 0 ) return false;
  20176. p = p.prevZ;
  20177. if ( n !== ear.prev && n !== ear.next &&
  20178. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  20179. area( n.prev, n, n.next ) >= 0 ) return false;
  20180. n = n.nextZ;
  20181. }
  20182. // look for remaining points in decreasing z-order
  20183. while ( p && p.z >= minZ ) {
  20184. if ( p !== ear.prev && p !== ear.next &&
  20185. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  20186. area( p.prev, p, p.next ) >= 0 ) return false;
  20187. p = p.prevZ;
  20188. }
  20189. // look for remaining points in increasing z-order
  20190. while ( n && n.z <= maxZ ) {
  20191. if ( n !== ear.prev && n !== ear.next &&
  20192. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  20193. area( n.prev, n, n.next ) >= 0 ) return false;
  20194. n = n.nextZ;
  20195. }
  20196. return true;
  20197. }
  20198. // go through all polygon nodes and cure small local self-intersections
  20199. function cureLocalIntersections( start, triangles, dim ) {
  20200. let p = start;
  20201. do {
  20202. const a = p.prev,
  20203. b = p.next.next;
  20204. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  20205. triangles.push( a.i / dim );
  20206. triangles.push( p.i / dim );
  20207. triangles.push( b.i / dim );
  20208. // remove two nodes involved
  20209. removeNode( p );
  20210. removeNode( p.next );
  20211. p = start = b;
  20212. }
  20213. p = p.next;
  20214. } while ( p !== start );
  20215. return filterPoints( p );
  20216. }
  20217. // try splitting polygon into two and triangulate them independently
  20218. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  20219. // look for a valid diagonal that divides the polygon into two
  20220. let a = start;
  20221. do {
  20222. let b = a.next.next;
  20223. while ( b !== a.prev ) {
  20224. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  20225. // split the polygon in two by the diagonal
  20226. let c = splitPolygon( a, b );
  20227. // filter colinear points around the cuts
  20228. a = filterPoints( a, a.next );
  20229. c = filterPoints( c, c.next );
  20230. // run earcut on each half
  20231. earcutLinked( a, triangles, dim, minX, minY, invSize );
  20232. earcutLinked( c, triangles, dim, minX, minY, invSize );
  20233. return;
  20234. }
  20235. b = b.next;
  20236. }
  20237. a = a.next;
  20238. } while ( a !== start );
  20239. }
  20240. // link every hole into the outer loop, producing a single-ring polygon without holes
  20241. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  20242. const queue = [];
  20243. let i, len, start, end, list;
  20244. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  20245. start = holeIndices[ i ] * dim;
  20246. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  20247. list = linkedList( data, start, end, dim, false );
  20248. if ( list === list.next ) list.steiner = true;
  20249. queue.push( getLeftmost( list ) );
  20250. }
  20251. queue.sort( compareX );
  20252. // process holes from left to right
  20253. for ( i = 0; i < queue.length; i ++ ) {
  20254. eliminateHole( queue[ i ], outerNode );
  20255. outerNode = filterPoints( outerNode, outerNode.next );
  20256. }
  20257. return outerNode;
  20258. }
  20259. function compareX( a, b ) {
  20260. return a.x - b.x;
  20261. }
  20262. // find a bridge between vertices that connects hole with an outer ring and and link it
  20263. function eliminateHole( hole, outerNode ) {
  20264. outerNode = findHoleBridge( hole, outerNode );
  20265. if ( outerNode ) {
  20266. const b = splitPolygon( outerNode, hole );
  20267. // filter collinear points around the cuts
  20268. filterPoints( outerNode, outerNode.next );
  20269. filterPoints( b, b.next );
  20270. }
  20271. }
  20272. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  20273. function findHoleBridge( hole, outerNode ) {
  20274. let p = outerNode;
  20275. const hx = hole.x;
  20276. const hy = hole.y;
  20277. let qx = - Infinity, m;
  20278. // find a segment intersected by a ray from the hole's leftmost point to the left;
  20279. // segment's endpoint with lesser x will be potential connection point
  20280. do {
  20281. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  20282. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  20283. if ( x <= hx && x > qx ) {
  20284. qx = x;
  20285. if ( x === hx ) {
  20286. if ( hy === p.y ) return p;
  20287. if ( hy === p.next.y ) return p.next;
  20288. }
  20289. m = p.x < p.next.x ? p : p.next;
  20290. }
  20291. }
  20292. p = p.next;
  20293. } while ( p !== outerNode );
  20294. if ( ! m ) return null;
  20295. if ( hx === qx ) return m; // hole touches outer segment; pick leftmost endpoint
  20296. // look for points inside the triangle of hole point, segment intersection and endpoint;
  20297. // if there are no points found, we have a valid connection;
  20298. // otherwise choose the point of the minimum angle with the ray as connection point
  20299. const stop = m,
  20300. mx = m.x,
  20301. my = m.y;
  20302. let tanMin = Infinity, tan;
  20303. p = m;
  20304. do {
  20305. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  20306. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  20307. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  20308. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  20309. m = p;
  20310. tanMin = tan;
  20311. }
  20312. }
  20313. p = p.next;
  20314. } while ( p !== stop );
  20315. return m;
  20316. }
  20317. // whether sector in vertex m contains sector in vertex p in the same coordinates
  20318. function sectorContainsSector( m, p ) {
  20319. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  20320. }
  20321. // interlink polygon nodes in z-order
  20322. function indexCurve( start, minX, minY, invSize ) {
  20323. let p = start;
  20324. do {
  20325. if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  20326. p.prevZ = p.prev;
  20327. p.nextZ = p.next;
  20328. p = p.next;
  20329. } while ( p !== start );
  20330. p.prevZ.nextZ = null;
  20331. p.prevZ = null;
  20332. sortLinked( p );
  20333. }
  20334. // Simon Tatham's linked list merge sort algorithm
  20335. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  20336. function sortLinked( list ) {
  20337. let i, p, q, e, tail, numMerges, pSize, qSize,
  20338. inSize = 1;
  20339. do {
  20340. p = list;
  20341. list = null;
  20342. tail = null;
  20343. numMerges = 0;
  20344. while ( p ) {
  20345. numMerges ++;
  20346. q = p;
  20347. pSize = 0;
  20348. for ( i = 0; i < inSize; i ++ ) {
  20349. pSize ++;
  20350. q = q.nextZ;
  20351. if ( ! q ) break;
  20352. }
  20353. qSize = inSize;
  20354. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  20355. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  20356. e = p;
  20357. p = p.nextZ;
  20358. pSize --;
  20359. } else {
  20360. e = q;
  20361. q = q.nextZ;
  20362. qSize --;
  20363. }
  20364. if ( tail ) tail.nextZ = e;
  20365. else list = e;
  20366. e.prevZ = tail;
  20367. tail = e;
  20368. }
  20369. p = q;
  20370. }
  20371. tail.nextZ = null;
  20372. inSize *= 2;
  20373. } while ( numMerges > 1 );
  20374. return list;
  20375. }
  20376. // z-order of a point given coords and inverse of the longer side of data bbox
  20377. function zOrder( x, y, minX, minY, invSize ) {
  20378. // coords are transformed into non-negative 15-bit integer range
  20379. x = 32767 * ( x - minX ) * invSize;
  20380. y = 32767 * ( y - minY ) * invSize;
  20381. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  20382. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  20383. x = ( x | ( x << 2 ) ) & 0x33333333;
  20384. x = ( x | ( x << 1 ) ) & 0x55555555;
  20385. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  20386. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  20387. y = ( y | ( y << 2 ) ) & 0x33333333;
  20388. y = ( y | ( y << 1 ) ) & 0x55555555;
  20389. return x | ( y << 1 );
  20390. }
  20391. // find the leftmost node of a polygon ring
  20392. function getLeftmost( start ) {
  20393. let p = start,
  20394. leftmost = start;
  20395. do {
  20396. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  20397. p = p.next;
  20398. } while ( p !== start );
  20399. return leftmost;
  20400. }
  20401. // check if a point lies within a convex triangle
  20402. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  20403. return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 &&
  20404. ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 &&
  20405. ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0;
  20406. }
  20407. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  20408. function isValidDiagonal( a, b ) {
  20409. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  20410. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  20411. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  20412. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  20413. }
  20414. // signed area of a triangle
  20415. function area( p, q, r ) {
  20416. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  20417. }
  20418. // check if two points are equal
  20419. function equals( p1, p2 ) {
  20420. return p1.x === p2.x && p1.y === p2.y;
  20421. }
  20422. // check if two segments intersect
  20423. function intersects( p1, q1, p2, q2 ) {
  20424. const o1 = sign( area( p1, q1, p2 ) );
  20425. const o2 = sign( area( p1, q1, q2 ) );
  20426. const o3 = sign( area( p2, q2, p1 ) );
  20427. const o4 = sign( area( p2, q2, q1 ) );
  20428. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  20429. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  20430. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  20431. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  20432. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  20433. return false;
  20434. }
  20435. // for collinear points p, q, r, check if point q lies on segment pr
  20436. function onSegment( p, q, r ) {
  20437. 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 );
  20438. }
  20439. function sign( num ) {
  20440. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  20441. }
  20442. // check if a polygon diagonal intersects any polygon segments
  20443. function intersectsPolygon( a, b ) {
  20444. let p = a;
  20445. do {
  20446. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  20447. intersects( p, p.next, a, b ) ) return true;
  20448. p = p.next;
  20449. } while ( p !== a );
  20450. return false;
  20451. }
  20452. // check if a polygon diagonal is locally inside the polygon
  20453. function locallyInside( a, b ) {
  20454. return area( a.prev, a, a.next ) < 0 ?
  20455. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  20456. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  20457. }
  20458. // check if the middle point of a polygon diagonal is inside the polygon
  20459. function middleInside( a, b ) {
  20460. let p = a,
  20461. inside = false;
  20462. const px = ( a.x + b.x ) / 2,
  20463. py = ( a.y + b.y ) / 2;
  20464. do {
  20465. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  20466. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  20467. inside = ! inside;
  20468. p = p.next;
  20469. } while ( p !== a );
  20470. return inside;
  20471. }
  20472. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  20473. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  20474. function splitPolygon( a, b ) {
  20475. const a2 = new Node( a.i, a.x, a.y ),
  20476. b2 = new Node( b.i, b.x, b.y ),
  20477. an = a.next,
  20478. bp = b.prev;
  20479. a.next = b;
  20480. b.prev = a;
  20481. a2.next = an;
  20482. an.prev = a2;
  20483. b2.next = a2;
  20484. a2.prev = b2;
  20485. bp.next = b2;
  20486. b2.prev = bp;
  20487. return b2;
  20488. }
  20489. // create a node and optionally link it with previous one (in a circular doubly linked list)
  20490. function insertNode( i, x, y, last ) {
  20491. const p = new Node( i, x, y );
  20492. if ( ! last ) {
  20493. p.prev = p;
  20494. p.next = p;
  20495. } else {
  20496. p.next = last.next;
  20497. p.prev = last;
  20498. last.next.prev = p;
  20499. last.next = p;
  20500. }
  20501. return p;
  20502. }
  20503. function removeNode( p ) {
  20504. p.next.prev = p.prev;
  20505. p.prev.next = p.next;
  20506. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  20507. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  20508. }
  20509. function Node( i, x, y ) {
  20510. // vertex index in coordinates array
  20511. this.i = i;
  20512. // vertex coordinates
  20513. this.x = x;
  20514. this.y = y;
  20515. // previous and next vertex nodes in a polygon ring
  20516. this.prev = null;
  20517. this.next = null;
  20518. // z-order curve value
  20519. this.z = null;
  20520. // previous and next nodes in z-order
  20521. this.prevZ = null;
  20522. this.nextZ = null;
  20523. // indicates whether this is a steiner point
  20524. this.steiner = false;
  20525. }
  20526. function signedArea( data, start, end, dim ) {
  20527. let sum = 0;
  20528. for ( let i = start, j = end - dim; i < end; i += dim ) {
  20529. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  20530. j = i;
  20531. }
  20532. return sum;
  20533. }
  20534. class ShapeUtils {
  20535. // calculate area of the contour polygon
  20536. static area( contour ) {
  20537. const n = contour.length;
  20538. let a = 0.0;
  20539. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  20540. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  20541. }
  20542. return a * 0.5;
  20543. }
  20544. static isClockWise( pts ) {
  20545. return ShapeUtils.area( pts ) < 0;
  20546. }
  20547. static triangulateShape( contour, holes ) {
  20548. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  20549. const holeIndices = []; // array of hole indices
  20550. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  20551. removeDupEndPts( contour );
  20552. addContour( vertices, contour );
  20553. //
  20554. let holeIndex = contour.length;
  20555. holes.forEach( removeDupEndPts );
  20556. for ( let i = 0; i < holes.length; i ++ ) {
  20557. holeIndices.push( holeIndex );
  20558. holeIndex += holes[ i ].length;
  20559. addContour( vertices, holes[ i ] );
  20560. }
  20561. //
  20562. const triangles = Earcut.triangulate( vertices, holeIndices );
  20563. //
  20564. for ( let i = 0; i < triangles.length; i += 3 ) {
  20565. faces.push( triangles.slice( i, i + 3 ) );
  20566. }
  20567. return faces;
  20568. }
  20569. }
  20570. function removeDupEndPts( points ) {
  20571. const l = points.length;
  20572. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  20573. points.pop();
  20574. }
  20575. }
  20576. function addContour( vertices, contour ) {
  20577. for ( let i = 0; i < contour.length; i ++ ) {
  20578. vertices.push( contour[ i ].x );
  20579. vertices.push( contour[ i ].y );
  20580. }
  20581. }
  20582. /**
  20583. * Creates extruded geometry from a path shape.
  20584. *
  20585. * parameters = {
  20586. *
  20587. * curveSegments: <int>, // number of points on the curves
  20588. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  20589. * depth: <float>, // Depth to extrude the shape
  20590. *
  20591. * bevelEnabled: <bool>, // turn on bevel
  20592. * bevelThickness: <float>, // how deep into the original shape bevel goes
  20593. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  20594. * bevelOffset: <float>, // how far from shape outline does bevel start
  20595. * bevelSegments: <int>, // number of bevel layers
  20596. *
  20597. * extrudePath: <THREE.Curve> // curve to extrude shape along
  20598. *
  20599. * UVGenerator: <Object> // object that provides UV generator functions
  20600. *
  20601. * }
  20602. */
  20603. class ExtrudeGeometry extends BufferGeometry {
  20604. constructor( shapes, options ) {
  20605. super();
  20606. this.type = 'ExtrudeGeometry';
  20607. this.parameters = {
  20608. shapes: shapes,
  20609. options: options
  20610. };
  20611. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  20612. const scope = this;
  20613. const verticesArray = [];
  20614. const uvArray = [];
  20615. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  20616. const shape = shapes[ i ];
  20617. addShape( shape );
  20618. }
  20619. // build geometry
  20620. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  20621. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  20622. this.computeVertexNormals();
  20623. // functions
  20624. function addShape( shape ) {
  20625. const placeholder = [];
  20626. // options
  20627. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  20628. const steps = options.steps !== undefined ? options.steps : 1;
  20629. let depth = options.depth !== undefined ? options.depth : 100;
  20630. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  20631. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  20632. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  20633. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  20634. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  20635. const extrudePath = options.extrudePath;
  20636. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  20637. // deprecated options
  20638. if ( options.amount !== undefined ) {
  20639. console.warn( 'THREE.ExtrudeBufferGeometry: amount has been renamed to depth.' );
  20640. depth = options.amount;
  20641. }
  20642. //
  20643. let extrudePts, extrudeByPath = false;
  20644. let splineTube, binormal, normal, position2;
  20645. if ( extrudePath ) {
  20646. extrudePts = extrudePath.getSpacedPoints( steps );
  20647. extrudeByPath = true;
  20648. bevelEnabled = false; // bevels not supported for path extrusion
  20649. // SETUP TNB variables
  20650. // TODO1 - have a .isClosed in spline?
  20651. splineTube = extrudePath.computeFrenetFrames( steps, false );
  20652. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  20653. binormal = new Vector3();
  20654. normal = new Vector3();
  20655. position2 = new Vector3();
  20656. }
  20657. // Safeguards if bevels are not enabled
  20658. if ( ! bevelEnabled ) {
  20659. bevelSegments = 0;
  20660. bevelThickness = 0;
  20661. bevelSize = 0;
  20662. bevelOffset = 0;
  20663. }
  20664. // Variables initialization
  20665. const shapePoints = shape.extractPoints( curveSegments );
  20666. let vertices = shapePoints.shape;
  20667. const holes = shapePoints.holes;
  20668. const reverse = ! ShapeUtils.isClockWise( vertices );
  20669. if ( reverse ) {
  20670. vertices = vertices.reverse();
  20671. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  20672. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20673. const ahole = holes[ h ];
  20674. if ( ShapeUtils.isClockWise( ahole ) ) {
  20675. holes[ h ] = ahole.reverse();
  20676. }
  20677. }
  20678. }
  20679. const faces = ShapeUtils.triangulateShape( vertices, holes );
  20680. /* Vertices */
  20681. const contour = vertices; // vertices has all points but contour has only points of circumference
  20682. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20683. const ahole = holes[ h ];
  20684. vertices = vertices.concat( ahole );
  20685. }
  20686. function scalePt2( pt, vec, size ) {
  20687. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  20688. return vec.clone().multiplyScalar( size ).add( pt );
  20689. }
  20690. const vlen = vertices.length, flen = faces.length;
  20691. // Find directions for point movement
  20692. function getBevelVec( inPt, inPrev, inNext ) {
  20693. // computes for inPt the corresponding point inPt' on a new contour
  20694. // shifted by 1 unit (length of normalized vector) to the left
  20695. // if we walk along contour clockwise, this new contour is outside the old one
  20696. //
  20697. // inPt' is the intersection of the two lines parallel to the two
  20698. // adjacent edges of inPt at a distance of 1 unit on the left side.
  20699. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  20700. // good reading for geometry algorithms (here: line-line intersection)
  20701. // http://geomalgorithms.com/a05-_intersect-1.html
  20702. const v_prev_x = inPt.x - inPrev.x,
  20703. v_prev_y = inPt.y - inPrev.y;
  20704. const v_next_x = inNext.x - inPt.x,
  20705. v_next_y = inNext.y - inPt.y;
  20706. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  20707. // check for collinear edges
  20708. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  20709. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  20710. // not collinear
  20711. // length of vectors for normalizing
  20712. const v_prev_len = Math.sqrt( v_prev_lensq );
  20713. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  20714. // shift adjacent points by unit vectors to the left
  20715. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  20716. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  20717. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  20718. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  20719. // scaling factor for v_prev to intersection point
  20720. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  20721. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  20722. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  20723. // vector from inPt to intersection point
  20724. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  20725. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  20726. // Don't normalize!, otherwise sharp corners become ugly
  20727. // but prevent crazy spikes
  20728. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  20729. if ( v_trans_lensq <= 2 ) {
  20730. return new Vector2( v_trans_x, v_trans_y );
  20731. } else {
  20732. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  20733. }
  20734. } else {
  20735. // handle special case of collinear edges
  20736. let direction_eq = false; // assumes: opposite
  20737. if ( v_prev_x > Number.EPSILON ) {
  20738. if ( v_next_x > Number.EPSILON ) {
  20739. direction_eq = true;
  20740. }
  20741. } else {
  20742. if ( v_prev_x < - Number.EPSILON ) {
  20743. if ( v_next_x < - Number.EPSILON ) {
  20744. direction_eq = true;
  20745. }
  20746. } else {
  20747. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  20748. direction_eq = true;
  20749. }
  20750. }
  20751. }
  20752. if ( direction_eq ) {
  20753. // console.log("Warning: lines are a straight sequence");
  20754. v_trans_x = - v_prev_y;
  20755. v_trans_y = v_prev_x;
  20756. shrink_by = Math.sqrt( v_prev_lensq );
  20757. } else {
  20758. // console.log("Warning: lines are a straight spike");
  20759. v_trans_x = v_prev_x;
  20760. v_trans_y = v_prev_y;
  20761. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  20762. }
  20763. }
  20764. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  20765. }
  20766. const contourMovements = [];
  20767. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  20768. if ( j === il ) j = 0;
  20769. if ( k === il ) k = 0;
  20770. // (j)---(i)---(k)
  20771. // console.log('i,j,k', i, j , k)
  20772. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  20773. }
  20774. const holesMovements = [];
  20775. let oneHoleMovements, verticesMovements = contourMovements.concat();
  20776. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20777. const ahole = holes[ h ];
  20778. oneHoleMovements = [];
  20779. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  20780. if ( j === il ) j = 0;
  20781. if ( k === il ) k = 0;
  20782. // (j)---(i)---(k)
  20783. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  20784. }
  20785. holesMovements.push( oneHoleMovements );
  20786. verticesMovements = verticesMovements.concat( oneHoleMovements );
  20787. }
  20788. // Loop bevelSegments, 1 for the front, 1 for the back
  20789. for ( let b = 0; b < bevelSegments; b ++ ) {
  20790. //for ( b = bevelSegments; b > 0; b -- ) {
  20791. const t = b / bevelSegments;
  20792. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  20793. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  20794. // contract shape
  20795. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  20796. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  20797. v( vert.x, vert.y, - z );
  20798. }
  20799. // expand holes
  20800. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20801. const ahole = holes[ h ];
  20802. oneHoleMovements = holesMovements[ h ];
  20803. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  20804. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  20805. v( vert.x, vert.y, - z );
  20806. }
  20807. }
  20808. }
  20809. const bs = bevelSize + bevelOffset;
  20810. // Back facing vertices
  20811. for ( let i = 0; i < vlen; i ++ ) {
  20812. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  20813. if ( ! extrudeByPath ) {
  20814. v( vert.x, vert.y, 0 );
  20815. } else {
  20816. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  20817. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  20818. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  20819. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  20820. v( position2.x, position2.y, position2.z );
  20821. }
  20822. }
  20823. // Add stepped vertices...
  20824. // Including front facing vertices
  20825. for ( let s = 1; s <= steps; s ++ ) {
  20826. for ( let i = 0; i < vlen; i ++ ) {
  20827. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  20828. if ( ! extrudeByPath ) {
  20829. v( vert.x, vert.y, depth / steps * s );
  20830. } else {
  20831. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  20832. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  20833. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  20834. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  20835. v( position2.x, position2.y, position2.z );
  20836. }
  20837. }
  20838. }
  20839. // Add bevel segments planes
  20840. //for ( b = 1; b <= bevelSegments; b ++ ) {
  20841. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  20842. const t = b / bevelSegments;
  20843. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  20844. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  20845. // contract shape
  20846. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  20847. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  20848. v( vert.x, vert.y, depth + z );
  20849. }
  20850. // expand holes
  20851. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20852. const ahole = holes[ h ];
  20853. oneHoleMovements = holesMovements[ h ];
  20854. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  20855. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  20856. if ( ! extrudeByPath ) {
  20857. v( vert.x, vert.y, depth + z );
  20858. } else {
  20859. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  20860. }
  20861. }
  20862. }
  20863. }
  20864. /* Faces */
  20865. // Top and bottom faces
  20866. buildLidFaces();
  20867. // Sides faces
  20868. buildSideFaces();
  20869. ///// Internal functions
  20870. function buildLidFaces() {
  20871. const start = verticesArray.length / 3;
  20872. if ( bevelEnabled ) {
  20873. let layer = 0; // steps + 1
  20874. let offset = vlen * layer;
  20875. // Bottom faces
  20876. for ( let i = 0; i < flen; i ++ ) {
  20877. const face = faces[ i ];
  20878. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  20879. }
  20880. layer = steps + bevelSegments * 2;
  20881. offset = vlen * layer;
  20882. // Top faces
  20883. for ( let i = 0; i < flen; i ++ ) {
  20884. const face = faces[ i ];
  20885. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  20886. }
  20887. } else {
  20888. // Bottom faces
  20889. for ( let i = 0; i < flen; i ++ ) {
  20890. const face = faces[ i ];
  20891. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  20892. }
  20893. // Top faces
  20894. for ( let i = 0; i < flen; i ++ ) {
  20895. const face = faces[ i ];
  20896. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  20897. }
  20898. }
  20899. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  20900. }
  20901. // Create faces for the z-sides of the shape
  20902. function buildSideFaces() {
  20903. const start = verticesArray.length / 3;
  20904. let layeroffset = 0;
  20905. sidewalls( contour, layeroffset );
  20906. layeroffset += contour.length;
  20907. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20908. const ahole = holes[ h ];
  20909. sidewalls( ahole, layeroffset );
  20910. //, true
  20911. layeroffset += ahole.length;
  20912. }
  20913. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  20914. }
  20915. function sidewalls( contour, layeroffset ) {
  20916. let i = contour.length;
  20917. while ( -- i >= 0 ) {
  20918. const j = i;
  20919. let k = i - 1;
  20920. if ( k < 0 ) k = contour.length - 1;
  20921. //console.log('b', i,j, i-1, k,vertices.length);
  20922. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  20923. const slen1 = vlen * s;
  20924. const slen2 = vlen * ( s + 1 );
  20925. const a = layeroffset + j + slen1,
  20926. b = layeroffset + k + slen1,
  20927. c = layeroffset + k + slen2,
  20928. d = layeroffset + j + slen2;
  20929. f4( a, b, c, d );
  20930. }
  20931. }
  20932. }
  20933. function v( x, y, z ) {
  20934. placeholder.push( x );
  20935. placeholder.push( y );
  20936. placeholder.push( z );
  20937. }
  20938. function f3( a, b, c ) {
  20939. addVertex( a );
  20940. addVertex( b );
  20941. addVertex( c );
  20942. const nextIndex = verticesArray.length / 3;
  20943. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  20944. addUV( uvs[ 0 ] );
  20945. addUV( uvs[ 1 ] );
  20946. addUV( uvs[ 2 ] );
  20947. }
  20948. function f4( a, b, c, d ) {
  20949. addVertex( a );
  20950. addVertex( b );
  20951. addVertex( d );
  20952. addVertex( b );
  20953. addVertex( c );
  20954. addVertex( d );
  20955. const nextIndex = verticesArray.length / 3;
  20956. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  20957. addUV( uvs[ 0 ] );
  20958. addUV( uvs[ 1 ] );
  20959. addUV( uvs[ 3 ] );
  20960. addUV( uvs[ 1 ] );
  20961. addUV( uvs[ 2 ] );
  20962. addUV( uvs[ 3 ] );
  20963. }
  20964. function addVertex( index ) {
  20965. verticesArray.push( placeholder[ index * 3 + 0 ] );
  20966. verticesArray.push( placeholder[ index * 3 + 1 ] );
  20967. verticesArray.push( placeholder[ index * 3 + 2 ] );
  20968. }
  20969. function addUV( vector2 ) {
  20970. uvArray.push( vector2.x );
  20971. uvArray.push( vector2.y );
  20972. }
  20973. }
  20974. }
  20975. toJSON() {
  20976. const data = super.toJSON();
  20977. const shapes = this.parameters.shapes;
  20978. const options = this.parameters.options;
  20979. return toJSON$1( shapes, options, data );
  20980. }
  20981. static fromJSON( data, shapes ) {
  20982. const geometryShapes = [];
  20983. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  20984. const shape = shapes[ data.shapes[ j ] ];
  20985. geometryShapes.push( shape );
  20986. }
  20987. const extrudePath = data.options.extrudePath;
  20988. if ( extrudePath !== undefined ) {
  20989. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  20990. }
  20991. return new ExtrudeGeometry( geometryShapes, data.options );
  20992. }
  20993. }
  20994. const WorldUVGenerator = {
  20995. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  20996. const a_x = vertices[ indexA * 3 ];
  20997. const a_y = vertices[ indexA * 3 + 1 ];
  20998. const b_x = vertices[ indexB * 3 ];
  20999. const b_y = vertices[ indexB * 3 + 1 ];
  21000. const c_x = vertices[ indexC * 3 ];
  21001. const c_y = vertices[ indexC * 3 + 1 ];
  21002. return [
  21003. new Vector2( a_x, a_y ),
  21004. new Vector2( b_x, b_y ),
  21005. new Vector2( c_x, c_y )
  21006. ];
  21007. },
  21008. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  21009. const a_x = vertices[ indexA * 3 ];
  21010. const a_y = vertices[ indexA * 3 + 1 ];
  21011. const a_z = vertices[ indexA * 3 + 2 ];
  21012. const b_x = vertices[ indexB * 3 ];
  21013. const b_y = vertices[ indexB * 3 + 1 ];
  21014. const b_z = vertices[ indexB * 3 + 2 ];
  21015. const c_x = vertices[ indexC * 3 ];
  21016. const c_y = vertices[ indexC * 3 + 1 ];
  21017. const c_z = vertices[ indexC * 3 + 2 ];
  21018. const d_x = vertices[ indexD * 3 ];
  21019. const d_y = vertices[ indexD * 3 + 1 ];
  21020. const d_z = vertices[ indexD * 3 + 2 ];
  21021. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  21022. return [
  21023. new Vector2( a_x, 1 - a_z ),
  21024. new Vector2( b_x, 1 - b_z ),
  21025. new Vector2( c_x, 1 - c_z ),
  21026. new Vector2( d_x, 1 - d_z )
  21027. ];
  21028. } else {
  21029. return [
  21030. new Vector2( a_y, 1 - a_z ),
  21031. new Vector2( b_y, 1 - b_z ),
  21032. new Vector2( c_y, 1 - c_z ),
  21033. new Vector2( d_y, 1 - d_z )
  21034. ];
  21035. }
  21036. }
  21037. };
  21038. function toJSON$1( shapes, options, data ) {
  21039. data.shapes = [];
  21040. if ( Array.isArray( shapes ) ) {
  21041. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21042. const shape = shapes[ i ];
  21043. data.shapes.push( shape.uuid );
  21044. }
  21045. } else {
  21046. data.shapes.push( shapes.uuid );
  21047. }
  21048. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  21049. return data;
  21050. }
  21051. class IcosahedronGeometry extends PolyhedronGeometry {
  21052. constructor( radius = 1, detail = 0 ) {
  21053. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  21054. const vertices = [
  21055. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  21056. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  21057. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  21058. ];
  21059. const indices = [
  21060. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  21061. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  21062. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  21063. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  21064. ];
  21065. super( vertices, indices, radius, detail );
  21066. this.type = 'IcosahedronGeometry';
  21067. this.parameters = {
  21068. radius: radius,
  21069. detail: detail
  21070. };
  21071. }
  21072. static fromJSON( data ) {
  21073. return new IcosahedronGeometry( data.radius, data.detail );
  21074. }
  21075. }
  21076. class LatheGeometry extends BufferGeometry {
  21077. constructor( points, segments = 12, phiStart = 0, phiLength = Math.PI * 2 ) {
  21078. super();
  21079. this.type = 'LatheGeometry';
  21080. this.parameters = {
  21081. points: points,
  21082. segments: segments,
  21083. phiStart: phiStart,
  21084. phiLength: phiLength
  21085. };
  21086. segments = Math.floor( segments );
  21087. // clamp phiLength so it's in range of [ 0, 2PI ]
  21088. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  21089. // buffers
  21090. const indices = [];
  21091. const vertices = [];
  21092. const uvs = [];
  21093. // helper variables
  21094. const inverseSegments = 1.0 / segments;
  21095. const vertex = new Vector3();
  21096. const uv = new Vector2();
  21097. // generate vertices and uvs
  21098. for ( let i = 0; i <= segments; i ++ ) {
  21099. const phi = phiStart + i * inverseSegments * phiLength;
  21100. const sin = Math.sin( phi );
  21101. const cos = Math.cos( phi );
  21102. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  21103. // vertex
  21104. vertex.x = points[ j ].x * sin;
  21105. vertex.y = points[ j ].y;
  21106. vertex.z = points[ j ].x * cos;
  21107. vertices.push( vertex.x, vertex.y, vertex.z );
  21108. // uv
  21109. uv.x = i / segments;
  21110. uv.y = j / ( points.length - 1 );
  21111. uvs.push( uv.x, uv.y );
  21112. }
  21113. }
  21114. // indices
  21115. for ( let i = 0; i < segments; i ++ ) {
  21116. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  21117. const base = j + i * points.length;
  21118. const a = base;
  21119. const b = base + points.length;
  21120. const c = base + points.length + 1;
  21121. const d = base + 1;
  21122. // faces
  21123. indices.push( a, b, d );
  21124. indices.push( b, c, d );
  21125. }
  21126. }
  21127. // build geometry
  21128. this.setIndex( indices );
  21129. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21130. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21131. // generate normals
  21132. this.computeVertexNormals();
  21133. // if the geometry is closed, we need to average the normals along the seam.
  21134. // because the corresponding vertices are identical (but still have different UVs).
  21135. if ( phiLength === Math.PI * 2 ) {
  21136. const normals = this.attributes.normal.array;
  21137. const n1 = new Vector3();
  21138. const n2 = new Vector3();
  21139. const n = new Vector3();
  21140. // this is the buffer offset for the last line of vertices
  21141. const base = segments * points.length * 3;
  21142. for ( let i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  21143. // select the normal of the vertex in the first line
  21144. n1.x = normals[ j + 0 ];
  21145. n1.y = normals[ j + 1 ];
  21146. n1.z = normals[ j + 2 ];
  21147. // select the normal of the vertex in the last line
  21148. n2.x = normals[ base + j + 0 ];
  21149. n2.y = normals[ base + j + 1 ];
  21150. n2.z = normals[ base + j + 2 ];
  21151. // average normals
  21152. n.addVectors( n1, n2 ).normalize();
  21153. // assign the new values to both normals
  21154. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  21155. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  21156. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  21157. }
  21158. }
  21159. }
  21160. static fromJSON( data ) {
  21161. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  21162. }
  21163. }
  21164. class OctahedronGeometry extends PolyhedronGeometry {
  21165. constructor( radius = 1, detail = 0 ) {
  21166. const vertices = [
  21167. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  21168. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  21169. ];
  21170. const indices = [
  21171. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  21172. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  21173. 1, 3, 4, 1, 4, 2
  21174. ];
  21175. super( vertices, indices, radius, detail );
  21176. this.type = 'OctahedronGeometry';
  21177. this.parameters = {
  21178. radius: radius,
  21179. detail: detail
  21180. };
  21181. }
  21182. static fromJSON( data ) {
  21183. return new OctahedronGeometry( data.radius, data.detail );
  21184. }
  21185. }
  21186. /**
  21187. * Parametric Surfaces Geometry
  21188. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  21189. */
  21190. class ParametricGeometry extends BufferGeometry {
  21191. constructor( func, slices, stacks ) {
  21192. super();
  21193. this.type = 'ParametricGeometry';
  21194. this.parameters = {
  21195. func: func,
  21196. slices: slices,
  21197. stacks: stacks
  21198. };
  21199. // buffers
  21200. const indices = [];
  21201. const vertices = [];
  21202. const normals = [];
  21203. const uvs = [];
  21204. const EPS = 0.00001;
  21205. const normal = new Vector3();
  21206. const p0 = new Vector3(), p1 = new Vector3();
  21207. const pu = new Vector3(), pv = new Vector3();
  21208. if ( func.length < 3 ) {
  21209. console.error( 'THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.' );
  21210. }
  21211. // generate vertices, normals and uvs
  21212. const sliceCount = slices + 1;
  21213. for ( let i = 0; i <= stacks; i ++ ) {
  21214. const v = i / stacks;
  21215. for ( let j = 0; j <= slices; j ++ ) {
  21216. const u = j / slices;
  21217. // vertex
  21218. func( u, v, p0 );
  21219. vertices.push( p0.x, p0.y, p0.z );
  21220. // normal
  21221. // approximate tangent vectors via finite differences
  21222. if ( u - EPS >= 0 ) {
  21223. func( u - EPS, v, p1 );
  21224. pu.subVectors( p0, p1 );
  21225. } else {
  21226. func( u + EPS, v, p1 );
  21227. pu.subVectors( p1, p0 );
  21228. }
  21229. if ( v - EPS >= 0 ) {
  21230. func( u, v - EPS, p1 );
  21231. pv.subVectors( p0, p1 );
  21232. } else {
  21233. func( u, v + EPS, p1 );
  21234. pv.subVectors( p1, p0 );
  21235. }
  21236. // cross product of tangent vectors returns surface normal
  21237. normal.crossVectors( pu, pv ).normalize();
  21238. normals.push( normal.x, normal.y, normal.z );
  21239. // uv
  21240. uvs.push( u, v );
  21241. }
  21242. }
  21243. // generate indices
  21244. for ( let i = 0; i < stacks; i ++ ) {
  21245. for ( let j = 0; j < slices; j ++ ) {
  21246. const a = i * sliceCount + j;
  21247. const b = i * sliceCount + j + 1;
  21248. const c = ( i + 1 ) * sliceCount + j + 1;
  21249. const d = ( i + 1 ) * sliceCount + j;
  21250. // faces one and two
  21251. indices.push( a, b, d );
  21252. indices.push( b, c, d );
  21253. }
  21254. }
  21255. // build geometry
  21256. this.setIndex( indices );
  21257. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21258. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21259. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21260. }
  21261. }
  21262. class RingGeometry extends BufferGeometry {
  21263. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21264. super();
  21265. this.type = 'RingGeometry';
  21266. this.parameters = {
  21267. innerRadius: innerRadius,
  21268. outerRadius: outerRadius,
  21269. thetaSegments: thetaSegments,
  21270. phiSegments: phiSegments,
  21271. thetaStart: thetaStart,
  21272. thetaLength: thetaLength
  21273. };
  21274. thetaSegments = Math.max( 3, thetaSegments );
  21275. phiSegments = Math.max( 1, phiSegments );
  21276. // buffers
  21277. const indices = [];
  21278. const vertices = [];
  21279. const normals = [];
  21280. const uvs = [];
  21281. // some helper variables
  21282. let radius = innerRadius;
  21283. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  21284. const vertex = new Vector3();
  21285. const uv = new Vector2();
  21286. // generate vertices, normals and uvs
  21287. for ( let j = 0; j <= phiSegments; j ++ ) {
  21288. for ( let i = 0; i <= thetaSegments; i ++ ) {
  21289. // values are generate from the inside of the ring to the outside
  21290. const segment = thetaStart + i / thetaSegments * thetaLength;
  21291. // vertex
  21292. vertex.x = radius * Math.cos( segment );
  21293. vertex.y = radius * Math.sin( segment );
  21294. vertices.push( vertex.x, vertex.y, vertex.z );
  21295. // normal
  21296. normals.push( 0, 0, 1 );
  21297. // uv
  21298. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  21299. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  21300. uvs.push( uv.x, uv.y );
  21301. }
  21302. // increase the radius for next row of vertices
  21303. radius += radiusStep;
  21304. }
  21305. // indices
  21306. for ( let j = 0; j < phiSegments; j ++ ) {
  21307. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  21308. for ( let i = 0; i < thetaSegments; i ++ ) {
  21309. const segment = i + thetaSegmentLevel;
  21310. const a = segment;
  21311. const b = segment + thetaSegments + 1;
  21312. const c = segment + thetaSegments + 2;
  21313. const d = segment + 1;
  21314. // faces
  21315. indices.push( a, b, d );
  21316. indices.push( b, c, d );
  21317. }
  21318. }
  21319. // build geometry
  21320. this.setIndex( indices );
  21321. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21322. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21323. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21324. }
  21325. static fromJSON( data ) {
  21326. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  21327. }
  21328. }
  21329. class ShapeGeometry extends BufferGeometry {
  21330. constructor( shapes, curveSegments = 12 ) {
  21331. super();
  21332. this.type = 'ShapeGeometry';
  21333. this.parameters = {
  21334. shapes: shapes,
  21335. curveSegments: curveSegments
  21336. };
  21337. // buffers
  21338. const indices = [];
  21339. const vertices = [];
  21340. const normals = [];
  21341. const uvs = [];
  21342. // helper variables
  21343. let groupStart = 0;
  21344. let groupCount = 0;
  21345. // allow single and array values for "shapes" parameter
  21346. if ( Array.isArray( shapes ) === false ) {
  21347. addShape( shapes );
  21348. } else {
  21349. for ( let i = 0; i < shapes.length; i ++ ) {
  21350. addShape( shapes[ i ] );
  21351. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  21352. groupStart += groupCount;
  21353. groupCount = 0;
  21354. }
  21355. }
  21356. // build geometry
  21357. this.setIndex( indices );
  21358. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21359. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21360. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21361. // helper functions
  21362. function addShape( shape ) {
  21363. const indexOffset = vertices.length / 3;
  21364. const points = shape.extractPoints( curveSegments );
  21365. let shapeVertices = points.shape;
  21366. const shapeHoles = points.holes;
  21367. // check direction of vertices
  21368. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  21369. shapeVertices = shapeVertices.reverse();
  21370. }
  21371. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21372. const shapeHole = shapeHoles[ i ];
  21373. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  21374. shapeHoles[ i ] = shapeHole.reverse();
  21375. }
  21376. }
  21377. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  21378. // join vertices of inner and outer paths to a single array
  21379. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21380. const shapeHole = shapeHoles[ i ];
  21381. shapeVertices = shapeVertices.concat( shapeHole );
  21382. }
  21383. // vertices, normals, uvs
  21384. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  21385. const vertex = shapeVertices[ i ];
  21386. vertices.push( vertex.x, vertex.y, 0 );
  21387. normals.push( 0, 0, 1 );
  21388. uvs.push( vertex.x, vertex.y ); // world uvs
  21389. }
  21390. // incides
  21391. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  21392. const face = faces[ i ];
  21393. const a = face[ 0 ] + indexOffset;
  21394. const b = face[ 1 ] + indexOffset;
  21395. const c = face[ 2 ] + indexOffset;
  21396. indices.push( a, b, c );
  21397. groupCount += 3;
  21398. }
  21399. }
  21400. }
  21401. toJSON() {
  21402. const data = super.toJSON();
  21403. const shapes = this.parameters.shapes;
  21404. return toJSON( shapes, data );
  21405. }
  21406. static fromJSON( data, shapes ) {
  21407. const geometryShapes = [];
  21408. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21409. const shape = shapes[ data.shapes[ j ] ];
  21410. geometryShapes.push( shape );
  21411. }
  21412. return new ShapeGeometry( geometryShapes, data.curveSegments );
  21413. }
  21414. }
  21415. function toJSON( shapes, data ) {
  21416. data.shapes = [];
  21417. if ( Array.isArray( shapes ) ) {
  21418. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21419. const shape = shapes[ i ];
  21420. data.shapes.push( shape.uuid );
  21421. }
  21422. } else {
  21423. data.shapes.push( shapes.uuid );
  21424. }
  21425. return data;
  21426. }
  21427. class SphereGeometry extends BufferGeometry {
  21428. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  21429. super();
  21430. this.type = 'SphereGeometry';
  21431. this.parameters = {
  21432. radius: radius,
  21433. widthSegments: widthSegments,
  21434. heightSegments: heightSegments,
  21435. phiStart: phiStart,
  21436. phiLength: phiLength,
  21437. thetaStart: thetaStart,
  21438. thetaLength: thetaLength
  21439. };
  21440. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  21441. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  21442. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  21443. let index = 0;
  21444. const grid = [];
  21445. const vertex = new Vector3();
  21446. const normal = new Vector3();
  21447. // buffers
  21448. const indices = [];
  21449. const vertices = [];
  21450. const normals = [];
  21451. const uvs = [];
  21452. // generate vertices, normals and uvs
  21453. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  21454. const verticesRow = [];
  21455. const v = iy / heightSegments;
  21456. // special case for the poles
  21457. let uOffset = 0;
  21458. if ( iy == 0 && thetaStart == 0 ) {
  21459. uOffset = 0.5 / widthSegments;
  21460. } else if ( iy == heightSegments && thetaEnd == Math.PI ) {
  21461. uOffset = - 0.5 / widthSegments;
  21462. }
  21463. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  21464. const u = ix / widthSegments;
  21465. // vertex
  21466. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21467. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  21468. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21469. vertices.push( vertex.x, vertex.y, vertex.z );
  21470. // normal
  21471. normal.copy( vertex ).normalize();
  21472. normals.push( normal.x, normal.y, normal.z );
  21473. // uv
  21474. uvs.push( u + uOffset, 1 - v );
  21475. verticesRow.push( index ++ );
  21476. }
  21477. grid.push( verticesRow );
  21478. }
  21479. // indices
  21480. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  21481. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  21482. const a = grid[ iy ][ ix + 1 ];
  21483. const b = grid[ iy ][ ix ];
  21484. const c = grid[ iy + 1 ][ ix ];
  21485. const d = grid[ iy + 1 ][ ix + 1 ];
  21486. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  21487. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  21488. }
  21489. }
  21490. // build geometry
  21491. this.setIndex( indices );
  21492. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21493. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21494. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21495. }
  21496. static fromJSON( data ) {
  21497. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  21498. }
  21499. }
  21500. class TetrahedronGeometry extends PolyhedronGeometry {
  21501. constructor( radius = 1, detail = 0 ) {
  21502. const vertices = [
  21503. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  21504. ];
  21505. const indices = [
  21506. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  21507. ];
  21508. super( vertices, indices, radius, detail );
  21509. this.type = 'TetrahedronGeometry';
  21510. this.parameters = {
  21511. radius: radius,
  21512. detail: detail
  21513. };
  21514. }
  21515. static fromJSON( data ) {
  21516. return new TetrahedronGeometry( data.radius, data.detail );
  21517. }
  21518. }
  21519. /**
  21520. * Text = 3D Text
  21521. *
  21522. * parameters = {
  21523. * font: <THREE.Font>, // font
  21524. *
  21525. * size: <float>, // size of the text
  21526. * height: <float>, // thickness to extrude text
  21527. * curveSegments: <int>, // number of points on the curves
  21528. *
  21529. * bevelEnabled: <bool>, // turn on bevel
  21530. * bevelThickness: <float>, // how deep into text bevel goes
  21531. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  21532. * bevelOffset: <float> // how far from text outline does bevel start
  21533. * }
  21534. */
  21535. class TextGeometry extends ExtrudeGeometry {
  21536. constructor( text, parameters = {} ) {
  21537. const font = parameters.font;
  21538. if ( ! ( font && font.isFont ) ) {
  21539. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  21540. return new BufferGeometry();
  21541. }
  21542. const shapes = font.generateShapes( text, parameters.size );
  21543. // translate parameters to ExtrudeGeometry API
  21544. parameters.depth = parameters.height !== undefined ? parameters.height : 50;
  21545. // defaults
  21546. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  21547. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  21548. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  21549. super( shapes, parameters );
  21550. this.type = 'TextGeometry';
  21551. }
  21552. }
  21553. class TorusGeometry extends BufferGeometry {
  21554. constructor( radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2 ) {
  21555. super();
  21556. this.type = 'TorusGeometry';
  21557. this.parameters = {
  21558. radius: radius,
  21559. tube: tube,
  21560. radialSegments: radialSegments,
  21561. tubularSegments: tubularSegments,
  21562. arc: arc
  21563. };
  21564. radialSegments = Math.floor( radialSegments );
  21565. tubularSegments = Math.floor( tubularSegments );
  21566. // buffers
  21567. const indices = [];
  21568. const vertices = [];
  21569. const normals = [];
  21570. const uvs = [];
  21571. // helper variables
  21572. const center = new Vector3();
  21573. const vertex = new Vector3();
  21574. const normal = new Vector3();
  21575. // generate vertices, normals and uvs
  21576. for ( let j = 0; j <= radialSegments; j ++ ) {
  21577. for ( let i = 0; i <= tubularSegments; i ++ ) {
  21578. const u = i / tubularSegments * arc;
  21579. const v = j / radialSegments * Math.PI * 2;
  21580. // vertex
  21581. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  21582. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  21583. vertex.z = tube * Math.sin( v );
  21584. vertices.push( vertex.x, vertex.y, vertex.z );
  21585. // normal
  21586. center.x = radius * Math.cos( u );
  21587. center.y = radius * Math.sin( u );
  21588. normal.subVectors( vertex, center ).normalize();
  21589. normals.push( normal.x, normal.y, normal.z );
  21590. // uv
  21591. uvs.push( i / tubularSegments );
  21592. uvs.push( j / radialSegments );
  21593. }
  21594. }
  21595. // generate indices
  21596. for ( let j = 1; j <= radialSegments; j ++ ) {
  21597. for ( let i = 1; i <= tubularSegments; i ++ ) {
  21598. // indices
  21599. const a = ( tubularSegments + 1 ) * j + i - 1;
  21600. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  21601. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  21602. const d = ( tubularSegments + 1 ) * j + i;
  21603. // faces
  21604. indices.push( a, b, d );
  21605. indices.push( b, c, d );
  21606. }
  21607. }
  21608. // build geometry
  21609. this.setIndex( indices );
  21610. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21611. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21612. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21613. }
  21614. static fromJSON( data ) {
  21615. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  21616. }
  21617. }
  21618. class TorusKnotGeometry extends BufferGeometry {
  21619. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  21620. super();
  21621. this.type = 'TorusKnotGeometry';
  21622. this.parameters = {
  21623. radius: radius,
  21624. tube: tube,
  21625. tubularSegments: tubularSegments,
  21626. radialSegments: radialSegments,
  21627. p: p,
  21628. q: q
  21629. };
  21630. tubularSegments = Math.floor( tubularSegments );
  21631. radialSegments = Math.floor( radialSegments );
  21632. // buffers
  21633. const indices = [];
  21634. const vertices = [];
  21635. const normals = [];
  21636. const uvs = [];
  21637. // helper variables
  21638. const vertex = new Vector3();
  21639. const normal = new Vector3();
  21640. const P1 = new Vector3();
  21641. const P2 = new Vector3();
  21642. const B = new Vector3();
  21643. const T = new Vector3();
  21644. const N = new Vector3();
  21645. // generate vertices, normals and uvs
  21646. for ( let i = 0; i <= tubularSegments; ++ i ) {
  21647. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  21648. const u = i / tubularSegments * p * Math.PI * 2;
  21649. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  21650. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  21651. calculatePositionOnCurve( u, p, q, radius, P1 );
  21652. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  21653. // calculate orthonormal basis
  21654. T.subVectors( P2, P1 );
  21655. N.addVectors( P2, P1 );
  21656. B.crossVectors( T, N );
  21657. N.crossVectors( B, T );
  21658. // normalize B, N. T can be ignored, we don't use it
  21659. B.normalize();
  21660. N.normalize();
  21661. for ( let j = 0; j <= radialSegments; ++ j ) {
  21662. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  21663. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  21664. const v = j / radialSegments * Math.PI * 2;
  21665. const cx = - tube * Math.cos( v );
  21666. const cy = tube * Math.sin( v );
  21667. // now calculate the final vertex position.
  21668. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  21669. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  21670. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  21671. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  21672. vertices.push( vertex.x, vertex.y, vertex.z );
  21673. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  21674. normal.subVectors( vertex, P1 ).normalize();
  21675. normals.push( normal.x, normal.y, normal.z );
  21676. // uv
  21677. uvs.push( i / tubularSegments );
  21678. uvs.push( j / radialSegments );
  21679. }
  21680. }
  21681. // generate indices
  21682. for ( let j = 1; j <= tubularSegments; j ++ ) {
  21683. for ( let i = 1; i <= radialSegments; i ++ ) {
  21684. // indices
  21685. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  21686. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  21687. const c = ( radialSegments + 1 ) * j + i;
  21688. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  21689. // faces
  21690. indices.push( a, b, d );
  21691. indices.push( b, c, d );
  21692. }
  21693. }
  21694. // build geometry
  21695. this.setIndex( indices );
  21696. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21697. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21698. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21699. // this function calculates the current position on the torus curve
  21700. function calculatePositionOnCurve( u, p, q, radius, position ) {
  21701. const cu = Math.cos( u );
  21702. const su = Math.sin( u );
  21703. const quOverP = q / p * u;
  21704. const cs = Math.cos( quOverP );
  21705. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  21706. position.y = radius * ( 2 + cs ) * su * 0.5;
  21707. position.z = radius * Math.sin( quOverP ) * 0.5;
  21708. }
  21709. }
  21710. static fromJSON( data ) {
  21711. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  21712. }
  21713. }
  21714. class TubeGeometry extends BufferGeometry {
  21715. constructor( path, tubularSegments = 64, radius = 1, radialSegments = 8, closed = false ) {
  21716. super();
  21717. this.type = 'TubeGeometry';
  21718. this.parameters = {
  21719. path: path,
  21720. tubularSegments: tubularSegments,
  21721. radius: radius,
  21722. radialSegments: radialSegments,
  21723. closed: closed
  21724. };
  21725. const frames = path.computeFrenetFrames( tubularSegments, closed );
  21726. // expose internals
  21727. this.tangents = frames.tangents;
  21728. this.normals = frames.normals;
  21729. this.binormals = frames.binormals;
  21730. // helper variables
  21731. const vertex = new Vector3();
  21732. const normal = new Vector3();
  21733. const uv = new Vector2();
  21734. let P = new Vector3();
  21735. // buffer
  21736. const vertices = [];
  21737. const normals = [];
  21738. const uvs = [];
  21739. const indices = [];
  21740. // create buffer data
  21741. generateBufferData();
  21742. // build geometry
  21743. this.setIndex( indices );
  21744. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21745. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21746. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21747. // functions
  21748. function generateBufferData() {
  21749. for ( let i = 0; i < tubularSegments; i ++ ) {
  21750. generateSegment( i );
  21751. }
  21752. // if the geometry is not closed, generate the last row of vertices and normals
  21753. // at the regular position on the given path
  21754. //
  21755. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  21756. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  21757. // uvs are generated in a separate function.
  21758. // this makes it easy compute correct values for closed geometries
  21759. generateUVs();
  21760. // finally create faces
  21761. generateIndices();
  21762. }
  21763. function generateSegment( i ) {
  21764. // we use getPointAt to sample evenly distributed points from the given path
  21765. P = path.getPointAt( i / tubularSegments, P );
  21766. // retrieve corresponding normal and binormal
  21767. const N = frames.normals[ i ];
  21768. const B = frames.binormals[ i ];
  21769. // generate normals and vertices for the current segment
  21770. for ( let j = 0; j <= radialSegments; j ++ ) {
  21771. const v = j / radialSegments * Math.PI * 2;
  21772. const sin = Math.sin( v );
  21773. const cos = - Math.cos( v );
  21774. // normal
  21775. normal.x = ( cos * N.x + sin * B.x );
  21776. normal.y = ( cos * N.y + sin * B.y );
  21777. normal.z = ( cos * N.z + sin * B.z );
  21778. normal.normalize();
  21779. normals.push( normal.x, normal.y, normal.z );
  21780. // vertex
  21781. vertex.x = P.x + radius * normal.x;
  21782. vertex.y = P.y + radius * normal.y;
  21783. vertex.z = P.z + radius * normal.z;
  21784. vertices.push( vertex.x, vertex.y, vertex.z );
  21785. }
  21786. }
  21787. function generateIndices() {
  21788. for ( let j = 1; j <= tubularSegments; j ++ ) {
  21789. for ( let i = 1; i <= radialSegments; i ++ ) {
  21790. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  21791. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  21792. const c = ( radialSegments + 1 ) * j + i;
  21793. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  21794. // faces
  21795. indices.push( a, b, d );
  21796. indices.push( b, c, d );
  21797. }
  21798. }
  21799. }
  21800. function generateUVs() {
  21801. for ( let i = 0; i <= tubularSegments; i ++ ) {
  21802. for ( let j = 0; j <= radialSegments; j ++ ) {
  21803. uv.x = i / tubularSegments;
  21804. uv.y = j / radialSegments;
  21805. uvs.push( uv.x, uv.y );
  21806. }
  21807. }
  21808. }
  21809. }
  21810. toJSON() {
  21811. const data = super.toJSON();
  21812. data.path = this.parameters.path.toJSON();
  21813. return data;
  21814. }
  21815. static fromJSON( data ) {
  21816. // This only works for built-in curves (e.g. CatmullRomCurve3).
  21817. // User defined curves or instances of CurvePath will not be deserialized.
  21818. return new TubeGeometry(
  21819. new Curves[ data.path.type ]().fromJSON( data.path ),
  21820. data.tubularSegments,
  21821. data.radius,
  21822. data.radialSegments,
  21823. data.closed
  21824. );
  21825. }
  21826. }
  21827. class WireframeGeometry extends BufferGeometry {
  21828. constructor( geometry ) {
  21829. super();
  21830. this.type = 'WireframeGeometry';
  21831. if ( geometry.isGeometry === true ) {
  21832. console.error( 'THREE.WireframeGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  21833. return;
  21834. }
  21835. // buffer
  21836. const vertices = [];
  21837. const edges = new Set();
  21838. // helper variables
  21839. const start = new Vector3();
  21840. const end = new Vector3();
  21841. if ( geometry.index !== null ) {
  21842. // indexed BufferGeometry
  21843. const position = geometry.attributes.position;
  21844. const indices = geometry.index;
  21845. let groups = geometry.groups;
  21846. if ( groups.length === 0 ) {
  21847. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  21848. }
  21849. // create a data structure that contains all eges without duplicates
  21850. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  21851. const group = groups[ o ];
  21852. const groupStart = group.start;
  21853. const groupCount = group.count;
  21854. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  21855. for ( let j = 0; j < 3; j ++ ) {
  21856. const index1 = indices.getX( i + j );
  21857. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  21858. start.fromBufferAttribute( position, index1 );
  21859. end.fromBufferAttribute( position, index2 );
  21860. if ( isUniqueEdge( start, end, edges ) === true ) {
  21861. vertices.push( start.x, start.y, start.z );
  21862. vertices.push( end.x, end.y, end.z );
  21863. }
  21864. }
  21865. }
  21866. }
  21867. } else {
  21868. // non-indexed BufferGeometry
  21869. const position = geometry.attributes.position;
  21870. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  21871. for ( let j = 0; j < 3; j ++ ) {
  21872. // three edges per triangle, an edge is represented as (index1, index2)
  21873. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  21874. const index1 = 3 * i + j;
  21875. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  21876. start.fromBufferAttribute( position, index1 );
  21877. end.fromBufferAttribute( position, index2 );
  21878. if ( isUniqueEdge( start, end, edges ) === true ) {
  21879. vertices.push( start.x, start.y, start.z );
  21880. vertices.push( end.x, end.y, end.z );
  21881. }
  21882. }
  21883. }
  21884. }
  21885. // build geometry
  21886. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21887. }
  21888. }
  21889. function isUniqueEdge( start, end, edges ) {
  21890. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  21891. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  21892. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  21893. return false;
  21894. } else {
  21895. edges.add( hash1, hash2 );
  21896. return true;
  21897. }
  21898. }
  21899. var Geometries = /*#__PURE__*/Object.freeze({
  21900. __proto__: null,
  21901. BoxGeometry: BoxGeometry,
  21902. BoxBufferGeometry: BoxGeometry,
  21903. CircleGeometry: CircleGeometry,
  21904. CircleBufferGeometry: CircleGeometry,
  21905. ConeGeometry: ConeGeometry,
  21906. ConeBufferGeometry: ConeGeometry,
  21907. CylinderGeometry: CylinderGeometry,
  21908. CylinderBufferGeometry: CylinderGeometry,
  21909. DodecahedronGeometry: DodecahedronGeometry,
  21910. DodecahedronBufferGeometry: DodecahedronGeometry,
  21911. EdgesGeometry: EdgesGeometry,
  21912. ExtrudeGeometry: ExtrudeGeometry,
  21913. ExtrudeBufferGeometry: ExtrudeGeometry,
  21914. IcosahedronGeometry: IcosahedronGeometry,
  21915. IcosahedronBufferGeometry: IcosahedronGeometry,
  21916. LatheGeometry: LatheGeometry,
  21917. LatheBufferGeometry: LatheGeometry,
  21918. OctahedronGeometry: OctahedronGeometry,
  21919. OctahedronBufferGeometry: OctahedronGeometry,
  21920. ParametricGeometry: ParametricGeometry,
  21921. ParametricBufferGeometry: ParametricGeometry,
  21922. PlaneGeometry: PlaneGeometry,
  21923. PlaneBufferGeometry: PlaneGeometry,
  21924. PolyhedronGeometry: PolyhedronGeometry,
  21925. PolyhedronBufferGeometry: PolyhedronGeometry,
  21926. RingGeometry: RingGeometry,
  21927. RingBufferGeometry: RingGeometry,
  21928. ShapeGeometry: ShapeGeometry,
  21929. ShapeBufferGeometry: ShapeGeometry,
  21930. SphereGeometry: SphereGeometry,
  21931. SphereBufferGeometry: SphereGeometry,
  21932. TetrahedronGeometry: TetrahedronGeometry,
  21933. TetrahedronBufferGeometry: TetrahedronGeometry,
  21934. TextGeometry: TextGeometry,
  21935. TextBufferGeometry: TextGeometry,
  21936. TorusGeometry: TorusGeometry,
  21937. TorusBufferGeometry: TorusGeometry,
  21938. TorusKnotGeometry: TorusKnotGeometry,
  21939. TorusKnotBufferGeometry: TorusKnotGeometry,
  21940. TubeGeometry: TubeGeometry,
  21941. TubeBufferGeometry: TubeGeometry,
  21942. WireframeGeometry: WireframeGeometry
  21943. });
  21944. /**
  21945. * parameters = {
  21946. * color: <THREE.Color>
  21947. * }
  21948. */
  21949. class ShadowMaterial extends Material {
  21950. constructor( parameters ) {
  21951. super();
  21952. this.type = 'ShadowMaterial';
  21953. this.color = new Color( 0x000000 );
  21954. this.transparent = true;
  21955. this.setValues( parameters );
  21956. }
  21957. copy( source ) {
  21958. super.copy( source );
  21959. this.color.copy( source.color );
  21960. return this;
  21961. }
  21962. }
  21963. ShadowMaterial.prototype.isShadowMaterial = true;
  21964. /**
  21965. * parameters = {
  21966. * color: <hex>,
  21967. * roughness: <float>,
  21968. * metalness: <float>,
  21969. * opacity: <float>,
  21970. *
  21971. * map: new THREE.Texture( <Image> ),
  21972. *
  21973. * lightMap: new THREE.Texture( <Image> ),
  21974. * lightMapIntensity: <float>
  21975. *
  21976. * aoMap: new THREE.Texture( <Image> ),
  21977. * aoMapIntensity: <float>
  21978. *
  21979. * emissive: <hex>,
  21980. * emissiveIntensity: <float>
  21981. * emissiveMap: new THREE.Texture( <Image> ),
  21982. *
  21983. * bumpMap: new THREE.Texture( <Image> ),
  21984. * bumpScale: <float>,
  21985. *
  21986. * normalMap: new THREE.Texture( <Image> ),
  21987. * normalMapType: THREE.TangentSpaceNormalMap,
  21988. * normalScale: <Vector2>,
  21989. *
  21990. * displacementMap: new THREE.Texture( <Image> ),
  21991. * displacementScale: <float>,
  21992. * displacementBias: <float>,
  21993. *
  21994. * roughnessMap: new THREE.Texture( <Image> ),
  21995. *
  21996. * metalnessMap: new THREE.Texture( <Image> ),
  21997. *
  21998. * alphaMap: new THREE.Texture( <Image> ),
  21999. *
  22000. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  22001. * envMapIntensity: <float>
  22002. *
  22003. * refractionRatio: <float>,
  22004. *
  22005. * wireframe: <boolean>,
  22006. * wireframeLinewidth: <float>,
  22007. *
  22008. * flatShading: <bool>
  22009. * }
  22010. */
  22011. class MeshStandardMaterial extends Material {
  22012. constructor( parameters ) {
  22013. super();
  22014. this.defines = { 'STANDARD': '' };
  22015. this.type = 'MeshStandardMaterial';
  22016. this.color = new Color( 0xffffff ); // diffuse
  22017. this.roughness = 1.0;
  22018. this.metalness = 0.0;
  22019. this.map = null;
  22020. this.lightMap = null;
  22021. this.lightMapIntensity = 1.0;
  22022. this.aoMap = null;
  22023. this.aoMapIntensity = 1.0;
  22024. this.emissive = new Color( 0x000000 );
  22025. this.emissiveIntensity = 1.0;
  22026. this.emissiveMap = null;
  22027. this.bumpMap = null;
  22028. this.bumpScale = 1;
  22029. this.normalMap = null;
  22030. this.normalMapType = TangentSpaceNormalMap;
  22031. this.normalScale = new Vector2( 1, 1 );
  22032. this.displacementMap = null;
  22033. this.displacementScale = 1;
  22034. this.displacementBias = 0;
  22035. this.roughnessMap = null;
  22036. this.metalnessMap = null;
  22037. this.alphaMap = null;
  22038. this.envMap = null;
  22039. this.envMapIntensity = 1.0;
  22040. this.refractionRatio = 0.98;
  22041. this.wireframe = false;
  22042. this.wireframeLinewidth = 1;
  22043. this.wireframeLinecap = 'round';
  22044. this.wireframeLinejoin = 'round';
  22045. this.flatShading = false;
  22046. this.setValues( parameters );
  22047. }
  22048. copy( source ) {
  22049. super.copy( source );
  22050. this.defines = { 'STANDARD': '' };
  22051. this.color.copy( source.color );
  22052. this.roughness = source.roughness;
  22053. this.metalness = source.metalness;
  22054. this.map = source.map;
  22055. this.lightMap = source.lightMap;
  22056. this.lightMapIntensity = source.lightMapIntensity;
  22057. this.aoMap = source.aoMap;
  22058. this.aoMapIntensity = source.aoMapIntensity;
  22059. this.emissive.copy( source.emissive );
  22060. this.emissiveMap = source.emissiveMap;
  22061. this.emissiveIntensity = source.emissiveIntensity;
  22062. this.bumpMap = source.bumpMap;
  22063. this.bumpScale = source.bumpScale;
  22064. this.normalMap = source.normalMap;
  22065. this.normalMapType = source.normalMapType;
  22066. this.normalScale.copy( source.normalScale );
  22067. this.displacementMap = source.displacementMap;
  22068. this.displacementScale = source.displacementScale;
  22069. this.displacementBias = source.displacementBias;
  22070. this.roughnessMap = source.roughnessMap;
  22071. this.metalnessMap = source.metalnessMap;
  22072. this.alphaMap = source.alphaMap;
  22073. this.envMap = source.envMap;
  22074. this.envMapIntensity = source.envMapIntensity;
  22075. this.refractionRatio = source.refractionRatio;
  22076. this.wireframe = source.wireframe;
  22077. this.wireframeLinewidth = source.wireframeLinewidth;
  22078. this.wireframeLinecap = source.wireframeLinecap;
  22079. this.wireframeLinejoin = source.wireframeLinejoin;
  22080. this.flatShading = source.flatShading;
  22081. return this;
  22082. }
  22083. }
  22084. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  22085. /**
  22086. * parameters = {
  22087. * clearcoat: <float>,
  22088. * clearcoatMap: new THREE.Texture( <Image> ),
  22089. * clearcoatRoughness: <float>,
  22090. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  22091. * clearcoatNormalScale: <Vector2>,
  22092. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  22093. *
  22094. * ior: <float>,
  22095. * reflectivity: <float>,
  22096. *
  22097. * sheenTint: <Color>,
  22098. *
  22099. * transmission: <float>,
  22100. * transmissionMap: new THREE.Texture( <Image> ),
  22101. *
  22102. * thickness: <float>,
  22103. * thicknessMap: new THREE.Texture( <Image> ),
  22104. * attenuationDistance: <float>,
  22105. * attenuationTint: <Color>,
  22106. *
  22107. * specularIntensity: <float>,
  22108. * specularIntensityhMap: new THREE.Texture( <Image> ),
  22109. * specularTint: <Color>,
  22110. * specularTintMap: new THREE.Texture( <Image> )
  22111. * }
  22112. */
  22113. class MeshPhysicalMaterial extends MeshStandardMaterial {
  22114. constructor( parameters ) {
  22115. super();
  22116. this.defines = {
  22117. 'STANDARD': '',
  22118. 'PHYSICAL': ''
  22119. };
  22120. this.type = 'MeshPhysicalMaterial';
  22121. this.clearcoatMap = null;
  22122. this.clearcoatRoughness = 0.0;
  22123. this.clearcoatRoughnessMap = null;
  22124. this.clearcoatNormalScale = new Vector2( 1, 1 );
  22125. this.clearcoatNormalMap = null;
  22126. this.ior = 1.5;
  22127. Object.defineProperty( this, 'reflectivity', {
  22128. get: function () {
  22129. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  22130. },
  22131. set: function ( reflectivity ) {
  22132. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  22133. }
  22134. } );
  22135. this.sheenTint = new Color( 0x000000 );
  22136. this.transmission = 0.0;
  22137. this.transmissionMap = null;
  22138. this.thickness = 0.01;
  22139. this.thicknessMap = null;
  22140. this.attenuationDistance = 0.0;
  22141. this.attenuationTint = new Color( 1, 1, 1 );
  22142. this.specularIntensity = 1.0;
  22143. this.specularIntensityMap = null;
  22144. this.specularTint = new Color( 1, 1, 1 );
  22145. this.specularTintMap = null;
  22146. this._clearcoat = 0;
  22147. this._transmission = 0;
  22148. this.setValues( parameters );
  22149. }
  22150. get clearcoat() {
  22151. return this._clearcoat;
  22152. }
  22153. set clearcoat( value ) {
  22154. if ( this._clearcoat > 0 !== value > 0 ) {
  22155. this.version ++;
  22156. }
  22157. this._clearcoat = value;
  22158. }
  22159. get transmission() {
  22160. return this._transmission;
  22161. }
  22162. set transmission( value ) {
  22163. if ( this._transmission > 0 !== value > 0 ) {
  22164. this.version ++;
  22165. }
  22166. this._transmission = value;
  22167. }
  22168. copy( source ) {
  22169. super.copy( source );
  22170. this.defines = {
  22171. 'STANDARD': '',
  22172. 'PHYSICAL': ''
  22173. };
  22174. this.clearcoat = source.clearcoat;
  22175. this.clearcoatMap = source.clearcoatMap;
  22176. this.clearcoatRoughness = source.clearcoatRoughness;
  22177. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  22178. this.clearcoatNormalMap = source.clearcoatNormalMap;
  22179. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  22180. this.ior = source.ior;
  22181. this.sheenTint.copy( source.sheenTint );
  22182. this.transmission = source.transmission;
  22183. this.transmissionMap = source.transmissionMap;
  22184. this.thickness = source.thickness;
  22185. this.thicknessMap = source.thicknessMap;
  22186. this.attenuationDistance = source.attenuationDistance;
  22187. this.attenuationTint.copy( source.attenuationTint );
  22188. this.specularIntensity = source.specularIntensity;
  22189. this.specularIntensityMap = source.specularIntensityMap;
  22190. this.specularTint.copy( source.specularTint );
  22191. this.specularTintMap = source.specularTintMap;
  22192. return this;
  22193. }
  22194. }
  22195. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  22196. /**
  22197. * parameters = {
  22198. * color: <hex>,
  22199. * specular: <hex>,
  22200. * shininess: <float>,
  22201. * opacity: <float>,
  22202. *
  22203. * map: new THREE.Texture( <Image> ),
  22204. *
  22205. * lightMap: new THREE.Texture( <Image> ),
  22206. * lightMapIntensity: <float>
  22207. *
  22208. * aoMap: new THREE.Texture( <Image> ),
  22209. * aoMapIntensity: <float>
  22210. *
  22211. * emissive: <hex>,
  22212. * emissiveIntensity: <float>
  22213. * emissiveMap: new THREE.Texture( <Image> ),
  22214. *
  22215. * bumpMap: new THREE.Texture( <Image> ),
  22216. * bumpScale: <float>,
  22217. *
  22218. * normalMap: new THREE.Texture( <Image> ),
  22219. * normalMapType: THREE.TangentSpaceNormalMap,
  22220. * normalScale: <Vector2>,
  22221. *
  22222. * displacementMap: new THREE.Texture( <Image> ),
  22223. * displacementScale: <float>,
  22224. * displacementBias: <float>,
  22225. *
  22226. * specularMap: new THREE.Texture( <Image> ),
  22227. *
  22228. * alphaMap: new THREE.Texture( <Image> ),
  22229. *
  22230. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  22231. * combine: THREE.MultiplyOperation,
  22232. * reflectivity: <float>,
  22233. * refractionRatio: <float>,
  22234. *
  22235. * wireframe: <boolean>,
  22236. * wireframeLinewidth: <float>,
  22237. *
  22238. * flatShading: <bool>
  22239. * }
  22240. */
  22241. class MeshPhongMaterial extends Material {
  22242. constructor( parameters ) {
  22243. super();
  22244. this.type = 'MeshPhongMaterial';
  22245. this.color = new Color( 0xffffff ); // diffuse
  22246. this.specular = new Color( 0x111111 );
  22247. this.shininess = 30;
  22248. this.map = null;
  22249. this.lightMap = null;
  22250. this.lightMapIntensity = 1.0;
  22251. this.aoMap = null;
  22252. this.aoMapIntensity = 1.0;
  22253. this.emissive = new Color( 0x000000 );
  22254. this.emissiveIntensity = 1.0;
  22255. this.emissiveMap = null;
  22256. this.bumpMap = null;
  22257. this.bumpScale = 1;
  22258. this.normalMap = null;
  22259. this.normalMapType = TangentSpaceNormalMap;
  22260. this.normalScale = new Vector2( 1, 1 );
  22261. this.displacementMap = null;
  22262. this.displacementScale = 1;
  22263. this.displacementBias = 0;
  22264. this.specularMap = null;
  22265. this.alphaMap = null;
  22266. this.envMap = null;
  22267. this.combine = MultiplyOperation;
  22268. this.reflectivity = 1;
  22269. this.refractionRatio = 0.98;
  22270. this.wireframe = false;
  22271. this.wireframeLinewidth = 1;
  22272. this.wireframeLinecap = 'round';
  22273. this.wireframeLinejoin = 'round';
  22274. this.flatShading = false;
  22275. this.setValues( parameters );
  22276. }
  22277. copy( source ) {
  22278. super.copy( source );
  22279. this.color.copy( source.color );
  22280. this.specular.copy( source.specular );
  22281. this.shininess = source.shininess;
  22282. this.map = source.map;
  22283. this.lightMap = source.lightMap;
  22284. this.lightMapIntensity = source.lightMapIntensity;
  22285. this.aoMap = source.aoMap;
  22286. this.aoMapIntensity = source.aoMapIntensity;
  22287. this.emissive.copy( source.emissive );
  22288. this.emissiveMap = source.emissiveMap;
  22289. this.emissiveIntensity = source.emissiveIntensity;
  22290. this.bumpMap = source.bumpMap;
  22291. this.bumpScale = source.bumpScale;
  22292. this.normalMap = source.normalMap;
  22293. this.normalMapType = source.normalMapType;
  22294. this.normalScale.copy( source.normalScale );
  22295. this.displacementMap = source.displacementMap;
  22296. this.displacementScale = source.displacementScale;
  22297. this.displacementBias = source.displacementBias;
  22298. this.specularMap = source.specularMap;
  22299. this.alphaMap = source.alphaMap;
  22300. this.envMap = source.envMap;
  22301. this.combine = source.combine;
  22302. this.reflectivity = source.reflectivity;
  22303. this.refractionRatio = source.refractionRatio;
  22304. this.wireframe = source.wireframe;
  22305. this.wireframeLinewidth = source.wireframeLinewidth;
  22306. this.wireframeLinecap = source.wireframeLinecap;
  22307. this.wireframeLinejoin = source.wireframeLinejoin;
  22308. this.flatShading = source.flatShading;
  22309. return this;
  22310. }
  22311. }
  22312. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  22313. /**
  22314. * parameters = {
  22315. * color: <hex>,
  22316. *
  22317. * map: new THREE.Texture( <Image> ),
  22318. * gradientMap: new THREE.Texture( <Image> ),
  22319. *
  22320. * lightMap: new THREE.Texture( <Image> ),
  22321. * lightMapIntensity: <float>
  22322. *
  22323. * aoMap: new THREE.Texture( <Image> ),
  22324. * aoMapIntensity: <float>
  22325. *
  22326. * emissive: <hex>,
  22327. * emissiveIntensity: <float>
  22328. * emissiveMap: new THREE.Texture( <Image> ),
  22329. *
  22330. * bumpMap: new THREE.Texture( <Image> ),
  22331. * bumpScale: <float>,
  22332. *
  22333. * normalMap: new THREE.Texture( <Image> ),
  22334. * normalMapType: THREE.TangentSpaceNormalMap,
  22335. * normalScale: <Vector2>,
  22336. *
  22337. * displacementMap: new THREE.Texture( <Image> ),
  22338. * displacementScale: <float>,
  22339. * displacementBias: <float>,
  22340. *
  22341. * alphaMap: new THREE.Texture( <Image> ),
  22342. *
  22343. * wireframe: <boolean>,
  22344. * wireframeLinewidth: <float>,
  22345. *
  22346. * }
  22347. */
  22348. class MeshToonMaterial extends Material {
  22349. constructor( parameters ) {
  22350. super();
  22351. this.defines = { 'TOON': '' };
  22352. this.type = 'MeshToonMaterial';
  22353. this.color = new Color( 0xffffff );
  22354. this.map = null;
  22355. this.gradientMap = null;
  22356. this.lightMap = null;
  22357. this.lightMapIntensity = 1.0;
  22358. this.aoMap = null;
  22359. this.aoMapIntensity = 1.0;
  22360. this.emissive = new Color( 0x000000 );
  22361. this.emissiveIntensity = 1.0;
  22362. this.emissiveMap = null;
  22363. this.bumpMap = null;
  22364. this.bumpScale = 1;
  22365. this.normalMap = null;
  22366. this.normalMapType = TangentSpaceNormalMap;
  22367. this.normalScale = new Vector2( 1, 1 );
  22368. this.displacementMap = null;
  22369. this.displacementScale = 1;
  22370. this.displacementBias = 0;
  22371. this.alphaMap = null;
  22372. this.wireframe = false;
  22373. this.wireframeLinewidth = 1;
  22374. this.wireframeLinecap = 'round';
  22375. this.wireframeLinejoin = 'round';
  22376. this.setValues( parameters );
  22377. }
  22378. copy( source ) {
  22379. super.copy( source );
  22380. this.color.copy( source.color );
  22381. this.map = source.map;
  22382. this.gradientMap = source.gradientMap;
  22383. this.lightMap = source.lightMap;
  22384. this.lightMapIntensity = source.lightMapIntensity;
  22385. this.aoMap = source.aoMap;
  22386. this.aoMapIntensity = source.aoMapIntensity;
  22387. this.emissive.copy( source.emissive );
  22388. this.emissiveMap = source.emissiveMap;
  22389. this.emissiveIntensity = source.emissiveIntensity;
  22390. this.bumpMap = source.bumpMap;
  22391. this.bumpScale = source.bumpScale;
  22392. this.normalMap = source.normalMap;
  22393. this.normalMapType = source.normalMapType;
  22394. this.normalScale.copy( source.normalScale );
  22395. this.displacementMap = source.displacementMap;
  22396. this.displacementScale = source.displacementScale;
  22397. this.displacementBias = source.displacementBias;
  22398. this.alphaMap = source.alphaMap;
  22399. this.wireframe = source.wireframe;
  22400. this.wireframeLinewidth = source.wireframeLinewidth;
  22401. this.wireframeLinecap = source.wireframeLinecap;
  22402. this.wireframeLinejoin = source.wireframeLinejoin;
  22403. return this;
  22404. }
  22405. }
  22406. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  22407. /**
  22408. * parameters = {
  22409. * opacity: <float>,
  22410. *
  22411. * bumpMap: new THREE.Texture( <Image> ),
  22412. * bumpScale: <float>,
  22413. *
  22414. * normalMap: new THREE.Texture( <Image> ),
  22415. * normalMapType: THREE.TangentSpaceNormalMap,
  22416. * normalScale: <Vector2>,
  22417. *
  22418. * displacementMap: new THREE.Texture( <Image> ),
  22419. * displacementScale: <float>,
  22420. * displacementBias: <float>,
  22421. *
  22422. * wireframe: <boolean>,
  22423. * wireframeLinewidth: <float>
  22424. *
  22425. * flatShading: <bool>
  22426. * }
  22427. */
  22428. class MeshNormalMaterial extends Material {
  22429. constructor( parameters ) {
  22430. super();
  22431. this.type = 'MeshNormalMaterial';
  22432. this.bumpMap = null;
  22433. this.bumpScale = 1;
  22434. this.normalMap = null;
  22435. this.normalMapType = TangentSpaceNormalMap;
  22436. this.normalScale = new Vector2( 1, 1 );
  22437. this.displacementMap = null;
  22438. this.displacementScale = 1;
  22439. this.displacementBias = 0;
  22440. this.wireframe = false;
  22441. this.wireframeLinewidth = 1;
  22442. this.fog = false;
  22443. this.flatShading = false;
  22444. this.setValues( parameters );
  22445. }
  22446. copy( source ) {
  22447. super.copy( source );
  22448. this.bumpMap = source.bumpMap;
  22449. this.bumpScale = source.bumpScale;
  22450. this.normalMap = source.normalMap;
  22451. this.normalMapType = source.normalMapType;
  22452. this.normalScale.copy( source.normalScale );
  22453. this.displacementMap = source.displacementMap;
  22454. this.displacementScale = source.displacementScale;
  22455. this.displacementBias = source.displacementBias;
  22456. this.wireframe = source.wireframe;
  22457. this.wireframeLinewidth = source.wireframeLinewidth;
  22458. this.flatShading = source.flatShading;
  22459. return this;
  22460. }
  22461. }
  22462. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  22463. /**
  22464. * parameters = {
  22465. * color: <hex>,
  22466. * opacity: <float>,
  22467. *
  22468. * map: new THREE.Texture( <Image> ),
  22469. *
  22470. * lightMap: new THREE.Texture( <Image> ),
  22471. * lightMapIntensity: <float>
  22472. *
  22473. * aoMap: new THREE.Texture( <Image> ),
  22474. * aoMapIntensity: <float>
  22475. *
  22476. * emissive: <hex>,
  22477. * emissiveIntensity: <float>
  22478. * emissiveMap: new THREE.Texture( <Image> ),
  22479. *
  22480. * specularMap: new THREE.Texture( <Image> ),
  22481. *
  22482. * alphaMap: new THREE.Texture( <Image> ),
  22483. *
  22484. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  22485. * combine: THREE.Multiply,
  22486. * reflectivity: <float>,
  22487. * refractionRatio: <float>,
  22488. *
  22489. * wireframe: <boolean>,
  22490. * wireframeLinewidth: <float>,
  22491. *
  22492. * }
  22493. */
  22494. class MeshLambertMaterial extends Material {
  22495. constructor( parameters ) {
  22496. super();
  22497. this.type = 'MeshLambertMaterial';
  22498. this.color = new Color( 0xffffff ); // diffuse
  22499. this.map = null;
  22500. this.lightMap = null;
  22501. this.lightMapIntensity = 1.0;
  22502. this.aoMap = null;
  22503. this.aoMapIntensity = 1.0;
  22504. this.emissive = new Color( 0x000000 );
  22505. this.emissiveIntensity = 1.0;
  22506. this.emissiveMap = null;
  22507. this.specularMap = null;
  22508. this.alphaMap = null;
  22509. this.envMap = null;
  22510. this.combine = MultiplyOperation;
  22511. this.reflectivity = 1;
  22512. this.refractionRatio = 0.98;
  22513. this.wireframe = false;
  22514. this.wireframeLinewidth = 1;
  22515. this.wireframeLinecap = 'round';
  22516. this.wireframeLinejoin = 'round';
  22517. this.setValues( parameters );
  22518. }
  22519. copy( source ) {
  22520. super.copy( source );
  22521. this.color.copy( source.color );
  22522. this.map = source.map;
  22523. this.lightMap = source.lightMap;
  22524. this.lightMapIntensity = source.lightMapIntensity;
  22525. this.aoMap = source.aoMap;
  22526. this.aoMapIntensity = source.aoMapIntensity;
  22527. this.emissive.copy( source.emissive );
  22528. this.emissiveMap = source.emissiveMap;
  22529. this.emissiveIntensity = source.emissiveIntensity;
  22530. this.specularMap = source.specularMap;
  22531. this.alphaMap = source.alphaMap;
  22532. this.envMap = source.envMap;
  22533. this.combine = source.combine;
  22534. this.reflectivity = source.reflectivity;
  22535. this.refractionRatio = source.refractionRatio;
  22536. this.wireframe = source.wireframe;
  22537. this.wireframeLinewidth = source.wireframeLinewidth;
  22538. this.wireframeLinecap = source.wireframeLinecap;
  22539. this.wireframeLinejoin = source.wireframeLinejoin;
  22540. return this;
  22541. }
  22542. }
  22543. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  22544. /**
  22545. * parameters = {
  22546. * color: <hex>,
  22547. * opacity: <float>,
  22548. *
  22549. * matcap: new THREE.Texture( <Image> ),
  22550. *
  22551. * map: new THREE.Texture( <Image> ),
  22552. *
  22553. * bumpMap: new THREE.Texture( <Image> ),
  22554. * bumpScale: <float>,
  22555. *
  22556. * normalMap: new THREE.Texture( <Image> ),
  22557. * normalMapType: THREE.TangentSpaceNormalMap,
  22558. * normalScale: <Vector2>,
  22559. *
  22560. * displacementMap: new THREE.Texture( <Image> ),
  22561. * displacementScale: <float>,
  22562. * displacementBias: <float>,
  22563. *
  22564. * alphaMap: new THREE.Texture( <Image> ),
  22565. *
  22566. * flatShading: <bool>
  22567. * }
  22568. */
  22569. class MeshMatcapMaterial extends Material {
  22570. constructor( parameters ) {
  22571. super();
  22572. this.defines = { 'MATCAP': '' };
  22573. this.type = 'MeshMatcapMaterial';
  22574. this.color = new Color( 0xffffff ); // diffuse
  22575. this.matcap = null;
  22576. this.map = null;
  22577. this.bumpMap = null;
  22578. this.bumpScale = 1;
  22579. this.normalMap = null;
  22580. this.normalMapType = TangentSpaceNormalMap;
  22581. this.normalScale = new Vector2( 1, 1 );
  22582. this.displacementMap = null;
  22583. this.displacementScale = 1;
  22584. this.displacementBias = 0;
  22585. this.alphaMap = null;
  22586. this.flatShading = false;
  22587. this.setValues( parameters );
  22588. }
  22589. copy( source ) {
  22590. super.copy( source );
  22591. this.defines = { 'MATCAP': '' };
  22592. this.color.copy( source.color );
  22593. this.matcap = source.matcap;
  22594. this.map = source.map;
  22595. this.bumpMap = source.bumpMap;
  22596. this.bumpScale = source.bumpScale;
  22597. this.normalMap = source.normalMap;
  22598. this.normalMapType = source.normalMapType;
  22599. this.normalScale.copy( source.normalScale );
  22600. this.displacementMap = source.displacementMap;
  22601. this.displacementScale = source.displacementScale;
  22602. this.displacementBias = source.displacementBias;
  22603. this.alphaMap = source.alphaMap;
  22604. this.flatShading = source.flatShading;
  22605. return this;
  22606. }
  22607. }
  22608. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  22609. /**
  22610. * parameters = {
  22611. * color: <hex>,
  22612. * opacity: <float>,
  22613. *
  22614. * linewidth: <float>,
  22615. *
  22616. * scale: <float>,
  22617. * dashSize: <float>,
  22618. * gapSize: <float>
  22619. * }
  22620. */
  22621. class LineDashedMaterial extends LineBasicMaterial {
  22622. constructor( parameters ) {
  22623. super();
  22624. this.type = 'LineDashedMaterial';
  22625. this.scale = 1;
  22626. this.dashSize = 3;
  22627. this.gapSize = 1;
  22628. this.setValues( parameters );
  22629. }
  22630. copy( source ) {
  22631. super.copy( source );
  22632. this.scale = source.scale;
  22633. this.dashSize = source.dashSize;
  22634. this.gapSize = source.gapSize;
  22635. return this;
  22636. }
  22637. }
  22638. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  22639. var Materials = /*#__PURE__*/Object.freeze({
  22640. __proto__: null,
  22641. ShadowMaterial: ShadowMaterial,
  22642. SpriteMaterial: SpriteMaterial,
  22643. RawShaderMaterial: RawShaderMaterial,
  22644. ShaderMaterial: ShaderMaterial,
  22645. PointsMaterial: PointsMaterial,
  22646. MeshPhysicalMaterial: MeshPhysicalMaterial,
  22647. MeshStandardMaterial: MeshStandardMaterial,
  22648. MeshPhongMaterial: MeshPhongMaterial,
  22649. MeshToonMaterial: MeshToonMaterial,
  22650. MeshNormalMaterial: MeshNormalMaterial,
  22651. MeshLambertMaterial: MeshLambertMaterial,
  22652. MeshDepthMaterial: MeshDepthMaterial,
  22653. MeshDistanceMaterial: MeshDistanceMaterial,
  22654. MeshBasicMaterial: MeshBasicMaterial,
  22655. MeshMatcapMaterial: MeshMatcapMaterial,
  22656. LineDashedMaterial: LineDashedMaterial,
  22657. LineBasicMaterial: LineBasicMaterial,
  22658. Material: Material
  22659. });
  22660. const AnimationUtils = {
  22661. // same as Array.prototype.slice, but also works on typed arrays
  22662. arraySlice: function ( array, from, to ) {
  22663. if ( AnimationUtils.isTypedArray( array ) ) {
  22664. // in ios9 array.subarray(from, undefined) will return empty array
  22665. // but array.subarray(from) or array.subarray(from, len) is correct
  22666. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  22667. }
  22668. return array.slice( from, to );
  22669. },
  22670. // converts an array to a specific type
  22671. convertArray: function ( array, type, forceClone ) {
  22672. if ( ! array || // let 'undefined' and 'null' pass
  22673. ! forceClone && array.constructor === type ) return array;
  22674. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  22675. return new type( array ); // create typed array
  22676. }
  22677. return Array.prototype.slice.call( array ); // create Array
  22678. },
  22679. isTypedArray: function ( object ) {
  22680. return ArrayBuffer.isView( object ) &&
  22681. ! ( object instanceof DataView );
  22682. },
  22683. // returns an array by which times and values can be sorted
  22684. getKeyframeOrder: function ( times ) {
  22685. function compareTime( i, j ) {
  22686. return times[ i ] - times[ j ];
  22687. }
  22688. const n = times.length;
  22689. const result = new Array( n );
  22690. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  22691. result.sort( compareTime );
  22692. return result;
  22693. },
  22694. // uses the array previously returned by 'getKeyframeOrder' to sort data
  22695. sortedArray: function ( values, stride, order ) {
  22696. const nValues = values.length;
  22697. const result = new values.constructor( nValues );
  22698. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  22699. const srcOffset = order[ i ] * stride;
  22700. for ( let j = 0; j !== stride; ++ j ) {
  22701. result[ dstOffset ++ ] = values[ srcOffset + j ];
  22702. }
  22703. }
  22704. return result;
  22705. },
  22706. // function for parsing AOS keyframe formats
  22707. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  22708. let i = 1, key = jsonKeys[ 0 ];
  22709. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  22710. key = jsonKeys[ i ++ ];
  22711. }
  22712. if ( key === undefined ) return; // no data
  22713. let value = key[ valuePropertyName ];
  22714. if ( value === undefined ) return; // no data
  22715. if ( Array.isArray( value ) ) {
  22716. do {
  22717. value = key[ valuePropertyName ];
  22718. if ( value !== undefined ) {
  22719. times.push( key.time );
  22720. values.push.apply( values, value ); // push all elements
  22721. }
  22722. key = jsonKeys[ i ++ ];
  22723. } while ( key !== undefined );
  22724. } else if ( value.toArray !== undefined ) {
  22725. // ...assume THREE.Math-ish
  22726. do {
  22727. value = key[ valuePropertyName ];
  22728. if ( value !== undefined ) {
  22729. times.push( key.time );
  22730. value.toArray( values, values.length );
  22731. }
  22732. key = jsonKeys[ i ++ ];
  22733. } while ( key !== undefined );
  22734. } else {
  22735. // otherwise push as-is
  22736. do {
  22737. value = key[ valuePropertyName ];
  22738. if ( value !== undefined ) {
  22739. times.push( key.time );
  22740. values.push( value );
  22741. }
  22742. key = jsonKeys[ i ++ ];
  22743. } while ( key !== undefined );
  22744. }
  22745. },
  22746. subclip: function ( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  22747. const clip = sourceClip.clone();
  22748. clip.name = name;
  22749. const tracks = [];
  22750. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22751. const track = clip.tracks[ i ];
  22752. const valueSize = track.getValueSize();
  22753. const times = [];
  22754. const values = [];
  22755. for ( let j = 0; j < track.times.length; ++ j ) {
  22756. const frame = track.times[ j ] * fps;
  22757. if ( frame < startFrame || frame >= endFrame ) continue;
  22758. times.push( track.times[ j ] );
  22759. for ( let k = 0; k < valueSize; ++ k ) {
  22760. values.push( track.values[ j * valueSize + k ] );
  22761. }
  22762. }
  22763. if ( times.length === 0 ) continue;
  22764. track.times = AnimationUtils.convertArray( times, track.times.constructor );
  22765. track.values = AnimationUtils.convertArray( values, track.values.constructor );
  22766. tracks.push( track );
  22767. }
  22768. clip.tracks = tracks;
  22769. // find minimum .times value across all tracks in the trimmed clip
  22770. let minStartTime = Infinity;
  22771. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22772. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  22773. minStartTime = clip.tracks[ i ].times[ 0 ];
  22774. }
  22775. }
  22776. // shift all tracks such that clip begins at t=0
  22777. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22778. clip.tracks[ i ].shift( - 1 * minStartTime );
  22779. }
  22780. clip.resetDuration();
  22781. return clip;
  22782. },
  22783. makeClipAdditive: function ( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  22784. if ( fps <= 0 ) fps = 30;
  22785. const numTracks = referenceClip.tracks.length;
  22786. const referenceTime = referenceFrame / fps;
  22787. // Make each track's values relative to the values at the reference frame
  22788. for ( let i = 0; i < numTracks; ++ i ) {
  22789. const referenceTrack = referenceClip.tracks[ i ];
  22790. const referenceTrackType = referenceTrack.ValueTypeName;
  22791. // Skip this track if it's non-numeric
  22792. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  22793. // Find the track in the target clip whose name and type matches the reference track
  22794. const targetTrack = targetClip.tracks.find( function ( track ) {
  22795. return track.name === referenceTrack.name
  22796. && track.ValueTypeName === referenceTrackType;
  22797. } );
  22798. if ( targetTrack === undefined ) continue;
  22799. let referenceOffset = 0;
  22800. const referenceValueSize = referenceTrack.getValueSize();
  22801. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  22802. referenceOffset = referenceValueSize / 3;
  22803. }
  22804. let targetOffset = 0;
  22805. const targetValueSize = targetTrack.getValueSize();
  22806. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  22807. targetOffset = targetValueSize / 3;
  22808. }
  22809. const lastIndex = referenceTrack.times.length - 1;
  22810. let referenceValue;
  22811. // Find the value to subtract out of the track
  22812. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  22813. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  22814. const startIndex = referenceOffset;
  22815. const endIndex = referenceValueSize - referenceOffset;
  22816. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex );
  22817. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  22818. // Reference frame is after the last keyframe, so just use the last keyframe
  22819. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  22820. const endIndex = startIndex + referenceValueSize - referenceOffset;
  22821. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex );
  22822. } else {
  22823. // Interpolate to the reference value
  22824. const interpolant = referenceTrack.createInterpolant();
  22825. const startIndex = referenceOffset;
  22826. const endIndex = referenceValueSize - referenceOffset;
  22827. interpolant.evaluate( referenceTime );
  22828. referenceValue = AnimationUtils.arraySlice( interpolant.resultBuffer, startIndex, endIndex );
  22829. }
  22830. // Conjugate the quaternion
  22831. if ( referenceTrackType === 'quaternion' ) {
  22832. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  22833. referenceQuat.toArray( referenceValue );
  22834. }
  22835. // Subtract the reference value from all of the track values
  22836. const numTimes = targetTrack.times.length;
  22837. for ( let j = 0; j < numTimes; ++ j ) {
  22838. const valueStart = j * targetValueSize + targetOffset;
  22839. if ( referenceTrackType === 'quaternion' ) {
  22840. // Multiply the conjugate for quaternion track types
  22841. Quaternion.multiplyQuaternionsFlat(
  22842. targetTrack.values,
  22843. valueStart,
  22844. referenceValue,
  22845. 0,
  22846. targetTrack.values,
  22847. valueStart
  22848. );
  22849. } else {
  22850. const valueEnd = targetValueSize - targetOffset * 2;
  22851. // Subtract each value for all other numeric track types
  22852. for ( let k = 0; k < valueEnd; ++ k ) {
  22853. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  22854. }
  22855. }
  22856. }
  22857. }
  22858. targetClip.blendMode = AdditiveAnimationBlendMode;
  22859. return targetClip;
  22860. }
  22861. };
  22862. /**
  22863. * Abstract base class of interpolants over parametric samples.
  22864. *
  22865. * The parameter domain is one dimensional, typically the time or a path
  22866. * along a curve defined by the data.
  22867. *
  22868. * The sample values can have any dimensionality and derived classes may
  22869. * apply special interpretations to the data.
  22870. *
  22871. * This class provides the interval seek in a Template Method, deferring
  22872. * the actual interpolation to derived classes.
  22873. *
  22874. * Time complexity is O(1) for linear access crossing at most two points
  22875. * and O(log N) for random access, where N is the number of positions.
  22876. *
  22877. * References:
  22878. *
  22879. * http://www.oodesign.com/template-method-pattern.html
  22880. *
  22881. */
  22882. class Interpolant {
  22883. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22884. this.parameterPositions = parameterPositions;
  22885. this._cachedIndex = 0;
  22886. this.resultBuffer = resultBuffer !== undefined ?
  22887. resultBuffer : new sampleValues.constructor( sampleSize );
  22888. this.sampleValues = sampleValues;
  22889. this.valueSize = sampleSize;
  22890. this.settings = null;
  22891. this.DefaultSettings_ = {};
  22892. }
  22893. evaluate( t ) {
  22894. const pp = this.parameterPositions;
  22895. let i1 = this._cachedIndex,
  22896. t1 = pp[ i1 ],
  22897. t0 = pp[ i1 - 1 ];
  22898. validate_interval: {
  22899. seek: {
  22900. let right;
  22901. linear_scan: {
  22902. //- See http://jsperf.com/comparison-to-undefined/3
  22903. //- slower code:
  22904. //-
  22905. //- if ( t >= t1 || t1 === undefined ) {
  22906. forward_scan: if ( ! ( t < t1 ) ) {
  22907. for ( let giveUpAt = i1 + 2; ; ) {
  22908. if ( t1 === undefined ) {
  22909. if ( t < t0 ) break forward_scan;
  22910. // after end
  22911. i1 = pp.length;
  22912. this._cachedIndex = i1;
  22913. return this.afterEnd_( i1 - 1, t, t0 );
  22914. }
  22915. if ( i1 === giveUpAt ) break; // this loop
  22916. t0 = t1;
  22917. t1 = pp[ ++ i1 ];
  22918. if ( t < t1 ) {
  22919. // we have arrived at the sought interval
  22920. break seek;
  22921. }
  22922. }
  22923. // prepare binary search on the right side of the index
  22924. right = pp.length;
  22925. break linear_scan;
  22926. }
  22927. //- slower code:
  22928. //- if ( t < t0 || t0 === undefined ) {
  22929. if ( ! ( t >= t0 ) ) {
  22930. // looping?
  22931. const t1global = pp[ 1 ];
  22932. if ( t < t1global ) {
  22933. i1 = 2; // + 1, using the scan for the details
  22934. t0 = t1global;
  22935. }
  22936. // linear reverse scan
  22937. for ( let giveUpAt = i1 - 2; ; ) {
  22938. if ( t0 === undefined ) {
  22939. // before start
  22940. this._cachedIndex = 0;
  22941. return this.beforeStart_( 0, t, t1 );
  22942. }
  22943. if ( i1 === giveUpAt ) break; // this loop
  22944. t1 = t0;
  22945. t0 = pp[ -- i1 - 1 ];
  22946. if ( t >= t0 ) {
  22947. // we have arrived at the sought interval
  22948. break seek;
  22949. }
  22950. }
  22951. // prepare binary search on the left side of the index
  22952. right = i1;
  22953. i1 = 0;
  22954. break linear_scan;
  22955. }
  22956. // the interval is valid
  22957. break validate_interval;
  22958. } // linear scan
  22959. // binary search
  22960. while ( i1 < right ) {
  22961. const mid = ( i1 + right ) >>> 1;
  22962. if ( t < pp[ mid ] ) {
  22963. right = mid;
  22964. } else {
  22965. i1 = mid + 1;
  22966. }
  22967. }
  22968. t1 = pp[ i1 ];
  22969. t0 = pp[ i1 - 1 ];
  22970. // check boundary cases, again
  22971. if ( t0 === undefined ) {
  22972. this._cachedIndex = 0;
  22973. return this.beforeStart_( 0, t, t1 );
  22974. }
  22975. if ( t1 === undefined ) {
  22976. i1 = pp.length;
  22977. this._cachedIndex = i1;
  22978. return this.afterEnd_( i1 - 1, t0, t );
  22979. }
  22980. } // seek
  22981. this._cachedIndex = i1;
  22982. this.intervalChanged_( i1, t0, t1 );
  22983. } // validate_interval
  22984. return this.interpolate_( i1, t0, t, t1 );
  22985. }
  22986. getSettings_() {
  22987. return this.settings || this.DefaultSettings_;
  22988. }
  22989. copySampleValue_( index ) {
  22990. // copies a sample value to the result buffer
  22991. const result = this.resultBuffer,
  22992. values = this.sampleValues,
  22993. stride = this.valueSize,
  22994. offset = index * stride;
  22995. for ( let i = 0; i !== stride; ++ i ) {
  22996. result[ i ] = values[ offset + i ];
  22997. }
  22998. return result;
  22999. }
  23000. // Template methods for derived classes:
  23001. interpolate_( /* i1, t0, t, t1 */ ) {
  23002. throw new Error( 'call to abstract method' );
  23003. // implementations shall return this.resultBuffer
  23004. }
  23005. intervalChanged_( /* i1, t0, t1 */ ) {
  23006. // empty
  23007. }
  23008. }
  23009. // ALIAS DEFINITIONS
  23010. Interpolant.prototype.beforeStart_ = Interpolant.prototype.copySampleValue_;
  23011. Interpolant.prototype.afterEnd_ = Interpolant.prototype.copySampleValue_;
  23012. /**
  23013. * Fast and simple cubic spline interpolant.
  23014. *
  23015. * It was derived from a Hermitian construction setting the first derivative
  23016. * at each sample position to the linear slope between neighboring positions
  23017. * over their parameter interval.
  23018. */
  23019. class CubicInterpolant extends Interpolant {
  23020. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23021. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23022. this._weightPrev = - 0;
  23023. this._offsetPrev = - 0;
  23024. this._weightNext = - 0;
  23025. this._offsetNext = - 0;
  23026. this.DefaultSettings_ = {
  23027. endingStart: ZeroCurvatureEnding,
  23028. endingEnd: ZeroCurvatureEnding
  23029. };
  23030. }
  23031. intervalChanged_( i1, t0, t1 ) {
  23032. const pp = this.parameterPositions;
  23033. let iPrev = i1 - 2,
  23034. iNext = i1 + 1,
  23035. tPrev = pp[ iPrev ],
  23036. tNext = pp[ iNext ];
  23037. if ( tPrev === undefined ) {
  23038. switch ( this.getSettings_().endingStart ) {
  23039. case ZeroSlopeEnding:
  23040. // f'(t0) = 0
  23041. iPrev = i1;
  23042. tPrev = 2 * t0 - t1;
  23043. break;
  23044. case WrapAroundEnding:
  23045. // use the other end of the curve
  23046. iPrev = pp.length - 2;
  23047. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  23048. break;
  23049. default: // ZeroCurvatureEnding
  23050. // f''(t0) = 0 a.k.a. Natural Spline
  23051. iPrev = i1;
  23052. tPrev = t1;
  23053. }
  23054. }
  23055. if ( tNext === undefined ) {
  23056. switch ( this.getSettings_().endingEnd ) {
  23057. case ZeroSlopeEnding:
  23058. // f'(tN) = 0
  23059. iNext = i1;
  23060. tNext = 2 * t1 - t0;
  23061. break;
  23062. case WrapAroundEnding:
  23063. // use the other end of the curve
  23064. iNext = 1;
  23065. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  23066. break;
  23067. default: // ZeroCurvatureEnding
  23068. // f''(tN) = 0, a.k.a. Natural Spline
  23069. iNext = i1 - 1;
  23070. tNext = t0;
  23071. }
  23072. }
  23073. const halfDt = ( t1 - t0 ) * 0.5,
  23074. stride = this.valueSize;
  23075. this._weightPrev = halfDt / ( t0 - tPrev );
  23076. this._weightNext = halfDt / ( tNext - t1 );
  23077. this._offsetPrev = iPrev * stride;
  23078. this._offsetNext = iNext * stride;
  23079. }
  23080. interpolate_( i1, t0, t, t1 ) {
  23081. const result = this.resultBuffer,
  23082. values = this.sampleValues,
  23083. stride = this.valueSize,
  23084. o1 = i1 * stride, o0 = o1 - stride,
  23085. oP = this._offsetPrev, oN = this._offsetNext,
  23086. wP = this._weightPrev, wN = this._weightNext,
  23087. p = ( t - t0 ) / ( t1 - t0 ),
  23088. pp = p * p,
  23089. ppp = pp * p;
  23090. // evaluate polynomials
  23091. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  23092. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  23093. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  23094. const sN = wN * ppp - wN * pp;
  23095. // combine data linearly
  23096. for ( let i = 0; i !== stride; ++ i ) {
  23097. result[ i ] =
  23098. sP * values[ oP + i ] +
  23099. s0 * values[ o0 + i ] +
  23100. s1 * values[ o1 + i ] +
  23101. sN * values[ oN + i ];
  23102. }
  23103. return result;
  23104. }
  23105. }
  23106. class LinearInterpolant extends Interpolant {
  23107. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23108. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23109. }
  23110. interpolate_( i1, t0, t, t1 ) {
  23111. const result = this.resultBuffer,
  23112. values = this.sampleValues,
  23113. stride = this.valueSize,
  23114. offset1 = i1 * stride,
  23115. offset0 = offset1 - stride,
  23116. weight1 = ( t - t0 ) / ( t1 - t0 ),
  23117. weight0 = 1 - weight1;
  23118. for ( let i = 0; i !== stride; ++ i ) {
  23119. result[ i ] =
  23120. values[ offset0 + i ] * weight0 +
  23121. values[ offset1 + i ] * weight1;
  23122. }
  23123. return result;
  23124. }
  23125. }
  23126. /**
  23127. *
  23128. * Interpolant that evaluates to the sample value at the position preceeding
  23129. * the parameter.
  23130. */
  23131. class DiscreteInterpolant extends Interpolant {
  23132. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23133. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23134. }
  23135. interpolate_( i1 /*, t0, t, t1 */ ) {
  23136. return this.copySampleValue_( i1 - 1 );
  23137. }
  23138. }
  23139. class KeyframeTrack {
  23140. constructor( name, times, values, interpolation ) {
  23141. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  23142. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  23143. this.name = name;
  23144. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  23145. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  23146. this.setInterpolation( interpolation || this.DefaultInterpolation );
  23147. }
  23148. // Serialization (in static context, because of constructor invocation
  23149. // and automatic invocation of .toJSON):
  23150. static toJSON( track ) {
  23151. const trackType = track.constructor;
  23152. let json;
  23153. // derived classes can define a static toJSON method
  23154. if ( trackType.toJSON !== this.toJSON ) {
  23155. json = trackType.toJSON( track );
  23156. } else {
  23157. // by default, we assume the data can be serialized as-is
  23158. json = {
  23159. 'name': track.name,
  23160. 'times': AnimationUtils.convertArray( track.times, Array ),
  23161. 'values': AnimationUtils.convertArray( track.values, Array )
  23162. };
  23163. const interpolation = track.getInterpolation();
  23164. if ( interpolation !== track.DefaultInterpolation ) {
  23165. json.interpolation = interpolation;
  23166. }
  23167. }
  23168. json.type = track.ValueTypeName; // mandatory
  23169. return json;
  23170. }
  23171. InterpolantFactoryMethodDiscrete( result ) {
  23172. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  23173. }
  23174. InterpolantFactoryMethodLinear( result ) {
  23175. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23176. }
  23177. InterpolantFactoryMethodSmooth( result ) {
  23178. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  23179. }
  23180. setInterpolation( interpolation ) {
  23181. let factoryMethod;
  23182. switch ( interpolation ) {
  23183. case InterpolateDiscrete:
  23184. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  23185. break;
  23186. case InterpolateLinear:
  23187. factoryMethod = this.InterpolantFactoryMethodLinear;
  23188. break;
  23189. case InterpolateSmooth:
  23190. factoryMethod = this.InterpolantFactoryMethodSmooth;
  23191. break;
  23192. }
  23193. if ( factoryMethod === undefined ) {
  23194. const message = 'unsupported interpolation for ' +
  23195. this.ValueTypeName + ' keyframe track named ' + this.name;
  23196. if ( this.createInterpolant === undefined ) {
  23197. // fall back to default, unless the default itself is messed up
  23198. if ( interpolation !== this.DefaultInterpolation ) {
  23199. this.setInterpolation( this.DefaultInterpolation );
  23200. } else {
  23201. throw new Error( message ); // fatal, in this case
  23202. }
  23203. }
  23204. console.warn( 'THREE.KeyframeTrack:', message );
  23205. return this;
  23206. }
  23207. this.createInterpolant = factoryMethod;
  23208. return this;
  23209. }
  23210. getInterpolation() {
  23211. switch ( this.createInterpolant ) {
  23212. case this.InterpolantFactoryMethodDiscrete:
  23213. return InterpolateDiscrete;
  23214. case this.InterpolantFactoryMethodLinear:
  23215. return InterpolateLinear;
  23216. case this.InterpolantFactoryMethodSmooth:
  23217. return InterpolateSmooth;
  23218. }
  23219. }
  23220. getValueSize() {
  23221. return this.values.length / this.times.length;
  23222. }
  23223. // move all keyframes either forwards or backwards in time
  23224. shift( timeOffset ) {
  23225. if ( timeOffset !== 0.0 ) {
  23226. const times = this.times;
  23227. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  23228. times[ i ] += timeOffset;
  23229. }
  23230. }
  23231. return this;
  23232. }
  23233. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  23234. scale( timeScale ) {
  23235. if ( timeScale !== 1.0 ) {
  23236. const times = this.times;
  23237. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  23238. times[ i ] *= timeScale;
  23239. }
  23240. }
  23241. return this;
  23242. }
  23243. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  23244. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  23245. trim( startTime, endTime ) {
  23246. const times = this.times,
  23247. nKeys = times.length;
  23248. let from = 0,
  23249. to = nKeys - 1;
  23250. while ( from !== nKeys && times[ from ] < startTime ) {
  23251. ++ from;
  23252. }
  23253. while ( to !== - 1 && times[ to ] > endTime ) {
  23254. -- to;
  23255. }
  23256. ++ to; // inclusive -> exclusive bound
  23257. if ( from !== 0 || to !== nKeys ) {
  23258. // empty tracks are forbidden, so keep at least one keyframe
  23259. if ( from >= to ) {
  23260. to = Math.max( to, 1 );
  23261. from = to - 1;
  23262. }
  23263. const stride = this.getValueSize();
  23264. this.times = AnimationUtils.arraySlice( times, from, to );
  23265. this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride );
  23266. }
  23267. return this;
  23268. }
  23269. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  23270. validate() {
  23271. let valid = true;
  23272. const valueSize = this.getValueSize();
  23273. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  23274. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  23275. valid = false;
  23276. }
  23277. const times = this.times,
  23278. values = this.values,
  23279. nKeys = times.length;
  23280. if ( nKeys === 0 ) {
  23281. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  23282. valid = false;
  23283. }
  23284. let prevTime = null;
  23285. for ( let i = 0; i !== nKeys; i ++ ) {
  23286. const currTime = times[ i ];
  23287. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  23288. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  23289. valid = false;
  23290. break;
  23291. }
  23292. if ( prevTime !== null && prevTime > currTime ) {
  23293. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  23294. valid = false;
  23295. break;
  23296. }
  23297. prevTime = currTime;
  23298. }
  23299. if ( values !== undefined ) {
  23300. if ( AnimationUtils.isTypedArray( values ) ) {
  23301. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  23302. const value = values[ i ];
  23303. if ( isNaN( value ) ) {
  23304. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  23305. valid = false;
  23306. break;
  23307. }
  23308. }
  23309. }
  23310. }
  23311. return valid;
  23312. }
  23313. // removes equivalent sequential keys as common in morph target sequences
  23314. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  23315. optimize() {
  23316. // times or values may be shared with other tracks, so overwriting is unsafe
  23317. const times = AnimationUtils.arraySlice( this.times ),
  23318. values = AnimationUtils.arraySlice( this.values ),
  23319. stride = this.getValueSize(),
  23320. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  23321. lastIndex = times.length - 1;
  23322. let writeIndex = 1;
  23323. for ( let i = 1; i < lastIndex; ++ i ) {
  23324. let keep = false;
  23325. const time = times[ i ];
  23326. const timeNext = times[ i + 1 ];
  23327. // remove adjacent keyframes scheduled at the same time
  23328. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  23329. if ( ! smoothInterpolation ) {
  23330. // remove unnecessary keyframes same as their neighbors
  23331. const offset = i * stride,
  23332. offsetP = offset - stride,
  23333. offsetN = offset + stride;
  23334. for ( let j = 0; j !== stride; ++ j ) {
  23335. const value = values[ offset + j ];
  23336. if ( value !== values[ offsetP + j ] ||
  23337. value !== values[ offsetN + j ] ) {
  23338. keep = true;
  23339. break;
  23340. }
  23341. }
  23342. } else {
  23343. keep = true;
  23344. }
  23345. }
  23346. // in-place compaction
  23347. if ( keep ) {
  23348. if ( i !== writeIndex ) {
  23349. times[ writeIndex ] = times[ i ];
  23350. const readOffset = i * stride,
  23351. writeOffset = writeIndex * stride;
  23352. for ( let j = 0; j !== stride; ++ j ) {
  23353. values[ writeOffset + j ] = values[ readOffset + j ];
  23354. }
  23355. }
  23356. ++ writeIndex;
  23357. }
  23358. }
  23359. // flush last keyframe (compaction looks ahead)
  23360. if ( lastIndex > 0 ) {
  23361. times[ writeIndex ] = times[ lastIndex ];
  23362. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  23363. values[ writeOffset + j ] = values[ readOffset + j ];
  23364. }
  23365. ++ writeIndex;
  23366. }
  23367. if ( writeIndex !== times.length ) {
  23368. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  23369. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  23370. } else {
  23371. this.times = times;
  23372. this.values = values;
  23373. }
  23374. return this;
  23375. }
  23376. clone() {
  23377. const times = AnimationUtils.arraySlice( this.times, 0 );
  23378. const values = AnimationUtils.arraySlice( this.values, 0 );
  23379. const TypedKeyframeTrack = this.constructor;
  23380. const track = new TypedKeyframeTrack( this.name, times, values );
  23381. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  23382. track.createInterpolant = this.createInterpolant;
  23383. return track;
  23384. }
  23385. }
  23386. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  23387. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  23388. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23389. /**
  23390. * A Track of Boolean keyframe values.
  23391. */
  23392. class BooleanKeyframeTrack extends KeyframeTrack {}
  23393. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  23394. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  23395. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23396. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23397. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23398. /**
  23399. * A Track of keyframe values that represent color.
  23400. */
  23401. class ColorKeyframeTrack extends KeyframeTrack {}
  23402. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  23403. /**
  23404. * A Track of numeric keyframe values.
  23405. */
  23406. class NumberKeyframeTrack extends KeyframeTrack {}
  23407. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  23408. /**
  23409. * Spherical linear unit quaternion interpolant.
  23410. */
  23411. class QuaternionLinearInterpolant extends Interpolant {
  23412. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23413. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23414. }
  23415. interpolate_( i1, t0, t, t1 ) {
  23416. const result = this.resultBuffer,
  23417. values = this.sampleValues,
  23418. stride = this.valueSize,
  23419. alpha = ( t - t0 ) / ( t1 - t0 );
  23420. let offset = i1 * stride;
  23421. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  23422. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  23423. }
  23424. return result;
  23425. }
  23426. }
  23427. /**
  23428. * A Track of quaternion keyframe values.
  23429. */
  23430. class QuaternionKeyframeTrack extends KeyframeTrack {
  23431. InterpolantFactoryMethodLinear( result ) {
  23432. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23433. }
  23434. }
  23435. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  23436. // ValueBufferType is inherited
  23437. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23438. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23439. /**
  23440. * A Track that interpolates Strings
  23441. */
  23442. class StringKeyframeTrack extends KeyframeTrack {}
  23443. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  23444. StringKeyframeTrack.prototype.ValueBufferType = Array;
  23445. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23446. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23447. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23448. /**
  23449. * A Track of vectored keyframe values.
  23450. */
  23451. class VectorKeyframeTrack extends KeyframeTrack {}
  23452. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  23453. class AnimationClip {
  23454. constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  23455. this.name = name;
  23456. this.tracks = tracks;
  23457. this.duration = duration;
  23458. this.blendMode = blendMode;
  23459. this.uuid = generateUUID();
  23460. // this means it should figure out its duration by scanning the tracks
  23461. if ( this.duration < 0 ) {
  23462. this.resetDuration();
  23463. }
  23464. }
  23465. static parse( json ) {
  23466. const tracks = [],
  23467. jsonTracks = json.tracks,
  23468. frameTime = 1.0 / ( json.fps || 1.0 );
  23469. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  23470. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  23471. }
  23472. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  23473. clip.uuid = json.uuid;
  23474. return clip;
  23475. }
  23476. static toJSON( clip ) {
  23477. const tracks = [],
  23478. clipTracks = clip.tracks;
  23479. const json = {
  23480. 'name': clip.name,
  23481. 'duration': clip.duration,
  23482. 'tracks': tracks,
  23483. 'uuid': clip.uuid,
  23484. 'blendMode': clip.blendMode
  23485. };
  23486. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  23487. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  23488. }
  23489. return json;
  23490. }
  23491. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  23492. const numMorphTargets = morphTargetSequence.length;
  23493. const tracks = [];
  23494. for ( let i = 0; i < numMorphTargets; i ++ ) {
  23495. let times = [];
  23496. let values = [];
  23497. times.push(
  23498. ( i + numMorphTargets - 1 ) % numMorphTargets,
  23499. i,
  23500. ( i + 1 ) % numMorphTargets );
  23501. values.push( 0, 1, 0 );
  23502. const order = AnimationUtils.getKeyframeOrder( times );
  23503. times = AnimationUtils.sortedArray( times, 1, order );
  23504. values = AnimationUtils.sortedArray( values, 1, order );
  23505. // if there is a key at the first frame, duplicate it as the
  23506. // last frame as well for perfect loop.
  23507. if ( ! noLoop && times[ 0 ] === 0 ) {
  23508. times.push( numMorphTargets );
  23509. values.push( values[ 0 ] );
  23510. }
  23511. tracks.push(
  23512. new NumberKeyframeTrack(
  23513. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  23514. times, values
  23515. ).scale( 1.0 / fps ) );
  23516. }
  23517. return new this( name, - 1, tracks );
  23518. }
  23519. static findByName( objectOrClipArray, name ) {
  23520. let clipArray = objectOrClipArray;
  23521. if ( ! Array.isArray( objectOrClipArray ) ) {
  23522. const o = objectOrClipArray;
  23523. clipArray = o.geometry && o.geometry.animations || o.animations;
  23524. }
  23525. for ( let i = 0; i < clipArray.length; i ++ ) {
  23526. if ( clipArray[ i ].name === name ) {
  23527. return clipArray[ i ];
  23528. }
  23529. }
  23530. return null;
  23531. }
  23532. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  23533. const animationToMorphTargets = {};
  23534. // tested with https://regex101.com/ on trick sequences
  23535. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  23536. const pattern = /^([\w-]*?)([\d]+)$/;
  23537. // sort morph target names into animation groups based
  23538. // patterns like Walk_001, Walk_002, Run_001, Run_002
  23539. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  23540. const morphTarget = morphTargets[ i ];
  23541. const parts = morphTarget.name.match( pattern );
  23542. if ( parts && parts.length > 1 ) {
  23543. const name = parts[ 1 ];
  23544. let animationMorphTargets = animationToMorphTargets[ name ];
  23545. if ( ! animationMorphTargets ) {
  23546. animationToMorphTargets[ name ] = animationMorphTargets = [];
  23547. }
  23548. animationMorphTargets.push( morphTarget );
  23549. }
  23550. }
  23551. const clips = [];
  23552. for ( const name in animationToMorphTargets ) {
  23553. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  23554. }
  23555. return clips;
  23556. }
  23557. // parse the animation.hierarchy format
  23558. static parseAnimation( animation, bones ) {
  23559. if ( ! animation ) {
  23560. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  23561. return null;
  23562. }
  23563. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  23564. // only return track if there are actually keys.
  23565. if ( animationKeys.length !== 0 ) {
  23566. const times = [];
  23567. const values = [];
  23568. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  23569. // empty keys are filtered out, so check again
  23570. if ( times.length !== 0 ) {
  23571. destTracks.push( new trackType( trackName, times, values ) );
  23572. }
  23573. }
  23574. };
  23575. const tracks = [];
  23576. const clipName = animation.name || 'default';
  23577. const fps = animation.fps || 30;
  23578. const blendMode = animation.blendMode;
  23579. // automatic length determination in AnimationClip.
  23580. let duration = animation.length || - 1;
  23581. const hierarchyTracks = animation.hierarchy || [];
  23582. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  23583. const animationKeys = hierarchyTracks[ h ].keys;
  23584. // skip empty tracks
  23585. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  23586. // process morph targets
  23587. if ( animationKeys[ 0 ].morphTargets ) {
  23588. // figure out all morph targets used in this track
  23589. const morphTargetNames = {};
  23590. let k;
  23591. for ( k = 0; k < animationKeys.length; k ++ ) {
  23592. if ( animationKeys[ k ].morphTargets ) {
  23593. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  23594. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  23595. }
  23596. }
  23597. }
  23598. // create a track for each morph target with all zero
  23599. // morphTargetInfluences except for the keys in which
  23600. // the morphTarget is named.
  23601. for ( const morphTargetName in morphTargetNames ) {
  23602. const times = [];
  23603. const values = [];
  23604. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  23605. const animationKey = animationKeys[ k ];
  23606. times.push( animationKey.time );
  23607. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  23608. }
  23609. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  23610. }
  23611. duration = morphTargetNames.length * ( fps || 1.0 );
  23612. } else {
  23613. // ...assume skeletal animation
  23614. const boneName = '.bones[' + bones[ h ].name + ']';
  23615. addNonemptyTrack(
  23616. VectorKeyframeTrack, boneName + '.position',
  23617. animationKeys, 'pos', tracks );
  23618. addNonemptyTrack(
  23619. QuaternionKeyframeTrack, boneName + '.quaternion',
  23620. animationKeys, 'rot', tracks );
  23621. addNonemptyTrack(
  23622. VectorKeyframeTrack, boneName + '.scale',
  23623. animationKeys, 'scl', tracks );
  23624. }
  23625. }
  23626. if ( tracks.length === 0 ) {
  23627. return null;
  23628. }
  23629. const clip = new this( clipName, duration, tracks, blendMode );
  23630. return clip;
  23631. }
  23632. resetDuration() {
  23633. const tracks = this.tracks;
  23634. let duration = 0;
  23635. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  23636. const track = this.tracks[ i ];
  23637. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  23638. }
  23639. this.duration = duration;
  23640. return this;
  23641. }
  23642. trim() {
  23643. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23644. this.tracks[ i ].trim( 0, this.duration );
  23645. }
  23646. return this;
  23647. }
  23648. validate() {
  23649. let valid = true;
  23650. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23651. valid = valid && this.tracks[ i ].validate();
  23652. }
  23653. return valid;
  23654. }
  23655. optimize() {
  23656. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23657. this.tracks[ i ].optimize();
  23658. }
  23659. return this;
  23660. }
  23661. clone() {
  23662. const tracks = [];
  23663. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23664. tracks.push( this.tracks[ i ].clone() );
  23665. }
  23666. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  23667. }
  23668. toJSON() {
  23669. return this.constructor.toJSON( this );
  23670. }
  23671. }
  23672. function getTrackTypeForValueTypeName( typeName ) {
  23673. switch ( typeName.toLowerCase() ) {
  23674. case 'scalar':
  23675. case 'double':
  23676. case 'float':
  23677. case 'number':
  23678. case 'integer':
  23679. return NumberKeyframeTrack;
  23680. case 'vector':
  23681. case 'vector2':
  23682. case 'vector3':
  23683. case 'vector4':
  23684. return VectorKeyframeTrack;
  23685. case 'color':
  23686. return ColorKeyframeTrack;
  23687. case 'quaternion':
  23688. return QuaternionKeyframeTrack;
  23689. case 'bool':
  23690. case 'boolean':
  23691. return BooleanKeyframeTrack;
  23692. case 'string':
  23693. return StringKeyframeTrack;
  23694. }
  23695. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  23696. }
  23697. function parseKeyframeTrack( json ) {
  23698. if ( json.type === undefined ) {
  23699. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  23700. }
  23701. const trackType = getTrackTypeForValueTypeName( json.type );
  23702. if ( json.times === undefined ) {
  23703. const times = [], values = [];
  23704. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  23705. json.times = times;
  23706. json.values = values;
  23707. }
  23708. // derived classes can define a static parse method
  23709. if ( trackType.parse !== undefined ) {
  23710. return trackType.parse( json );
  23711. } else {
  23712. // by default, we assume a constructor compatible with the base
  23713. return new trackType( json.name, json.times, json.values, json.interpolation );
  23714. }
  23715. }
  23716. const Cache = {
  23717. enabled: false,
  23718. files: {},
  23719. add: function ( key, file ) {
  23720. if ( this.enabled === false ) return;
  23721. // console.log( 'THREE.Cache', 'Adding key:', key );
  23722. this.files[ key ] = file;
  23723. },
  23724. get: function ( key ) {
  23725. if ( this.enabled === false ) return;
  23726. // console.log( 'THREE.Cache', 'Checking key:', key );
  23727. return this.files[ key ];
  23728. },
  23729. remove: function ( key ) {
  23730. delete this.files[ key ];
  23731. },
  23732. clear: function () {
  23733. this.files = {};
  23734. }
  23735. };
  23736. class LoadingManager {
  23737. constructor( onLoad, onProgress, onError ) {
  23738. const scope = this;
  23739. let isLoading = false;
  23740. let itemsLoaded = 0;
  23741. let itemsTotal = 0;
  23742. let urlModifier = undefined;
  23743. const handlers = [];
  23744. // Refer to #5689 for the reason why we don't set .onStart
  23745. // in the constructor
  23746. this.onStart = undefined;
  23747. this.onLoad = onLoad;
  23748. this.onProgress = onProgress;
  23749. this.onError = onError;
  23750. this.itemStart = function ( url ) {
  23751. itemsTotal ++;
  23752. if ( isLoading === false ) {
  23753. if ( scope.onStart !== undefined ) {
  23754. scope.onStart( url, itemsLoaded, itemsTotal );
  23755. }
  23756. }
  23757. isLoading = true;
  23758. };
  23759. this.itemEnd = function ( url ) {
  23760. itemsLoaded ++;
  23761. if ( scope.onProgress !== undefined ) {
  23762. scope.onProgress( url, itemsLoaded, itemsTotal );
  23763. }
  23764. if ( itemsLoaded === itemsTotal ) {
  23765. isLoading = false;
  23766. if ( scope.onLoad !== undefined ) {
  23767. scope.onLoad();
  23768. }
  23769. }
  23770. };
  23771. this.itemError = function ( url ) {
  23772. if ( scope.onError !== undefined ) {
  23773. scope.onError( url );
  23774. }
  23775. };
  23776. this.resolveURL = function ( url ) {
  23777. if ( urlModifier ) {
  23778. return urlModifier( url );
  23779. }
  23780. return url;
  23781. };
  23782. this.setURLModifier = function ( transform ) {
  23783. urlModifier = transform;
  23784. return this;
  23785. };
  23786. this.addHandler = function ( regex, loader ) {
  23787. handlers.push( regex, loader );
  23788. return this;
  23789. };
  23790. this.removeHandler = function ( regex ) {
  23791. const index = handlers.indexOf( regex );
  23792. if ( index !== - 1 ) {
  23793. handlers.splice( index, 2 );
  23794. }
  23795. return this;
  23796. };
  23797. this.getHandler = function ( file ) {
  23798. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  23799. const regex = handlers[ i ];
  23800. const loader = handlers[ i + 1 ];
  23801. if ( regex.global ) regex.lastIndex = 0; // see #17920
  23802. if ( regex.test( file ) ) {
  23803. return loader;
  23804. }
  23805. }
  23806. return null;
  23807. };
  23808. }
  23809. }
  23810. const DefaultLoadingManager = new LoadingManager();
  23811. class Loader {
  23812. constructor( manager ) {
  23813. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23814. this.crossOrigin = 'anonymous';
  23815. this.withCredentials = false;
  23816. this.path = '';
  23817. this.resourcePath = '';
  23818. this.requestHeader = {};
  23819. }
  23820. load( /* url, onLoad, onProgress, onError */ ) {}
  23821. loadAsync( url, onProgress ) {
  23822. const scope = this;
  23823. return new Promise( function ( resolve, reject ) {
  23824. scope.load( url, resolve, onProgress, reject );
  23825. } );
  23826. }
  23827. parse( /* data */ ) {}
  23828. setCrossOrigin( crossOrigin ) {
  23829. this.crossOrigin = crossOrigin;
  23830. return this;
  23831. }
  23832. setWithCredentials( value ) {
  23833. this.withCredentials = value;
  23834. return this;
  23835. }
  23836. setPath( path ) {
  23837. this.path = path;
  23838. return this;
  23839. }
  23840. setResourcePath( resourcePath ) {
  23841. this.resourcePath = resourcePath;
  23842. return this;
  23843. }
  23844. setRequestHeader( requestHeader ) {
  23845. this.requestHeader = requestHeader;
  23846. return this;
  23847. }
  23848. }
  23849. const loading = {};
  23850. class FileLoader extends Loader {
  23851. constructor( manager ) {
  23852. super( manager );
  23853. }
  23854. load( url, onLoad, onProgress, onError ) {
  23855. if ( url === undefined ) url = '';
  23856. if ( this.path !== undefined ) url = this.path + url;
  23857. url = this.manager.resolveURL( url );
  23858. const scope = this;
  23859. const cached = Cache.get( url );
  23860. if ( cached !== undefined ) {
  23861. scope.manager.itemStart( url );
  23862. setTimeout( function () {
  23863. if ( onLoad ) onLoad( cached );
  23864. scope.manager.itemEnd( url );
  23865. }, 0 );
  23866. return cached;
  23867. }
  23868. // Check if request is duplicate
  23869. if ( loading[ url ] !== undefined ) {
  23870. loading[ url ].push( {
  23871. onLoad: onLoad,
  23872. onProgress: onProgress,
  23873. onError: onError
  23874. } );
  23875. return;
  23876. }
  23877. // Check for data: URI
  23878. const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  23879. const dataUriRegexResult = url.match( dataUriRegex );
  23880. let request;
  23881. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  23882. if ( dataUriRegexResult ) {
  23883. const mimeType = dataUriRegexResult[ 1 ];
  23884. const isBase64 = !! dataUriRegexResult[ 2 ];
  23885. let data = dataUriRegexResult[ 3 ];
  23886. data = decodeURIComponent( data );
  23887. if ( isBase64 ) data = atob( data );
  23888. try {
  23889. let response;
  23890. const responseType = ( this.responseType || '' ).toLowerCase();
  23891. switch ( responseType ) {
  23892. case 'arraybuffer':
  23893. case 'blob':
  23894. const view = new Uint8Array( data.length );
  23895. for ( let i = 0; i < data.length; i ++ ) {
  23896. view[ i ] = data.charCodeAt( i );
  23897. }
  23898. if ( responseType === 'blob' ) {
  23899. response = new Blob( [ view.buffer ], { type: mimeType } );
  23900. } else {
  23901. response = view.buffer;
  23902. }
  23903. break;
  23904. case 'document':
  23905. const parser = new DOMParser();
  23906. response = parser.parseFromString( data, mimeType );
  23907. break;
  23908. case 'json':
  23909. response = JSON.parse( data );
  23910. break;
  23911. default: // 'text' or other
  23912. response = data;
  23913. break;
  23914. }
  23915. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  23916. setTimeout( function () {
  23917. if ( onLoad ) onLoad( response );
  23918. scope.manager.itemEnd( url );
  23919. }, 0 );
  23920. } catch ( error ) {
  23921. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  23922. setTimeout( function () {
  23923. if ( onError ) onError( error );
  23924. scope.manager.itemError( url );
  23925. scope.manager.itemEnd( url );
  23926. }, 0 );
  23927. }
  23928. } else {
  23929. // Initialise array for duplicate requests
  23930. loading[ url ] = [];
  23931. loading[ url ].push( {
  23932. onLoad: onLoad,
  23933. onProgress: onProgress,
  23934. onError: onError
  23935. } );
  23936. request = new XMLHttpRequest();
  23937. request.open( 'GET', url, true );
  23938. request.addEventListener( 'load', function ( event ) {
  23939. const response = this.response;
  23940. const callbacks = loading[ url ];
  23941. delete loading[ url ];
  23942. if ( this.status === 200 || this.status === 0 ) {
  23943. // Some browsers return HTTP Status 0 when using non-http protocol
  23944. // e.g. 'file://' or 'data://'. Handle as success.
  23945. if ( this.status === 0 ) console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  23946. // Add to cache only on HTTP success, so that we do not cache
  23947. // error response bodies as proper responses to requests.
  23948. Cache.add( url, response );
  23949. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23950. const callback = callbacks[ i ];
  23951. if ( callback.onLoad ) callback.onLoad( response );
  23952. }
  23953. scope.manager.itemEnd( url );
  23954. } else {
  23955. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23956. const callback = callbacks[ i ];
  23957. if ( callback.onError ) callback.onError( event );
  23958. }
  23959. scope.manager.itemError( url );
  23960. scope.manager.itemEnd( url );
  23961. }
  23962. }, false );
  23963. request.addEventListener( 'progress', function ( event ) {
  23964. const callbacks = loading[ url ];
  23965. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23966. const callback = callbacks[ i ];
  23967. if ( callback.onProgress ) callback.onProgress( event );
  23968. }
  23969. }, false );
  23970. request.addEventListener( 'error', function ( event ) {
  23971. const callbacks = loading[ url ];
  23972. delete loading[ url ];
  23973. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23974. const callback = callbacks[ i ];
  23975. if ( callback.onError ) callback.onError( event );
  23976. }
  23977. scope.manager.itemError( url );
  23978. scope.manager.itemEnd( url );
  23979. }, false );
  23980. request.addEventListener( 'abort', function ( event ) {
  23981. const callbacks = loading[ url ];
  23982. delete loading[ url ];
  23983. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23984. const callback = callbacks[ i ];
  23985. if ( callback.onError ) callback.onError( event );
  23986. }
  23987. scope.manager.itemError( url );
  23988. scope.manager.itemEnd( url );
  23989. }, false );
  23990. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  23991. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  23992. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  23993. for ( const header in this.requestHeader ) {
  23994. request.setRequestHeader( header, this.requestHeader[ header ] );
  23995. }
  23996. request.send( null );
  23997. }
  23998. scope.manager.itemStart( url );
  23999. return request;
  24000. }
  24001. setResponseType( value ) {
  24002. this.responseType = value;
  24003. return this;
  24004. }
  24005. setMimeType( value ) {
  24006. this.mimeType = value;
  24007. return this;
  24008. }
  24009. }
  24010. class AnimationLoader extends Loader {
  24011. constructor( manager ) {
  24012. super( manager );
  24013. }
  24014. load( url, onLoad, onProgress, onError ) {
  24015. const scope = this;
  24016. const loader = new FileLoader( this.manager );
  24017. loader.setPath( this.path );
  24018. loader.setRequestHeader( this.requestHeader );
  24019. loader.setWithCredentials( this.withCredentials );
  24020. loader.load( url, function ( text ) {
  24021. try {
  24022. onLoad( scope.parse( JSON.parse( text ) ) );
  24023. } catch ( e ) {
  24024. if ( onError ) {
  24025. onError( e );
  24026. } else {
  24027. console.error( e );
  24028. }
  24029. scope.manager.itemError( url );
  24030. }
  24031. }, onProgress, onError );
  24032. }
  24033. parse( json ) {
  24034. const animations = [];
  24035. for ( let i = 0; i < json.length; i ++ ) {
  24036. const clip = AnimationClip.parse( json[ i ] );
  24037. animations.push( clip );
  24038. }
  24039. return animations;
  24040. }
  24041. }
  24042. /**
  24043. * Abstract Base class to block based textures loader (dds, pvr, ...)
  24044. *
  24045. * Sub classes have to implement the parse() method which will be used in load().
  24046. */
  24047. class CompressedTextureLoader extends Loader {
  24048. constructor( manager ) {
  24049. super( manager );
  24050. }
  24051. load( url, onLoad, onProgress, onError ) {
  24052. const scope = this;
  24053. const images = [];
  24054. const texture = new CompressedTexture();
  24055. const loader = new FileLoader( this.manager );
  24056. loader.setPath( this.path );
  24057. loader.setResponseType( 'arraybuffer' );
  24058. loader.setRequestHeader( this.requestHeader );
  24059. loader.setWithCredentials( scope.withCredentials );
  24060. let loaded = 0;
  24061. function loadTexture( i ) {
  24062. loader.load( url[ i ], function ( buffer ) {
  24063. const texDatas = scope.parse( buffer, true );
  24064. images[ i ] = {
  24065. width: texDatas.width,
  24066. height: texDatas.height,
  24067. format: texDatas.format,
  24068. mipmaps: texDatas.mipmaps
  24069. };
  24070. loaded += 1;
  24071. if ( loaded === 6 ) {
  24072. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  24073. texture.image = images;
  24074. texture.format = texDatas.format;
  24075. texture.needsUpdate = true;
  24076. if ( onLoad ) onLoad( texture );
  24077. }
  24078. }, onProgress, onError );
  24079. }
  24080. if ( Array.isArray( url ) ) {
  24081. for ( let i = 0, il = url.length; i < il; ++ i ) {
  24082. loadTexture( i );
  24083. }
  24084. } else {
  24085. // compressed cubemap texture stored in a single DDS file
  24086. loader.load( url, function ( buffer ) {
  24087. const texDatas = scope.parse( buffer, true );
  24088. if ( texDatas.isCubemap ) {
  24089. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  24090. for ( let f = 0; f < faces; f ++ ) {
  24091. images[ f ] = { mipmaps: [] };
  24092. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  24093. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  24094. images[ f ].format = texDatas.format;
  24095. images[ f ].width = texDatas.width;
  24096. images[ f ].height = texDatas.height;
  24097. }
  24098. }
  24099. texture.image = images;
  24100. } else {
  24101. texture.image.width = texDatas.width;
  24102. texture.image.height = texDatas.height;
  24103. texture.mipmaps = texDatas.mipmaps;
  24104. }
  24105. if ( texDatas.mipmapCount === 1 ) {
  24106. texture.minFilter = LinearFilter;
  24107. }
  24108. texture.format = texDatas.format;
  24109. texture.needsUpdate = true;
  24110. if ( onLoad ) onLoad( texture );
  24111. }, onProgress, onError );
  24112. }
  24113. return texture;
  24114. }
  24115. }
  24116. class ImageLoader extends Loader {
  24117. constructor( manager ) {
  24118. super( manager );
  24119. }
  24120. load( url, onLoad, onProgress, onError ) {
  24121. if ( this.path !== undefined ) url = this.path + url;
  24122. url = this.manager.resolveURL( url );
  24123. const scope = this;
  24124. const cached = Cache.get( url );
  24125. if ( cached !== undefined ) {
  24126. scope.manager.itemStart( url );
  24127. setTimeout( function () {
  24128. if ( onLoad ) onLoad( cached );
  24129. scope.manager.itemEnd( url );
  24130. }, 0 );
  24131. return cached;
  24132. }
  24133. const image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  24134. function onImageLoad() {
  24135. image.removeEventListener( 'load', onImageLoad, false );
  24136. image.removeEventListener( 'error', onImageError, false );
  24137. Cache.add( url, this );
  24138. if ( onLoad ) onLoad( this );
  24139. scope.manager.itemEnd( url );
  24140. }
  24141. function onImageError( event ) {
  24142. image.removeEventListener( 'load', onImageLoad, false );
  24143. image.removeEventListener( 'error', onImageError, false );
  24144. if ( onError ) onError( event );
  24145. scope.manager.itemError( url );
  24146. scope.manager.itemEnd( url );
  24147. }
  24148. image.addEventListener( 'load', onImageLoad, false );
  24149. image.addEventListener( 'error', onImageError, false );
  24150. if ( url.substr( 0, 5 ) !== 'data:' ) {
  24151. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  24152. }
  24153. scope.manager.itemStart( url );
  24154. image.src = url;
  24155. return image;
  24156. }
  24157. }
  24158. class CubeTextureLoader extends Loader {
  24159. constructor( manager ) {
  24160. super( manager );
  24161. }
  24162. load( urls, onLoad, onProgress, onError ) {
  24163. const texture = new CubeTexture();
  24164. const loader = new ImageLoader( this.manager );
  24165. loader.setCrossOrigin( this.crossOrigin );
  24166. loader.setPath( this.path );
  24167. let loaded = 0;
  24168. function loadTexture( i ) {
  24169. loader.load( urls[ i ], function ( image ) {
  24170. texture.images[ i ] = image;
  24171. loaded ++;
  24172. if ( loaded === 6 ) {
  24173. texture.needsUpdate = true;
  24174. if ( onLoad ) onLoad( texture );
  24175. }
  24176. }, undefined, onError );
  24177. }
  24178. for ( let i = 0; i < urls.length; ++ i ) {
  24179. loadTexture( i );
  24180. }
  24181. return texture;
  24182. }
  24183. }
  24184. /**
  24185. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  24186. *
  24187. * Sub classes have to implement the parse() method which will be used in load().
  24188. */
  24189. class DataTextureLoader extends Loader {
  24190. constructor( manager ) {
  24191. super( manager );
  24192. }
  24193. load( url, onLoad, onProgress, onError ) {
  24194. const scope = this;
  24195. const texture = new DataTexture();
  24196. const loader = new FileLoader( this.manager );
  24197. loader.setResponseType( 'arraybuffer' );
  24198. loader.setRequestHeader( this.requestHeader );
  24199. loader.setPath( this.path );
  24200. loader.setWithCredentials( scope.withCredentials );
  24201. loader.load( url, function ( buffer ) {
  24202. const texData = scope.parse( buffer );
  24203. if ( ! texData ) return;
  24204. if ( texData.image !== undefined ) {
  24205. texture.image = texData.image;
  24206. } else if ( texData.data !== undefined ) {
  24207. texture.image.width = texData.width;
  24208. texture.image.height = texData.height;
  24209. texture.image.data = texData.data;
  24210. }
  24211. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  24212. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  24213. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  24214. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  24215. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  24216. if ( texData.encoding !== undefined ) {
  24217. texture.encoding = texData.encoding;
  24218. }
  24219. if ( texData.flipY !== undefined ) {
  24220. texture.flipY = texData.flipY;
  24221. }
  24222. if ( texData.format !== undefined ) {
  24223. texture.format = texData.format;
  24224. }
  24225. if ( texData.type !== undefined ) {
  24226. texture.type = texData.type;
  24227. }
  24228. if ( texData.mipmaps !== undefined ) {
  24229. texture.mipmaps = texData.mipmaps;
  24230. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  24231. }
  24232. if ( texData.mipmapCount === 1 ) {
  24233. texture.minFilter = LinearFilter;
  24234. }
  24235. if ( texData.generateMipmaps !== undefined ) {
  24236. texture.generateMipmaps = texData.generateMipmaps;
  24237. }
  24238. texture.needsUpdate = true;
  24239. if ( onLoad ) onLoad( texture, texData );
  24240. }, onProgress, onError );
  24241. return texture;
  24242. }
  24243. }
  24244. class TextureLoader extends Loader {
  24245. constructor( manager ) {
  24246. super( manager );
  24247. }
  24248. load( url, onLoad, onProgress, onError ) {
  24249. const texture = new Texture();
  24250. const loader = new ImageLoader( this.manager );
  24251. loader.setCrossOrigin( this.crossOrigin );
  24252. loader.setPath( this.path );
  24253. loader.load( url, function ( image ) {
  24254. texture.image = image;
  24255. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  24256. const isJPEG = url.search( /\.jpe?g($|\?)/i ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  24257. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  24258. texture.needsUpdate = true;
  24259. if ( onLoad !== undefined ) {
  24260. onLoad( texture );
  24261. }
  24262. }, onProgress, onError );
  24263. return texture;
  24264. }
  24265. }
  24266. /**************************************************************
  24267. * Curved Path - a curve path is simply a array of connected
  24268. * curves, but retains the api of a curve
  24269. **************************************************************/
  24270. class CurvePath extends Curve {
  24271. constructor() {
  24272. super();
  24273. this.type = 'CurvePath';
  24274. this.curves = [];
  24275. this.autoClose = false; // Automatically closes the path
  24276. }
  24277. add( curve ) {
  24278. this.curves.push( curve );
  24279. }
  24280. closePath() {
  24281. // Add a line curve if start and end of lines are not connected
  24282. const startPoint = this.curves[ 0 ].getPoint( 0 );
  24283. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  24284. if ( ! startPoint.equals( endPoint ) ) {
  24285. this.curves.push( new LineCurve( endPoint, startPoint ) );
  24286. }
  24287. }
  24288. // To get accurate point with reference to
  24289. // entire path distance at time t,
  24290. // following has to be done:
  24291. // 1. Length of each sub path have to be known
  24292. // 2. Locate and identify type of curve
  24293. // 3. Get t for the curve
  24294. // 4. Return curve.getPointAt(t')
  24295. getPoint( t ) {
  24296. const d = t * this.getLength();
  24297. const curveLengths = this.getCurveLengths();
  24298. let i = 0;
  24299. // To think about boundaries points.
  24300. while ( i < curveLengths.length ) {
  24301. if ( curveLengths[ i ] >= d ) {
  24302. const diff = curveLengths[ i ] - d;
  24303. const curve = this.curves[ i ];
  24304. const segmentLength = curve.getLength();
  24305. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  24306. return curve.getPointAt( u );
  24307. }
  24308. i ++;
  24309. }
  24310. return null;
  24311. // loop where sum != 0, sum > d , sum+1 <d
  24312. }
  24313. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  24314. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  24315. // getPoint() depends on getLength
  24316. getLength() {
  24317. const lens = this.getCurveLengths();
  24318. return lens[ lens.length - 1 ];
  24319. }
  24320. // cacheLengths must be recalculated.
  24321. updateArcLengths() {
  24322. this.needsUpdate = true;
  24323. this.cacheLengths = null;
  24324. this.getCurveLengths();
  24325. }
  24326. // Compute lengths and cache them
  24327. // We cannot overwrite getLengths() because UtoT mapping uses it.
  24328. getCurveLengths() {
  24329. // We use cache values if curves and cache array are same length
  24330. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  24331. return this.cacheLengths;
  24332. }
  24333. // Get length of sub-curve
  24334. // Push sums into cached array
  24335. const lengths = [];
  24336. let sums = 0;
  24337. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24338. sums += this.curves[ i ].getLength();
  24339. lengths.push( sums );
  24340. }
  24341. this.cacheLengths = lengths;
  24342. return lengths;
  24343. }
  24344. getSpacedPoints( divisions = 40 ) {
  24345. const points = [];
  24346. for ( let i = 0; i <= divisions; i ++ ) {
  24347. points.push( this.getPoint( i / divisions ) );
  24348. }
  24349. if ( this.autoClose ) {
  24350. points.push( points[ 0 ] );
  24351. }
  24352. return points;
  24353. }
  24354. getPoints( divisions = 12 ) {
  24355. const points = [];
  24356. let last;
  24357. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  24358. const curve = curves[ i ];
  24359. const resolution = ( curve && curve.isEllipseCurve ) ? divisions * 2
  24360. : ( curve && ( curve.isLineCurve || curve.isLineCurve3 ) ) ? 1
  24361. : ( curve && curve.isSplineCurve ) ? divisions * curve.points.length
  24362. : divisions;
  24363. const pts = curve.getPoints( resolution );
  24364. for ( let j = 0; j < pts.length; j ++ ) {
  24365. const point = pts[ j ];
  24366. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  24367. points.push( point );
  24368. last = point;
  24369. }
  24370. }
  24371. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  24372. points.push( points[ 0 ] );
  24373. }
  24374. return points;
  24375. }
  24376. copy( source ) {
  24377. super.copy( source );
  24378. this.curves = [];
  24379. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  24380. const curve = source.curves[ i ];
  24381. this.curves.push( curve.clone() );
  24382. }
  24383. this.autoClose = source.autoClose;
  24384. return this;
  24385. }
  24386. toJSON() {
  24387. const data = super.toJSON();
  24388. data.autoClose = this.autoClose;
  24389. data.curves = [];
  24390. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24391. const curve = this.curves[ i ];
  24392. data.curves.push( curve.toJSON() );
  24393. }
  24394. return data;
  24395. }
  24396. fromJSON( json ) {
  24397. super.fromJSON( json );
  24398. this.autoClose = json.autoClose;
  24399. this.curves = [];
  24400. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  24401. const curve = json.curves[ i ];
  24402. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  24403. }
  24404. return this;
  24405. }
  24406. }
  24407. class Path extends CurvePath {
  24408. constructor( points ) {
  24409. super();
  24410. this.type = 'Path';
  24411. this.currentPoint = new Vector2();
  24412. if ( points ) {
  24413. this.setFromPoints( points );
  24414. }
  24415. }
  24416. setFromPoints( points ) {
  24417. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  24418. for ( let i = 1, l = points.length; i < l; i ++ ) {
  24419. this.lineTo( points[ i ].x, points[ i ].y );
  24420. }
  24421. return this;
  24422. }
  24423. moveTo( x, y ) {
  24424. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  24425. return this;
  24426. }
  24427. lineTo( x, y ) {
  24428. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  24429. this.curves.push( curve );
  24430. this.currentPoint.set( x, y );
  24431. return this;
  24432. }
  24433. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  24434. const curve = new QuadraticBezierCurve(
  24435. this.currentPoint.clone(),
  24436. new Vector2( aCPx, aCPy ),
  24437. new Vector2( aX, aY )
  24438. );
  24439. this.curves.push( curve );
  24440. this.currentPoint.set( aX, aY );
  24441. return this;
  24442. }
  24443. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  24444. const curve = new CubicBezierCurve(
  24445. this.currentPoint.clone(),
  24446. new Vector2( aCP1x, aCP1y ),
  24447. new Vector2( aCP2x, aCP2y ),
  24448. new Vector2( aX, aY )
  24449. );
  24450. this.curves.push( curve );
  24451. this.currentPoint.set( aX, aY );
  24452. return this;
  24453. }
  24454. splineThru( pts /*Array of Vector*/ ) {
  24455. const npts = [ this.currentPoint.clone() ].concat( pts );
  24456. const curve = new SplineCurve( npts );
  24457. this.curves.push( curve );
  24458. this.currentPoint.copy( pts[ pts.length - 1 ] );
  24459. return this;
  24460. }
  24461. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24462. const x0 = this.currentPoint.x;
  24463. const y0 = this.currentPoint.y;
  24464. this.absarc( aX + x0, aY + y0, aRadius,
  24465. aStartAngle, aEndAngle, aClockwise );
  24466. return this;
  24467. }
  24468. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24469. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24470. return this;
  24471. }
  24472. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24473. const x0 = this.currentPoint.x;
  24474. const y0 = this.currentPoint.y;
  24475. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24476. return this;
  24477. }
  24478. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24479. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24480. if ( this.curves.length > 0 ) {
  24481. // if a previous curve is present, attempt to join
  24482. const firstPoint = curve.getPoint( 0 );
  24483. if ( ! firstPoint.equals( this.currentPoint ) ) {
  24484. this.lineTo( firstPoint.x, firstPoint.y );
  24485. }
  24486. }
  24487. this.curves.push( curve );
  24488. const lastPoint = curve.getPoint( 1 );
  24489. this.currentPoint.copy( lastPoint );
  24490. return this;
  24491. }
  24492. copy( source ) {
  24493. super.copy( source );
  24494. this.currentPoint.copy( source.currentPoint );
  24495. return this;
  24496. }
  24497. toJSON() {
  24498. const data = super.toJSON();
  24499. data.currentPoint = this.currentPoint.toArray();
  24500. return data;
  24501. }
  24502. fromJSON( json ) {
  24503. super.fromJSON( json );
  24504. this.currentPoint.fromArray( json.currentPoint );
  24505. return this;
  24506. }
  24507. }
  24508. class Shape extends Path {
  24509. constructor( points ) {
  24510. super( points );
  24511. this.uuid = generateUUID();
  24512. this.type = 'Shape';
  24513. this.holes = [];
  24514. }
  24515. getPointsHoles( divisions ) {
  24516. const holesPts = [];
  24517. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24518. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  24519. }
  24520. return holesPts;
  24521. }
  24522. // get points of shape and holes (keypoints based on segments parameter)
  24523. extractPoints( divisions ) {
  24524. return {
  24525. shape: this.getPoints( divisions ),
  24526. holes: this.getPointsHoles( divisions )
  24527. };
  24528. }
  24529. copy( source ) {
  24530. super.copy( source );
  24531. this.holes = [];
  24532. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  24533. const hole = source.holes[ i ];
  24534. this.holes.push( hole.clone() );
  24535. }
  24536. return this;
  24537. }
  24538. toJSON() {
  24539. const data = super.toJSON();
  24540. data.uuid = this.uuid;
  24541. data.holes = [];
  24542. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24543. const hole = this.holes[ i ];
  24544. data.holes.push( hole.toJSON() );
  24545. }
  24546. return data;
  24547. }
  24548. fromJSON( json ) {
  24549. super.fromJSON( json );
  24550. this.uuid = json.uuid;
  24551. this.holes = [];
  24552. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  24553. const hole = json.holes[ i ];
  24554. this.holes.push( new Path().fromJSON( hole ) );
  24555. }
  24556. return this;
  24557. }
  24558. }
  24559. class Light extends Object3D {
  24560. constructor( color, intensity = 1 ) {
  24561. super();
  24562. this.type = 'Light';
  24563. this.color = new Color( color );
  24564. this.intensity = intensity;
  24565. }
  24566. dispose() {
  24567. // Empty here in base class; some subclasses override.
  24568. }
  24569. copy( source ) {
  24570. super.copy( source );
  24571. this.color.copy( source.color );
  24572. this.intensity = source.intensity;
  24573. return this;
  24574. }
  24575. toJSON( meta ) {
  24576. const data = super.toJSON( meta );
  24577. data.object.color = this.color.getHex();
  24578. data.object.intensity = this.intensity;
  24579. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  24580. if ( this.distance !== undefined ) data.object.distance = this.distance;
  24581. if ( this.angle !== undefined ) data.object.angle = this.angle;
  24582. if ( this.decay !== undefined ) data.object.decay = this.decay;
  24583. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  24584. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  24585. return data;
  24586. }
  24587. }
  24588. Light.prototype.isLight = true;
  24589. class HemisphereLight extends Light {
  24590. constructor( skyColor, groundColor, intensity ) {
  24591. super( skyColor, intensity );
  24592. this.type = 'HemisphereLight';
  24593. this.position.copy( Object3D.DefaultUp );
  24594. this.updateMatrix();
  24595. this.groundColor = new Color( groundColor );
  24596. }
  24597. copy( source ) {
  24598. Light.prototype.copy.call( this, source );
  24599. this.groundColor.copy( source.groundColor );
  24600. return this;
  24601. }
  24602. }
  24603. HemisphereLight.prototype.isHemisphereLight = true;
  24604. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  24605. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  24606. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  24607. class LightShadow {
  24608. constructor( camera ) {
  24609. this.camera = camera;
  24610. this.bias = 0;
  24611. this.normalBias = 0;
  24612. this.radius = 1;
  24613. this.blurSamples = 8;
  24614. this.mapSize = new Vector2( 512, 512 );
  24615. this.map = null;
  24616. this.mapPass = null;
  24617. this.matrix = new Matrix4();
  24618. this.autoUpdate = true;
  24619. this.needsUpdate = false;
  24620. this._frustum = new Frustum();
  24621. this._frameExtents = new Vector2( 1, 1 );
  24622. this._viewportCount = 1;
  24623. this._viewports = [
  24624. new Vector4( 0, 0, 1, 1 )
  24625. ];
  24626. }
  24627. getViewportCount() {
  24628. return this._viewportCount;
  24629. }
  24630. getFrustum() {
  24631. return this._frustum;
  24632. }
  24633. updateMatrices( light ) {
  24634. const shadowCamera = this.camera;
  24635. const shadowMatrix = this.matrix;
  24636. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  24637. shadowCamera.position.copy( _lightPositionWorld$1 );
  24638. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  24639. shadowCamera.lookAt( _lookTarget$1 );
  24640. shadowCamera.updateMatrixWorld();
  24641. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  24642. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  24643. shadowMatrix.set(
  24644. 0.5, 0.0, 0.0, 0.5,
  24645. 0.0, 0.5, 0.0, 0.5,
  24646. 0.0, 0.0, 0.5, 0.5,
  24647. 0.0, 0.0, 0.0, 1.0
  24648. );
  24649. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  24650. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  24651. }
  24652. getViewport( viewportIndex ) {
  24653. return this._viewports[ viewportIndex ];
  24654. }
  24655. getFrameExtents() {
  24656. return this._frameExtents;
  24657. }
  24658. dispose() {
  24659. if ( this.map ) {
  24660. this.map.dispose();
  24661. }
  24662. if ( this.mapPass ) {
  24663. this.mapPass.dispose();
  24664. }
  24665. }
  24666. copy( source ) {
  24667. this.camera = source.camera.clone();
  24668. this.bias = source.bias;
  24669. this.radius = source.radius;
  24670. this.mapSize.copy( source.mapSize );
  24671. return this;
  24672. }
  24673. clone() {
  24674. return new this.constructor().copy( this );
  24675. }
  24676. toJSON() {
  24677. const object = {};
  24678. if ( this.bias !== 0 ) object.bias = this.bias;
  24679. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  24680. if ( this.radius !== 1 ) object.radius = this.radius;
  24681. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  24682. object.camera = this.camera.toJSON( false ).object;
  24683. delete object.camera.matrix;
  24684. return object;
  24685. }
  24686. }
  24687. class SpotLightShadow extends LightShadow {
  24688. constructor() {
  24689. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  24690. this.focus = 1;
  24691. }
  24692. updateMatrices( light ) {
  24693. const camera = this.camera;
  24694. const fov = RAD2DEG * 2 * light.angle * this.focus;
  24695. const aspect = this.mapSize.width / this.mapSize.height;
  24696. const far = light.distance || camera.far;
  24697. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  24698. camera.fov = fov;
  24699. camera.aspect = aspect;
  24700. camera.far = far;
  24701. camera.updateProjectionMatrix();
  24702. }
  24703. super.updateMatrices( light );
  24704. }
  24705. copy( source ) {
  24706. super.copy( source );
  24707. this.focus = source.focus;
  24708. return this;
  24709. }
  24710. }
  24711. SpotLightShadow.prototype.isSpotLightShadow = true;
  24712. class SpotLight extends Light {
  24713. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1 ) {
  24714. super( color, intensity );
  24715. this.type = 'SpotLight';
  24716. this.position.copy( Object3D.DefaultUp );
  24717. this.updateMatrix();
  24718. this.target = new Object3D();
  24719. this.distance = distance;
  24720. this.angle = angle;
  24721. this.penumbra = penumbra;
  24722. this.decay = decay; // for physically correct lights, should be 2.
  24723. this.shadow = new SpotLightShadow();
  24724. }
  24725. get power() {
  24726. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24727. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  24728. return this.intensity * Math.PI;
  24729. }
  24730. set power( power ) {
  24731. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24732. this.intensity = power / Math.PI;
  24733. }
  24734. dispose() {
  24735. this.shadow.dispose();
  24736. }
  24737. copy( source ) {
  24738. super.copy( source );
  24739. this.distance = source.distance;
  24740. this.angle = source.angle;
  24741. this.penumbra = source.penumbra;
  24742. this.decay = source.decay;
  24743. this.target = source.target.clone();
  24744. this.shadow = source.shadow.clone();
  24745. return this;
  24746. }
  24747. }
  24748. SpotLight.prototype.isSpotLight = true;
  24749. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  24750. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  24751. const _lookTarget = /*@__PURE__*/ new Vector3();
  24752. class PointLightShadow extends LightShadow {
  24753. constructor() {
  24754. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  24755. this._frameExtents = new Vector2( 4, 2 );
  24756. this._viewportCount = 6;
  24757. this._viewports = [
  24758. // These viewports map a cube-map onto a 2D texture with the
  24759. // following orientation:
  24760. //
  24761. // xzXZ
  24762. // y Y
  24763. //
  24764. // X - Positive x direction
  24765. // x - Negative x direction
  24766. // Y - Positive y direction
  24767. // y - Negative y direction
  24768. // Z - Positive z direction
  24769. // z - Negative z direction
  24770. // positive X
  24771. new Vector4( 2, 1, 1, 1 ),
  24772. // negative X
  24773. new Vector4( 0, 1, 1, 1 ),
  24774. // positive Z
  24775. new Vector4( 3, 1, 1, 1 ),
  24776. // negative Z
  24777. new Vector4( 1, 1, 1, 1 ),
  24778. // positive Y
  24779. new Vector4( 3, 0, 1, 1 ),
  24780. // negative Y
  24781. new Vector4( 1, 0, 1, 1 )
  24782. ];
  24783. this._cubeDirections = [
  24784. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  24785. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  24786. ];
  24787. this._cubeUps = [
  24788. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  24789. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  24790. ];
  24791. }
  24792. updateMatrices( light, viewportIndex = 0 ) {
  24793. const camera = this.camera;
  24794. const shadowMatrix = this.matrix;
  24795. const far = light.distance || camera.far;
  24796. if ( far !== camera.far ) {
  24797. camera.far = far;
  24798. camera.updateProjectionMatrix();
  24799. }
  24800. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  24801. camera.position.copy( _lightPositionWorld );
  24802. _lookTarget.copy( camera.position );
  24803. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  24804. camera.up.copy( this._cubeUps[ viewportIndex ] );
  24805. camera.lookAt( _lookTarget );
  24806. camera.updateMatrixWorld();
  24807. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  24808. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  24809. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  24810. }
  24811. }
  24812. PointLightShadow.prototype.isPointLightShadow = true;
  24813. class PointLight extends Light {
  24814. constructor( color, intensity, distance = 0, decay = 1 ) {
  24815. super( color, intensity );
  24816. this.type = 'PointLight';
  24817. this.distance = distance;
  24818. this.decay = decay; // for physically correct lights, should be 2.
  24819. this.shadow = new PointLightShadow();
  24820. }
  24821. get power() {
  24822. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24823. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  24824. return this.intensity * 4 * Math.PI;
  24825. }
  24826. set power( power ) {
  24827. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24828. this.intensity = power / ( 4 * Math.PI );
  24829. }
  24830. dispose() {
  24831. this.shadow.dispose();
  24832. }
  24833. copy( source ) {
  24834. super.copy( source );
  24835. this.distance = source.distance;
  24836. this.decay = source.decay;
  24837. this.shadow = source.shadow.clone();
  24838. return this;
  24839. }
  24840. }
  24841. PointLight.prototype.isPointLight = true;
  24842. class DirectionalLightShadow extends LightShadow {
  24843. constructor() {
  24844. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  24845. }
  24846. }
  24847. DirectionalLightShadow.prototype.isDirectionalLightShadow = true;
  24848. class DirectionalLight extends Light {
  24849. constructor( color, intensity ) {
  24850. super( color, intensity );
  24851. this.type = 'DirectionalLight';
  24852. this.position.copy( Object3D.DefaultUp );
  24853. this.updateMatrix();
  24854. this.target = new Object3D();
  24855. this.shadow = new DirectionalLightShadow();
  24856. }
  24857. dispose() {
  24858. this.shadow.dispose();
  24859. }
  24860. copy( source ) {
  24861. super.copy( source );
  24862. this.target = source.target.clone();
  24863. this.shadow = source.shadow.clone();
  24864. return this;
  24865. }
  24866. }
  24867. DirectionalLight.prototype.isDirectionalLight = true;
  24868. class AmbientLight extends Light {
  24869. constructor( color, intensity ) {
  24870. super( color, intensity );
  24871. this.type = 'AmbientLight';
  24872. }
  24873. }
  24874. AmbientLight.prototype.isAmbientLight = true;
  24875. class RectAreaLight extends Light {
  24876. constructor( color, intensity, width = 10, height = 10 ) {
  24877. super( color, intensity );
  24878. this.type = 'RectAreaLight';
  24879. this.width = width;
  24880. this.height = height;
  24881. }
  24882. get power() {
  24883. // compute the light's luminous power (in lumens) from its intensity (in nits)
  24884. return this.intensity * this.width * this.height * Math.PI;
  24885. }
  24886. set power( power ) {
  24887. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  24888. this.intensity = power / ( this.width * this.height * Math.PI );
  24889. }
  24890. copy( source ) {
  24891. super.copy( source );
  24892. this.width = source.width;
  24893. this.height = source.height;
  24894. return this;
  24895. }
  24896. toJSON( meta ) {
  24897. const data = super.toJSON( meta );
  24898. data.object.width = this.width;
  24899. data.object.height = this.height;
  24900. return data;
  24901. }
  24902. }
  24903. RectAreaLight.prototype.isRectAreaLight = true;
  24904. /**
  24905. * Primary reference:
  24906. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24907. *
  24908. * Secondary reference:
  24909. * https://www.ppsloan.org/publications/StupidSH36.pdf
  24910. */
  24911. // 3-band SH defined by 9 coefficients
  24912. class SphericalHarmonics3 {
  24913. constructor() {
  24914. this.coefficients = [];
  24915. for ( let i = 0; i < 9; i ++ ) {
  24916. this.coefficients.push( new Vector3() );
  24917. }
  24918. }
  24919. set( coefficients ) {
  24920. for ( let i = 0; i < 9; i ++ ) {
  24921. this.coefficients[ i ].copy( coefficients[ i ] );
  24922. }
  24923. return this;
  24924. }
  24925. zero() {
  24926. for ( let i = 0; i < 9; i ++ ) {
  24927. this.coefficients[ i ].set( 0, 0, 0 );
  24928. }
  24929. return this;
  24930. }
  24931. // get the radiance in the direction of the normal
  24932. // target is a Vector3
  24933. getAt( normal, target ) {
  24934. // normal is assumed to be unit length
  24935. const x = normal.x, y = normal.y, z = normal.z;
  24936. const coeff = this.coefficients;
  24937. // band 0
  24938. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  24939. // band 1
  24940. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  24941. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  24942. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  24943. // band 2
  24944. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  24945. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  24946. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  24947. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  24948. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  24949. return target;
  24950. }
  24951. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  24952. // target is a Vector3
  24953. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24954. getIrradianceAt( normal, target ) {
  24955. // normal is assumed to be unit length
  24956. const x = normal.x, y = normal.y, z = normal.z;
  24957. const coeff = this.coefficients;
  24958. // band 0
  24959. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  24960. // band 1
  24961. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  24962. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  24963. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  24964. // band 2
  24965. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  24966. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  24967. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  24968. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  24969. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  24970. return target;
  24971. }
  24972. add( sh ) {
  24973. for ( let i = 0; i < 9; i ++ ) {
  24974. this.coefficients[ i ].add( sh.coefficients[ i ] );
  24975. }
  24976. return this;
  24977. }
  24978. addScaledSH( sh, s ) {
  24979. for ( let i = 0; i < 9; i ++ ) {
  24980. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  24981. }
  24982. return this;
  24983. }
  24984. scale( s ) {
  24985. for ( let i = 0; i < 9; i ++ ) {
  24986. this.coefficients[ i ].multiplyScalar( s );
  24987. }
  24988. return this;
  24989. }
  24990. lerp( sh, alpha ) {
  24991. for ( let i = 0; i < 9; i ++ ) {
  24992. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  24993. }
  24994. return this;
  24995. }
  24996. equals( sh ) {
  24997. for ( let i = 0; i < 9; i ++ ) {
  24998. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  24999. return false;
  25000. }
  25001. }
  25002. return true;
  25003. }
  25004. copy( sh ) {
  25005. return this.set( sh.coefficients );
  25006. }
  25007. clone() {
  25008. return new this.constructor().copy( this );
  25009. }
  25010. fromArray( array, offset = 0 ) {
  25011. const coefficients = this.coefficients;
  25012. for ( let i = 0; i < 9; i ++ ) {
  25013. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  25014. }
  25015. return this;
  25016. }
  25017. toArray( array = [], offset = 0 ) {
  25018. const coefficients = this.coefficients;
  25019. for ( let i = 0; i < 9; i ++ ) {
  25020. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  25021. }
  25022. return array;
  25023. }
  25024. // evaluate the basis functions
  25025. // shBasis is an Array[ 9 ]
  25026. static getBasisAt( normal, shBasis ) {
  25027. // normal is assumed to be unit length
  25028. const x = normal.x, y = normal.y, z = normal.z;
  25029. // band 0
  25030. shBasis[ 0 ] = 0.282095;
  25031. // band 1
  25032. shBasis[ 1 ] = 0.488603 * y;
  25033. shBasis[ 2 ] = 0.488603 * z;
  25034. shBasis[ 3 ] = 0.488603 * x;
  25035. // band 2
  25036. shBasis[ 4 ] = 1.092548 * x * y;
  25037. shBasis[ 5 ] = 1.092548 * y * z;
  25038. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  25039. shBasis[ 7 ] = 1.092548 * x * z;
  25040. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  25041. }
  25042. }
  25043. SphericalHarmonics3.prototype.isSphericalHarmonics3 = true;
  25044. class LightProbe extends Light {
  25045. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  25046. super( undefined, intensity );
  25047. this.sh = sh;
  25048. }
  25049. copy( source ) {
  25050. super.copy( source );
  25051. this.sh.copy( source.sh );
  25052. return this;
  25053. }
  25054. fromJSON( json ) {
  25055. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  25056. this.sh.fromArray( json.sh );
  25057. return this;
  25058. }
  25059. toJSON( meta ) {
  25060. const data = super.toJSON( meta );
  25061. data.object.sh = this.sh.toArray();
  25062. return data;
  25063. }
  25064. }
  25065. LightProbe.prototype.isLightProbe = true;
  25066. class MaterialLoader extends Loader {
  25067. constructor( manager ) {
  25068. super( manager );
  25069. this.textures = {};
  25070. }
  25071. load( url, onLoad, onProgress, onError ) {
  25072. const scope = this;
  25073. const loader = new FileLoader( scope.manager );
  25074. loader.setPath( scope.path );
  25075. loader.setRequestHeader( scope.requestHeader );
  25076. loader.setWithCredentials( scope.withCredentials );
  25077. loader.load( url, function ( text ) {
  25078. try {
  25079. onLoad( scope.parse( JSON.parse( text ) ) );
  25080. } catch ( e ) {
  25081. if ( onError ) {
  25082. onError( e );
  25083. } else {
  25084. console.error( e );
  25085. }
  25086. scope.manager.itemError( url );
  25087. }
  25088. }, onProgress, onError );
  25089. }
  25090. parse( json ) {
  25091. const textures = this.textures;
  25092. function getTexture( name ) {
  25093. if ( textures[ name ] === undefined ) {
  25094. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  25095. }
  25096. return textures[ name ];
  25097. }
  25098. const material = new Materials[ json.type ]();
  25099. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  25100. if ( json.name !== undefined ) material.name = json.name;
  25101. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  25102. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  25103. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  25104. if ( json.sheenTint !== undefined ) material.sheenTint = new Color().setHex( json.sheenTint );
  25105. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  25106. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  25107. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  25108. if ( json.specularTint !== undefined && material.specularTint !== undefined ) material.specularTint.setHex( json.specularTint );
  25109. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  25110. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  25111. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  25112. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  25113. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  25114. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  25115. if ( json.attenuationTint !== undefined && material.attenuationTint !== undefined ) material.attenuationTint.setHex( json.attenuationTint );
  25116. if ( json.fog !== undefined ) material.fog = json.fog;
  25117. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  25118. if ( json.blending !== undefined ) material.blending = json.blending;
  25119. if ( json.combine !== undefined ) material.combine = json.combine;
  25120. if ( json.side !== undefined ) material.side = json.side;
  25121. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  25122. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  25123. if ( json.format !== undefined ) material.format = json.format;
  25124. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  25125. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  25126. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  25127. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  25128. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  25129. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  25130. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  25131. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  25132. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  25133. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  25134. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  25135. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  25136. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  25137. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  25138. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  25139. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  25140. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  25141. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  25142. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  25143. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  25144. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  25145. if ( json.scale !== undefined ) material.scale = json.scale;
  25146. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  25147. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  25148. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  25149. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  25150. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  25151. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  25152. if ( json.visible !== undefined ) material.visible = json.visible;
  25153. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  25154. if ( json.userData !== undefined ) material.userData = json.userData;
  25155. if ( json.vertexColors !== undefined ) {
  25156. if ( typeof json.vertexColors === 'number' ) {
  25157. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  25158. } else {
  25159. material.vertexColors = json.vertexColors;
  25160. }
  25161. }
  25162. // Shader Material
  25163. if ( json.uniforms !== undefined ) {
  25164. for ( const name in json.uniforms ) {
  25165. const uniform = json.uniforms[ name ];
  25166. material.uniforms[ name ] = {};
  25167. switch ( uniform.type ) {
  25168. case 't':
  25169. material.uniforms[ name ].value = getTexture( uniform.value );
  25170. break;
  25171. case 'c':
  25172. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  25173. break;
  25174. case 'v2':
  25175. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  25176. break;
  25177. case 'v3':
  25178. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  25179. break;
  25180. case 'v4':
  25181. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  25182. break;
  25183. case 'm3':
  25184. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  25185. break;
  25186. case 'm4':
  25187. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  25188. break;
  25189. default:
  25190. material.uniforms[ name ].value = uniform.value;
  25191. }
  25192. }
  25193. }
  25194. if ( json.defines !== undefined ) material.defines = json.defines;
  25195. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  25196. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  25197. if ( json.extensions !== undefined ) {
  25198. for ( const key in json.extensions ) {
  25199. material.extensions[ key ] = json.extensions[ key ];
  25200. }
  25201. }
  25202. // Deprecated
  25203. if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading
  25204. // for PointsMaterial
  25205. if ( json.size !== undefined ) material.size = json.size;
  25206. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  25207. // maps
  25208. if ( json.map !== undefined ) material.map = getTexture( json.map );
  25209. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  25210. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  25211. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  25212. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  25213. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  25214. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  25215. if ( json.normalScale !== undefined ) {
  25216. let normalScale = json.normalScale;
  25217. if ( Array.isArray( normalScale ) === false ) {
  25218. // Blender exporter used to export a scalar. See #7459
  25219. normalScale = [ normalScale, normalScale ];
  25220. }
  25221. material.normalScale = new Vector2().fromArray( normalScale );
  25222. }
  25223. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  25224. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  25225. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  25226. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  25227. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  25228. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  25229. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  25230. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  25231. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  25232. if ( json.specularTintMap !== undefined ) material.specularTintMap = getTexture( json.specularTintMap );
  25233. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  25234. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  25235. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  25236. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  25237. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  25238. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  25239. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  25240. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  25241. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  25242. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  25243. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  25244. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  25245. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  25246. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  25247. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  25248. return material;
  25249. }
  25250. setTextures( value ) {
  25251. this.textures = value;
  25252. return this;
  25253. }
  25254. }
  25255. class LoaderUtils {
  25256. static decodeText( array ) {
  25257. if ( typeof TextDecoder !== 'undefined' ) {
  25258. return new TextDecoder().decode( array );
  25259. }
  25260. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  25261. // throws a "maximum call stack size exceeded" error for large arrays.
  25262. let s = '';
  25263. for ( let i = 0, il = array.length; i < il; i ++ ) {
  25264. // Implicitly assumes little-endian.
  25265. s += String.fromCharCode( array[ i ] );
  25266. }
  25267. try {
  25268. // merges multi-byte utf-8 characters.
  25269. return decodeURIComponent( escape( s ) );
  25270. } catch ( e ) { // see #16358
  25271. return s;
  25272. }
  25273. }
  25274. static extractUrlBase( url ) {
  25275. const index = url.lastIndexOf( '/' );
  25276. if ( index === - 1 ) return './';
  25277. return url.substr( 0, index + 1 );
  25278. }
  25279. }
  25280. class InstancedBufferGeometry extends BufferGeometry {
  25281. constructor() {
  25282. super();
  25283. this.type = 'InstancedBufferGeometry';
  25284. this.instanceCount = Infinity;
  25285. }
  25286. copy( source ) {
  25287. super.copy( source );
  25288. this.instanceCount = source.instanceCount;
  25289. return this;
  25290. }
  25291. clone() {
  25292. return new this.constructor().copy( this );
  25293. }
  25294. toJSON() {
  25295. const data = super.toJSON( this );
  25296. data.instanceCount = this.instanceCount;
  25297. data.isInstancedBufferGeometry = true;
  25298. return data;
  25299. }
  25300. }
  25301. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  25302. class BufferGeometryLoader extends Loader {
  25303. constructor( manager ) {
  25304. super( manager );
  25305. }
  25306. load( url, onLoad, onProgress, onError ) {
  25307. const scope = this;
  25308. const loader = new FileLoader( scope.manager );
  25309. loader.setPath( scope.path );
  25310. loader.setRequestHeader( scope.requestHeader );
  25311. loader.setWithCredentials( scope.withCredentials );
  25312. loader.load( url, function ( text ) {
  25313. try {
  25314. onLoad( scope.parse( JSON.parse( text ) ) );
  25315. } catch ( e ) {
  25316. if ( onError ) {
  25317. onError( e );
  25318. } else {
  25319. console.error( e );
  25320. }
  25321. scope.manager.itemError( url );
  25322. }
  25323. }, onProgress, onError );
  25324. }
  25325. parse( json ) {
  25326. const interleavedBufferMap = {};
  25327. const arrayBufferMap = {};
  25328. function getInterleavedBuffer( json, uuid ) {
  25329. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  25330. const interleavedBuffers = json.interleavedBuffers;
  25331. const interleavedBuffer = interleavedBuffers[ uuid ];
  25332. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  25333. const array = getTypedArray( interleavedBuffer.type, buffer );
  25334. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  25335. ib.uuid = interleavedBuffer.uuid;
  25336. interleavedBufferMap[ uuid ] = ib;
  25337. return ib;
  25338. }
  25339. function getArrayBuffer( json, uuid ) {
  25340. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  25341. const arrayBuffers = json.arrayBuffers;
  25342. const arrayBuffer = arrayBuffers[ uuid ];
  25343. const ab = new Uint32Array( arrayBuffer ).buffer;
  25344. arrayBufferMap[ uuid ] = ab;
  25345. return ab;
  25346. }
  25347. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  25348. const index = json.data.index;
  25349. if ( index !== undefined ) {
  25350. const typedArray = getTypedArray( index.type, index.array );
  25351. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  25352. }
  25353. const attributes = json.data.attributes;
  25354. for ( const key in attributes ) {
  25355. const attribute = attributes[ key ];
  25356. let bufferAttribute;
  25357. if ( attribute.isInterleavedBufferAttribute ) {
  25358. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25359. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25360. } else {
  25361. const typedArray = getTypedArray( attribute.type, attribute.array );
  25362. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  25363. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  25364. }
  25365. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25366. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  25367. if ( attribute.updateRange !== undefined ) {
  25368. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  25369. bufferAttribute.updateRange.count = attribute.updateRange.count;
  25370. }
  25371. geometry.setAttribute( key, bufferAttribute );
  25372. }
  25373. const morphAttributes = json.data.morphAttributes;
  25374. if ( morphAttributes ) {
  25375. for ( const key in morphAttributes ) {
  25376. const attributeArray = morphAttributes[ key ];
  25377. const array = [];
  25378. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  25379. const attribute = attributeArray[ i ];
  25380. let bufferAttribute;
  25381. if ( attribute.isInterleavedBufferAttribute ) {
  25382. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25383. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25384. } else {
  25385. const typedArray = getTypedArray( attribute.type, attribute.array );
  25386. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  25387. }
  25388. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25389. array.push( bufferAttribute );
  25390. }
  25391. geometry.morphAttributes[ key ] = array;
  25392. }
  25393. }
  25394. const morphTargetsRelative = json.data.morphTargetsRelative;
  25395. if ( morphTargetsRelative ) {
  25396. geometry.morphTargetsRelative = true;
  25397. }
  25398. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  25399. if ( groups !== undefined ) {
  25400. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  25401. const group = groups[ i ];
  25402. geometry.addGroup( group.start, group.count, group.materialIndex );
  25403. }
  25404. }
  25405. const boundingSphere = json.data.boundingSphere;
  25406. if ( boundingSphere !== undefined ) {
  25407. const center = new Vector3();
  25408. if ( boundingSphere.center !== undefined ) {
  25409. center.fromArray( boundingSphere.center );
  25410. }
  25411. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  25412. }
  25413. if ( json.name ) geometry.name = json.name;
  25414. if ( json.userData ) geometry.userData = json.userData;
  25415. return geometry;
  25416. }
  25417. }
  25418. class ObjectLoader extends Loader {
  25419. constructor( manager ) {
  25420. super( manager );
  25421. }
  25422. load( url, onLoad, onProgress, onError ) {
  25423. const scope = this;
  25424. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  25425. this.resourcePath = this.resourcePath || path;
  25426. const loader = new FileLoader( this.manager );
  25427. loader.setPath( this.path );
  25428. loader.setRequestHeader( this.requestHeader );
  25429. loader.setWithCredentials( this.withCredentials );
  25430. loader.load( url, function ( text ) {
  25431. let json = null;
  25432. try {
  25433. json = JSON.parse( text );
  25434. } catch ( error ) {
  25435. if ( onError !== undefined ) onError( error );
  25436. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  25437. return;
  25438. }
  25439. const metadata = json.metadata;
  25440. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  25441. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  25442. return;
  25443. }
  25444. scope.parse( json, onLoad );
  25445. }, onProgress, onError );
  25446. }
  25447. async loadAsync( url, onProgress ) {
  25448. const scope = this;
  25449. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  25450. this.resourcePath = this.resourcePath || path;
  25451. const loader = new FileLoader( this.manager );
  25452. loader.setPath( this.path );
  25453. loader.setRequestHeader( this.requestHeader );
  25454. loader.setWithCredentials( this.withCredentials );
  25455. const text = await loader.loadAsync( url, onProgress );
  25456. const json = JSON.parse( text );
  25457. const metadata = json.metadata;
  25458. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  25459. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  25460. }
  25461. return await scope.parseAsync( json );
  25462. }
  25463. parse( json, onLoad ) {
  25464. const animations = this.parseAnimations( json.animations );
  25465. const shapes = this.parseShapes( json.shapes );
  25466. const geometries = this.parseGeometries( json.geometries, shapes );
  25467. const images = this.parseImages( json.images, function () {
  25468. if ( onLoad !== undefined ) onLoad( object );
  25469. } );
  25470. const textures = this.parseTextures( json.textures, images );
  25471. const materials = this.parseMaterials( json.materials, textures );
  25472. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  25473. const skeletons = this.parseSkeletons( json.skeletons, object );
  25474. this.bindSkeletons( object, skeletons );
  25475. //
  25476. if ( onLoad !== undefined ) {
  25477. let hasImages = false;
  25478. for ( const uuid in images ) {
  25479. if ( images[ uuid ] instanceof HTMLImageElement ) {
  25480. hasImages = true;
  25481. break;
  25482. }
  25483. }
  25484. if ( hasImages === false ) onLoad( object );
  25485. }
  25486. return object;
  25487. }
  25488. async parseAsync( json ) {
  25489. const animations = this.parseAnimations( json.animations );
  25490. const shapes = this.parseShapes( json.shapes );
  25491. const geometries = this.parseGeometries( json.geometries, shapes );
  25492. const images = await this.parseImagesAsync( json.images );
  25493. const textures = this.parseTextures( json.textures, images );
  25494. const materials = this.parseMaterials( json.materials, textures );
  25495. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  25496. const skeletons = this.parseSkeletons( json.skeletons, object );
  25497. this.bindSkeletons( object, skeletons );
  25498. return object;
  25499. }
  25500. parseShapes( json ) {
  25501. const shapes = {};
  25502. if ( json !== undefined ) {
  25503. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25504. const shape = new Shape().fromJSON( json[ i ] );
  25505. shapes[ shape.uuid ] = shape;
  25506. }
  25507. }
  25508. return shapes;
  25509. }
  25510. parseSkeletons( json, object ) {
  25511. const skeletons = {};
  25512. const bones = {};
  25513. // generate bone lookup table
  25514. object.traverse( function ( child ) {
  25515. if ( child.isBone ) bones[ child.uuid ] = child;
  25516. } );
  25517. // create skeletons
  25518. if ( json !== undefined ) {
  25519. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25520. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  25521. skeletons[ skeleton.uuid ] = skeleton;
  25522. }
  25523. }
  25524. return skeletons;
  25525. }
  25526. parseGeometries( json, shapes ) {
  25527. const geometries = {};
  25528. if ( json !== undefined ) {
  25529. const bufferGeometryLoader = new BufferGeometryLoader();
  25530. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25531. let geometry;
  25532. const data = json[ i ];
  25533. switch ( data.type ) {
  25534. case 'BufferGeometry':
  25535. case 'InstancedBufferGeometry':
  25536. geometry = bufferGeometryLoader.parse( data );
  25537. break;
  25538. case 'Geometry':
  25539. console.error( 'THREE.ObjectLoader: The legacy Geometry type is no longer supported.' );
  25540. break;
  25541. default:
  25542. if ( data.type in Geometries ) {
  25543. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  25544. } else {
  25545. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  25546. }
  25547. }
  25548. geometry.uuid = data.uuid;
  25549. if ( data.name !== undefined ) geometry.name = data.name;
  25550. if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData;
  25551. geometries[ data.uuid ] = geometry;
  25552. }
  25553. }
  25554. return geometries;
  25555. }
  25556. parseMaterials( json, textures ) {
  25557. const cache = {}; // MultiMaterial
  25558. const materials = {};
  25559. if ( json !== undefined ) {
  25560. const loader = new MaterialLoader();
  25561. loader.setTextures( textures );
  25562. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25563. const data = json[ i ];
  25564. if ( data.type === 'MultiMaterial' ) {
  25565. // Deprecated
  25566. const array = [];
  25567. for ( let j = 0; j < data.materials.length; j ++ ) {
  25568. const material = data.materials[ j ];
  25569. if ( cache[ material.uuid ] === undefined ) {
  25570. cache[ material.uuid ] = loader.parse( material );
  25571. }
  25572. array.push( cache[ material.uuid ] );
  25573. }
  25574. materials[ data.uuid ] = array;
  25575. } else {
  25576. if ( cache[ data.uuid ] === undefined ) {
  25577. cache[ data.uuid ] = loader.parse( data );
  25578. }
  25579. materials[ data.uuid ] = cache[ data.uuid ];
  25580. }
  25581. }
  25582. }
  25583. return materials;
  25584. }
  25585. parseAnimations( json ) {
  25586. const animations = {};
  25587. if ( json !== undefined ) {
  25588. for ( let i = 0; i < json.length; i ++ ) {
  25589. const data = json[ i ];
  25590. const clip = AnimationClip.parse( data );
  25591. animations[ clip.uuid ] = clip;
  25592. }
  25593. }
  25594. return animations;
  25595. }
  25596. parseImages( json, onLoad ) {
  25597. const scope = this;
  25598. const images = {};
  25599. let loader;
  25600. function loadImage( url ) {
  25601. scope.manager.itemStart( url );
  25602. return loader.load( url, function () {
  25603. scope.manager.itemEnd( url );
  25604. }, undefined, function () {
  25605. scope.manager.itemError( url );
  25606. scope.manager.itemEnd( url );
  25607. } );
  25608. }
  25609. function deserializeImage( image ) {
  25610. if ( typeof image === 'string' ) {
  25611. const url = image;
  25612. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25613. return loadImage( path );
  25614. } else {
  25615. if ( image.data ) {
  25616. return {
  25617. data: getTypedArray( image.type, image.data ),
  25618. width: image.width,
  25619. height: image.height
  25620. };
  25621. } else {
  25622. return null;
  25623. }
  25624. }
  25625. }
  25626. if ( json !== undefined && json.length > 0 ) {
  25627. const manager = new LoadingManager( onLoad );
  25628. loader = new ImageLoader( manager );
  25629. loader.setCrossOrigin( this.crossOrigin );
  25630. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25631. const image = json[ i ];
  25632. const url = image.url;
  25633. if ( Array.isArray( url ) ) {
  25634. // load array of images e.g CubeTexture
  25635. images[ image.uuid ] = [];
  25636. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25637. const currentUrl = url[ j ];
  25638. const deserializedImage = deserializeImage( currentUrl );
  25639. if ( deserializedImage !== null ) {
  25640. if ( deserializedImage instanceof HTMLImageElement ) {
  25641. images[ image.uuid ].push( deserializedImage );
  25642. } else {
  25643. // special case: handle array of data textures for cube textures
  25644. images[ image.uuid ].push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25645. }
  25646. }
  25647. }
  25648. } else {
  25649. // load single image
  25650. const deserializedImage = deserializeImage( image.url );
  25651. if ( deserializedImage !== null ) {
  25652. images[ image.uuid ] = deserializedImage;
  25653. }
  25654. }
  25655. }
  25656. }
  25657. return images;
  25658. }
  25659. async parseImagesAsync( json ) {
  25660. const scope = this;
  25661. const images = {};
  25662. let loader;
  25663. async function deserializeImage( image ) {
  25664. if ( typeof image === 'string' ) {
  25665. const url = image;
  25666. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25667. return await loader.loadAsync( path );
  25668. } else {
  25669. if ( image.data ) {
  25670. return {
  25671. data: getTypedArray( image.type, image.data ),
  25672. width: image.width,
  25673. height: image.height
  25674. };
  25675. } else {
  25676. return null;
  25677. }
  25678. }
  25679. }
  25680. if ( json !== undefined && json.length > 0 ) {
  25681. loader = new ImageLoader( this.manager );
  25682. loader.setCrossOrigin( this.crossOrigin );
  25683. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25684. const image = json[ i ];
  25685. const url = image.url;
  25686. if ( Array.isArray( url ) ) {
  25687. // load array of images e.g CubeTexture
  25688. images[ image.uuid ] = [];
  25689. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25690. const currentUrl = url[ j ];
  25691. const deserializedImage = await deserializeImage( currentUrl );
  25692. if ( deserializedImage !== null ) {
  25693. if ( deserializedImage instanceof HTMLImageElement ) {
  25694. images[ image.uuid ].push( deserializedImage );
  25695. } else {
  25696. // special case: handle array of data textures for cube textures
  25697. images[ image.uuid ].push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25698. }
  25699. }
  25700. }
  25701. } else {
  25702. // load single image
  25703. const deserializedImage = await deserializeImage( image.url );
  25704. if ( deserializedImage !== null ) {
  25705. images[ image.uuid ] = deserializedImage;
  25706. }
  25707. }
  25708. }
  25709. }
  25710. return images;
  25711. }
  25712. parseTextures( json, images ) {
  25713. function parseConstant( value, type ) {
  25714. if ( typeof value === 'number' ) return value;
  25715. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  25716. return type[ value ];
  25717. }
  25718. const textures = {};
  25719. if ( json !== undefined ) {
  25720. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25721. const data = json[ i ];
  25722. if ( data.image === undefined ) {
  25723. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  25724. }
  25725. if ( images[ data.image ] === undefined ) {
  25726. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  25727. }
  25728. let texture;
  25729. const image = images[ data.image ];
  25730. if ( Array.isArray( image ) ) {
  25731. texture = new CubeTexture( image );
  25732. if ( image.length === 6 ) texture.needsUpdate = true;
  25733. } else {
  25734. if ( image && image.data ) {
  25735. texture = new DataTexture( image.data, image.width, image.height );
  25736. } else {
  25737. texture = new Texture( image );
  25738. }
  25739. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  25740. }
  25741. texture.uuid = data.uuid;
  25742. if ( data.name !== undefined ) texture.name = data.name;
  25743. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  25744. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  25745. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  25746. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  25747. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  25748. if ( data.wrap !== undefined ) {
  25749. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  25750. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  25751. }
  25752. if ( data.format !== undefined ) texture.format = data.format;
  25753. if ( data.type !== undefined ) texture.type = data.type;
  25754. if ( data.encoding !== undefined ) texture.encoding = data.encoding;
  25755. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  25756. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  25757. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  25758. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  25759. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  25760. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  25761. textures[ data.uuid ] = texture;
  25762. }
  25763. }
  25764. return textures;
  25765. }
  25766. parseObject( data, geometries, materials, textures, animations ) {
  25767. let object;
  25768. function getGeometry( name ) {
  25769. if ( geometries[ name ] === undefined ) {
  25770. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  25771. }
  25772. return geometries[ name ];
  25773. }
  25774. function getMaterial( name ) {
  25775. if ( name === undefined ) return undefined;
  25776. if ( Array.isArray( name ) ) {
  25777. const array = [];
  25778. for ( let i = 0, l = name.length; i < l; i ++ ) {
  25779. const uuid = name[ i ];
  25780. if ( materials[ uuid ] === undefined ) {
  25781. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  25782. }
  25783. array.push( materials[ uuid ] );
  25784. }
  25785. return array;
  25786. }
  25787. if ( materials[ name ] === undefined ) {
  25788. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  25789. }
  25790. return materials[ name ];
  25791. }
  25792. function getTexture( uuid ) {
  25793. if ( textures[ uuid ] === undefined ) {
  25794. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  25795. }
  25796. return textures[ uuid ];
  25797. }
  25798. let geometry, material;
  25799. switch ( data.type ) {
  25800. case 'Scene':
  25801. object = new Scene();
  25802. if ( data.background !== undefined ) {
  25803. if ( Number.isInteger( data.background ) ) {
  25804. object.background = new Color( data.background );
  25805. } else {
  25806. object.background = getTexture( data.background );
  25807. }
  25808. }
  25809. if ( data.environment !== undefined ) {
  25810. object.environment = getTexture( data.environment );
  25811. }
  25812. if ( data.fog !== undefined ) {
  25813. if ( data.fog.type === 'Fog' ) {
  25814. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  25815. } else if ( data.fog.type === 'FogExp2' ) {
  25816. object.fog = new FogExp2( data.fog.color, data.fog.density );
  25817. }
  25818. }
  25819. break;
  25820. case 'PerspectiveCamera':
  25821. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  25822. if ( data.focus !== undefined ) object.focus = data.focus;
  25823. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25824. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  25825. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  25826. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25827. break;
  25828. case 'OrthographicCamera':
  25829. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  25830. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25831. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25832. break;
  25833. case 'AmbientLight':
  25834. object = new AmbientLight( data.color, data.intensity );
  25835. break;
  25836. case 'DirectionalLight':
  25837. object = new DirectionalLight( data.color, data.intensity );
  25838. break;
  25839. case 'PointLight':
  25840. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  25841. break;
  25842. case 'RectAreaLight':
  25843. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  25844. break;
  25845. case 'SpotLight':
  25846. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  25847. break;
  25848. case 'HemisphereLight':
  25849. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  25850. break;
  25851. case 'LightProbe':
  25852. object = new LightProbe().fromJSON( data );
  25853. break;
  25854. case 'SkinnedMesh':
  25855. geometry = getGeometry( data.geometry );
  25856. material = getMaterial( data.material );
  25857. object = new SkinnedMesh( geometry, material );
  25858. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  25859. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  25860. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  25861. break;
  25862. case 'Mesh':
  25863. geometry = getGeometry( data.geometry );
  25864. material = getMaterial( data.material );
  25865. object = new Mesh( geometry, material );
  25866. break;
  25867. case 'InstancedMesh':
  25868. geometry = getGeometry( data.geometry );
  25869. material = getMaterial( data.material );
  25870. const count = data.count;
  25871. const instanceMatrix = data.instanceMatrix;
  25872. const instanceColor = data.instanceColor;
  25873. object = new InstancedMesh( geometry, material, count );
  25874. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  25875. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  25876. break;
  25877. case 'LOD':
  25878. object = new LOD();
  25879. break;
  25880. case 'Line':
  25881. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  25882. break;
  25883. case 'LineLoop':
  25884. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  25885. break;
  25886. case 'LineSegments':
  25887. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  25888. break;
  25889. case 'PointCloud':
  25890. case 'Points':
  25891. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  25892. break;
  25893. case 'Sprite':
  25894. object = new Sprite( getMaterial( data.material ) );
  25895. break;
  25896. case 'Group':
  25897. object = new Group();
  25898. break;
  25899. case 'Bone':
  25900. object = new Bone();
  25901. break;
  25902. default:
  25903. object = new Object3D();
  25904. }
  25905. object.uuid = data.uuid;
  25906. if ( data.name !== undefined ) object.name = data.name;
  25907. if ( data.matrix !== undefined ) {
  25908. object.matrix.fromArray( data.matrix );
  25909. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  25910. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  25911. } else {
  25912. if ( data.position !== undefined ) object.position.fromArray( data.position );
  25913. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  25914. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  25915. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  25916. }
  25917. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  25918. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  25919. if ( data.shadow ) {
  25920. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  25921. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  25922. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  25923. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  25924. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  25925. }
  25926. if ( data.visible !== undefined ) object.visible = data.visible;
  25927. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  25928. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  25929. if ( data.userData !== undefined ) object.userData = data.userData;
  25930. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  25931. if ( data.children !== undefined ) {
  25932. const children = data.children;
  25933. for ( let i = 0; i < children.length; i ++ ) {
  25934. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  25935. }
  25936. }
  25937. if ( data.animations !== undefined ) {
  25938. const objectAnimations = data.animations;
  25939. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  25940. const uuid = objectAnimations[ i ];
  25941. object.animations.push( animations[ uuid ] );
  25942. }
  25943. }
  25944. if ( data.type === 'LOD' ) {
  25945. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  25946. const levels = data.levels;
  25947. for ( let l = 0; l < levels.length; l ++ ) {
  25948. const level = levels[ l ];
  25949. const child = object.getObjectByProperty( 'uuid', level.object );
  25950. if ( child !== undefined ) {
  25951. object.addLevel( child, level.distance );
  25952. }
  25953. }
  25954. }
  25955. return object;
  25956. }
  25957. bindSkeletons( object, skeletons ) {
  25958. if ( Object.keys( skeletons ).length === 0 ) return;
  25959. object.traverse( function ( child ) {
  25960. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  25961. const skeleton = skeletons[ child.skeleton ];
  25962. if ( skeleton === undefined ) {
  25963. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  25964. } else {
  25965. child.bind( skeleton, child.bindMatrix );
  25966. }
  25967. }
  25968. } );
  25969. }
  25970. /* DEPRECATED */
  25971. setTexturePath( value ) {
  25972. console.warn( 'THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().' );
  25973. return this.setResourcePath( value );
  25974. }
  25975. }
  25976. const TEXTURE_MAPPING = {
  25977. UVMapping: UVMapping,
  25978. CubeReflectionMapping: CubeReflectionMapping,
  25979. CubeRefractionMapping: CubeRefractionMapping,
  25980. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  25981. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  25982. CubeUVReflectionMapping: CubeUVReflectionMapping,
  25983. CubeUVRefractionMapping: CubeUVRefractionMapping
  25984. };
  25985. const TEXTURE_WRAPPING = {
  25986. RepeatWrapping: RepeatWrapping,
  25987. ClampToEdgeWrapping: ClampToEdgeWrapping,
  25988. MirroredRepeatWrapping: MirroredRepeatWrapping
  25989. };
  25990. const TEXTURE_FILTER = {
  25991. NearestFilter: NearestFilter,
  25992. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  25993. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  25994. LinearFilter: LinearFilter,
  25995. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  25996. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  25997. };
  25998. class ImageBitmapLoader extends Loader {
  25999. constructor( manager ) {
  26000. super( manager );
  26001. if ( typeof createImageBitmap === 'undefined' ) {
  26002. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  26003. }
  26004. if ( typeof fetch === 'undefined' ) {
  26005. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  26006. }
  26007. this.options = { premultiplyAlpha: 'none' };
  26008. }
  26009. setOptions( options ) {
  26010. this.options = options;
  26011. return this;
  26012. }
  26013. load( url, onLoad, onProgress, onError ) {
  26014. if ( url === undefined ) url = '';
  26015. if ( this.path !== undefined ) url = this.path + url;
  26016. url = this.manager.resolveURL( url );
  26017. const scope = this;
  26018. const cached = Cache.get( url );
  26019. if ( cached !== undefined ) {
  26020. scope.manager.itemStart( url );
  26021. setTimeout( function () {
  26022. if ( onLoad ) onLoad( cached );
  26023. scope.manager.itemEnd( url );
  26024. }, 0 );
  26025. return cached;
  26026. }
  26027. const fetchOptions = {};
  26028. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  26029. fetchOptions.headers = this.requestHeader;
  26030. fetch( url, fetchOptions ).then( function ( res ) {
  26031. return res.blob();
  26032. } ).then( function ( blob ) {
  26033. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  26034. } ).then( function ( imageBitmap ) {
  26035. Cache.add( url, imageBitmap );
  26036. if ( onLoad ) onLoad( imageBitmap );
  26037. scope.manager.itemEnd( url );
  26038. } ).catch( function ( e ) {
  26039. if ( onError ) onError( e );
  26040. scope.manager.itemError( url );
  26041. scope.manager.itemEnd( url );
  26042. } );
  26043. scope.manager.itemStart( url );
  26044. }
  26045. }
  26046. ImageBitmapLoader.prototype.isImageBitmapLoader = true;
  26047. class ShapePath {
  26048. constructor() {
  26049. this.type = 'ShapePath';
  26050. this.color = new Color();
  26051. this.subPaths = [];
  26052. this.currentPath = null;
  26053. }
  26054. moveTo( x, y ) {
  26055. this.currentPath = new Path();
  26056. this.subPaths.push( this.currentPath );
  26057. this.currentPath.moveTo( x, y );
  26058. return this;
  26059. }
  26060. lineTo( x, y ) {
  26061. this.currentPath.lineTo( x, y );
  26062. return this;
  26063. }
  26064. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  26065. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  26066. return this;
  26067. }
  26068. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  26069. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  26070. return this;
  26071. }
  26072. splineThru( pts ) {
  26073. this.currentPath.splineThru( pts );
  26074. return this;
  26075. }
  26076. toShapes( isCCW, noHoles ) {
  26077. function toShapesNoHoles( inSubpaths ) {
  26078. const shapes = [];
  26079. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  26080. const tmpPath = inSubpaths[ i ];
  26081. const tmpShape = new Shape();
  26082. tmpShape.curves = tmpPath.curves;
  26083. shapes.push( tmpShape );
  26084. }
  26085. return shapes;
  26086. }
  26087. function isPointInsidePolygon( inPt, inPolygon ) {
  26088. const polyLen = inPolygon.length;
  26089. // inPt on polygon contour => immediate success or
  26090. // toggling of inside/outside at every single! intersection point of an edge
  26091. // with the horizontal line through inPt, left of inPt
  26092. // not counting lowerY endpoints of edges and whole edges on that line
  26093. let inside = false;
  26094. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  26095. let edgeLowPt = inPolygon[ p ];
  26096. let edgeHighPt = inPolygon[ q ];
  26097. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  26098. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  26099. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  26100. // not parallel
  26101. if ( edgeDy < 0 ) {
  26102. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  26103. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  26104. }
  26105. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  26106. if ( inPt.y === edgeLowPt.y ) {
  26107. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  26108. // continue; // no intersection or edgeLowPt => doesn't count !!!
  26109. } else {
  26110. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  26111. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  26112. if ( perpEdge < 0 ) continue;
  26113. inside = ! inside; // true intersection left of inPt
  26114. }
  26115. } else {
  26116. // parallel or collinear
  26117. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  26118. // edge lies on the same horizontal line as inPt
  26119. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  26120. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  26121. // continue;
  26122. }
  26123. }
  26124. return inside;
  26125. }
  26126. const isClockWise = ShapeUtils.isClockWise;
  26127. const subPaths = this.subPaths;
  26128. if ( subPaths.length === 0 ) return [];
  26129. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  26130. let solid, tmpPath, tmpShape;
  26131. const shapes = [];
  26132. if ( subPaths.length === 1 ) {
  26133. tmpPath = subPaths[ 0 ];
  26134. tmpShape = new Shape();
  26135. tmpShape.curves = tmpPath.curves;
  26136. shapes.push( tmpShape );
  26137. return shapes;
  26138. }
  26139. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  26140. holesFirst = isCCW ? ! holesFirst : holesFirst;
  26141. // console.log("Holes first", holesFirst);
  26142. const betterShapeHoles = [];
  26143. const newShapes = [];
  26144. let newShapeHoles = [];
  26145. let mainIdx = 0;
  26146. let tmpPoints;
  26147. newShapes[ mainIdx ] = undefined;
  26148. newShapeHoles[ mainIdx ] = [];
  26149. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  26150. tmpPath = subPaths[ i ];
  26151. tmpPoints = tmpPath.getPoints();
  26152. solid = isClockWise( tmpPoints );
  26153. solid = isCCW ? ! solid : solid;
  26154. if ( solid ) {
  26155. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  26156. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  26157. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  26158. if ( holesFirst ) mainIdx ++;
  26159. newShapeHoles[ mainIdx ] = [];
  26160. //console.log('cw', i);
  26161. } else {
  26162. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  26163. //console.log('ccw', i);
  26164. }
  26165. }
  26166. // only Holes? -> probably all Shapes with wrong orientation
  26167. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  26168. if ( newShapes.length > 1 ) {
  26169. let ambiguous = false;
  26170. const toChange = [];
  26171. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  26172. betterShapeHoles[ sIdx ] = [];
  26173. }
  26174. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  26175. const sho = newShapeHoles[ sIdx ];
  26176. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  26177. const ho = sho[ hIdx ];
  26178. let hole_unassigned = true;
  26179. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  26180. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  26181. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  26182. if ( hole_unassigned ) {
  26183. hole_unassigned = false;
  26184. betterShapeHoles[ s2Idx ].push( ho );
  26185. } else {
  26186. ambiguous = true;
  26187. }
  26188. }
  26189. }
  26190. if ( hole_unassigned ) {
  26191. betterShapeHoles[ sIdx ].push( ho );
  26192. }
  26193. }
  26194. }
  26195. // console.log("ambiguous: ", ambiguous);
  26196. if ( toChange.length > 0 ) {
  26197. // console.log("to change: ", toChange);
  26198. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  26199. }
  26200. }
  26201. let tmpHoles;
  26202. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  26203. tmpShape = newShapes[ i ].s;
  26204. shapes.push( tmpShape );
  26205. tmpHoles = newShapeHoles[ i ];
  26206. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  26207. tmpShape.holes.push( tmpHoles[ j ].h );
  26208. }
  26209. }
  26210. //console.log("shape", shapes);
  26211. return shapes;
  26212. }
  26213. }
  26214. class Font {
  26215. constructor( data ) {
  26216. this.type = 'Font';
  26217. this.data = data;
  26218. }
  26219. generateShapes( text, size = 100 ) {
  26220. const shapes = [];
  26221. const paths = createPaths( text, size, this.data );
  26222. for ( let p = 0, pl = paths.length; p < pl; p ++ ) {
  26223. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  26224. }
  26225. return shapes;
  26226. }
  26227. }
  26228. function createPaths( text, size, data ) {
  26229. const chars = Array.from( text );
  26230. const scale = size / data.resolution;
  26231. const line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  26232. const paths = [];
  26233. let offsetX = 0, offsetY = 0;
  26234. for ( let i = 0; i < chars.length; i ++ ) {
  26235. const char = chars[ i ];
  26236. if ( char === '\n' ) {
  26237. offsetX = 0;
  26238. offsetY -= line_height;
  26239. } else {
  26240. const ret = createPath( char, scale, offsetX, offsetY, data );
  26241. offsetX += ret.offsetX;
  26242. paths.push( ret.path );
  26243. }
  26244. }
  26245. return paths;
  26246. }
  26247. function createPath( char, scale, offsetX, offsetY, data ) {
  26248. const glyph = data.glyphs[ char ] || data.glyphs[ '?' ];
  26249. if ( ! glyph ) {
  26250. console.error( 'THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.' );
  26251. return;
  26252. }
  26253. const path = new ShapePath();
  26254. let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  26255. if ( glyph.o ) {
  26256. const outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  26257. for ( let i = 0, l = outline.length; i < l; ) {
  26258. const action = outline[ i ++ ];
  26259. switch ( action ) {
  26260. case 'm': // moveTo
  26261. x = outline[ i ++ ] * scale + offsetX;
  26262. y = outline[ i ++ ] * scale + offsetY;
  26263. path.moveTo( x, y );
  26264. break;
  26265. case 'l': // lineTo
  26266. x = outline[ i ++ ] * scale + offsetX;
  26267. y = outline[ i ++ ] * scale + offsetY;
  26268. path.lineTo( x, y );
  26269. break;
  26270. case 'q': // quadraticCurveTo
  26271. cpx = outline[ i ++ ] * scale + offsetX;
  26272. cpy = outline[ i ++ ] * scale + offsetY;
  26273. cpx1 = outline[ i ++ ] * scale + offsetX;
  26274. cpy1 = outline[ i ++ ] * scale + offsetY;
  26275. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  26276. break;
  26277. case 'b': // bezierCurveTo
  26278. cpx = outline[ i ++ ] * scale + offsetX;
  26279. cpy = outline[ i ++ ] * scale + offsetY;
  26280. cpx1 = outline[ i ++ ] * scale + offsetX;
  26281. cpy1 = outline[ i ++ ] * scale + offsetY;
  26282. cpx2 = outline[ i ++ ] * scale + offsetX;
  26283. cpy2 = outline[ i ++ ] * scale + offsetY;
  26284. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  26285. break;
  26286. }
  26287. }
  26288. }
  26289. return { offsetX: glyph.ha * scale, path: path };
  26290. }
  26291. Font.prototype.isFont = true;
  26292. class FontLoader extends Loader {
  26293. constructor( manager ) {
  26294. super( manager );
  26295. }
  26296. load( url, onLoad, onProgress, onError ) {
  26297. const scope = this;
  26298. const loader = new FileLoader( this.manager );
  26299. loader.setPath( this.path );
  26300. loader.setRequestHeader( this.requestHeader );
  26301. loader.setWithCredentials( scope.withCredentials );
  26302. loader.load( url, function ( text ) {
  26303. let json;
  26304. try {
  26305. json = JSON.parse( text );
  26306. } catch ( e ) {
  26307. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  26308. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  26309. }
  26310. const font = scope.parse( json );
  26311. if ( onLoad ) onLoad( font );
  26312. }, onProgress, onError );
  26313. }
  26314. parse( json ) {
  26315. return new Font( json );
  26316. }
  26317. }
  26318. let _context;
  26319. const AudioContext = {
  26320. getContext: function () {
  26321. if ( _context === undefined ) {
  26322. _context = new ( window.AudioContext || window.webkitAudioContext )();
  26323. }
  26324. return _context;
  26325. },
  26326. setContext: function ( value ) {
  26327. _context = value;
  26328. }
  26329. };
  26330. class AudioLoader extends Loader {
  26331. constructor( manager ) {
  26332. super( manager );
  26333. }
  26334. load( url, onLoad, onProgress, onError ) {
  26335. const scope = this;
  26336. const loader = new FileLoader( this.manager );
  26337. loader.setResponseType( 'arraybuffer' );
  26338. loader.setPath( this.path );
  26339. loader.setRequestHeader( this.requestHeader );
  26340. loader.setWithCredentials( this.withCredentials );
  26341. loader.load( url, function ( buffer ) {
  26342. try {
  26343. // Create a copy of the buffer. The `decodeAudioData` method
  26344. // detaches the buffer when complete, preventing reuse.
  26345. const bufferCopy = buffer.slice( 0 );
  26346. const context = AudioContext.getContext();
  26347. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  26348. onLoad( audioBuffer );
  26349. } );
  26350. } catch ( e ) {
  26351. if ( onError ) {
  26352. onError( e );
  26353. } else {
  26354. console.error( e );
  26355. }
  26356. scope.manager.itemError( url );
  26357. }
  26358. }, onProgress, onError );
  26359. }
  26360. }
  26361. class HemisphereLightProbe extends LightProbe {
  26362. constructor( skyColor, groundColor, intensity = 1 ) {
  26363. super( undefined, intensity );
  26364. const color1 = new Color().set( skyColor );
  26365. const color2 = new Color().set( groundColor );
  26366. const sky = new Vector3( color1.r, color1.g, color1.b );
  26367. const ground = new Vector3( color2.r, color2.g, color2.b );
  26368. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  26369. const c0 = Math.sqrt( Math.PI );
  26370. const c1 = c0 * Math.sqrt( 0.75 );
  26371. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  26372. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  26373. }
  26374. }
  26375. HemisphereLightProbe.prototype.isHemisphereLightProbe = true;
  26376. class AmbientLightProbe extends LightProbe {
  26377. constructor( color, intensity = 1 ) {
  26378. super( undefined, intensity );
  26379. const color1 = new Color().set( color );
  26380. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  26381. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  26382. }
  26383. }
  26384. AmbientLightProbe.prototype.isAmbientLightProbe = true;
  26385. const _eyeRight = /*@__PURE__*/ new Matrix4();
  26386. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  26387. class StereoCamera {
  26388. constructor() {
  26389. this.type = 'StereoCamera';
  26390. this.aspect = 1;
  26391. this.eyeSep = 0.064;
  26392. this.cameraL = new PerspectiveCamera();
  26393. this.cameraL.layers.enable( 1 );
  26394. this.cameraL.matrixAutoUpdate = false;
  26395. this.cameraR = new PerspectiveCamera();
  26396. this.cameraR.layers.enable( 2 );
  26397. this.cameraR.matrixAutoUpdate = false;
  26398. this._cache = {
  26399. focus: null,
  26400. fov: null,
  26401. aspect: null,
  26402. near: null,
  26403. far: null,
  26404. zoom: null,
  26405. eyeSep: null
  26406. };
  26407. }
  26408. update( camera ) {
  26409. const cache = this._cache;
  26410. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  26411. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  26412. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  26413. if ( needsUpdate ) {
  26414. cache.focus = camera.focus;
  26415. cache.fov = camera.fov;
  26416. cache.aspect = camera.aspect * this.aspect;
  26417. cache.near = camera.near;
  26418. cache.far = camera.far;
  26419. cache.zoom = camera.zoom;
  26420. cache.eyeSep = this.eyeSep;
  26421. // Off-axis stereoscopic effect based on
  26422. // http://paulbourke.net/stereographics/stereorender/
  26423. const projectionMatrix = camera.projectionMatrix.clone();
  26424. const eyeSepHalf = cache.eyeSep / 2;
  26425. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  26426. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  26427. let xmin, xmax;
  26428. // translate xOffset
  26429. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  26430. _eyeRight.elements[ 12 ] = eyeSepHalf;
  26431. // for left eye
  26432. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  26433. xmax = ymax * cache.aspect + eyeSepOnProjection;
  26434. projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  26435. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26436. this.cameraL.projectionMatrix.copy( projectionMatrix );
  26437. // for right eye
  26438. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  26439. xmax = ymax * cache.aspect - eyeSepOnProjection;
  26440. projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  26441. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26442. this.cameraR.projectionMatrix.copy( projectionMatrix );
  26443. }
  26444. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  26445. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  26446. }
  26447. }
  26448. class Clock {
  26449. constructor( autoStart = true ) {
  26450. this.autoStart = autoStart;
  26451. this.startTime = 0;
  26452. this.oldTime = 0;
  26453. this.elapsedTime = 0;
  26454. this.running = false;
  26455. }
  26456. start() {
  26457. this.startTime = now();
  26458. this.oldTime = this.startTime;
  26459. this.elapsedTime = 0;
  26460. this.running = true;
  26461. }
  26462. stop() {
  26463. this.getElapsedTime();
  26464. this.running = false;
  26465. this.autoStart = false;
  26466. }
  26467. getElapsedTime() {
  26468. this.getDelta();
  26469. return this.elapsedTime;
  26470. }
  26471. getDelta() {
  26472. let diff = 0;
  26473. if ( this.autoStart && ! this.running ) {
  26474. this.start();
  26475. return 0;
  26476. }
  26477. if ( this.running ) {
  26478. const newTime = now();
  26479. diff = ( newTime - this.oldTime ) / 1000;
  26480. this.oldTime = newTime;
  26481. this.elapsedTime += diff;
  26482. }
  26483. return diff;
  26484. }
  26485. }
  26486. function now() {
  26487. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  26488. }
  26489. const _position$1 = /*@__PURE__*/ new Vector3();
  26490. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  26491. const _scale$1 = /*@__PURE__*/ new Vector3();
  26492. const _orientation$1 = /*@__PURE__*/ new Vector3();
  26493. class AudioListener extends Object3D {
  26494. constructor() {
  26495. super();
  26496. this.type = 'AudioListener';
  26497. this.context = AudioContext.getContext();
  26498. this.gain = this.context.createGain();
  26499. this.gain.connect( this.context.destination );
  26500. this.filter = null;
  26501. this.timeDelta = 0;
  26502. // private
  26503. this._clock = new Clock();
  26504. }
  26505. getInput() {
  26506. return this.gain;
  26507. }
  26508. removeFilter() {
  26509. if ( this.filter !== null ) {
  26510. this.gain.disconnect( this.filter );
  26511. this.filter.disconnect( this.context.destination );
  26512. this.gain.connect( this.context.destination );
  26513. this.filter = null;
  26514. }
  26515. return this;
  26516. }
  26517. getFilter() {
  26518. return this.filter;
  26519. }
  26520. setFilter( value ) {
  26521. if ( this.filter !== null ) {
  26522. this.gain.disconnect( this.filter );
  26523. this.filter.disconnect( this.context.destination );
  26524. } else {
  26525. this.gain.disconnect( this.context.destination );
  26526. }
  26527. this.filter = value;
  26528. this.gain.connect( this.filter );
  26529. this.filter.connect( this.context.destination );
  26530. return this;
  26531. }
  26532. getMasterVolume() {
  26533. return this.gain.gain.value;
  26534. }
  26535. setMasterVolume( value ) {
  26536. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26537. return this;
  26538. }
  26539. updateMatrixWorld( force ) {
  26540. super.updateMatrixWorld( force );
  26541. const listener = this.context.listener;
  26542. const up = this.up;
  26543. this.timeDelta = this._clock.getDelta();
  26544. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  26545. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  26546. if ( listener.positionX ) {
  26547. // code path for Chrome (see #14393)
  26548. const endTime = this.context.currentTime + this.timeDelta;
  26549. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  26550. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  26551. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  26552. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  26553. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  26554. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  26555. listener.upX.linearRampToValueAtTime( up.x, endTime );
  26556. listener.upY.linearRampToValueAtTime( up.y, endTime );
  26557. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  26558. } else {
  26559. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  26560. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  26561. }
  26562. }
  26563. }
  26564. class Audio extends Object3D {
  26565. constructor( listener ) {
  26566. super();
  26567. this.type = 'Audio';
  26568. this.listener = listener;
  26569. this.context = listener.context;
  26570. this.gain = this.context.createGain();
  26571. this.gain.connect( listener.getInput() );
  26572. this.autoplay = false;
  26573. this.buffer = null;
  26574. this.detune = 0;
  26575. this.loop = false;
  26576. this.loopStart = 0;
  26577. this.loopEnd = 0;
  26578. this.offset = 0;
  26579. this.duration = undefined;
  26580. this.playbackRate = 1;
  26581. this.isPlaying = false;
  26582. this.hasPlaybackControl = true;
  26583. this.source = null;
  26584. this.sourceType = 'empty';
  26585. this._startedAt = 0;
  26586. this._progress = 0;
  26587. this._connected = false;
  26588. this.filters = [];
  26589. }
  26590. getOutput() {
  26591. return this.gain;
  26592. }
  26593. setNodeSource( audioNode ) {
  26594. this.hasPlaybackControl = false;
  26595. this.sourceType = 'audioNode';
  26596. this.source = audioNode;
  26597. this.connect();
  26598. return this;
  26599. }
  26600. setMediaElementSource( mediaElement ) {
  26601. this.hasPlaybackControl = false;
  26602. this.sourceType = 'mediaNode';
  26603. this.source = this.context.createMediaElementSource( mediaElement );
  26604. this.connect();
  26605. return this;
  26606. }
  26607. setMediaStreamSource( mediaStream ) {
  26608. this.hasPlaybackControl = false;
  26609. this.sourceType = 'mediaStreamNode';
  26610. this.source = this.context.createMediaStreamSource( mediaStream );
  26611. this.connect();
  26612. return this;
  26613. }
  26614. setBuffer( audioBuffer ) {
  26615. this.buffer = audioBuffer;
  26616. this.sourceType = 'buffer';
  26617. if ( this.autoplay ) this.play();
  26618. return this;
  26619. }
  26620. play( delay = 0 ) {
  26621. if ( this.isPlaying === true ) {
  26622. console.warn( 'THREE.Audio: Audio is already playing.' );
  26623. return;
  26624. }
  26625. if ( this.hasPlaybackControl === false ) {
  26626. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26627. return;
  26628. }
  26629. this._startedAt = this.context.currentTime + delay;
  26630. const source = this.context.createBufferSource();
  26631. source.buffer = this.buffer;
  26632. source.loop = this.loop;
  26633. source.loopStart = this.loopStart;
  26634. source.loopEnd = this.loopEnd;
  26635. source.onended = this.onEnded.bind( this );
  26636. source.start( this._startedAt, this._progress + this.offset, this.duration );
  26637. this.isPlaying = true;
  26638. this.source = source;
  26639. this.setDetune( this.detune );
  26640. this.setPlaybackRate( this.playbackRate );
  26641. return this.connect();
  26642. }
  26643. pause() {
  26644. if ( this.hasPlaybackControl === false ) {
  26645. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26646. return;
  26647. }
  26648. if ( this.isPlaying === true ) {
  26649. // update current progress
  26650. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  26651. if ( this.loop === true ) {
  26652. // ensure _progress does not exceed duration with looped audios
  26653. this._progress = this._progress % ( this.duration || this.buffer.duration );
  26654. }
  26655. this.source.stop();
  26656. this.source.onended = null;
  26657. this.isPlaying = false;
  26658. }
  26659. return this;
  26660. }
  26661. stop() {
  26662. if ( this.hasPlaybackControl === false ) {
  26663. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26664. return;
  26665. }
  26666. this._progress = 0;
  26667. this.source.stop();
  26668. this.source.onended = null;
  26669. this.isPlaying = false;
  26670. return this;
  26671. }
  26672. connect() {
  26673. if ( this.filters.length > 0 ) {
  26674. this.source.connect( this.filters[ 0 ] );
  26675. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26676. this.filters[ i - 1 ].connect( this.filters[ i ] );
  26677. }
  26678. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  26679. } else {
  26680. this.source.connect( this.getOutput() );
  26681. }
  26682. this._connected = true;
  26683. return this;
  26684. }
  26685. disconnect() {
  26686. if ( this.filters.length > 0 ) {
  26687. this.source.disconnect( this.filters[ 0 ] );
  26688. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26689. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  26690. }
  26691. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  26692. } else {
  26693. this.source.disconnect( this.getOutput() );
  26694. }
  26695. this._connected = false;
  26696. return this;
  26697. }
  26698. getFilters() {
  26699. return this.filters;
  26700. }
  26701. setFilters( value ) {
  26702. if ( ! value ) value = [];
  26703. if ( this._connected === true ) {
  26704. this.disconnect();
  26705. this.filters = value.slice();
  26706. this.connect();
  26707. } else {
  26708. this.filters = value.slice();
  26709. }
  26710. return this;
  26711. }
  26712. setDetune( value ) {
  26713. this.detune = value;
  26714. if ( this.source.detune === undefined ) return; // only set detune when available
  26715. if ( this.isPlaying === true ) {
  26716. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  26717. }
  26718. return this;
  26719. }
  26720. getDetune() {
  26721. return this.detune;
  26722. }
  26723. getFilter() {
  26724. return this.getFilters()[ 0 ];
  26725. }
  26726. setFilter( filter ) {
  26727. return this.setFilters( filter ? [ filter ] : [] );
  26728. }
  26729. setPlaybackRate( value ) {
  26730. if ( this.hasPlaybackControl === false ) {
  26731. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26732. return;
  26733. }
  26734. this.playbackRate = value;
  26735. if ( this.isPlaying === true ) {
  26736. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  26737. }
  26738. return this;
  26739. }
  26740. getPlaybackRate() {
  26741. return this.playbackRate;
  26742. }
  26743. onEnded() {
  26744. this.isPlaying = false;
  26745. }
  26746. getLoop() {
  26747. if ( this.hasPlaybackControl === false ) {
  26748. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26749. return false;
  26750. }
  26751. return this.loop;
  26752. }
  26753. setLoop( value ) {
  26754. if ( this.hasPlaybackControl === false ) {
  26755. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26756. return;
  26757. }
  26758. this.loop = value;
  26759. if ( this.isPlaying === true ) {
  26760. this.source.loop = this.loop;
  26761. }
  26762. return this;
  26763. }
  26764. setLoopStart( value ) {
  26765. this.loopStart = value;
  26766. return this;
  26767. }
  26768. setLoopEnd( value ) {
  26769. this.loopEnd = value;
  26770. return this;
  26771. }
  26772. getVolume() {
  26773. return this.gain.gain.value;
  26774. }
  26775. setVolume( value ) {
  26776. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26777. return this;
  26778. }
  26779. }
  26780. const _position = /*@__PURE__*/ new Vector3();
  26781. const _quaternion = /*@__PURE__*/ new Quaternion();
  26782. const _scale = /*@__PURE__*/ new Vector3();
  26783. const _orientation = /*@__PURE__*/ new Vector3();
  26784. class PositionalAudio extends Audio {
  26785. constructor( listener ) {
  26786. super( listener );
  26787. this.panner = this.context.createPanner();
  26788. this.panner.panningModel = 'HRTF';
  26789. this.panner.connect( this.gain );
  26790. }
  26791. getOutput() {
  26792. return this.panner;
  26793. }
  26794. getRefDistance() {
  26795. return this.panner.refDistance;
  26796. }
  26797. setRefDistance( value ) {
  26798. this.panner.refDistance = value;
  26799. return this;
  26800. }
  26801. getRolloffFactor() {
  26802. return this.panner.rolloffFactor;
  26803. }
  26804. setRolloffFactor( value ) {
  26805. this.panner.rolloffFactor = value;
  26806. return this;
  26807. }
  26808. getDistanceModel() {
  26809. return this.panner.distanceModel;
  26810. }
  26811. setDistanceModel( value ) {
  26812. this.panner.distanceModel = value;
  26813. return this;
  26814. }
  26815. getMaxDistance() {
  26816. return this.panner.maxDistance;
  26817. }
  26818. setMaxDistance( value ) {
  26819. this.panner.maxDistance = value;
  26820. return this;
  26821. }
  26822. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  26823. this.panner.coneInnerAngle = coneInnerAngle;
  26824. this.panner.coneOuterAngle = coneOuterAngle;
  26825. this.panner.coneOuterGain = coneOuterGain;
  26826. return this;
  26827. }
  26828. updateMatrixWorld( force ) {
  26829. super.updateMatrixWorld( force );
  26830. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  26831. this.matrixWorld.decompose( _position, _quaternion, _scale );
  26832. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  26833. const panner = this.panner;
  26834. if ( panner.positionX ) {
  26835. // code path for Chrome and Firefox (see #14393)
  26836. const endTime = this.context.currentTime + this.listener.timeDelta;
  26837. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  26838. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  26839. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  26840. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  26841. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  26842. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  26843. } else {
  26844. panner.setPosition( _position.x, _position.y, _position.z );
  26845. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  26846. }
  26847. }
  26848. }
  26849. class AudioAnalyser {
  26850. constructor( audio, fftSize = 2048 ) {
  26851. this.analyser = audio.context.createAnalyser();
  26852. this.analyser.fftSize = fftSize;
  26853. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  26854. audio.getOutput().connect( this.analyser );
  26855. }
  26856. getFrequencyData() {
  26857. this.analyser.getByteFrequencyData( this.data );
  26858. return this.data;
  26859. }
  26860. getAverageFrequency() {
  26861. let value = 0;
  26862. const data = this.getFrequencyData();
  26863. for ( let i = 0; i < data.length; i ++ ) {
  26864. value += data[ i ];
  26865. }
  26866. return value / data.length;
  26867. }
  26868. }
  26869. class PropertyMixer {
  26870. constructor( binding, typeName, valueSize ) {
  26871. this.binding = binding;
  26872. this.valueSize = valueSize;
  26873. let mixFunction,
  26874. mixFunctionAdditive,
  26875. setIdentity;
  26876. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  26877. //
  26878. // interpolators can use .buffer as their .result
  26879. // the data then goes to 'incoming'
  26880. //
  26881. // 'accu0' and 'accu1' are used frame-interleaved for
  26882. // the cumulative result and are compared to detect
  26883. // changes
  26884. //
  26885. // 'orig' stores the original state of the property
  26886. //
  26887. // 'add' is used for additive cumulative results
  26888. //
  26889. // 'work' is optional and is only present for quaternion types. It is used
  26890. // to store intermediate quaternion multiplication results
  26891. switch ( typeName ) {
  26892. case 'quaternion':
  26893. mixFunction = this._slerp;
  26894. mixFunctionAdditive = this._slerpAdditive;
  26895. setIdentity = this._setAdditiveIdentityQuaternion;
  26896. this.buffer = new Float64Array( valueSize * 6 );
  26897. this._workIndex = 5;
  26898. break;
  26899. case 'string':
  26900. case 'bool':
  26901. mixFunction = this._select;
  26902. // Use the regular mix function and for additive on these types,
  26903. // additive is not relevant for non-numeric types
  26904. mixFunctionAdditive = this._select;
  26905. setIdentity = this._setAdditiveIdentityOther;
  26906. this.buffer = new Array( valueSize * 5 );
  26907. break;
  26908. default:
  26909. mixFunction = this._lerp;
  26910. mixFunctionAdditive = this._lerpAdditive;
  26911. setIdentity = this._setAdditiveIdentityNumeric;
  26912. this.buffer = new Float64Array( valueSize * 5 );
  26913. }
  26914. this._mixBufferRegion = mixFunction;
  26915. this._mixBufferRegionAdditive = mixFunctionAdditive;
  26916. this._setIdentity = setIdentity;
  26917. this._origIndex = 3;
  26918. this._addIndex = 4;
  26919. this.cumulativeWeight = 0;
  26920. this.cumulativeWeightAdditive = 0;
  26921. this.useCount = 0;
  26922. this.referenceCount = 0;
  26923. }
  26924. // accumulate data in the 'incoming' region into 'accu<i>'
  26925. accumulate( accuIndex, weight ) {
  26926. // note: happily accumulating nothing when weight = 0, the caller knows
  26927. // the weight and shouldn't have made the call in the first place
  26928. const buffer = this.buffer,
  26929. stride = this.valueSize,
  26930. offset = accuIndex * stride + stride;
  26931. let currentWeight = this.cumulativeWeight;
  26932. if ( currentWeight === 0 ) {
  26933. // accuN := incoming * weight
  26934. for ( let i = 0; i !== stride; ++ i ) {
  26935. buffer[ offset + i ] = buffer[ i ];
  26936. }
  26937. currentWeight = weight;
  26938. } else {
  26939. // accuN := accuN + incoming * weight
  26940. currentWeight += weight;
  26941. const mix = weight / currentWeight;
  26942. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  26943. }
  26944. this.cumulativeWeight = currentWeight;
  26945. }
  26946. // accumulate data in the 'incoming' region into 'add'
  26947. accumulateAdditive( weight ) {
  26948. const buffer = this.buffer,
  26949. stride = this.valueSize,
  26950. offset = stride * this._addIndex;
  26951. if ( this.cumulativeWeightAdditive === 0 ) {
  26952. // add = identity
  26953. this._setIdentity();
  26954. }
  26955. // add := add + incoming * weight
  26956. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  26957. this.cumulativeWeightAdditive += weight;
  26958. }
  26959. // apply the state of 'accu<i>' to the binding when accus differ
  26960. apply( accuIndex ) {
  26961. const stride = this.valueSize,
  26962. buffer = this.buffer,
  26963. offset = accuIndex * stride + stride,
  26964. weight = this.cumulativeWeight,
  26965. weightAdditive = this.cumulativeWeightAdditive,
  26966. binding = this.binding;
  26967. this.cumulativeWeight = 0;
  26968. this.cumulativeWeightAdditive = 0;
  26969. if ( weight < 1 ) {
  26970. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26971. const originalValueOffset = stride * this._origIndex;
  26972. this._mixBufferRegion(
  26973. buffer, offset, originalValueOffset, 1 - weight, stride );
  26974. }
  26975. if ( weightAdditive > 0 ) {
  26976. // accuN := accuN + additive accuN
  26977. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  26978. }
  26979. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  26980. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  26981. // value has changed -> update scene graph
  26982. binding.setValue( buffer, offset );
  26983. break;
  26984. }
  26985. }
  26986. }
  26987. // remember the state of the bound property and copy it to both accus
  26988. saveOriginalState() {
  26989. const binding = this.binding;
  26990. const buffer = this.buffer,
  26991. stride = this.valueSize,
  26992. originalValueOffset = stride * this._origIndex;
  26993. binding.getValue( buffer, originalValueOffset );
  26994. // accu[0..1] := orig -- initially detect changes against the original
  26995. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  26996. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  26997. }
  26998. // Add to identity for additive
  26999. this._setIdentity();
  27000. this.cumulativeWeight = 0;
  27001. this.cumulativeWeightAdditive = 0;
  27002. }
  27003. // apply the state previously taken via 'saveOriginalState' to the binding
  27004. restoreOriginalState() {
  27005. const originalValueOffset = this.valueSize * 3;
  27006. this.binding.setValue( this.buffer, originalValueOffset );
  27007. }
  27008. _setAdditiveIdentityNumeric() {
  27009. const startIndex = this._addIndex * this.valueSize;
  27010. const endIndex = startIndex + this.valueSize;
  27011. for ( let i = startIndex; i < endIndex; i ++ ) {
  27012. this.buffer[ i ] = 0;
  27013. }
  27014. }
  27015. _setAdditiveIdentityQuaternion() {
  27016. this._setAdditiveIdentityNumeric();
  27017. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  27018. }
  27019. _setAdditiveIdentityOther() {
  27020. const startIndex = this._origIndex * this.valueSize;
  27021. const targetIndex = this._addIndex * this.valueSize;
  27022. for ( let i = 0; i < this.valueSize; i ++ ) {
  27023. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  27024. }
  27025. }
  27026. // mix functions
  27027. _select( buffer, dstOffset, srcOffset, t, stride ) {
  27028. if ( t >= 0.5 ) {
  27029. for ( let i = 0; i !== stride; ++ i ) {
  27030. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  27031. }
  27032. }
  27033. }
  27034. _slerp( buffer, dstOffset, srcOffset, t ) {
  27035. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  27036. }
  27037. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  27038. const workOffset = this._workIndex * stride;
  27039. // Store result in intermediate buffer offset
  27040. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  27041. // Slerp to the intermediate result
  27042. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  27043. }
  27044. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  27045. const s = 1 - t;
  27046. for ( let i = 0; i !== stride; ++ i ) {
  27047. const j = dstOffset + i;
  27048. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  27049. }
  27050. }
  27051. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  27052. for ( let i = 0; i !== stride; ++ i ) {
  27053. const j = dstOffset + i;
  27054. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  27055. }
  27056. }
  27057. }
  27058. // Characters [].:/ are reserved for track binding syntax.
  27059. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  27060. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  27061. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  27062. // only latin characters, and the unicode \p{L} is not yet supported. So
  27063. // instead, we exclude reserved characters and match everything else.
  27064. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  27065. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  27066. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  27067. // be matched to parse the rest of the track name.
  27068. const _directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  27069. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  27070. const _nodeRe = /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  27071. // Object on target node, and accessor. May not contain reserved
  27072. // characters. Accessor may contain any character except closing bracket.
  27073. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  27074. // Property and accessor. May not contain reserved characters. Accessor may
  27075. // contain any non-bracket characters.
  27076. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  27077. const _trackRe = new RegExp( ''
  27078. + '^'
  27079. + _directoryRe
  27080. + _nodeRe
  27081. + _objectRe
  27082. + _propertyRe
  27083. + '$'
  27084. );
  27085. const _supportedObjectNames = [ 'material', 'materials', 'bones' ];
  27086. class Composite {
  27087. constructor( targetGroup, path, optionalParsedPath ) {
  27088. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  27089. this._targetGroup = targetGroup;
  27090. this._bindings = targetGroup.subscribe_( path, parsedPath );
  27091. }
  27092. getValue( array, offset ) {
  27093. this.bind(); // bind all binding
  27094. const firstValidIndex = this._targetGroup.nCachedObjects_,
  27095. binding = this._bindings[ firstValidIndex ];
  27096. // and only call .getValue on the first
  27097. if ( binding !== undefined ) binding.getValue( array, offset );
  27098. }
  27099. setValue( array, offset ) {
  27100. const bindings = this._bindings;
  27101. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  27102. bindings[ i ].setValue( array, offset );
  27103. }
  27104. }
  27105. bind() {
  27106. const bindings = this._bindings;
  27107. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  27108. bindings[ i ].bind();
  27109. }
  27110. }
  27111. unbind() {
  27112. const bindings = this._bindings;
  27113. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  27114. bindings[ i ].unbind();
  27115. }
  27116. }
  27117. }
  27118. // Note: This class uses a State pattern on a per-method basis:
  27119. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  27120. // prototype version of these methods with one that represents
  27121. // the bound state. When the property is not found, the methods
  27122. // become no-ops.
  27123. class PropertyBinding {
  27124. constructor( rootNode, path, parsedPath ) {
  27125. this.path = path;
  27126. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  27127. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  27128. this.rootNode = rootNode;
  27129. // initial state of these methods that calls 'bind'
  27130. this.getValue = this._getValue_unbound;
  27131. this.setValue = this._setValue_unbound;
  27132. }
  27133. static create( root, path, parsedPath ) {
  27134. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  27135. return new PropertyBinding( root, path, parsedPath );
  27136. } else {
  27137. return new PropertyBinding.Composite( root, path, parsedPath );
  27138. }
  27139. }
  27140. /**
  27141. * Replaces spaces with underscores and removes unsupported characters from
  27142. * node names, to ensure compatibility with parseTrackName().
  27143. *
  27144. * @param {string} name Node name to be sanitized.
  27145. * @return {string}
  27146. */
  27147. static sanitizeNodeName( name ) {
  27148. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  27149. }
  27150. static parseTrackName( trackName ) {
  27151. const matches = _trackRe.exec( trackName );
  27152. if ( ! matches ) {
  27153. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  27154. }
  27155. const results = {
  27156. // directoryName: matches[ 1 ], // (tschw) currently unused
  27157. nodeName: matches[ 2 ],
  27158. objectName: matches[ 3 ],
  27159. objectIndex: matches[ 4 ],
  27160. propertyName: matches[ 5 ], // required
  27161. propertyIndex: matches[ 6 ]
  27162. };
  27163. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  27164. if ( lastDot !== undefined && lastDot !== - 1 ) {
  27165. const objectName = results.nodeName.substring( lastDot + 1 );
  27166. // Object names must be checked against an allowlist. Otherwise, there
  27167. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  27168. // 'bar' could be the objectName, or part of a nodeName (which can
  27169. // include '.' characters).
  27170. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  27171. results.nodeName = results.nodeName.substring( 0, lastDot );
  27172. results.objectName = objectName;
  27173. }
  27174. }
  27175. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  27176. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  27177. }
  27178. return results;
  27179. }
  27180. static findNode( root, nodeName ) {
  27181. if ( ! nodeName || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  27182. return root;
  27183. }
  27184. // search into skeleton bones.
  27185. if ( root.skeleton ) {
  27186. const bone = root.skeleton.getBoneByName( nodeName );
  27187. if ( bone !== undefined ) {
  27188. return bone;
  27189. }
  27190. }
  27191. // search into node subtree.
  27192. if ( root.children ) {
  27193. const searchNodeSubtree = function ( children ) {
  27194. for ( let i = 0; i < children.length; i ++ ) {
  27195. const childNode = children[ i ];
  27196. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  27197. return childNode;
  27198. }
  27199. const result = searchNodeSubtree( childNode.children );
  27200. if ( result ) return result;
  27201. }
  27202. return null;
  27203. };
  27204. const subTreeNode = searchNodeSubtree( root.children );
  27205. if ( subTreeNode ) {
  27206. return subTreeNode;
  27207. }
  27208. }
  27209. return null;
  27210. }
  27211. // these are used to "bind" a nonexistent property
  27212. _getValue_unavailable() {}
  27213. _setValue_unavailable() {}
  27214. // Getters
  27215. _getValue_direct( buffer, offset ) {
  27216. buffer[ offset ] = this.targetObject[ this.propertyName ];
  27217. }
  27218. _getValue_array( buffer, offset ) {
  27219. const source = this.resolvedProperty;
  27220. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  27221. buffer[ offset ++ ] = source[ i ];
  27222. }
  27223. }
  27224. _getValue_arrayElement( buffer, offset ) {
  27225. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  27226. }
  27227. _getValue_toArray( buffer, offset ) {
  27228. this.resolvedProperty.toArray( buffer, offset );
  27229. }
  27230. // Direct
  27231. _setValue_direct( buffer, offset ) {
  27232. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27233. }
  27234. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  27235. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27236. this.targetObject.needsUpdate = true;
  27237. }
  27238. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27239. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27240. this.targetObject.matrixWorldNeedsUpdate = true;
  27241. }
  27242. // EntireArray
  27243. _setValue_array( buffer, offset ) {
  27244. const dest = this.resolvedProperty;
  27245. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27246. dest[ i ] = buffer[ offset ++ ];
  27247. }
  27248. }
  27249. _setValue_array_setNeedsUpdate( buffer, offset ) {
  27250. const dest = this.resolvedProperty;
  27251. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27252. dest[ i ] = buffer[ offset ++ ];
  27253. }
  27254. this.targetObject.needsUpdate = true;
  27255. }
  27256. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27257. const dest = this.resolvedProperty;
  27258. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27259. dest[ i ] = buffer[ offset ++ ];
  27260. }
  27261. this.targetObject.matrixWorldNeedsUpdate = true;
  27262. }
  27263. // ArrayElement
  27264. _setValue_arrayElement( buffer, offset ) {
  27265. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27266. }
  27267. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  27268. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27269. this.targetObject.needsUpdate = true;
  27270. }
  27271. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27272. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27273. this.targetObject.matrixWorldNeedsUpdate = true;
  27274. }
  27275. // HasToFromArray
  27276. _setValue_fromArray( buffer, offset ) {
  27277. this.resolvedProperty.fromArray( buffer, offset );
  27278. }
  27279. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  27280. this.resolvedProperty.fromArray( buffer, offset );
  27281. this.targetObject.needsUpdate = true;
  27282. }
  27283. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27284. this.resolvedProperty.fromArray( buffer, offset );
  27285. this.targetObject.matrixWorldNeedsUpdate = true;
  27286. }
  27287. _getValue_unbound( targetArray, offset ) {
  27288. this.bind();
  27289. this.getValue( targetArray, offset );
  27290. }
  27291. _setValue_unbound( sourceArray, offset ) {
  27292. this.bind();
  27293. this.setValue( sourceArray, offset );
  27294. }
  27295. // create getter / setter pair for a property in the scene graph
  27296. bind() {
  27297. let targetObject = this.node;
  27298. const parsedPath = this.parsedPath;
  27299. const objectName = parsedPath.objectName;
  27300. const propertyName = parsedPath.propertyName;
  27301. let propertyIndex = parsedPath.propertyIndex;
  27302. if ( ! targetObject ) {
  27303. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  27304. this.node = targetObject;
  27305. }
  27306. // set fail state so we can just 'return' on error
  27307. this.getValue = this._getValue_unavailable;
  27308. this.setValue = this._setValue_unavailable;
  27309. // ensure there is a value node
  27310. if ( ! targetObject ) {
  27311. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  27312. return;
  27313. }
  27314. if ( objectName ) {
  27315. let objectIndex = parsedPath.objectIndex;
  27316. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  27317. switch ( objectName ) {
  27318. case 'materials':
  27319. if ( ! targetObject.material ) {
  27320. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  27321. return;
  27322. }
  27323. if ( ! targetObject.material.materials ) {
  27324. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  27325. return;
  27326. }
  27327. targetObject = targetObject.material.materials;
  27328. break;
  27329. case 'bones':
  27330. if ( ! targetObject.skeleton ) {
  27331. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  27332. return;
  27333. }
  27334. // potential future optimization: skip this if propertyIndex is already an integer
  27335. // and convert the integer string to a true integer.
  27336. targetObject = targetObject.skeleton.bones;
  27337. // support resolving morphTarget names into indices.
  27338. for ( let i = 0; i < targetObject.length; i ++ ) {
  27339. if ( targetObject[ i ].name === objectIndex ) {
  27340. objectIndex = i;
  27341. break;
  27342. }
  27343. }
  27344. break;
  27345. default:
  27346. if ( targetObject[ objectName ] === undefined ) {
  27347. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  27348. return;
  27349. }
  27350. targetObject = targetObject[ objectName ];
  27351. }
  27352. if ( objectIndex !== undefined ) {
  27353. if ( targetObject[ objectIndex ] === undefined ) {
  27354. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  27355. return;
  27356. }
  27357. targetObject = targetObject[ objectIndex ];
  27358. }
  27359. }
  27360. // resolve property
  27361. const nodeProperty = targetObject[ propertyName ];
  27362. if ( nodeProperty === undefined ) {
  27363. const nodeName = parsedPath.nodeName;
  27364. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  27365. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  27366. return;
  27367. }
  27368. // determine versioning scheme
  27369. let versioning = this.Versioning.None;
  27370. this.targetObject = targetObject;
  27371. if ( targetObject.needsUpdate !== undefined ) { // material
  27372. versioning = this.Versioning.NeedsUpdate;
  27373. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  27374. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  27375. }
  27376. // determine how the property gets bound
  27377. let bindingType = this.BindingType.Direct;
  27378. if ( propertyIndex !== undefined ) {
  27379. // access a sub element of the property array (only primitives are supported right now)
  27380. if ( propertyName === 'morphTargetInfluences' ) {
  27381. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  27382. // support resolving morphTarget names into indices.
  27383. if ( ! targetObject.geometry ) {
  27384. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  27385. return;
  27386. }
  27387. if ( targetObject.geometry.isBufferGeometry ) {
  27388. if ( ! targetObject.geometry.morphAttributes ) {
  27389. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  27390. return;
  27391. }
  27392. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  27393. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  27394. }
  27395. } else {
  27396. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this );
  27397. return;
  27398. }
  27399. }
  27400. bindingType = this.BindingType.ArrayElement;
  27401. this.resolvedProperty = nodeProperty;
  27402. this.propertyIndex = propertyIndex;
  27403. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  27404. // must use copy for Object3D.Euler/Quaternion
  27405. bindingType = this.BindingType.HasFromToArray;
  27406. this.resolvedProperty = nodeProperty;
  27407. } else if ( Array.isArray( nodeProperty ) ) {
  27408. bindingType = this.BindingType.EntireArray;
  27409. this.resolvedProperty = nodeProperty;
  27410. } else {
  27411. this.propertyName = propertyName;
  27412. }
  27413. // select getter / setter
  27414. this.getValue = this.GetterByBindingType[ bindingType ];
  27415. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  27416. }
  27417. unbind() {
  27418. this.node = null;
  27419. // back to the prototype version of getValue / setValue
  27420. // note: avoiding to mutate the shape of 'this' via 'delete'
  27421. this.getValue = this._getValue_unbound;
  27422. this.setValue = this._setValue_unbound;
  27423. }
  27424. }
  27425. PropertyBinding.Composite = Composite;
  27426. PropertyBinding.prototype.BindingType = {
  27427. Direct: 0,
  27428. EntireArray: 1,
  27429. ArrayElement: 2,
  27430. HasFromToArray: 3
  27431. };
  27432. PropertyBinding.prototype.Versioning = {
  27433. None: 0,
  27434. NeedsUpdate: 1,
  27435. MatrixWorldNeedsUpdate: 2
  27436. };
  27437. PropertyBinding.prototype.GetterByBindingType = [
  27438. PropertyBinding.prototype._getValue_direct,
  27439. PropertyBinding.prototype._getValue_array,
  27440. PropertyBinding.prototype._getValue_arrayElement,
  27441. PropertyBinding.prototype._getValue_toArray,
  27442. ];
  27443. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  27444. [
  27445. // Direct
  27446. PropertyBinding.prototype._setValue_direct,
  27447. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  27448. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  27449. ], [
  27450. // EntireArray
  27451. PropertyBinding.prototype._setValue_array,
  27452. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  27453. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  27454. ], [
  27455. // ArrayElement
  27456. PropertyBinding.prototype._setValue_arrayElement,
  27457. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  27458. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  27459. ], [
  27460. // HasToFromArray
  27461. PropertyBinding.prototype._setValue_fromArray,
  27462. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  27463. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  27464. ]
  27465. ];
  27466. /**
  27467. *
  27468. * A group of objects that receives a shared animation state.
  27469. *
  27470. * Usage:
  27471. *
  27472. * - Add objects you would otherwise pass as 'root' to the
  27473. * constructor or the .clipAction method of AnimationMixer.
  27474. *
  27475. * - Instead pass this object as 'root'.
  27476. *
  27477. * - You can also add and remove objects later when the mixer
  27478. * is running.
  27479. *
  27480. * Note:
  27481. *
  27482. * Objects of this class appear as one object to the mixer,
  27483. * so cache control of the individual objects must be done
  27484. * on the group.
  27485. *
  27486. * Limitation:
  27487. *
  27488. * - The animated properties must be compatible among the
  27489. * all objects in the group.
  27490. *
  27491. * - A single property can either be controlled through a
  27492. * target group or directly, but not both.
  27493. */
  27494. class AnimationObjectGroup {
  27495. constructor() {
  27496. this.uuid = generateUUID();
  27497. // cached objects followed by the active ones
  27498. this._objects = Array.prototype.slice.call( arguments );
  27499. this.nCachedObjects_ = 0; // threshold
  27500. // note: read by PropertyBinding.Composite
  27501. const indices = {};
  27502. this._indicesByUUID = indices; // for bookkeeping
  27503. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27504. indices[ arguments[ i ].uuid ] = i;
  27505. }
  27506. this._paths = []; // inside: string
  27507. this._parsedPaths = []; // inside: { we don't care, here }
  27508. this._bindings = []; // inside: Array< PropertyBinding >
  27509. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  27510. const scope = this;
  27511. this.stats = {
  27512. objects: {
  27513. get total() {
  27514. return scope._objects.length;
  27515. },
  27516. get inUse() {
  27517. return this.total - scope.nCachedObjects_;
  27518. }
  27519. },
  27520. get bindingsPerObject() {
  27521. return scope._bindings.length;
  27522. }
  27523. };
  27524. }
  27525. add() {
  27526. const objects = this._objects,
  27527. indicesByUUID = this._indicesByUUID,
  27528. paths = this._paths,
  27529. parsedPaths = this._parsedPaths,
  27530. bindings = this._bindings,
  27531. nBindings = bindings.length;
  27532. let knownObject = undefined,
  27533. nObjects = objects.length,
  27534. nCachedObjects = this.nCachedObjects_;
  27535. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27536. const object = arguments[ i ],
  27537. uuid = object.uuid;
  27538. let index = indicesByUUID[ uuid ];
  27539. if ( index === undefined ) {
  27540. // unknown object -> add it to the ACTIVE region
  27541. index = nObjects ++;
  27542. indicesByUUID[ uuid ] = index;
  27543. objects.push( object );
  27544. // accounting is done, now do the same for all bindings
  27545. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27546. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  27547. }
  27548. } else if ( index < nCachedObjects ) {
  27549. knownObject = objects[ index ];
  27550. // move existing object to the ACTIVE region
  27551. const firstActiveIndex = -- nCachedObjects,
  27552. lastCachedObject = objects[ firstActiveIndex ];
  27553. indicesByUUID[ lastCachedObject.uuid ] = index;
  27554. objects[ index ] = lastCachedObject;
  27555. indicesByUUID[ uuid ] = firstActiveIndex;
  27556. objects[ firstActiveIndex ] = object;
  27557. // accounting is done, now do the same for all bindings
  27558. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27559. const bindingsForPath = bindings[ j ],
  27560. lastCached = bindingsForPath[ firstActiveIndex ];
  27561. let binding = bindingsForPath[ index ];
  27562. bindingsForPath[ index ] = lastCached;
  27563. if ( binding === undefined ) {
  27564. // since we do not bother to create new bindings
  27565. // for objects that are cached, the binding may
  27566. // or may not exist
  27567. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  27568. }
  27569. bindingsForPath[ firstActiveIndex ] = binding;
  27570. }
  27571. } else if ( objects[ index ] !== knownObject ) {
  27572. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  27573. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  27574. } // else the object is already where we want it to be
  27575. } // for arguments
  27576. this.nCachedObjects_ = nCachedObjects;
  27577. }
  27578. remove() {
  27579. const objects = this._objects,
  27580. indicesByUUID = this._indicesByUUID,
  27581. bindings = this._bindings,
  27582. nBindings = bindings.length;
  27583. let nCachedObjects = this.nCachedObjects_;
  27584. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27585. const object = arguments[ i ],
  27586. uuid = object.uuid,
  27587. index = indicesByUUID[ uuid ];
  27588. if ( index !== undefined && index >= nCachedObjects ) {
  27589. // move existing object into the CACHED region
  27590. const lastCachedIndex = nCachedObjects ++,
  27591. firstActiveObject = objects[ lastCachedIndex ];
  27592. indicesByUUID[ firstActiveObject.uuid ] = index;
  27593. objects[ index ] = firstActiveObject;
  27594. indicesByUUID[ uuid ] = lastCachedIndex;
  27595. objects[ lastCachedIndex ] = object;
  27596. // accounting is done, now do the same for all bindings
  27597. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27598. const bindingsForPath = bindings[ j ],
  27599. firstActive = bindingsForPath[ lastCachedIndex ],
  27600. binding = bindingsForPath[ index ];
  27601. bindingsForPath[ index ] = firstActive;
  27602. bindingsForPath[ lastCachedIndex ] = binding;
  27603. }
  27604. }
  27605. } // for arguments
  27606. this.nCachedObjects_ = nCachedObjects;
  27607. }
  27608. // remove & forget
  27609. uncache() {
  27610. const objects = this._objects,
  27611. indicesByUUID = this._indicesByUUID,
  27612. bindings = this._bindings,
  27613. nBindings = bindings.length;
  27614. let nCachedObjects = this.nCachedObjects_,
  27615. nObjects = objects.length;
  27616. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27617. const object = arguments[ i ],
  27618. uuid = object.uuid,
  27619. index = indicesByUUID[ uuid ];
  27620. if ( index !== undefined ) {
  27621. delete indicesByUUID[ uuid ];
  27622. if ( index < nCachedObjects ) {
  27623. // object is cached, shrink the CACHED region
  27624. const firstActiveIndex = -- nCachedObjects,
  27625. lastCachedObject = objects[ firstActiveIndex ],
  27626. lastIndex = -- nObjects,
  27627. lastObject = objects[ lastIndex ];
  27628. // last cached object takes this object's place
  27629. indicesByUUID[ lastCachedObject.uuid ] = index;
  27630. objects[ index ] = lastCachedObject;
  27631. // last object goes to the activated slot and pop
  27632. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  27633. objects[ firstActiveIndex ] = lastObject;
  27634. objects.pop();
  27635. // accounting is done, now do the same for all bindings
  27636. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27637. const bindingsForPath = bindings[ j ],
  27638. lastCached = bindingsForPath[ firstActiveIndex ],
  27639. last = bindingsForPath[ lastIndex ];
  27640. bindingsForPath[ index ] = lastCached;
  27641. bindingsForPath[ firstActiveIndex ] = last;
  27642. bindingsForPath.pop();
  27643. }
  27644. } else {
  27645. // object is active, just swap with the last and pop
  27646. const lastIndex = -- nObjects,
  27647. lastObject = objects[ lastIndex ];
  27648. if ( lastIndex > 0 ) {
  27649. indicesByUUID[ lastObject.uuid ] = index;
  27650. }
  27651. objects[ index ] = lastObject;
  27652. objects.pop();
  27653. // accounting is done, now do the same for all bindings
  27654. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27655. const bindingsForPath = bindings[ j ];
  27656. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  27657. bindingsForPath.pop();
  27658. }
  27659. } // cached or active
  27660. } // if object is known
  27661. } // for arguments
  27662. this.nCachedObjects_ = nCachedObjects;
  27663. }
  27664. // Internal interface used by befriended PropertyBinding.Composite:
  27665. subscribe_( path, parsedPath ) {
  27666. // returns an array of bindings for the given path that is changed
  27667. // according to the contained objects in the group
  27668. const indicesByPath = this._bindingsIndicesByPath;
  27669. let index = indicesByPath[ path ];
  27670. const bindings = this._bindings;
  27671. if ( index !== undefined ) return bindings[ index ];
  27672. const paths = this._paths,
  27673. parsedPaths = this._parsedPaths,
  27674. objects = this._objects,
  27675. nObjects = objects.length,
  27676. nCachedObjects = this.nCachedObjects_,
  27677. bindingsForPath = new Array( nObjects );
  27678. index = bindings.length;
  27679. indicesByPath[ path ] = index;
  27680. paths.push( path );
  27681. parsedPaths.push( parsedPath );
  27682. bindings.push( bindingsForPath );
  27683. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  27684. const object = objects[ i ];
  27685. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  27686. }
  27687. return bindingsForPath;
  27688. }
  27689. unsubscribe_( path ) {
  27690. // tells the group to forget about a property path and no longer
  27691. // update the array previously obtained with 'subscribe_'
  27692. const indicesByPath = this._bindingsIndicesByPath,
  27693. index = indicesByPath[ path ];
  27694. if ( index !== undefined ) {
  27695. const paths = this._paths,
  27696. parsedPaths = this._parsedPaths,
  27697. bindings = this._bindings,
  27698. lastBindingsIndex = bindings.length - 1,
  27699. lastBindings = bindings[ lastBindingsIndex ],
  27700. lastBindingsPath = path[ lastBindingsIndex ];
  27701. indicesByPath[ lastBindingsPath ] = index;
  27702. bindings[ index ] = lastBindings;
  27703. bindings.pop();
  27704. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  27705. parsedPaths.pop();
  27706. paths[ index ] = paths[ lastBindingsIndex ];
  27707. paths.pop();
  27708. }
  27709. }
  27710. }
  27711. AnimationObjectGroup.prototype.isAnimationObjectGroup = true;
  27712. class AnimationAction {
  27713. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  27714. this._mixer = mixer;
  27715. this._clip = clip;
  27716. this._localRoot = localRoot;
  27717. this.blendMode = blendMode;
  27718. const tracks = clip.tracks,
  27719. nTracks = tracks.length,
  27720. interpolants = new Array( nTracks );
  27721. const interpolantSettings = {
  27722. endingStart: ZeroCurvatureEnding,
  27723. endingEnd: ZeroCurvatureEnding
  27724. };
  27725. for ( let i = 0; i !== nTracks; ++ i ) {
  27726. const interpolant = tracks[ i ].createInterpolant( null );
  27727. interpolants[ i ] = interpolant;
  27728. interpolant.settings = interpolantSettings;
  27729. }
  27730. this._interpolantSettings = interpolantSettings;
  27731. this._interpolants = interpolants; // bound by the mixer
  27732. // inside: PropertyMixer (managed by the mixer)
  27733. this._propertyBindings = new Array( nTracks );
  27734. this._cacheIndex = null; // for the memory manager
  27735. this._byClipCacheIndex = null; // for the memory manager
  27736. this._timeScaleInterpolant = null;
  27737. this._weightInterpolant = null;
  27738. this.loop = LoopRepeat;
  27739. this._loopCount = - 1;
  27740. // global mixer time when the action is to be started
  27741. // it's set back to 'null' upon start of the action
  27742. this._startTime = null;
  27743. // scaled local time of the action
  27744. // gets clamped or wrapped to 0..clip.duration according to loop
  27745. this.time = 0;
  27746. this.timeScale = 1;
  27747. this._effectiveTimeScale = 1;
  27748. this.weight = 1;
  27749. this._effectiveWeight = 1;
  27750. this.repetitions = Infinity; // no. of repetitions when looping
  27751. this.paused = false; // true -> zero effective time scale
  27752. this.enabled = true; // false -> zero effective weight
  27753. this.clampWhenFinished = false;// keep feeding the last frame?
  27754. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  27755. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  27756. }
  27757. // State & Scheduling
  27758. play() {
  27759. this._mixer._activateAction( this );
  27760. return this;
  27761. }
  27762. stop() {
  27763. this._mixer._deactivateAction( this );
  27764. return this.reset();
  27765. }
  27766. reset() {
  27767. this.paused = false;
  27768. this.enabled = true;
  27769. this.time = 0; // restart clip
  27770. this._loopCount = - 1;// forget previous loops
  27771. this._startTime = null;// forget scheduling
  27772. return this.stopFading().stopWarping();
  27773. }
  27774. isRunning() {
  27775. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  27776. this._startTime === null && this._mixer._isActiveAction( this );
  27777. }
  27778. // return true when play has been called
  27779. isScheduled() {
  27780. return this._mixer._isActiveAction( this );
  27781. }
  27782. startAt( time ) {
  27783. this._startTime = time;
  27784. return this;
  27785. }
  27786. setLoop( mode, repetitions ) {
  27787. this.loop = mode;
  27788. this.repetitions = repetitions;
  27789. return this;
  27790. }
  27791. // Weight
  27792. // set the weight stopping any scheduled fading
  27793. // although .enabled = false yields an effective weight of zero, this
  27794. // method does *not* change .enabled, because it would be confusing
  27795. setEffectiveWeight( weight ) {
  27796. this.weight = weight;
  27797. // note: same logic as when updated at runtime
  27798. this._effectiveWeight = this.enabled ? weight : 0;
  27799. return this.stopFading();
  27800. }
  27801. // return the weight considering fading and .enabled
  27802. getEffectiveWeight() {
  27803. return this._effectiveWeight;
  27804. }
  27805. fadeIn( duration ) {
  27806. return this._scheduleFading( duration, 0, 1 );
  27807. }
  27808. fadeOut( duration ) {
  27809. return this._scheduleFading( duration, 1, 0 );
  27810. }
  27811. crossFadeFrom( fadeOutAction, duration, warp ) {
  27812. fadeOutAction.fadeOut( duration );
  27813. this.fadeIn( duration );
  27814. if ( warp ) {
  27815. const fadeInDuration = this._clip.duration,
  27816. fadeOutDuration = fadeOutAction._clip.duration,
  27817. startEndRatio = fadeOutDuration / fadeInDuration,
  27818. endStartRatio = fadeInDuration / fadeOutDuration;
  27819. fadeOutAction.warp( 1.0, startEndRatio, duration );
  27820. this.warp( endStartRatio, 1.0, duration );
  27821. }
  27822. return this;
  27823. }
  27824. crossFadeTo( fadeInAction, duration, warp ) {
  27825. return fadeInAction.crossFadeFrom( this, duration, warp );
  27826. }
  27827. stopFading() {
  27828. const weightInterpolant = this._weightInterpolant;
  27829. if ( weightInterpolant !== null ) {
  27830. this._weightInterpolant = null;
  27831. this._mixer._takeBackControlInterpolant( weightInterpolant );
  27832. }
  27833. return this;
  27834. }
  27835. // Time Scale Control
  27836. // set the time scale stopping any scheduled warping
  27837. // although .paused = true yields an effective time scale of zero, this
  27838. // method does *not* change .paused, because it would be confusing
  27839. setEffectiveTimeScale( timeScale ) {
  27840. this.timeScale = timeScale;
  27841. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  27842. return this.stopWarping();
  27843. }
  27844. // return the time scale considering warping and .paused
  27845. getEffectiveTimeScale() {
  27846. return this._effectiveTimeScale;
  27847. }
  27848. setDuration( duration ) {
  27849. this.timeScale = this._clip.duration / duration;
  27850. return this.stopWarping();
  27851. }
  27852. syncWith( action ) {
  27853. this.time = action.time;
  27854. this.timeScale = action.timeScale;
  27855. return this.stopWarping();
  27856. }
  27857. halt( duration ) {
  27858. return this.warp( this._effectiveTimeScale, 0, duration );
  27859. }
  27860. warp( startTimeScale, endTimeScale, duration ) {
  27861. const mixer = this._mixer,
  27862. now = mixer.time,
  27863. timeScale = this.timeScale;
  27864. let interpolant = this._timeScaleInterpolant;
  27865. if ( interpolant === null ) {
  27866. interpolant = mixer._lendControlInterpolant();
  27867. this._timeScaleInterpolant = interpolant;
  27868. }
  27869. const times = interpolant.parameterPositions,
  27870. values = interpolant.sampleValues;
  27871. times[ 0 ] = now;
  27872. times[ 1 ] = now + duration;
  27873. values[ 0 ] = startTimeScale / timeScale;
  27874. values[ 1 ] = endTimeScale / timeScale;
  27875. return this;
  27876. }
  27877. stopWarping() {
  27878. const timeScaleInterpolant = this._timeScaleInterpolant;
  27879. if ( timeScaleInterpolant !== null ) {
  27880. this._timeScaleInterpolant = null;
  27881. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  27882. }
  27883. return this;
  27884. }
  27885. // Object Accessors
  27886. getMixer() {
  27887. return this._mixer;
  27888. }
  27889. getClip() {
  27890. return this._clip;
  27891. }
  27892. getRoot() {
  27893. return this._localRoot || this._mixer._root;
  27894. }
  27895. // Interna
  27896. _update( time, deltaTime, timeDirection, accuIndex ) {
  27897. // called by the mixer
  27898. if ( ! this.enabled ) {
  27899. // call ._updateWeight() to update ._effectiveWeight
  27900. this._updateWeight( time );
  27901. return;
  27902. }
  27903. const startTime = this._startTime;
  27904. if ( startTime !== null ) {
  27905. // check for scheduled start of action
  27906. const timeRunning = ( time - startTime ) * timeDirection;
  27907. if ( timeRunning < 0 || timeDirection === 0 ) {
  27908. return; // yet to come / don't decide when delta = 0
  27909. }
  27910. // start
  27911. this._startTime = null; // unschedule
  27912. deltaTime = timeDirection * timeRunning;
  27913. }
  27914. // apply time scale and advance time
  27915. deltaTime *= this._updateTimeScale( time );
  27916. const clipTime = this._updateTime( deltaTime );
  27917. // note: _updateTime may disable the action resulting in
  27918. // an effective weight of 0
  27919. const weight = this._updateWeight( time );
  27920. if ( weight > 0 ) {
  27921. const interpolants = this._interpolants;
  27922. const propertyMixers = this._propertyBindings;
  27923. switch ( this.blendMode ) {
  27924. case AdditiveAnimationBlendMode:
  27925. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27926. interpolants[ j ].evaluate( clipTime );
  27927. propertyMixers[ j ].accumulateAdditive( weight );
  27928. }
  27929. break;
  27930. case NormalAnimationBlendMode:
  27931. default:
  27932. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27933. interpolants[ j ].evaluate( clipTime );
  27934. propertyMixers[ j ].accumulate( accuIndex, weight );
  27935. }
  27936. }
  27937. }
  27938. }
  27939. _updateWeight( time ) {
  27940. let weight = 0;
  27941. if ( this.enabled ) {
  27942. weight = this.weight;
  27943. const interpolant = this._weightInterpolant;
  27944. if ( interpolant !== null ) {
  27945. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27946. weight *= interpolantValue;
  27947. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27948. this.stopFading();
  27949. if ( interpolantValue === 0 ) {
  27950. // faded out, disable
  27951. this.enabled = false;
  27952. }
  27953. }
  27954. }
  27955. }
  27956. this._effectiveWeight = weight;
  27957. return weight;
  27958. }
  27959. _updateTimeScale( time ) {
  27960. let timeScale = 0;
  27961. if ( ! this.paused ) {
  27962. timeScale = this.timeScale;
  27963. const interpolant = this._timeScaleInterpolant;
  27964. if ( interpolant !== null ) {
  27965. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27966. timeScale *= interpolantValue;
  27967. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27968. this.stopWarping();
  27969. if ( timeScale === 0 ) {
  27970. // motion has halted, pause
  27971. this.paused = true;
  27972. } else {
  27973. // warp done - apply final time scale
  27974. this.timeScale = timeScale;
  27975. }
  27976. }
  27977. }
  27978. }
  27979. this._effectiveTimeScale = timeScale;
  27980. return timeScale;
  27981. }
  27982. _updateTime( deltaTime ) {
  27983. const duration = this._clip.duration;
  27984. const loop = this.loop;
  27985. let time = this.time + deltaTime;
  27986. let loopCount = this._loopCount;
  27987. const pingPong = ( loop === LoopPingPong );
  27988. if ( deltaTime === 0 ) {
  27989. if ( loopCount === - 1 ) return time;
  27990. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  27991. }
  27992. if ( loop === LoopOnce ) {
  27993. if ( loopCount === - 1 ) {
  27994. // just started
  27995. this._loopCount = 0;
  27996. this._setEndings( true, true, false );
  27997. }
  27998. handle_stop: {
  27999. if ( time >= duration ) {
  28000. time = duration;
  28001. } else if ( time < 0 ) {
  28002. time = 0;
  28003. } else {
  28004. this.time = time;
  28005. break handle_stop;
  28006. }
  28007. if ( this.clampWhenFinished ) this.paused = true;
  28008. else this.enabled = false;
  28009. this.time = time;
  28010. this._mixer.dispatchEvent( {
  28011. type: 'finished', action: this,
  28012. direction: deltaTime < 0 ? - 1 : 1
  28013. } );
  28014. }
  28015. } else { // repetitive Repeat or PingPong
  28016. if ( loopCount === - 1 ) {
  28017. // just started
  28018. if ( deltaTime >= 0 ) {
  28019. loopCount = 0;
  28020. this._setEndings( true, this.repetitions === 0, pingPong );
  28021. } else {
  28022. // when looping in reverse direction, the initial
  28023. // transition through zero counts as a repetition,
  28024. // so leave loopCount at -1
  28025. this._setEndings( this.repetitions === 0, true, pingPong );
  28026. }
  28027. }
  28028. if ( time >= duration || time < 0 ) {
  28029. // wrap around
  28030. const loopDelta = Math.floor( time / duration ); // signed
  28031. time -= duration * loopDelta;
  28032. loopCount += Math.abs( loopDelta );
  28033. const pending = this.repetitions - loopCount;
  28034. if ( pending <= 0 ) {
  28035. // have to stop (switch state, clamp time, fire event)
  28036. if ( this.clampWhenFinished ) this.paused = true;
  28037. else this.enabled = false;
  28038. time = deltaTime > 0 ? duration : 0;
  28039. this.time = time;
  28040. this._mixer.dispatchEvent( {
  28041. type: 'finished', action: this,
  28042. direction: deltaTime > 0 ? 1 : - 1
  28043. } );
  28044. } else {
  28045. // keep running
  28046. if ( pending === 1 ) {
  28047. // entering the last round
  28048. const atStart = deltaTime < 0;
  28049. this._setEndings( atStart, ! atStart, pingPong );
  28050. } else {
  28051. this._setEndings( false, false, pingPong );
  28052. }
  28053. this._loopCount = loopCount;
  28054. this.time = time;
  28055. this._mixer.dispatchEvent( {
  28056. type: 'loop', action: this, loopDelta: loopDelta
  28057. } );
  28058. }
  28059. } else {
  28060. this.time = time;
  28061. }
  28062. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  28063. // invert time for the "pong round"
  28064. return duration - time;
  28065. }
  28066. }
  28067. return time;
  28068. }
  28069. _setEndings( atStart, atEnd, pingPong ) {
  28070. const settings = this._interpolantSettings;
  28071. if ( pingPong ) {
  28072. settings.endingStart = ZeroSlopeEnding;
  28073. settings.endingEnd = ZeroSlopeEnding;
  28074. } else {
  28075. // assuming for LoopOnce atStart == atEnd == true
  28076. if ( atStart ) {
  28077. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  28078. } else {
  28079. settings.endingStart = WrapAroundEnding;
  28080. }
  28081. if ( atEnd ) {
  28082. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  28083. } else {
  28084. settings.endingEnd = WrapAroundEnding;
  28085. }
  28086. }
  28087. }
  28088. _scheduleFading( duration, weightNow, weightThen ) {
  28089. const mixer = this._mixer, now = mixer.time;
  28090. let interpolant = this._weightInterpolant;
  28091. if ( interpolant === null ) {
  28092. interpolant = mixer._lendControlInterpolant();
  28093. this._weightInterpolant = interpolant;
  28094. }
  28095. const times = interpolant.parameterPositions,
  28096. values = interpolant.sampleValues;
  28097. times[ 0 ] = now;
  28098. values[ 0 ] = weightNow;
  28099. times[ 1 ] = now + duration;
  28100. values[ 1 ] = weightThen;
  28101. return this;
  28102. }
  28103. }
  28104. class AnimationMixer extends EventDispatcher {
  28105. constructor( root ) {
  28106. super();
  28107. this._root = root;
  28108. this._initMemoryManager();
  28109. this._accuIndex = 0;
  28110. this.time = 0;
  28111. this.timeScale = 1.0;
  28112. }
  28113. _bindAction( action, prototypeAction ) {
  28114. const root = action._localRoot || this._root,
  28115. tracks = action._clip.tracks,
  28116. nTracks = tracks.length,
  28117. bindings = action._propertyBindings,
  28118. interpolants = action._interpolants,
  28119. rootUuid = root.uuid,
  28120. bindingsByRoot = this._bindingsByRootAndName;
  28121. let bindingsByName = bindingsByRoot[ rootUuid ];
  28122. if ( bindingsByName === undefined ) {
  28123. bindingsByName = {};
  28124. bindingsByRoot[ rootUuid ] = bindingsByName;
  28125. }
  28126. for ( let i = 0; i !== nTracks; ++ i ) {
  28127. const track = tracks[ i ],
  28128. trackName = track.name;
  28129. let binding = bindingsByName[ trackName ];
  28130. if ( binding !== undefined ) {
  28131. bindings[ i ] = binding;
  28132. } else {
  28133. binding = bindings[ i ];
  28134. if ( binding !== undefined ) {
  28135. // existing binding, make sure the cache knows
  28136. if ( binding._cacheIndex === null ) {
  28137. ++ binding.referenceCount;
  28138. this._addInactiveBinding( binding, rootUuid, trackName );
  28139. }
  28140. continue;
  28141. }
  28142. const path = prototypeAction && prototypeAction.
  28143. _propertyBindings[ i ].binding.parsedPath;
  28144. binding = new PropertyMixer(
  28145. PropertyBinding.create( root, trackName, path ),
  28146. track.ValueTypeName, track.getValueSize() );
  28147. ++ binding.referenceCount;
  28148. this._addInactiveBinding( binding, rootUuid, trackName );
  28149. bindings[ i ] = binding;
  28150. }
  28151. interpolants[ i ].resultBuffer = binding.buffer;
  28152. }
  28153. }
  28154. _activateAction( action ) {
  28155. if ( ! this._isActiveAction( action ) ) {
  28156. if ( action._cacheIndex === null ) {
  28157. // this action has been forgotten by the cache, but the user
  28158. // appears to be still using it -> rebind
  28159. const rootUuid = ( action._localRoot || this._root ).uuid,
  28160. clipUuid = action._clip.uuid,
  28161. actionsForClip = this._actionsByClip[ clipUuid ];
  28162. this._bindAction( action,
  28163. actionsForClip && actionsForClip.knownActions[ 0 ] );
  28164. this._addInactiveAction( action, clipUuid, rootUuid );
  28165. }
  28166. const bindings = action._propertyBindings;
  28167. // increment reference counts / sort out state
  28168. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28169. const binding = bindings[ i ];
  28170. if ( binding.useCount ++ === 0 ) {
  28171. this._lendBinding( binding );
  28172. binding.saveOriginalState();
  28173. }
  28174. }
  28175. this._lendAction( action );
  28176. }
  28177. }
  28178. _deactivateAction( action ) {
  28179. if ( this._isActiveAction( action ) ) {
  28180. const bindings = action._propertyBindings;
  28181. // decrement reference counts / sort out state
  28182. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28183. const binding = bindings[ i ];
  28184. if ( -- binding.useCount === 0 ) {
  28185. binding.restoreOriginalState();
  28186. this._takeBackBinding( binding );
  28187. }
  28188. }
  28189. this._takeBackAction( action );
  28190. }
  28191. }
  28192. // Memory manager
  28193. _initMemoryManager() {
  28194. this._actions = []; // 'nActiveActions' followed by inactive ones
  28195. this._nActiveActions = 0;
  28196. this._actionsByClip = {};
  28197. // inside:
  28198. // {
  28199. // knownActions: Array< AnimationAction > - used as prototypes
  28200. // actionByRoot: AnimationAction - lookup
  28201. // }
  28202. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  28203. this._nActiveBindings = 0;
  28204. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  28205. this._controlInterpolants = []; // same game as above
  28206. this._nActiveControlInterpolants = 0;
  28207. const scope = this;
  28208. this.stats = {
  28209. actions: {
  28210. get total() {
  28211. return scope._actions.length;
  28212. },
  28213. get inUse() {
  28214. return scope._nActiveActions;
  28215. }
  28216. },
  28217. bindings: {
  28218. get total() {
  28219. return scope._bindings.length;
  28220. },
  28221. get inUse() {
  28222. return scope._nActiveBindings;
  28223. }
  28224. },
  28225. controlInterpolants: {
  28226. get total() {
  28227. return scope._controlInterpolants.length;
  28228. },
  28229. get inUse() {
  28230. return scope._nActiveControlInterpolants;
  28231. }
  28232. }
  28233. };
  28234. }
  28235. // Memory management for AnimationAction objects
  28236. _isActiveAction( action ) {
  28237. const index = action._cacheIndex;
  28238. return index !== null && index < this._nActiveActions;
  28239. }
  28240. _addInactiveAction( action, clipUuid, rootUuid ) {
  28241. const actions = this._actions,
  28242. actionsByClip = this._actionsByClip;
  28243. let actionsForClip = actionsByClip[ clipUuid ];
  28244. if ( actionsForClip === undefined ) {
  28245. actionsForClip = {
  28246. knownActions: [ action ],
  28247. actionByRoot: {}
  28248. };
  28249. action._byClipCacheIndex = 0;
  28250. actionsByClip[ clipUuid ] = actionsForClip;
  28251. } else {
  28252. const knownActions = actionsForClip.knownActions;
  28253. action._byClipCacheIndex = knownActions.length;
  28254. knownActions.push( action );
  28255. }
  28256. action._cacheIndex = actions.length;
  28257. actions.push( action );
  28258. actionsForClip.actionByRoot[ rootUuid ] = action;
  28259. }
  28260. _removeInactiveAction( action ) {
  28261. const actions = this._actions,
  28262. lastInactiveAction = actions[ actions.length - 1 ],
  28263. cacheIndex = action._cacheIndex;
  28264. lastInactiveAction._cacheIndex = cacheIndex;
  28265. actions[ cacheIndex ] = lastInactiveAction;
  28266. actions.pop();
  28267. action._cacheIndex = null;
  28268. const clipUuid = action._clip.uuid,
  28269. actionsByClip = this._actionsByClip,
  28270. actionsForClip = actionsByClip[ clipUuid ],
  28271. knownActionsForClip = actionsForClip.knownActions,
  28272. lastKnownAction =
  28273. knownActionsForClip[ knownActionsForClip.length - 1 ],
  28274. byClipCacheIndex = action._byClipCacheIndex;
  28275. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  28276. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  28277. knownActionsForClip.pop();
  28278. action._byClipCacheIndex = null;
  28279. const actionByRoot = actionsForClip.actionByRoot,
  28280. rootUuid = ( action._localRoot || this._root ).uuid;
  28281. delete actionByRoot[ rootUuid ];
  28282. if ( knownActionsForClip.length === 0 ) {
  28283. delete actionsByClip[ clipUuid ];
  28284. }
  28285. this._removeInactiveBindingsForAction( action );
  28286. }
  28287. _removeInactiveBindingsForAction( action ) {
  28288. const bindings = action._propertyBindings;
  28289. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28290. const binding = bindings[ i ];
  28291. if ( -- binding.referenceCount === 0 ) {
  28292. this._removeInactiveBinding( binding );
  28293. }
  28294. }
  28295. }
  28296. _lendAction( action ) {
  28297. // [ active actions | inactive actions ]
  28298. // [ active actions >| inactive actions ]
  28299. // s a
  28300. // <-swap->
  28301. // a s
  28302. const actions = this._actions,
  28303. prevIndex = action._cacheIndex,
  28304. lastActiveIndex = this._nActiveActions ++,
  28305. firstInactiveAction = actions[ lastActiveIndex ];
  28306. action._cacheIndex = lastActiveIndex;
  28307. actions[ lastActiveIndex ] = action;
  28308. firstInactiveAction._cacheIndex = prevIndex;
  28309. actions[ prevIndex ] = firstInactiveAction;
  28310. }
  28311. _takeBackAction( action ) {
  28312. // [ active actions | inactive actions ]
  28313. // [ active actions |< inactive actions ]
  28314. // a s
  28315. // <-swap->
  28316. // s a
  28317. const actions = this._actions,
  28318. prevIndex = action._cacheIndex,
  28319. firstInactiveIndex = -- this._nActiveActions,
  28320. lastActiveAction = actions[ firstInactiveIndex ];
  28321. action._cacheIndex = firstInactiveIndex;
  28322. actions[ firstInactiveIndex ] = action;
  28323. lastActiveAction._cacheIndex = prevIndex;
  28324. actions[ prevIndex ] = lastActiveAction;
  28325. }
  28326. // Memory management for PropertyMixer objects
  28327. _addInactiveBinding( binding, rootUuid, trackName ) {
  28328. const bindingsByRoot = this._bindingsByRootAndName,
  28329. bindings = this._bindings;
  28330. let bindingByName = bindingsByRoot[ rootUuid ];
  28331. if ( bindingByName === undefined ) {
  28332. bindingByName = {};
  28333. bindingsByRoot[ rootUuid ] = bindingByName;
  28334. }
  28335. bindingByName[ trackName ] = binding;
  28336. binding._cacheIndex = bindings.length;
  28337. bindings.push( binding );
  28338. }
  28339. _removeInactiveBinding( binding ) {
  28340. const bindings = this._bindings,
  28341. propBinding = binding.binding,
  28342. rootUuid = propBinding.rootNode.uuid,
  28343. trackName = propBinding.path,
  28344. bindingsByRoot = this._bindingsByRootAndName,
  28345. bindingByName = bindingsByRoot[ rootUuid ],
  28346. lastInactiveBinding = bindings[ bindings.length - 1 ],
  28347. cacheIndex = binding._cacheIndex;
  28348. lastInactiveBinding._cacheIndex = cacheIndex;
  28349. bindings[ cacheIndex ] = lastInactiveBinding;
  28350. bindings.pop();
  28351. delete bindingByName[ trackName ];
  28352. if ( Object.keys( bindingByName ).length === 0 ) {
  28353. delete bindingsByRoot[ rootUuid ];
  28354. }
  28355. }
  28356. _lendBinding( binding ) {
  28357. const bindings = this._bindings,
  28358. prevIndex = binding._cacheIndex,
  28359. lastActiveIndex = this._nActiveBindings ++,
  28360. firstInactiveBinding = bindings[ lastActiveIndex ];
  28361. binding._cacheIndex = lastActiveIndex;
  28362. bindings[ lastActiveIndex ] = binding;
  28363. firstInactiveBinding._cacheIndex = prevIndex;
  28364. bindings[ prevIndex ] = firstInactiveBinding;
  28365. }
  28366. _takeBackBinding( binding ) {
  28367. const bindings = this._bindings,
  28368. prevIndex = binding._cacheIndex,
  28369. firstInactiveIndex = -- this._nActiveBindings,
  28370. lastActiveBinding = bindings[ firstInactiveIndex ];
  28371. binding._cacheIndex = firstInactiveIndex;
  28372. bindings[ firstInactiveIndex ] = binding;
  28373. lastActiveBinding._cacheIndex = prevIndex;
  28374. bindings[ prevIndex ] = lastActiveBinding;
  28375. }
  28376. // Memory management of Interpolants for weight and time scale
  28377. _lendControlInterpolant() {
  28378. const interpolants = this._controlInterpolants,
  28379. lastActiveIndex = this._nActiveControlInterpolants ++;
  28380. let interpolant = interpolants[ lastActiveIndex ];
  28381. if ( interpolant === undefined ) {
  28382. interpolant = new LinearInterpolant(
  28383. new Float32Array( 2 ), new Float32Array( 2 ),
  28384. 1, this._controlInterpolantsResultBuffer );
  28385. interpolant.__cacheIndex = lastActiveIndex;
  28386. interpolants[ lastActiveIndex ] = interpolant;
  28387. }
  28388. return interpolant;
  28389. }
  28390. _takeBackControlInterpolant( interpolant ) {
  28391. const interpolants = this._controlInterpolants,
  28392. prevIndex = interpolant.__cacheIndex,
  28393. firstInactiveIndex = -- this._nActiveControlInterpolants,
  28394. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  28395. interpolant.__cacheIndex = firstInactiveIndex;
  28396. interpolants[ firstInactiveIndex ] = interpolant;
  28397. lastActiveInterpolant.__cacheIndex = prevIndex;
  28398. interpolants[ prevIndex ] = lastActiveInterpolant;
  28399. }
  28400. // return an action for a clip optionally using a custom root target
  28401. // object (this method allocates a lot of dynamic memory in case a
  28402. // previously unknown clip/root combination is specified)
  28403. clipAction( clip, optionalRoot, blendMode ) {
  28404. const root = optionalRoot || this._root,
  28405. rootUuid = root.uuid;
  28406. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  28407. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  28408. const actionsForClip = this._actionsByClip[ clipUuid ];
  28409. let prototypeAction = null;
  28410. if ( blendMode === undefined ) {
  28411. if ( clipObject !== null ) {
  28412. blendMode = clipObject.blendMode;
  28413. } else {
  28414. blendMode = NormalAnimationBlendMode;
  28415. }
  28416. }
  28417. if ( actionsForClip !== undefined ) {
  28418. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  28419. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  28420. return existingAction;
  28421. }
  28422. // we know the clip, so we don't have to parse all
  28423. // the bindings again but can just copy
  28424. prototypeAction = actionsForClip.knownActions[ 0 ];
  28425. // also, take the clip from the prototype action
  28426. if ( clipObject === null )
  28427. clipObject = prototypeAction._clip;
  28428. }
  28429. // clip must be known when specified via string
  28430. if ( clipObject === null ) return null;
  28431. // allocate all resources required to run it
  28432. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  28433. this._bindAction( newAction, prototypeAction );
  28434. // and make the action known to the memory manager
  28435. this._addInactiveAction( newAction, clipUuid, rootUuid );
  28436. return newAction;
  28437. }
  28438. // get an existing action
  28439. existingAction( clip, optionalRoot ) {
  28440. const root = optionalRoot || this._root,
  28441. rootUuid = root.uuid,
  28442. clipObject = typeof clip === 'string' ?
  28443. AnimationClip.findByName( root, clip ) : clip,
  28444. clipUuid = clipObject ? clipObject.uuid : clip,
  28445. actionsForClip = this._actionsByClip[ clipUuid ];
  28446. if ( actionsForClip !== undefined ) {
  28447. return actionsForClip.actionByRoot[ rootUuid ] || null;
  28448. }
  28449. return null;
  28450. }
  28451. // deactivates all previously scheduled actions
  28452. stopAllAction() {
  28453. const actions = this._actions,
  28454. nActions = this._nActiveActions;
  28455. for ( let i = nActions - 1; i >= 0; -- i ) {
  28456. actions[ i ].stop();
  28457. }
  28458. return this;
  28459. }
  28460. // advance the time and update apply the animation
  28461. update( deltaTime ) {
  28462. deltaTime *= this.timeScale;
  28463. const actions = this._actions,
  28464. nActions = this._nActiveActions,
  28465. time = this.time += deltaTime,
  28466. timeDirection = Math.sign( deltaTime ),
  28467. accuIndex = this._accuIndex ^= 1;
  28468. // run active actions
  28469. for ( let i = 0; i !== nActions; ++ i ) {
  28470. const action = actions[ i ];
  28471. action._update( time, deltaTime, timeDirection, accuIndex );
  28472. }
  28473. // update scene graph
  28474. const bindings = this._bindings,
  28475. nBindings = this._nActiveBindings;
  28476. for ( let i = 0; i !== nBindings; ++ i ) {
  28477. bindings[ i ].apply( accuIndex );
  28478. }
  28479. return this;
  28480. }
  28481. // Allows you to seek to a specific time in an animation.
  28482. setTime( timeInSeconds ) {
  28483. this.time = 0; // Zero out time attribute for AnimationMixer object;
  28484. for ( let i = 0; i < this._actions.length; i ++ ) {
  28485. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  28486. }
  28487. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  28488. }
  28489. // return this mixer's root target object
  28490. getRoot() {
  28491. return this._root;
  28492. }
  28493. // free all resources specific to a particular clip
  28494. uncacheClip( clip ) {
  28495. const actions = this._actions,
  28496. clipUuid = clip.uuid,
  28497. actionsByClip = this._actionsByClip,
  28498. actionsForClip = actionsByClip[ clipUuid ];
  28499. if ( actionsForClip !== undefined ) {
  28500. // note: just calling _removeInactiveAction would mess up the
  28501. // iteration state and also require updating the state we can
  28502. // just throw away
  28503. const actionsToRemove = actionsForClip.knownActions;
  28504. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  28505. const action = actionsToRemove[ i ];
  28506. this._deactivateAction( action );
  28507. const cacheIndex = action._cacheIndex,
  28508. lastInactiveAction = actions[ actions.length - 1 ];
  28509. action._cacheIndex = null;
  28510. action._byClipCacheIndex = null;
  28511. lastInactiveAction._cacheIndex = cacheIndex;
  28512. actions[ cacheIndex ] = lastInactiveAction;
  28513. actions.pop();
  28514. this._removeInactiveBindingsForAction( action );
  28515. }
  28516. delete actionsByClip[ clipUuid ];
  28517. }
  28518. }
  28519. // free all resources specific to a particular root target object
  28520. uncacheRoot( root ) {
  28521. const rootUuid = root.uuid,
  28522. actionsByClip = this._actionsByClip;
  28523. for ( const clipUuid in actionsByClip ) {
  28524. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  28525. action = actionByRoot[ rootUuid ];
  28526. if ( action !== undefined ) {
  28527. this._deactivateAction( action );
  28528. this._removeInactiveAction( action );
  28529. }
  28530. }
  28531. const bindingsByRoot = this._bindingsByRootAndName,
  28532. bindingByName = bindingsByRoot[ rootUuid ];
  28533. if ( bindingByName !== undefined ) {
  28534. for ( const trackName in bindingByName ) {
  28535. const binding = bindingByName[ trackName ];
  28536. binding.restoreOriginalState();
  28537. this._removeInactiveBinding( binding );
  28538. }
  28539. }
  28540. }
  28541. // remove a targeted clip from the cache
  28542. uncacheAction( clip, optionalRoot ) {
  28543. const action = this.existingAction( clip, optionalRoot );
  28544. if ( action !== null ) {
  28545. this._deactivateAction( action );
  28546. this._removeInactiveAction( action );
  28547. }
  28548. }
  28549. }
  28550. AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array( 1 );
  28551. class Uniform {
  28552. constructor( value ) {
  28553. if ( typeof value === 'string' ) {
  28554. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  28555. value = arguments[ 1 ];
  28556. }
  28557. this.value = value;
  28558. }
  28559. clone() {
  28560. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  28561. }
  28562. }
  28563. class InstancedInterleavedBuffer extends InterleavedBuffer {
  28564. constructor( array, stride, meshPerAttribute = 1 ) {
  28565. super( array, stride );
  28566. this.meshPerAttribute = meshPerAttribute;
  28567. }
  28568. copy( source ) {
  28569. super.copy( source );
  28570. this.meshPerAttribute = source.meshPerAttribute;
  28571. return this;
  28572. }
  28573. clone( data ) {
  28574. const ib = super.clone( data );
  28575. ib.meshPerAttribute = this.meshPerAttribute;
  28576. return ib;
  28577. }
  28578. toJSON( data ) {
  28579. const json = super.toJSON( data );
  28580. json.isInstancedInterleavedBuffer = true;
  28581. json.meshPerAttribute = this.meshPerAttribute;
  28582. return json;
  28583. }
  28584. }
  28585. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  28586. class GLBufferAttribute {
  28587. constructor( buffer, type, itemSize, elementSize, count ) {
  28588. this.buffer = buffer;
  28589. this.type = type;
  28590. this.itemSize = itemSize;
  28591. this.elementSize = elementSize;
  28592. this.count = count;
  28593. this.version = 0;
  28594. }
  28595. set needsUpdate( value ) {
  28596. if ( value === true ) this.version ++;
  28597. }
  28598. setBuffer( buffer ) {
  28599. this.buffer = buffer;
  28600. return this;
  28601. }
  28602. setType( type, elementSize ) {
  28603. this.type = type;
  28604. this.elementSize = elementSize;
  28605. return this;
  28606. }
  28607. setItemSize( itemSize ) {
  28608. this.itemSize = itemSize;
  28609. return this;
  28610. }
  28611. setCount( count ) {
  28612. this.count = count;
  28613. return this;
  28614. }
  28615. }
  28616. GLBufferAttribute.prototype.isGLBufferAttribute = true;
  28617. class Raycaster {
  28618. constructor( origin, direction, near = 0, far = Infinity ) {
  28619. this.ray = new Ray( origin, direction );
  28620. // direction is assumed to be normalized (for accurate distance calculations)
  28621. this.near = near;
  28622. this.far = far;
  28623. this.camera = null;
  28624. this.layers = new Layers();
  28625. this.params = {
  28626. Mesh: {},
  28627. Line: { threshold: 1 },
  28628. LOD: {},
  28629. Points: { threshold: 1 },
  28630. Sprite: {}
  28631. };
  28632. }
  28633. set( origin, direction ) {
  28634. // direction is assumed to be normalized (for accurate distance calculations)
  28635. this.ray.set( origin, direction );
  28636. }
  28637. setFromCamera( coords, camera ) {
  28638. if ( camera && camera.isPerspectiveCamera ) {
  28639. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  28640. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  28641. this.camera = camera;
  28642. } else if ( camera && camera.isOrthographicCamera ) {
  28643. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  28644. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  28645. this.camera = camera;
  28646. } else {
  28647. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  28648. }
  28649. }
  28650. intersectObject( object, recursive = false, intersects = [] ) {
  28651. intersectObject( object, this, intersects, recursive );
  28652. intersects.sort( ascSort );
  28653. return intersects;
  28654. }
  28655. intersectObjects( objects, recursive = false, intersects = [] ) {
  28656. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  28657. intersectObject( objects[ i ], this, intersects, recursive );
  28658. }
  28659. intersects.sort( ascSort );
  28660. return intersects;
  28661. }
  28662. }
  28663. function ascSort( a, b ) {
  28664. return a.distance - b.distance;
  28665. }
  28666. function intersectObject( object, raycaster, intersects, recursive ) {
  28667. if ( object.layers.test( raycaster.layers ) ) {
  28668. object.raycast( raycaster, intersects );
  28669. }
  28670. if ( recursive === true ) {
  28671. const children = object.children;
  28672. for ( let i = 0, l = children.length; i < l; i ++ ) {
  28673. intersectObject( children[ i ], raycaster, intersects, true );
  28674. }
  28675. }
  28676. }
  28677. /**
  28678. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  28679. *
  28680. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  28681. * The azimuthal angle (theta) is measured from the positive z-axis.
  28682. */
  28683. class Spherical {
  28684. constructor( radius = 1, phi = 0, theta = 0 ) {
  28685. this.radius = radius;
  28686. this.phi = phi; // polar angle
  28687. this.theta = theta; // azimuthal angle
  28688. return this;
  28689. }
  28690. set( radius, phi, theta ) {
  28691. this.radius = radius;
  28692. this.phi = phi;
  28693. this.theta = theta;
  28694. return this;
  28695. }
  28696. copy( other ) {
  28697. this.radius = other.radius;
  28698. this.phi = other.phi;
  28699. this.theta = other.theta;
  28700. return this;
  28701. }
  28702. // restrict phi to be betwee EPS and PI-EPS
  28703. makeSafe() {
  28704. const EPS = 0.000001;
  28705. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  28706. return this;
  28707. }
  28708. setFromVector3( v ) {
  28709. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28710. }
  28711. setFromCartesianCoords( x, y, z ) {
  28712. this.radius = Math.sqrt( x * x + y * y + z * z );
  28713. if ( this.radius === 0 ) {
  28714. this.theta = 0;
  28715. this.phi = 0;
  28716. } else {
  28717. this.theta = Math.atan2( x, z );
  28718. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  28719. }
  28720. return this;
  28721. }
  28722. clone() {
  28723. return new this.constructor().copy( this );
  28724. }
  28725. }
  28726. /**
  28727. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  28728. */
  28729. class Cylindrical {
  28730. constructor( radius = 1, theta = 0, y = 0 ) {
  28731. this.radius = radius; // distance from the origin to a point in the x-z plane
  28732. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  28733. this.y = y; // height above the x-z plane
  28734. return this;
  28735. }
  28736. set( radius, theta, y ) {
  28737. this.radius = radius;
  28738. this.theta = theta;
  28739. this.y = y;
  28740. return this;
  28741. }
  28742. copy( other ) {
  28743. this.radius = other.radius;
  28744. this.theta = other.theta;
  28745. this.y = other.y;
  28746. return this;
  28747. }
  28748. setFromVector3( v ) {
  28749. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28750. }
  28751. setFromCartesianCoords( x, y, z ) {
  28752. this.radius = Math.sqrt( x * x + z * z );
  28753. this.theta = Math.atan2( x, z );
  28754. this.y = y;
  28755. return this;
  28756. }
  28757. clone() {
  28758. return new this.constructor().copy( this );
  28759. }
  28760. }
  28761. const _vector$4 = /*@__PURE__*/ new Vector2();
  28762. class Box2 {
  28763. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  28764. this.min = min;
  28765. this.max = max;
  28766. }
  28767. set( min, max ) {
  28768. this.min.copy( min );
  28769. this.max.copy( max );
  28770. return this;
  28771. }
  28772. setFromPoints( points ) {
  28773. this.makeEmpty();
  28774. for ( let i = 0, il = points.length; i < il; i ++ ) {
  28775. this.expandByPoint( points[ i ] );
  28776. }
  28777. return this;
  28778. }
  28779. setFromCenterAndSize( center, size ) {
  28780. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  28781. this.min.copy( center ).sub( halfSize );
  28782. this.max.copy( center ).add( halfSize );
  28783. return this;
  28784. }
  28785. clone() {
  28786. return new this.constructor().copy( this );
  28787. }
  28788. copy( box ) {
  28789. this.min.copy( box.min );
  28790. this.max.copy( box.max );
  28791. return this;
  28792. }
  28793. makeEmpty() {
  28794. this.min.x = this.min.y = + Infinity;
  28795. this.max.x = this.max.y = - Infinity;
  28796. return this;
  28797. }
  28798. isEmpty() {
  28799. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  28800. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  28801. }
  28802. getCenter( target ) {
  28803. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  28804. }
  28805. getSize( target ) {
  28806. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  28807. }
  28808. expandByPoint( point ) {
  28809. this.min.min( point );
  28810. this.max.max( point );
  28811. return this;
  28812. }
  28813. expandByVector( vector ) {
  28814. this.min.sub( vector );
  28815. this.max.add( vector );
  28816. return this;
  28817. }
  28818. expandByScalar( scalar ) {
  28819. this.min.addScalar( - scalar );
  28820. this.max.addScalar( scalar );
  28821. return this;
  28822. }
  28823. containsPoint( point ) {
  28824. return point.x < this.min.x || point.x > this.max.x ||
  28825. point.y < this.min.y || point.y > this.max.y ? false : true;
  28826. }
  28827. containsBox( box ) {
  28828. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  28829. this.min.y <= box.min.y && box.max.y <= this.max.y;
  28830. }
  28831. getParameter( point, target ) {
  28832. // This can potentially have a divide by zero if the box
  28833. // has a size dimension of 0.
  28834. return target.set(
  28835. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  28836. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  28837. );
  28838. }
  28839. intersectsBox( box ) {
  28840. // using 4 splitting planes to rule out intersections
  28841. return box.max.x < this.min.x || box.min.x > this.max.x ||
  28842. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  28843. }
  28844. clampPoint( point, target ) {
  28845. return target.copy( point ).clamp( this.min, this.max );
  28846. }
  28847. distanceToPoint( point ) {
  28848. const clampedPoint = _vector$4.copy( point ).clamp( this.min, this.max );
  28849. return clampedPoint.sub( point ).length();
  28850. }
  28851. intersect( box ) {
  28852. this.min.max( box.min );
  28853. this.max.min( box.max );
  28854. return this;
  28855. }
  28856. union( box ) {
  28857. this.min.min( box.min );
  28858. this.max.max( box.max );
  28859. return this;
  28860. }
  28861. translate( offset ) {
  28862. this.min.add( offset );
  28863. this.max.add( offset );
  28864. return this;
  28865. }
  28866. equals( box ) {
  28867. return box.min.equals( this.min ) && box.max.equals( this.max );
  28868. }
  28869. }
  28870. Box2.prototype.isBox2 = true;
  28871. const _startP = /*@__PURE__*/ new Vector3();
  28872. const _startEnd = /*@__PURE__*/ new Vector3();
  28873. class Line3 {
  28874. constructor( start = new Vector3(), end = new Vector3() ) {
  28875. this.start = start;
  28876. this.end = end;
  28877. }
  28878. set( start, end ) {
  28879. this.start.copy( start );
  28880. this.end.copy( end );
  28881. return this;
  28882. }
  28883. copy( line ) {
  28884. this.start.copy( line.start );
  28885. this.end.copy( line.end );
  28886. return this;
  28887. }
  28888. getCenter( target ) {
  28889. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  28890. }
  28891. delta( target ) {
  28892. return target.subVectors( this.end, this.start );
  28893. }
  28894. distanceSq() {
  28895. return this.start.distanceToSquared( this.end );
  28896. }
  28897. distance() {
  28898. return this.start.distanceTo( this.end );
  28899. }
  28900. at( t, target ) {
  28901. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28902. }
  28903. closestPointToPointParameter( point, clampToLine ) {
  28904. _startP.subVectors( point, this.start );
  28905. _startEnd.subVectors( this.end, this.start );
  28906. const startEnd2 = _startEnd.dot( _startEnd );
  28907. const startEnd_startP = _startEnd.dot( _startP );
  28908. let t = startEnd_startP / startEnd2;
  28909. if ( clampToLine ) {
  28910. t = clamp( t, 0, 1 );
  28911. }
  28912. return t;
  28913. }
  28914. closestPointToPoint( point, clampToLine, target ) {
  28915. const t = this.closestPointToPointParameter( point, clampToLine );
  28916. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28917. }
  28918. applyMatrix4( matrix ) {
  28919. this.start.applyMatrix4( matrix );
  28920. this.end.applyMatrix4( matrix );
  28921. return this;
  28922. }
  28923. equals( line ) {
  28924. return line.start.equals( this.start ) && line.end.equals( this.end );
  28925. }
  28926. clone() {
  28927. return new this.constructor().copy( this );
  28928. }
  28929. }
  28930. class ImmediateRenderObject extends Object3D {
  28931. constructor( material ) {
  28932. super();
  28933. this.material = material;
  28934. this.render = function ( /* renderCallback */ ) {};
  28935. this.hasPositions = false;
  28936. this.hasNormals = false;
  28937. this.hasColors = false;
  28938. this.hasUvs = false;
  28939. this.positionArray = null;
  28940. this.normalArray = null;
  28941. this.colorArray = null;
  28942. this.uvArray = null;
  28943. this.count = 0;
  28944. }
  28945. }
  28946. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  28947. const _vector$3 = /*@__PURE__*/ new Vector3();
  28948. class SpotLightHelper extends Object3D {
  28949. constructor( light, color ) {
  28950. super();
  28951. this.light = light;
  28952. this.light.updateMatrixWorld();
  28953. this.matrix = light.matrixWorld;
  28954. this.matrixAutoUpdate = false;
  28955. this.color = color;
  28956. const geometry = new BufferGeometry();
  28957. const positions = [
  28958. 0, 0, 0, 0, 0, 1,
  28959. 0, 0, 0, 1, 0, 1,
  28960. 0, 0, 0, - 1, 0, 1,
  28961. 0, 0, 0, 0, 1, 1,
  28962. 0, 0, 0, 0, - 1, 1
  28963. ];
  28964. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  28965. const p1 = ( i / l ) * Math.PI * 2;
  28966. const p2 = ( j / l ) * Math.PI * 2;
  28967. positions.push(
  28968. Math.cos( p1 ), Math.sin( p1 ), 1,
  28969. Math.cos( p2 ), Math.sin( p2 ), 1
  28970. );
  28971. }
  28972. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28973. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28974. this.cone = new LineSegments( geometry, material );
  28975. this.add( this.cone );
  28976. this.update();
  28977. }
  28978. dispose() {
  28979. this.cone.geometry.dispose();
  28980. this.cone.material.dispose();
  28981. }
  28982. update() {
  28983. this.light.updateMatrixWorld();
  28984. const coneLength = this.light.distance ? this.light.distance : 1000;
  28985. const coneWidth = coneLength * Math.tan( this.light.angle );
  28986. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  28987. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  28988. this.cone.lookAt( _vector$3 );
  28989. if ( this.color !== undefined ) {
  28990. this.cone.material.color.set( this.color );
  28991. } else {
  28992. this.cone.material.color.copy( this.light.color );
  28993. }
  28994. }
  28995. }
  28996. const _vector$2 = /*@__PURE__*/ new Vector3();
  28997. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  28998. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  28999. class SkeletonHelper extends LineSegments {
  29000. constructor( object ) {
  29001. const bones = getBoneList( object );
  29002. const geometry = new BufferGeometry();
  29003. const vertices = [];
  29004. const colors = [];
  29005. const color1 = new Color( 0, 0, 1 );
  29006. const color2 = new Color( 0, 1, 0 );
  29007. for ( let i = 0; i < bones.length; i ++ ) {
  29008. const bone = bones[ i ];
  29009. if ( bone.parent && bone.parent.isBone ) {
  29010. vertices.push( 0, 0, 0 );
  29011. vertices.push( 0, 0, 0 );
  29012. colors.push( color1.r, color1.g, color1.b );
  29013. colors.push( color2.r, color2.g, color2.b );
  29014. }
  29015. }
  29016. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29017. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29018. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  29019. super( geometry, material );
  29020. this.type = 'SkeletonHelper';
  29021. this.isSkeletonHelper = true;
  29022. this.root = object;
  29023. this.bones = bones;
  29024. this.matrix = object.matrixWorld;
  29025. this.matrixAutoUpdate = false;
  29026. }
  29027. updateMatrixWorld( force ) {
  29028. const bones = this.bones;
  29029. const geometry = this.geometry;
  29030. const position = geometry.getAttribute( 'position' );
  29031. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  29032. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  29033. const bone = bones[ i ];
  29034. if ( bone.parent && bone.parent.isBone ) {
  29035. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  29036. _vector$2.setFromMatrixPosition( _boneMatrix );
  29037. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  29038. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  29039. _vector$2.setFromMatrixPosition( _boneMatrix );
  29040. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  29041. j += 2;
  29042. }
  29043. }
  29044. geometry.getAttribute( 'position' ).needsUpdate = true;
  29045. super.updateMatrixWorld( force );
  29046. }
  29047. }
  29048. function getBoneList( object ) {
  29049. const boneList = [];
  29050. if ( object && object.isBone ) {
  29051. boneList.push( object );
  29052. }
  29053. for ( let i = 0; i < object.children.length; i ++ ) {
  29054. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  29055. }
  29056. return boneList;
  29057. }
  29058. class PointLightHelper extends Mesh {
  29059. constructor( light, sphereSize, color ) {
  29060. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  29061. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  29062. super( geometry, material );
  29063. this.light = light;
  29064. this.light.updateMatrixWorld();
  29065. this.color = color;
  29066. this.type = 'PointLightHelper';
  29067. this.matrix = this.light.matrixWorld;
  29068. this.matrixAutoUpdate = false;
  29069. this.update();
  29070. /*
  29071. // TODO: delete this comment?
  29072. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  29073. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  29074. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  29075. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  29076. const d = light.distance;
  29077. if ( d === 0.0 ) {
  29078. this.lightDistance.visible = false;
  29079. } else {
  29080. this.lightDistance.scale.set( d, d, d );
  29081. }
  29082. this.add( this.lightDistance );
  29083. */
  29084. }
  29085. dispose() {
  29086. this.geometry.dispose();
  29087. this.material.dispose();
  29088. }
  29089. update() {
  29090. if ( this.color !== undefined ) {
  29091. this.material.color.set( this.color );
  29092. } else {
  29093. this.material.color.copy( this.light.color );
  29094. }
  29095. /*
  29096. const d = this.light.distance;
  29097. if ( d === 0.0 ) {
  29098. this.lightDistance.visible = false;
  29099. } else {
  29100. this.lightDistance.visible = true;
  29101. this.lightDistance.scale.set( d, d, d );
  29102. }
  29103. */
  29104. }
  29105. }
  29106. const _vector$1 = /*@__PURE__*/ new Vector3();
  29107. const _color1 = /*@__PURE__*/ new Color();
  29108. const _color2 = /*@__PURE__*/ new Color();
  29109. class HemisphereLightHelper extends Object3D {
  29110. constructor( light, size, color ) {
  29111. super();
  29112. this.light = light;
  29113. this.light.updateMatrixWorld();
  29114. this.matrix = light.matrixWorld;
  29115. this.matrixAutoUpdate = false;
  29116. this.color = color;
  29117. const geometry = new OctahedronGeometry( size );
  29118. geometry.rotateY( Math.PI * 0.5 );
  29119. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  29120. if ( this.color === undefined ) this.material.vertexColors = true;
  29121. const position = geometry.getAttribute( 'position' );
  29122. const colors = new Float32Array( position.count * 3 );
  29123. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  29124. this.add( new Mesh( geometry, this.material ) );
  29125. this.update();
  29126. }
  29127. dispose() {
  29128. this.children[ 0 ].geometry.dispose();
  29129. this.children[ 0 ].material.dispose();
  29130. }
  29131. update() {
  29132. const mesh = this.children[ 0 ];
  29133. if ( this.color !== undefined ) {
  29134. this.material.color.set( this.color );
  29135. } else {
  29136. const colors = mesh.geometry.getAttribute( 'color' );
  29137. _color1.copy( this.light.color );
  29138. _color2.copy( this.light.groundColor );
  29139. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  29140. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  29141. colors.setXYZ( i, color.r, color.g, color.b );
  29142. }
  29143. colors.needsUpdate = true;
  29144. }
  29145. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  29146. }
  29147. }
  29148. class GridHelper extends LineSegments {
  29149. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  29150. color1 = new Color( color1 );
  29151. color2 = new Color( color2 );
  29152. const center = divisions / 2;
  29153. const step = size / divisions;
  29154. const halfSize = size / 2;
  29155. const vertices = [], colors = [];
  29156. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  29157. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  29158. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  29159. const color = i === center ? color1 : color2;
  29160. color.toArray( colors, j ); j += 3;
  29161. color.toArray( colors, j ); j += 3;
  29162. color.toArray( colors, j ); j += 3;
  29163. color.toArray( colors, j ); j += 3;
  29164. }
  29165. const geometry = new BufferGeometry();
  29166. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29167. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29168. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29169. super( geometry, material );
  29170. this.type = 'GridHelper';
  29171. }
  29172. }
  29173. class PolarGridHelper extends LineSegments {
  29174. constructor( radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  29175. color1 = new Color( color1 );
  29176. color2 = new Color( color2 );
  29177. const vertices = [];
  29178. const colors = [];
  29179. // create the radials
  29180. for ( let i = 0; i <= radials; i ++ ) {
  29181. const v = ( i / radials ) * ( Math.PI * 2 );
  29182. const x = Math.sin( v ) * radius;
  29183. const z = Math.cos( v ) * radius;
  29184. vertices.push( 0, 0, 0 );
  29185. vertices.push( x, 0, z );
  29186. const color = ( i & 1 ) ? color1 : color2;
  29187. colors.push( color.r, color.g, color.b );
  29188. colors.push( color.r, color.g, color.b );
  29189. }
  29190. // create the circles
  29191. for ( let i = 0; i <= circles; i ++ ) {
  29192. const color = ( i & 1 ) ? color1 : color2;
  29193. const r = radius - ( radius / circles * i );
  29194. for ( let j = 0; j < divisions; j ++ ) {
  29195. // first vertex
  29196. let v = ( j / divisions ) * ( Math.PI * 2 );
  29197. let x = Math.sin( v ) * r;
  29198. let z = Math.cos( v ) * r;
  29199. vertices.push( x, 0, z );
  29200. colors.push( color.r, color.g, color.b );
  29201. // second vertex
  29202. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  29203. x = Math.sin( v ) * r;
  29204. z = Math.cos( v ) * r;
  29205. vertices.push( x, 0, z );
  29206. colors.push( color.r, color.g, color.b );
  29207. }
  29208. }
  29209. const geometry = new BufferGeometry();
  29210. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29211. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29212. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29213. super( geometry, material );
  29214. this.type = 'PolarGridHelper';
  29215. }
  29216. }
  29217. const _v1 = /*@__PURE__*/ new Vector3();
  29218. const _v2 = /*@__PURE__*/ new Vector3();
  29219. const _v3 = /*@__PURE__*/ new Vector3();
  29220. class DirectionalLightHelper extends Object3D {
  29221. constructor( light, size, color ) {
  29222. super();
  29223. this.light = light;
  29224. this.light.updateMatrixWorld();
  29225. this.matrix = light.matrixWorld;
  29226. this.matrixAutoUpdate = false;
  29227. this.color = color;
  29228. if ( size === undefined ) size = 1;
  29229. let geometry = new BufferGeometry();
  29230. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  29231. - size, size, 0,
  29232. size, size, 0,
  29233. size, - size, 0,
  29234. - size, - size, 0,
  29235. - size, size, 0
  29236. ], 3 ) );
  29237. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  29238. this.lightPlane = new Line( geometry, material );
  29239. this.add( this.lightPlane );
  29240. geometry = new BufferGeometry();
  29241. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  29242. this.targetLine = new Line( geometry, material );
  29243. this.add( this.targetLine );
  29244. this.update();
  29245. }
  29246. dispose() {
  29247. this.lightPlane.geometry.dispose();
  29248. this.lightPlane.material.dispose();
  29249. this.targetLine.geometry.dispose();
  29250. this.targetLine.material.dispose();
  29251. }
  29252. update() {
  29253. _v1.setFromMatrixPosition( this.light.matrixWorld );
  29254. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  29255. _v3.subVectors( _v2, _v1 );
  29256. this.lightPlane.lookAt( _v2 );
  29257. if ( this.color !== undefined ) {
  29258. this.lightPlane.material.color.set( this.color );
  29259. this.targetLine.material.color.set( this.color );
  29260. } else {
  29261. this.lightPlane.material.color.copy( this.light.color );
  29262. this.targetLine.material.color.copy( this.light.color );
  29263. }
  29264. this.targetLine.lookAt( _v2 );
  29265. this.targetLine.scale.z = _v3.length();
  29266. }
  29267. }
  29268. const _vector = /*@__PURE__*/ new Vector3();
  29269. const _camera = /*@__PURE__*/ new Camera();
  29270. /**
  29271. * - shows frustum, line of sight and up of the camera
  29272. * - suitable for fast updates
  29273. * - based on frustum visualization in lightgl.js shadowmap example
  29274. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  29275. */
  29276. class CameraHelper extends LineSegments {
  29277. constructor( camera ) {
  29278. const geometry = new BufferGeometry();
  29279. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  29280. const vertices = [];
  29281. const colors = [];
  29282. const pointMap = {};
  29283. // colors
  29284. const colorFrustum = new Color( 0xffaa00 );
  29285. const colorCone = new Color( 0xff0000 );
  29286. const colorUp = new Color( 0x00aaff );
  29287. const colorTarget = new Color( 0xffffff );
  29288. const colorCross = new Color( 0x333333 );
  29289. // near
  29290. addLine( 'n1', 'n2', colorFrustum );
  29291. addLine( 'n2', 'n4', colorFrustum );
  29292. addLine( 'n4', 'n3', colorFrustum );
  29293. addLine( 'n3', 'n1', colorFrustum );
  29294. // far
  29295. addLine( 'f1', 'f2', colorFrustum );
  29296. addLine( 'f2', 'f4', colorFrustum );
  29297. addLine( 'f4', 'f3', colorFrustum );
  29298. addLine( 'f3', 'f1', colorFrustum );
  29299. // sides
  29300. addLine( 'n1', 'f1', colorFrustum );
  29301. addLine( 'n2', 'f2', colorFrustum );
  29302. addLine( 'n3', 'f3', colorFrustum );
  29303. addLine( 'n4', 'f4', colorFrustum );
  29304. // cone
  29305. addLine( 'p', 'n1', colorCone );
  29306. addLine( 'p', 'n2', colorCone );
  29307. addLine( 'p', 'n3', colorCone );
  29308. addLine( 'p', 'n4', colorCone );
  29309. // up
  29310. addLine( 'u1', 'u2', colorUp );
  29311. addLine( 'u2', 'u3', colorUp );
  29312. addLine( 'u3', 'u1', colorUp );
  29313. // target
  29314. addLine( 'c', 't', colorTarget );
  29315. addLine( 'p', 'c', colorCross );
  29316. // cross
  29317. addLine( 'cn1', 'cn2', colorCross );
  29318. addLine( 'cn3', 'cn4', colorCross );
  29319. addLine( 'cf1', 'cf2', colorCross );
  29320. addLine( 'cf3', 'cf4', colorCross );
  29321. function addLine( a, b, color ) {
  29322. addPoint( a, color );
  29323. addPoint( b, color );
  29324. }
  29325. function addPoint( id, color ) {
  29326. vertices.push( 0, 0, 0 );
  29327. colors.push( color.r, color.g, color.b );
  29328. if ( pointMap[ id ] === undefined ) {
  29329. pointMap[ id ] = [];
  29330. }
  29331. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  29332. }
  29333. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29334. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29335. super( geometry, material );
  29336. this.type = 'CameraHelper';
  29337. this.camera = camera;
  29338. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  29339. this.matrix = camera.matrixWorld;
  29340. this.matrixAutoUpdate = false;
  29341. this.pointMap = pointMap;
  29342. this.update();
  29343. }
  29344. update() {
  29345. const geometry = this.geometry;
  29346. const pointMap = this.pointMap;
  29347. const w = 1, h = 1;
  29348. // we need just camera projection matrix inverse
  29349. // world matrix must be identity
  29350. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  29351. // center / target
  29352. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  29353. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  29354. // near
  29355. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  29356. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  29357. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  29358. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  29359. // far
  29360. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  29361. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  29362. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  29363. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  29364. // up
  29365. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  29366. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  29367. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  29368. // cross
  29369. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  29370. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  29371. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  29372. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  29373. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  29374. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  29375. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  29376. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  29377. geometry.getAttribute( 'position' ).needsUpdate = true;
  29378. }
  29379. dispose() {
  29380. this.geometry.dispose();
  29381. this.material.dispose();
  29382. }
  29383. }
  29384. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  29385. _vector.set( x, y, z ).unproject( camera );
  29386. const points = pointMap[ point ];
  29387. if ( points !== undefined ) {
  29388. const position = geometry.getAttribute( 'position' );
  29389. for ( let i = 0, l = points.length; i < l; i ++ ) {
  29390. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  29391. }
  29392. }
  29393. }
  29394. const _box = /*@__PURE__*/ new Box3();
  29395. class BoxHelper extends LineSegments {
  29396. constructor( object, color = 0xffff00 ) {
  29397. 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 ] );
  29398. const positions = new Float32Array( 8 * 3 );
  29399. const geometry = new BufferGeometry();
  29400. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29401. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  29402. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29403. this.object = object;
  29404. this.type = 'BoxHelper';
  29405. this.matrixAutoUpdate = false;
  29406. this.update();
  29407. }
  29408. update( object ) {
  29409. if ( object !== undefined ) {
  29410. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  29411. }
  29412. if ( this.object !== undefined ) {
  29413. _box.setFromObject( this.object );
  29414. }
  29415. if ( _box.isEmpty() ) return;
  29416. const min = _box.min;
  29417. const max = _box.max;
  29418. /*
  29419. 5____4
  29420. 1/___0/|
  29421. | 6__|_7
  29422. 2/___3/
  29423. 0: max.x, max.y, max.z
  29424. 1: min.x, max.y, max.z
  29425. 2: min.x, min.y, max.z
  29426. 3: max.x, min.y, max.z
  29427. 4: max.x, max.y, min.z
  29428. 5: min.x, max.y, min.z
  29429. 6: min.x, min.y, min.z
  29430. 7: max.x, min.y, min.z
  29431. */
  29432. const position = this.geometry.attributes.position;
  29433. const array = position.array;
  29434. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  29435. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  29436. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  29437. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  29438. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  29439. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  29440. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  29441. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  29442. position.needsUpdate = true;
  29443. this.geometry.computeBoundingSphere();
  29444. }
  29445. setFromObject( object ) {
  29446. this.object = object;
  29447. this.update();
  29448. return this;
  29449. }
  29450. copy( source ) {
  29451. LineSegments.prototype.copy.call( this, source );
  29452. this.object = source.object;
  29453. return this;
  29454. }
  29455. }
  29456. class Box3Helper extends LineSegments {
  29457. constructor( box, color = 0xffff00 ) {
  29458. 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 ] );
  29459. 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 ];
  29460. const geometry = new BufferGeometry();
  29461. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29462. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29463. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29464. this.box = box;
  29465. this.type = 'Box3Helper';
  29466. this.geometry.computeBoundingSphere();
  29467. }
  29468. updateMatrixWorld( force ) {
  29469. const box = this.box;
  29470. if ( box.isEmpty() ) return;
  29471. box.getCenter( this.position );
  29472. box.getSize( this.scale );
  29473. this.scale.multiplyScalar( 0.5 );
  29474. super.updateMatrixWorld( force );
  29475. }
  29476. }
  29477. class PlaneHelper extends Line {
  29478. constructor( plane, size = 1, hex = 0xffff00 ) {
  29479. const color = hex;
  29480. const positions = [ 1, - 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0 ];
  29481. const geometry = new BufferGeometry();
  29482. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29483. geometry.computeBoundingSphere();
  29484. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29485. this.type = 'PlaneHelper';
  29486. this.plane = plane;
  29487. this.size = size;
  29488. const positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];
  29489. const geometry2 = new BufferGeometry();
  29490. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  29491. geometry2.computeBoundingSphere();
  29492. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  29493. }
  29494. updateMatrixWorld( force ) {
  29495. let scale = - this.plane.constant;
  29496. if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter
  29497. this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );
  29498. this.children[ 0 ].material.side = ( scale < 0 ) ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  29499. this.lookAt( this.plane.normal );
  29500. super.updateMatrixWorld( force );
  29501. }
  29502. }
  29503. const _axis = /*@__PURE__*/ new Vector3();
  29504. let _lineGeometry, _coneGeometry;
  29505. class ArrowHelper extends Object3D {
  29506. // dir is assumed to be normalized
  29507. 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 ) {
  29508. super();
  29509. this.type = 'ArrowHelper';
  29510. if ( _lineGeometry === undefined ) {
  29511. _lineGeometry = new BufferGeometry();
  29512. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  29513. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  29514. _coneGeometry.translate( 0, - 0.5, 0 );
  29515. }
  29516. this.position.copy( origin );
  29517. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29518. this.line.matrixAutoUpdate = false;
  29519. this.add( this.line );
  29520. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  29521. this.cone.matrixAutoUpdate = false;
  29522. this.add( this.cone );
  29523. this.setDirection( dir );
  29524. this.setLength( length, headLength, headWidth );
  29525. }
  29526. setDirection( dir ) {
  29527. // dir is assumed to be normalized
  29528. if ( dir.y > 0.99999 ) {
  29529. this.quaternion.set( 0, 0, 0, 1 );
  29530. } else if ( dir.y < - 0.99999 ) {
  29531. this.quaternion.set( 1, 0, 0, 0 );
  29532. } else {
  29533. _axis.set( dir.z, 0, - dir.x ).normalize();
  29534. const radians = Math.acos( dir.y );
  29535. this.quaternion.setFromAxisAngle( _axis, radians );
  29536. }
  29537. }
  29538. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  29539. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  29540. this.line.updateMatrix();
  29541. this.cone.scale.set( headWidth, headLength, headWidth );
  29542. this.cone.position.y = length;
  29543. this.cone.updateMatrix();
  29544. }
  29545. setColor( color ) {
  29546. this.line.material.color.set( color );
  29547. this.cone.material.color.set( color );
  29548. }
  29549. copy( source ) {
  29550. super.copy( source, false );
  29551. this.line.copy( source.line );
  29552. this.cone.copy( source.cone );
  29553. return this;
  29554. }
  29555. }
  29556. class AxesHelper extends LineSegments {
  29557. constructor( size = 1 ) {
  29558. const vertices = [
  29559. 0, 0, 0, size, 0, 0,
  29560. 0, 0, 0, 0, size, 0,
  29561. 0, 0, 0, 0, 0, size
  29562. ];
  29563. const colors = [
  29564. 1, 0, 0, 1, 0.6, 0,
  29565. 0, 1, 0, 0.6, 1, 0,
  29566. 0, 0, 1, 0, 0.6, 1
  29567. ];
  29568. const geometry = new BufferGeometry();
  29569. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29570. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29571. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29572. super( geometry, material );
  29573. this.type = 'AxesHelper';
  29574. }
  29575. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  29576. const color = new Color();
  29577. const array = this.geometry.attributes.color.array;
  29578. color.set( xAxisColor );
  29579. color.toArray( array, 0 );
  29580. color.toArray( array, 3 );
  29581. color.set( yAxisColor );
  29582. color.toArray( array, 6 );
  29583. color.toArray( array, 9 );
  29584. color.set( zAxisColor );
  29585. color.toArray( array, 12 );
  29586. color.toArray( array, 15 );
  29587. this.geometry.attributes.color.needsUpdate = true;
  29588. return this;
  29589. }
  29590. dispose() {
  29591. this.geometry.dispose();
  29592. this.material.dispose();
  29593. }
  29594. }
  29595. const _floatView = new Float32Array( 1 );
  29596. const _int32View = new Int32Array( _floatView.buffer );
  29597. class DataUtils {
  29598. // Converts float32 to float16 (stored as uint16 value).
  29599. static toHalfFloat( val ) {
  29600. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  29601. /* This method is faster than the OpenEXR implementation (very often
  29602. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  29603. * by James Tursa?s half-precision code. */
  29604. _floatView[ 0 ] = val;
  29605. const x = _int32View[ 0 ];
  29606. let bits = ( x >> 16 ) & 0x8000; /* Get the sign */
  29607. let m = ( x >> 12 ) & 0x07ff; /* Keep one extra bit for rounding */
  29608. const e = ( x >> 23 ) & 0xff; /* Using int is faster here */
  29609. /* If zero, or denormal, or exponent underflows too much for a denormal
  29610. * half, return signed zero. */
  29611. if ( e < 103 ) return bits;
  29612. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  29613. if ( e > 142 ) {
  29614. bits |= 0x7c00;
  29615. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  29616. * not Inf, so make sure we set one mantissa bit too. */
  29617. bits |= ( ( e == 255 ) ? 0 : 1 ) && ( x & 0x007fffff );
  29618. return bits;
  29619. }
  29620. /* If exponent underflows but not too much, return a denormal */
  29621. if ( e < 113 ) {
  29622. m |= 0x0800;
  29623. /* Extra rounding may overflow and set mantissa to 0 and exponent
  29624. * to 1, which is OK. */
  29625. bits |= ( m >> ( 114 - e ) ) + ( ( m >> ( 113 - e ) ) & 1 );
  29626. return bits;
  29627. }
  29628. bits |= ( ( e - 112 ) << 10 ) | ( m >> 1 );
  29629. /* Extra rounding. An overflow will set mantissa to 0 and increment
  29630. * the exponent, which is OK. */
  29631. bits += m & 1;
  29632. return bits;
  29633. }
  29634. }
  29635. const LineStrip = 0;
  29636. const LinePieces = 1;
  29637. const NoColors = 0;
  29638. const FaceColors = 1;
  29639. const VertexColors = 2;
  29640. function MeshFaceMaterial( materials ) {
  29641. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  29642. return materials;
  29643. }
  29644. function MultiMaterial( materials = [] ) {
  29645. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  29646. materials.isMultiMaterial = true;
  29647. materials.materials = materials;
  29648. materials.clone = function () {
  29649. return materials.slice();
  29650. };
  29651. return materials;
  29652. }
  29653. function PointCloud( geometry, material ) {
  29654. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  29655. return new Points( geometry, material );
  29656. }
  29657. function Particle( material ) {
  29658. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  29659. return new Sprite( material );
  29660. }
  29661. function ParticleSystem( geometry, material ) {
  29662. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  29663. return new Points( geometry, material );
  29664. }
  29665. function PointCloudMaterial( parameters ) {
  29666. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  29667. return new PointsMaterial( parameters );
  29668. }
  29669. function ParticleBasicMaterial( parameters ) {
  29670. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  29671. return new PointsMaterial( parameters );
  29672. }
  29673. function ParticleSystemMaterial( parameters ) {
  29674. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  29675. return new PointsMaterial( parameters );
  29676. }
  29677. function Vertex( x, y, z ) {
  29678. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  29679. return new Vector3( x, y, z );
  29680. }
  29681. //
  29682. function DynamicBufferAttribute( array, itemSize ) {
  29683. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.' );
  29684. return new BufferAttribute( array, itemSize ).setUsage( DynamicDrawUsage );
  29685. }
  29686. function Int8Attribute( array, itemSize ) {
  29687. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  29688. return new Int8BufferAttribute( array, itemSize );
  29689. }
  29690. function Uint8Attribute( array, itemSize ) {
  29691. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  29692. return new Uint8BufferAttribute( array, itemSize );
  29693. }
  29694. function Uint8ClampedAttribute( array, itemSize ) {
  29695. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  29696. return new Uint8ClampedBufferAttribute( array, itemSize );
  29697. }
  29698. function Int16Attribute( array, itemSize ) {
  29699. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  29700. return new Int16BufferAttribute( array, itemSize );
  29701. }
  29702. function Uint16Attribute( array, itemSize ) {
  29703. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  29704. return new Uint16BufferAttribute( array, itemSize );
  29705. }
  29706. function Int32Attribute( array, itemSize ) {
  29707. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  29708. return new Int32BufferAttribute( array, itemSize );
  29709. }
  29710. function Uint32Attribute( array, itemSize ) {
  29711. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  29712. return new Uint32BufferAttribute( array, itemSize );
  29713. }
  29714. function Float32Attribute( array, itemSize ) {
  29715. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  29716. return new Float32BufferAttribute( array, itemSize );
  29717. }
  29718. function Float64Attribute( array, itemSize ) {
  29719. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  29720. return new Float64BufferAttribute( array, itemSize );
  29721. }
  29722. //
  29723. Curve.create = function ( construct, getPoint ) {
  29724. console.log( 'THREE.Curve.create() has been deprecated' );
  29725. construct.prototype = Object.create( Curve.prototype );
  29726. construct.prototype.constructor = construct;
  29727. construct.prototype.getPoint = getPoint;
  29728. return construct;
  29729. };
  29730. //
  29731. Path.prototype.fromPoints = function ( points ) {
  29732. console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' );
  29733. return this.setFromPoints( points );
  29734. };
  29735. //
  29736. function AxisHelper( size ) {
  29737. console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' );
  29738. return new AxesHelper( size );
  29739. }
  29740. function BoundingBoxHelper( object, color ) {
  29741. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  29742. return new BoxHelper( object, color );
  29743. }
  29744. function EdgesHelper( object, hex ) {
  29745. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  29746. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  29747. }
  29748. GridHelper.prototype.setColors = function () {
  29749. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  29750. };
  29751. SkeletonHelper.prototype.update = function () {
  29752. console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
  29753. };
  29754. function WireframeHelper( object, hex ) {
  29755. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  29756. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  29757. }
  29758. //
  29759. Loader.prototype.extractUrlBase = function ( url ) {
  29760. console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' );
  29761. return LoaderUtils.extractUrlBase( url );
  29762. };
  29763. Loader.Handlers = {
  29764. add: function ( /* regex, loader */ ) {
  29765. console.error( 'THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.' );
  29766. },
  29767. get: function ( /* file */ ) {
  29768. console.error( 'THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.' );
  29769. }
  29770. };
  29771. function XHRLoader( manager ) {
  29772. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  29773. return new FileLoader( manager );
  29774. }
  29775. function BinaryTextureLoader( manager ) {
  29776. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  29777. return new DataTextureLoader( manager );
  29778. }
  29779. //
  29780. Box2.prototype.center = function ( optionalTarget ) {
  29781. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  29782. return this.getCenter( optionalTarget );
  29783. };
  29784. Box2.prototype.empty = function () {
  29785. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  29786. return this.isEmpty();
  29787. };
  29788. Box2.prototype.isIntersectionBox = function ( box ) {
  29789. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  29790. return this.intersectsBox( box );
  29791. };
  29792. Box2.prototype.size = function ( optionalTarget ) {
  29793. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  29794. return this.getSize( optionalTarget );
  29795. };
  29796. //
  29797. Box3.prototype.center = function ( optionalTarget ) {
  29798. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  29799. return this.getCenter( optionalTarget );
  29800. };
  29801. Box3.prototype.empty = function () {
  29802. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  29803. return this.isEmpty();
  29804. };
  29805. Box3.prototype.isIntersectionBox = function ( box ) {
  29806. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  29807. return this.intersectsBox( box );
  29808. };
  29809. Box3.prototype.isIntersectionSphere = function ( sphere ) {
  29810. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  29811. return this.intersectsSphere( sphere );
  29812. };
  29813. Box3.prototype.size = function ( optionalTarget ) {
  29814. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  29815. return this.getSize( optionalTarget );
  29816. };
  29817. //
  29818. Sphere.prototype.empty = function () {
  29819. console.warn( 'THREE.Sphere: .empty() has been renamed to .isEmpty().' );
  29820. return this.isEmpty();
  29821. };
  29822. //
  29823. Frustum.prototype.setFromMatrix = function ( m ) {
  29824. console.warn( 'THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().' );
  29825. return this.setFromProjectionMatrix( m );
  29826. };
  29827. //
  29828. Line3.prototype.center = function ( optionalTarget ) {
  29829. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  29830. return this.getCenter( optionalTarget );
  29831. };
  29832. //
  29833. Matrix3.prototype.flattenToArrayOffset = function ( array, offset ) {
  29834. console.warn( 'THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' );
  29835. return this.toArray( array, offset );
  29836. };
  29837. Matrix3.prototype.multiplyVector3 = function ( vector ) {
  29838. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  29839. return vector.applyMatrix3( this );
  29840. };
  29841. Matrix3.prototype.multiplyVector3Array = function ( /* a */ ) {
  29842. console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
  29843. };
  29844. Matrix3.prototype.applyToBufferAttribute = function ( attribute ) {
  29845. console.warn( 'THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.' );
  29846. return attribute.applyMatrix3( this );
  29847. };
  29848. Matrix3.prototype.applyToVector3Array = function ( /* array, offset, length */ ) {
  29849. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  29850. };
  29851. Matrix3.prototype.getInverse = function ( matrix ) {
  29852. console.warn( 'THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' );
  29853. return this.copy( matrix ).invert();
  29854. };
  29855. //
  29856. Matrix4.prototype.extractPosition = function ( m ) {
  29857. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  29858. return this.copyPosition( m );
  29859. };
  29860. Matrix4.prototype.flattenToArrayOffset = function ( array, offset ) {
  29861. console.warn( 'THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' );
  29862. return this.toArray( array, offset );
  29863. };
  29864. Matrix4.prototype.getPosition = function () {
  29865. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  29866. return new Vector3().setFromMatrixColumn( this, 3 );
  29867. };
  29868. Matrix4.prototype.setRotationFromQuaternion = function ( q ) {
  29869. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  29870. return this.makeRotationFromQuaternion( q );
  29871. };
  29872. Matrix4.prototype.multiplyToArray = function () {
  29873. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  29874. };
  29875. Matrix4.prototype.multiplyVector3 = function ( vector ) {
  29876. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  29877. return vector.applyMatrix4( this );
  29878. };
  29879. Matrix4.prototype.multiplyVector4 = function ( vector ) {
  29880. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  29881. return vector.applyMatrix4( this );
  29882. };
  29883. Matrix4.prototype.multiplyVector3Array = function ( /* a */ ) {
  29884. console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
  29885. };
  29886. Matrix4.prototype.rotateAxis = function ( v ) {
  29887. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  29888. v.transformDirection( this );
  29889. };
  29890. Matrix4.prototype.crossVector = function ( vector ) {
  29891. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  29892. return vector.applyMatrix4( this );
  29893. };
  29894. Matrix4.prototype.translate = function () {
  29895. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  29896. };
  29897. Matrix4.prototype.rotateX = function () {
  29898. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  29899. };
  29900. Matrix4.prototype.rotateY = function () {
  29901. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  29902. };
  29903. Matrix4.prototype.rotateZ = function () {
  29904. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  29905. };
  29906. Matrix4.prototype.rotateByAxis = function () {
  29907. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  29908. };
  29909. Matrix4.prototype.applyToBufferAttribute = function ( attribute ) {
  29910. console.warn( 'THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.' );
  29911. return attribute.applyMatrix4( this );
  29912. };
  29913. Matrix4.prototype.applyToVector3Array = function ( /* array, offset, length */ ) {
  29914. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  29915. };
  29916. Matrix4.prototype.makeFrustum = function ( left, right, bottom, top, near, far ) {
  29917. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  29918. return this.makePerspective( left, right, top, bottom, near, far );
  29919. };
  29920. Matrix4.prototype.getInverse = function ( matrix ) {
  29921. console.warn( 'THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' );
  29922. return this.copy( matrix ).invert();
  29923. };
  29924. //
  29925. Plane.prototype.isIntersectionLine = function ( line ) {
  29926. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  29927. return this.intersectsLine( line );
  29928. };
  29929. //
  29930. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  29931. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  29932. return vector.applyQuaternion( this );
  29933. };
  29934. Quaternion.prototype.inverse = function ( ) {
  29935. console.warn( 'THREE.Quaternion: .inverse() has been renamed to invert().' );
  29936. return this.invert();
  29937. };
  29938. //
  29939. Ray.prototype.isIntersectionBox = function ( box ) {
  29940. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  29941. return this.intersectsBox( box );
  29942. };
  29943. Ray.prototype.isIntersectionPlane = function ( plane ) {
  29944. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  29945. return this.intersectsPlane( plane );
  29946. };
  29947. Ray.prototype.isIntersectionSphere = function ( sphere ) {
  29948. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  29949. return this.intersectsSphere( sphere );
  29950. };
  29951. //
  29952. Triangle.prototype.area = function () {
  29953. console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' );
  29954. return this.getArea();
  29955. };
  29956. Triangle.prototype.barycoordFromPoint = function ( point, target ) {
  29957. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  29958. return this.getBarycoord( point, target );
  29959. };
  29960. Triangle.prototype.midpoint = function ( target ) {
  29961. console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' );
  29962. return this.getMidpoint( target );
  29963. };
  29964. Triangle.prototypenormal = function ( target ) {
  29965. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  29966. return this.getNormal( target );
  29967. };
  29968. Triangle.prototype.plane = function ( target ) {
  29969. console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' );
  29970. return this.getPlane( target );
  29971. };
  29972. Triangle.barycoordFromPoint = function ( point, a, b, c, target ) {
  29973. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  29974. return Triangle.getBarycoord( point, a, b, c, target );
  29975. };
  29976. Triangle.normal = function ( a, b, c, target ) {
  29977. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  29978. return Triangle.getNormal( a, b, c, target );
  29979. };
  29980. //
  29981. Shape.prototype.extractAllPoints = function ( divisions ) {
  29982. console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' );
  29983. return this.extractPoints( divisions );
  29984. };
  29985. Shape.prototype.extrude = function ( options ) {
  29986. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  29987. return new ExtrudeGeometry( this, options );
  29988. };
  29989. Shape.prototype.makeGeometry = function ( options ) {
  29990. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  29991. return new ShapeGeometry( this, options );
  29992. };
  29993. //
  29994. Vector2.prototype.fromAttribute = function ( attribute, index, offset ) {
  29995. console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  29996. return this.fromBufferAttribute( attribute, index, offset );
  29997. };
  29998. Vector2.prototype.distanceToManhattan = function ( v ) {
  29999. console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  30000. return this.manhattanDistanceTo( v );
  30001. };
  30002. Vector2.prototype.lengthManhattan = function () {
  30003. console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' );
  30004. return this.manhattanLength();
  30005. };
  30006. //
  30007. Vector3.prototype.setEulerFromRotationMatrix = function () {
  30008. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  30009. };
  30010. Vector3.prototype.setEulerFromQuaternion = function () {
  30011. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  30012. };
  30013. Vector3.prototype.getPositionFromMatrix = function ( m ) {
  30014. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  30015. return this.setFromMatrixPosition( m );
  30016. };
  30017. Vector3.prototype.getScaleFromMatrix = function ( m ) {
  30018. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  30019. return this.setFromMatrixScale( m );
  30020. };
  30021. Vector3.prototype.getColumnFromMatrix = function ( index, matrix ) {
  30022. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  30023. return this.setFromMatrixColumn( matrix, index );
  30024. };
  30025. Vector3.prototype.applyProjection = function ( m ) {
  30026. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  30027. return this.applyMatrix4( m );
  30028. };
  30029. Vector3.prototype.fromAttribute = function ( attribute, index, offset ) {
  30030. console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  30031. return this.fromBufferAttribute( attribute, index, offset );
  30032. };
  30033. Vector3.prototype.distanceToManhattan = function ( v ) {
  30034. console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  30035. return this.manhattanDistanceTo( v );
  30036. };
  30037. Vector3.prototype.lengthManhattan = function () {
  30038. console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' );
  30039. return this.manhattanLength();
  30040. };
  30041. //
  30042. Vector4.prototype.fromAttribute = function ( attribute, index, offset ) {
  30043. console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  30044. return this.fromBufferAttribute( attribute, index, offset );
  30045. };
  30046. Vector4.prototype.lengthManhattan = function () {
  30047. console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' );
  30048. return this.manhattanLength();
  30049. };
  30050. //
  30051. Object3D.prototype.getChildByName = function ( name ) {
  30052. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  30053. return this.getObjectByName( name );
  30054. };
  30055. Object3D.prototype.renderDepth = function () {
  30056. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  30057. };
  30058. Object3D.prototype.translate = function ( distance, axis ) {
  30059. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  30060. return this.translateOnAxis( axis, distance );
  30061. };
  30062. Object3D.prototype.getWorldRotation = function () {
  30063. console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' );
  30064. };
  30065. Object3D.prototype.applyMatrix = function ( matrix ) {
  30066. console.warn( 'THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().' );
  30067. return this.applyMatrix4( matrix );
  30068. };
  30069. Object.defineProperties( Object3D.prototype, {
  30070. eulerOrder: {
  30071. get: function () {
  30072. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  30073. return this.rotation.order;
  30074. },
  30075. set: function ( value ) {
  30076. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  30077. this.rotation.order = value;
  30078. }
  30079. },
  30080. useQuaternion: {
  30081. get: function () {
  30082. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  30083. },
  30084. set: function () {
  30085. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  30086. }
  30087. }
  30088. } );
  30089. Mesh.prototype.setDrawMode = function () {
  30090. console.error( 'THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  30091. };
  30092. Object.defineProperties( Mesh.prototype, {
  30093. drawMode: {
  30094. get: function () {
  30095. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.' );
  30096. return TrianglesDrawMode;
  30097. },
  30098. set: function () {
  30099. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  30100. }
  30101. }
  30102. } );
  30103. SkinnedMesh.prototype.initBones = function () {
  30104. console.error( 'THREE.SkinnedMesh: initBones() has been removed.' );
  30105. };
  30106. //
  30107. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  30108. console.warn( 'THREE.PerspectiveCamera.setLens is deprecated. ' +
  30109. 'Use .setFocalLength and .filmGauge for a photographic setup.' );
  30110. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  30111. this.setFocalLength( focalLength );
  30112. };
  30113. //
  30114. Object.defineProperties( Light.prototype, {
  30115. onlyShadow: {
  30116. set: function () {
  30117. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  30118. }
  30119. },
  30120. shadowCameraFov: {
  30121. set: function ( value ) {
  30122. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  30123. this.shadow.camera.fov = value;
  30124. }
  30125. },
  30126. shadowCameraLeft: {
  30127. set: function ( value ) {
  30128. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  30129. this.shadow.camera.left = value;
  30130. }
  30131. },
  30132. shadowCameraRight: {
  30133. set: function ( value ) {
  30134. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  30135. this.shadow.camera.right = value;
  30136. }
  30137. },
  30138. shadowCameraTop: {
  30139. set: function ( value ) {
  30140. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  30141. this.shadow.camera.top = value;
  30142. }
  30143. },
  30144. shadowCameraBottom: {
  30145. set: function ( value ) {
  30146. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  30147. this.shadow.camera.bottom = value;
  30148. }
  30149. },
  30150. shadowCameraNear: {
  30151. set: function ( value ) {
  30152. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  30153. this.shadow.camera.near = value;
  30154. }
  30155. },
  30156. shadowCameraFar: {
  30157. set: function ( value ) {
  30158. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  30159. this.shadow.camera.far = value;
  30160. }
  30161. },
  30162. shadowCameraVisible: {
  30163. set: function () {
  30164. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  30165. }
  30166. },
  30167. shadowBias: {
  30168. set: function ( value ) {
  30169. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  30170. this.shadow.bias = value;
  30171. }
  30172. },
  30173. shadowDarkness: {
  30174. set: function () {
  30175. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  30176. }
  30177. },
  30178. shadowMapWidth: {
  30179. set: function ( value ) {
  30180. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  30181. this.shadow.mapSize.width = value;
  30182. }
  30183. },
  30184. shadowMapHeight: {
  30185. set: function ( value ) {
  30186. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  30187. this.shadow.mapSize.height = value;
  30188. }
  30189. }
  30190. } );
  30191. //
  30192. Object.defineProperties( BufferAttribute.prototype, {
  30193. length: {
  30194. get: function () {
  30195. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  30196. return this.array.length;
  30197. }
  30198. },
  30199. dynamic: {
  30200. get: function () {
  30201. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  30202. return this.usage === DynamicDrawUsage;
  30203. },
  30204. set: function ( /* value */ ) {
  30205. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  30206. this.setUsage( DynamicDrawUsage );
  30207. }
  30208. }
  30209. } );
  30210. BufferAttribute.prototype.setDynamic = function ( value ) {
  30211. console.warn( 'THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  30212. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  30213. return this;
  30214. };
  30215. BufferAttribute.prototype.copyIndicesArray = function ( /* indices */ ) {
  30216. console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' );
  30217. },
  30218. BufferAttribute.prototype.setArray = function ( /* array */ ) {
  30219. console.error( 'THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  30220. };
  30221. //
  30222. BufferGeometry.prototype.addIndex = function ( index ) {
  30223. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  30224. this.setIndex( index );
  30225. };
  30226. BufferGeometry.prototype.addAttribute = function ( name, attribute ) {
  30227. console.warn( 'THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().' );
  30228. if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
  30229. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  30230. return this.setAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  30231. }
  30232. if ( name === 'index' ) {
  30233. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  30234. this.setIndex( attribute );
  30235. return this;
  30236. }
  30237. return this.setAttribute( name, attribute );
  30238. };
  30239. BufferGeometry.prototype.addDrawCall = function ( start, count, indexOffset ) {
  30240. if ( indexOffset !== undefined ) {
  30241. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  30242. }
  30243. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  30244. this.addGroup( start, count );
  30245. };
  30246. BufferGeometry.prototype.clearDrawCalls = function () {
  30247. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  30248. this.clearGroups();
  30249. };
  30250. BufferGeometry.prototype.computeOffsets = function () {
  30251. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  30252. };
  30253. BufferGeometry.prototype.removeAttribute = function ( name ) {
  30254. console.warn( 'THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().' );
  30255. return this.deleteAttribute( name );
  30256. };
  30257. BufferGeometry.prototype.applyMatrix = function ( matrix ) {
  30258. console.warn( 'THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().' );
  30259. return this.applyMatrix4( matrix );
  30260. };
  30261. Object.defineProperties( BufferGeometry.prototype, {
  30262. drawcalls: {
  30263. get: function () {
  30264. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  30265. return this.groups;
  30266. }
  30267. },
  30268. offsets: {
  30269. get: function () {
  30270. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  30271. return this.groups;
  30272. }
  30273. }
  30274. } );
  30275. InterleavedBuffer.prototype.setDynamic = function ( value ) {
  30276. console.warn( 'THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  30277. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  30278. return this;
  30279. };
  30280. InterleavedBuffer.prototype.setArray = function ( /* array */ ) {
  30281. console.error( 'THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  30282. };
  30283. //
  30284. ExtrudeGeometry.prototype.getArrays = function () {
  30285. console.error( 'THREE.ExtrudeGeometry: .getArrays() has been removed.' );
  30286. };
  30287. ExtrudeGeometry.prototype.addShapeList = function () {
  30288. console.error( 'THREE.ExtrudeGeometry: .addShapeList() has been removed.' );
  30289. };
  30290. ExtrudeGeometry.prototype.addShape = function () {
  30291. console.error( 'THREE.ExtrudeGeometry: .addShape() has been removed.' );
  30292. };
  30293. //
  30294. Scene.prototype.dispose = function () {
  30295. console.error( 'THREE.Scene: .dispose() has been removed.' );
  30296. };
  30297. //
  30298. Uniform.prototype.onUpdate = function () {
  30299. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  30300. return this;
  30301. };
  30302. //
  30303. Object.defineProperties( Material.prototype, {
  30304. wrapAround: {
  30305. get: function () {
  30306. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  30307. },
  30308. set: function () {
  30309. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  30310. }
  30311. },
  30312. overdraw: {
  30313. get: function () {
  30314. console.warn( 'THREE.Material: .overdraw has been removed.' );
  30315. },
  30316. set: function () {
  30317. console.warn( 'THREE.Material: .overdraw has been removed.' );
  30318. }
  30319. },
  30320. wrapRGB: {
  30321. get: function () {
  30322. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  30323. return new Color();
  30324. }
  30325. },
  30326. shading: {
  30327. get: function () {
  30328. console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  30329. },
  30330. set: function ( value ) {
  30331. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  30332. this.flatShading = ( value === FlatShading );
  30333. }
  30334. },
  30335. stencilMask: {
  30336. get: function () {
  30337. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  30338. return this.stencilFuncMask;
  30339. },
  30340. set: function ( value ) {
  30341. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  30342. this.stencilFuncMask = value;
  30343. }
  30344. },
  30345. vertexTangents: {
  30346. get: function () {
  30347. console.warn( 'THREE.' + this.type + ': .vertexTangents has been removed.' );
  30348. },
  30349. set: function () {
  30350. console.warn( 'THREE.' + this.type + ': .vertexTangents has been removed.' );
  30351. }
  30352. },
  30353. } );
  30354. Object.defineProperties( ShaderMaterial.prototype, {
  30355. derivatives: {
  30356. get: function () {
  30357. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  30358. return this.extensions.derivatives;
  30359. },
  30360. set: function ( value ) {
  30361. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  30362. this.extensions.derivatives = value;
  30363. }
  30364. }
  30365. } );
  30366. //
  30367. WebGLRenderer.prototype.clearTarget = function ( renderTarget, color, depth, stencil ) {
  30368. console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' );
  30369. this.setRenderTarget( renderTarget );
  30370. this.clear( color, depth, stencil );
  30371. };
  30372. WebGLRenderer.prototype.animate = function ( callback ) {
  30373. console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' );
  30374. this.setAnimationLoop( callback );
  30375. };
  30376. WebGLRenderer.prototype.getCurrentRenderTarget = function () {
  30377. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  30378. return this.getRenderTarget();
  30379. };
  30380. WebGLRenderer.prototype.getMaxAnisotropy = function () {
  30381. console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
  30382. return this.capabilities.getMaxAnisotropy();
  30383. };
  30384. WebGLRenderer.prototype.getPrecision = function () {
  30385. console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
  30386. return this.capabilities.precision;
  30387. };
  30388. WebGLRenderer.prototype.resetGLState = function () {
  30389. console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' );
  30390. return this.state.reset();
  30391. };
  30392. WebGLRenderer.prototype.supportsFloatTextures = function () {
  30393. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  30394. return this.extensions.get( 'OES_texture_float' );
  30395. };
  30396. WebGLRenderer.prototype.supportsHalfFloatTextures = function () {
  30397. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  30398. return this.extensions.get( 'OES_texture_half_float' );
  30399. };
  30400. WebGLRenderer.prototype.supportsStandardDerivatives = function () {
  30401. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  30402. return this.extensions.get( 'OES_standard_derivatives' );
  30403. };
  30404. WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () {
  30405. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  30406. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  30407. };
  30408. WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () {
  30409. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  30410. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  30411. };
  30412. WebGLRenderer.prototype.supportsBlendMinMax = function () {
  30413. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  30414. return this.extensions.get( 'EXT_blend_minmax' );
  30415. };
  30416. WebGLRenderer.prototype.supportsVertexTextures = function () {
  30417. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  30418. return this.capabilities.vertexTextures;
  30419. };
  30420. WebGLRenderer.prototype.supportsInstancedArrays = function () {
  30421. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  30422. return this.extensions.get( 'ANGLE_instanced_arrays' );
  30423. };
  30424. WebGLRenderer.prototype.enableScissorTest = function ( boolean ) {
  30425. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  30426. this.setScissorTest( boolean );
  30427. };
  30428. WebGLRenderer.prototype.initMaterial = function () {
  30429. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  30430. };
  30431. WebGLRenderer.prototype.addPrePlugin = function () {
  30432. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  30433. };
  30434. WebGLRenderer.prototype.addPostPlugin = function () {
  30435. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  30436. };
  30437. WebGLRenderer.prototype.updateShadowMap = function () {
  30438. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  30439. };
  30440. WebGLRenderer.prototype.setFaceCulling = function () {
  30441. console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' );
  30442. };
  30443. WebGLRenderer.prototype.allocTextureUnit = function () {
  30444. console.warn( 'THREE.WebGLRenderer: .allocTextureUnit() has been removed.' );
  30445. };
  30446. WebGLRenderer.prototype.setTexture = function () {
  30447. console.warn( 'THREE.WebGLRenderer: .setTexture() has been removed.' );
  30448. };
  30449. WebGLRenderer.prototype.setTexture2D = function () {
  30450. console.warn( 'THREE.WebGLRenderer: .setTexture2D() has been removed.' );
  30451. };
  30452. WebGLRenderer.prototype.setTextureCube = function () {
  30453. console.warn( 'THREE.WebGLRenderer: .setTextureCube() has been removed.' );
  30454. };
  30455. WebGLRenderer.prototype.getActiveMipMapLevel = function () {
  30456. console.warn( 'THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().' );
  30457. return this.getActiveMipmapLevel();
  30458. };
  30459. Object.defineProperties( WebGLRenderer.prototype, {
  30460. shadowMapEnabled: {
  30461. get: function () {
  30462. return this.shadowMap.enabled;
  30463. },
  30464. set: function ( value ) {
  30465. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  30466. this.shadowMap.enabled = value;
  30467. }
  30468. },
  30469. shadowMapType: {
  30470. get: function () {
  30471. return this.shadowMap.type;
  30472. },
  30473. set: function ( value ) {
  30474. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  30475. this.shadowMap.type = value;
  30476. }
  30477. },
  30478. shadowMapCullFace: {
  30479. get: function () {
  30480. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  30481. return undefined;
  30482. },
  30483. set: function ( /* value */ ) {
  30484. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  30485. }
  30486. },
  30487. context: {
  30488. get: function () {
  30489. console.warn( 'THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.' );
  30490. return this.getContext();
  30491. }
  30492. },
  30493. vr: {
  30494. get: function () {
  30495. console.warn( 'THREE.WebGLRenderer: .vr has been renamed to .xr' );
  30496. return this.xr;
  30497. }
  30498. },
  30499. gammaInput: {
  30500. get: function () {
  30501. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  30502. return false;
  30503. },
  30504. set: function () {
  30505. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  30506. }
  30507. },
  30508. gammaOutput: {
  30509. get: function () {
  30510. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  30511. return false;
  30512. },
  30513. set: function ( value ) {
  30514. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  30515. this.outputEncoding = ( value === true ) ? sRGBEncoding : LinearEncoding;
  30516. }
  30517. },
  30518. toneMappingWhitePoint: {
  30519. get: function () {
  30520. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  30521. return 1.0;
  30522. },
  30523. set: function () {
  30524. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  30525. }
  30526. },
  30527. } );
  30528. Object.defineProperties( WebGLShadowMap.prototype, {
  30529. cullFace: {
  30530. get: function () {
  30531. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  30532. return undefined;
  30533. },
  30534. set: function ( /* cullFace */ ) {
  30535. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  30536. }
  30537. },
  30538. renderReverseSided: {
  30539. get: function () {
  30540. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  30541. return undefined;
  30542. },
  30543. set: function () {
  30544. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  30545. }
  30546. },
  30547. renderSingleSided: {
  30548. get: function () {
  30549. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  30550. return undefined;
  30551. },
  30552. set: function () {
  30553. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  30554. }
  30555. }
  30556. } );
  30557. function WebGLRenderTargetCube( width, height, options ) {
  30558. console.warn( 'THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).' );
  30559. return new WebGLCubeRenderTarget( width, options );
  30560. }
  30561. //
  30562. Object.defineProperties( WebGLRenderTarget.prototype, {
  30563. wrapS: {
  30564. get: function () {
  30565. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  30566. return this.texture.wrapS;
  30567. },
  30568. set: function ( value ) {
  30569. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  30570. this.texture.wrapS = value;
  30571. }
  30572. },
  30573. wrapT: {
  30574. get: function () {
  30575. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  30576. return this.texture.wrapT;
  30577. },
  30578. set: function ( value ) {
  30579. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  30580. this.texture.wrapT = value;
  30581. }
  30582. },
  30583. magFilter: {
  30584. get: function () {
  30585. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  30586. return this.texture.magFilter;
  30587. },
  30588. set: function ( value ) {
  30589. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  30590. this.texture.magFilter = value;
  30591. }
  30592. },
  30593. minFilter: {
  30594. get: function () {
  30595. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  30596. return this.texture.minFilter;
  30597. },
  30598. set: function ( value ) {
  30599. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  30600. this.texture.minFilter = value;
  30601. }
  30602. },
  30603. anisotropy: {
  30604. get: function () {
  30605. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  30606. return this.texture.anisotropy;
  30607. },
  30608. set: function ( value ) {
  30609. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  30610. this.texture.anisotropy = value;
  30611. }
  30612. },
  30613. offset: {
  30614. get: function () {
  30615. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  30616. return this.texture.offset;
  30617. },
  30618. set: function ( value ) {
  30619. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  30620. this.texture.offset = value;
  30621. }
  30622. },
  30623. repeat: {
  30624. get: function () {
  30625. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  30626. return this.texture.repeat;
  30627. },
  30628. set: function ( value ) {
  30629. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  30630. this.texture.repeat = value;
  30631. }
  30632. },
  30633. format: {
  30634. get: function () {
  30635. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  30636. return this.texture.format;
  30637. },
  30638. set: function ( value ) {
  30639. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  30640. this.texture.format = value;
  30641. }
  30642. },
  30643. type: {
  30644. get: function () {
  30645. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  30646. return this.texture.type;
  30647. },
  30648. set: function ( value ) {
  30649. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  30650. this.texture.type = value;
  30651. }
  30652. },
  30653. generateMipmaps: {
  30654. get: function () {
  30655. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  30656. return this.texture.generateMipmaps;
  30657. },
  30658. set: function ( value ) {
  30659. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  30660. this.texture.generateMipmaps = value;
  30661. }
  30662. }
  30663. } );
  30664. //
  30665. Audio.prototype.load = function ( file ) {
  30666. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  30667. const scope = this;
  30668. const audioLoader = new AudioLoader();
  30669. audioLoader.load( file, function ( buffer ) {
  30670. scope.setBuffer( buffer );
  30671. } );
  30672. return this;
  30673. };
  30674. AudioAnalyser.prototype.getData = function () {
  30675. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  30676. return this.getFrequencyData();
  30677. };
  30678. //
  30679. CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) {
  30680. console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' );
  30681. return this.update( renderer, scene );
  30682. };
  30683. CubeCamera.prototype.clear = function ( renderer, color, depth, stencil ) {
  30684. console.warn( 'THREE.CubeCamera: .clear() is now .renderTarget.clear().' );
  30685. return this.renderTarget.clear( renderer, color, depth, stencil );
  30686. };
  30687. ImageUtils.crossOrigin = undefined;
  30688. ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) {
  30689. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  30690. const loader = new TextureLoader();
  30691. loader.setCrossOrigin( this.crossOrigin );
  30692. const texture = loader.load( url, onLoad, undefined, onError );
  30693. if ( mapping ) texture.mapping = mapping;
  30694. return texture;
  30695. };
  30696. ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) {
  30697. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  30698. const loader = new CubeTextureLoader();
  30699. loader.setCrossOrigin( this.crossOrigin );
  30700. const texture = loader.load( urls, onLoad, undefined, onError );
  30701. if ( mapping ) texture.mapping = mapping;
  30702. return texture;
  30703. };
  30704. ImageUtils.loadCompressedTexture = function () {
  30705. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  30706. };
  30707. ImageUtils.loadCompressedTextureCube = function () {
  30708. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  30709. };
  30710. //
  30711. function CanvasRenderer() {
  30712. console.error( 'THREE.CanvasRenderer has been removed' );
  30713. }
  30714. //
  30715. function JSONLoader() {
  30716. console.error( 'THREE.JSONLoader has been removed.' );
  30717. }
  30718. //
  30719. const SceneUtils = {
  30720. createMultiMaterialObject: function ( /* geometry, materials */ ) {
  30721. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  30722. },
  30723. detach: function ( /* child, parent, scene */ ) {
  30724. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  30725. },
  30726. attach: function ( /* child, scene, parent */ ) {
  30727. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  30728. }
  30729. };
  30730. //
  30731. function LensFlare() {
  30732. console.error( 'THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js' );
  30733. }
  30734. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  30735. /* eslint-disable no-undef */
  30736. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  30737. revision: REVISION,
  30738. } } ) );
  30739. /* eslint-enable no-undef */
  30740. }
  30741. if ( typeof window !== 'undefined' ) {
  30742. if ( window.__THREE__ ) {
  30743. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  30744. } else {
  30745. window.__THREE__ = REVISION;
  30746. }
  30747. }
  30748. /***/ }),
  30749. /***/ "./node_modules/three/examples/jsm/loaders/GLTFLoader.js":
  30750. /*!***************************************************************!*\
  30751. !*** ./node_modules/three/examples/jsm/loaders/GLTFLoader.js ***!
  30752. \***************************************************************/
  30753. /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
  30754. "use strict";
  30755. __webpack_require__.r(__webpack_exports__);
  30756. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  30757. /* harmony export */ "GLTFLoader": () => (/* binding */ GLTFLoader)
  30758. /* harmony export */ });
  30759. /* harmony import */ var three__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! three */ "./node_modules/three/build/three.module.js");
  30760. class GLTFLoader extends three__WEBPACK_IMPORTED_MODULE_0__.Loader {
  30761. constructor( manager ) {
  30762. super( manager );
  30763. this.dracoLoader = null;
  30764. this.ktx2Loader = null;
  30765. this.meshoptDecoder = null;
  30766. this.pluginCallbacks = [];
  30767. this.register( function ( parser ) {
  30768. return new GLTFMaterialsClearcoatExtension( parser );
  30769. } );
  30770. this.register( function ( parser ) {
  30771. return new GLTFTextureBasisUExtension( parser );
  30772. } );
  30773. this.register( function ( parser ) {
  30774. return new GLTFTextureWebPExtension( parser );
  30775. } );
  30776. this.register( function ( parser ) {
  30777. return new GLTFMaterialsTransmissionExtension( parser );
  30778. } );
  30779. this.register( function ( parser ) {
  30780. return new GLTFMaterialsVolumeExtension( parser );
  30781. } );
  30782. this.register( function ( parser ) {
  30783. return new GLTFMaterialsIorExtension( parser );
  30784. } );
  30785. this.register( function ( parser ) {
  30786. return new GLTFMaterialsSpecularExtension( parser );
  30787. } );
  30788. this.register( function ( parser ) {
  30789. return new GLTFLightsExtension( parser );
  30790. } );
  30791. this.register( function ( parser ) {
  30792. return new GLTFMeshoptCompression( parser );
  30793. } );
  30794. }
  30795. load( url, onLoad, onProgress, onError ) {
  30796. const scope = this;
  30797. let resourcePath;
  30798. if ( this.resourcePath !== '' ) {
  30799. resourcePath = this.resourcePath;
  30800. } else if ( this.path !== '' ) {
  30801. resourcePath = this.path;
  30802. } else {
  30803. resourcePath = three__WEBPACK_IMPORTED_MODULE_0__.LoaderUtils.extractUrlBase( url );
  30804. }
  30805. // Tells the LoadingManager to track an extra item, which resolves after
  30806. // the model is fully loaded. This means the count of items loaded will
  30807. // be incorrect, but ensures manager.onLoad() does not fire early.
  30808. this.manager.itemStart( url );
  30809. const _onError = function ( e ) {
  30810. if ( onError ) {
  30811. onError( e );
  30812. } else {
  30813. console.error( e );
  30814. }
  30815. scope.manager.itemError( url );
  30816. scope.manager.itemEnd( url );
  30817. };
  30818. const loader = new three__WEBPACK_IMPORTED_MODULE_0__.FileLoader( this.manager );
  30819. loader.setPath( this.path );
  30820. loader.setResponseType( 'arraybuffer' );
  30821. loader.setRequestHeader( this.requestHeader );
  30822. loader.setWithCredentials( this.withCredentials );
  30823. loader.load( url, function ( data ) {
  30824. try {
  30825. scope.parse( data, resourcePath, function ( gltf ) {
  30826. onLoad( gltf );
  30827. scope.manager.itemEnd( url );
  30828. }, _onError );
  30829. } catch ( e ) {
  30830. _onError( e );
  30831. }
  30832. }, onProgress, _onError );
  30833. }
  30834. setDRACOLoader( dracoLoader ) {
  30835. this.dracoLoader = dracoLoader;
  30836. return this;
  30837. }
  30838. setDDSLoader() {
  30839. throw new Error(
  30840. 'THREE.GLTFLoader: "MSFT_texture_dds" no longer supported. Please update to "KHR_texture_basisu".'
  30841. );
  30842. }
  30843. setKTX2Loader( ktx2Loader ) {
  30844. this.ktx2Loader = ktx2Loader;
  30845. return this;
  30846. }
  30847. setMeshoptDecoder( meshoptDecoder ) {
  30848. this.meshoptDecoder = meshoptDecoder;
  30849. return this;
  30850. }
  30851. register( callback ) {
  30852. if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) {
  30853. this.pluginCallbacks.push( callback );
  30854. }
  30855. return this;
  30856. }
  30857. unregister( callback ) {
  30858. if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) {
  30859. this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 );
  30860. }
  30861. return this;
  30862. }
  30863. parse( data, path, onLoad, onError ) {
  30864. let content;
  30865. const extensions = {};
  30866. const plugins = {};
  30867. if ( typeof data === 'string' ) {
  30868. content = data;
  30869. } else {
  30870. const magic = three__WEBPACK_IMPORTED_MODULE_0__.LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  30871. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  30872. try {
  30873. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  30874. } catch ( error ) {
  30875. if ( onError ) onError( error );
  30876. return;
  30877. }
  30878. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  30879. } else {
  30880. content = three__WEBPACK_IMPORTED_MODULE_0__.LoaderUtils.decodeText( new Uint8Array( data ) );
  30881. }
  30882. }
  30883. const json = JSON.parse( content );
  30884. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  30885. if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) );
  30886. return;
  30887. }
  30888. const parser = new GLTFParser( json, {
  30889. path: path || this.resourcePath || '',
  30890. crossOrigin: this.crossOrigin,
  30891. requestHeader: this.requestHeader,
  30892. manager: this.manager,
  30893. ktx2Loader: this.ktx2Loader,
  30894. meshoptDecoder: this.meshoptDecoder
  30895. } );
  30896. parser.fileLoader.setRequestHeader( this.requestHeader );
  30897. for ( let i = 0; i < this.pluginCallbacks.length; i ++ ) {
  30898. const plugin = this.pluginCallbacks[ i ]( parser );
  30899. plugins[ plugin.name ] = plugin;
  30900. // Workaround to avoid determining as unknown extension
  30901. // in addUnknownExtensionsToUserData().
  30902. // Remove this workaround if we move all the existing
  30903. // extension handlers to plugin system
  30904. extensions[ plugin.name ] = true;
  30905. }
  30906. if ( json.extensionsUsed ) {
  30907. for ( let i = 0; i < json.extensionsUsed.length; ++ i ) {
  30908. const extensionName = json.extensionsUsed[ i ];
  30909. const extensionsRequired = json.extensionsRequired || [];
  30910. switch ( extensionName ) {
  30911. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  30912. extensions[ extensionName ] = new GLTFMaterialsUnlitExtension();
  30913. break;
  30914. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  30915. extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  30916. break;
  30917. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  30918. extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );
  30919. break;
  30920. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  30921. extensions[ extensionName ] = new GLTFTextureTransformExtension();
  30922. break;
  30923. case EXTENSIONS.KHR_MESH_QUANTIZATION:
  30924. extensions[ extensionName ] = new GLTFMeshQuantizationExtension();
  30925. break;
  30926. default:
  30927. if ( extensionsRequired.indexOf( extensionName ) >= 0 && plugins[ extensionName ] === undefined ) {
  30928. console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' );
  30929. }
  30930. }
  30931. }
  30932. }
  30933. parser.setExtensions( extensions );
  30934. parser.setPlugins( plugins );
  30935. parser.parse( onLoad, onError );
  30936. }
  30937. }
  30938. /* GLTFREGISTRY */
  30939. function GLTFRegistry() {
  30940. let objects = {};
  30941. return {
  30942. get: function ( key ) {
  30943. return objects[ key ];
  30944. },
  30945. add: function ( key, object ) {
  30946. objects[ key ] = object;
  30947. },
  30948. remove: function ( key ) {
  30949. delete objects[ key ];
  30950. },
  30951. removeAll: function () {
  30952. objects = {};
  30953. }
  30954. };
  30955. }
  30956. /*********************************/
  30957. /********** EXTENSIONS ***********/
  30958. /*********************************/
  30959. const EXTENSIONS = {
  30960. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  30961. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  30962. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  30963. KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',
  30964. KHR_MATERIALS_IOR: 'KHR_materials_ior',
  30965. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  30966. KHR_MATERIALS_SPECULAR: 'KHR_materials_specular',
  30967. KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission',
  30968. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  30969. KHR_MATERIALS_VOLUME: 'KHR_materials_volume',
  30970. KHR_TEXTURE_BASISU: 'KHR_texture_basisu',
  30971. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  30972. KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',
  30973. EXT_TEXTURE_WEBP: 'EXT_texture_webp',
  30974. EXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression'
  30975. };
  30976. /**
  30977. * Punctual Lights Extension
  30978. *
  30979. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  30980. */
  30981. class GLTFLightsExtension {
  30982. constructor( parser ) {
  30983. this.parser = parser;
  30984. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  30985. // Object3D instance caches
  30986. this.cache = { refs: {}, uses: {} };
  30987. }
  30988. _markDefs() {
  30989. const parser = this.parser;
  30990. const nodeDefs = this.parser.json.nodes || [];
  30991. for ( let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  30992. const nodeDef = nodeDefs[ nodeIndex ];
  30993. if ( nodeDef.extensions
  30994. && nodeDef.extensions[ this.name ]
  30995. && nodeDef.extensions[ this.name ].light !== undefined ) {
  30996. parser._addNodeRef( this.cache, nodeDef.extensions[ this.name ].light );
  30997. }
  30998. }
  30999. }
  31000. _loadLight( lightIndex ) {
  31001. const parser = this.parser;
  31002. const cacheKey = 'light:' + lightIndex;
  31003. let dependency = parser.cache.get( cacheKey );
  31004. if ( dependency ) return dependency;
  31005. const json = parser.json;
  31006. const extensions = ( json.extensions && json.extensions[ this.name ] ) || {};
  31007. const lightDefs = extensions.lights || [];
  31008. const lightDef = lightDefs[ lightIndex ];
  31009. let lightNode;
  31010. const color = new three__WEBPACK_IMPORTED_MODULE_0__.Color( 0xffffff );
  31011. if ( lightDef.color !== undefined ) color.fromArray( lightDef.color );
  31012. const range = lightDef.range !== undefined ? lightDef.range : 0;
  31013. switch ( lightDef.type ) {
  31014. case 'directional':
  31015. lightNode = new three__WEBPACK_IMPORTED_MODULE_0__.DirectionalLight( color );
  31016. lightNode.target.position.set( 0, 0, - 1 );
  31017. lightNode.add( lightNode.target );
  31018. break;
  31019. case 'point':
  31020. lightNode = new three__WEBPACK_IMPORTED_MODULE_0__.PointLight( color );
  31021. lightNode.distance = range;
  31022. break;
  31023. case 'spot':
  31024. lightNode = new three__WEBPACK_IMPORTED_MODULE_0__.SpotLight( color );
  31025. lightNode.distance = range;
  31026. // Handle spotlight properties.
  31027. lightDef.spot = lightDef.spot || {};
  31028. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  31029. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  31030. lightNode.angle = lightDef.spot.outerConeAngle;
  31031. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  31032. lightNode.target.position.set( 0, 0, - 1 );
  31033. lightNode.add( lightNode.target );
  31034. break;
  31035. default:
  31036. throw new Error( 'THREE.GLTFLoader: Unexpected light type: ' + lightDef.type );
  31037. }
  31038. // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  31039. // here, because node-level parsing will only override position if explicitly specified.
  31040. lightNode.position.set( 0, 0, 0 );
  31041. lightNode.decay = 2;
  31042. if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;
  31043. lightNode.name = parser.createUniqueName( lightDef.name || ( 'light_' + lightIndex ) );
  31044. dependency = Promise.resolve( lightNode );
  31045. parser.cache.add( cacheKey, dependency );
  31046. return dependency;
  31047. }
  31048. createNodeAttachment( nodeIndex ) {
  31049. const self = this;
  31050. const parser = this.parser;
  31051. const json = parser.json;
  31052. const nodeDef = json.nodes[ nodeIndex ];
  31053. const lightDef = ( nodeDef.extensions && nodeDef.extensions[ this.name ] ) || {};
  31054. const lightIndex = lightDef.light;
  31055. if ( lightIndex === undefined ) return null;
  31056. return this._loadLight( lightIndex ).then( function ( light ) {
  31057. return parser._getNodeRef( self.cache, lightIndex, light );
  31058. } );
  31059. }
  31060. }
  31061. /**
  31062. * Unlit Materials Extension
  31063. *
  31064. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  31065. */
  31066. class GLTFMaterialsUnlitExtension {
  31067. constructor() {
  31068. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  31069. }
  31070. getMaterialType() {
  31071. return three__WEBPACK_IMPORTED_MODULE_0__.MeshBasicMaterial;
  31072. }
  31073. extendParams( materialParams, materialDef, parser ) {
  31074. const pending = [];
  31075. materialParams.color = new three__WEBPACK_IMPORTED_MODULE_0__.Color( 1.0, 1.0, 1.0 );
  31076. materialParams.opacity = 1.0;
  31077. const metallicRoughness = materialDef.pbrMetallicRoughness;
  31078. if ( metallicRoughness ) {
  31079. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  31080. const array = metallicRoughness.baseColorFactor;
  31081. materialParams.color.fromArray( array );
  31082. materialParams.opacity = array[ 3 ];
  31083. }
  31084. if ( metallicRoughness.baseColorTexture !== undefined ) {
  31085. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  31086. }
  31087. }
  31088. return Promise.all( pending );
  31089. }
  31090. }
  31091. /**
  31092. * Clearcoat Materials Extension
  31093. *
  31094. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
  31095. */
  31096. class GLTFMaterialsClearcoatExtension {
  31097. constructor( parser ) {
  31098. this.parser = parser;
  31099. this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;
  31100. }
  31101. getMaterialType( materialIndex ) {
  31102. const parser = this.parser;
  31103. const materialDef = parser.json.materials[ materialIndex ];
  31104. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  31105. return three__WEBPACK_IMPORTED_MODULE_0__.MeshPhysicalMaterial;
  31106. }
  31107. extendMaterialParams( materialIndex, materialParams ) {
  31108. const parser = this.parser;
  31109. const materialDef = parser.json.materials[ materialIndex ];
  31110. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  31111. return Promise.resolve();
  31112. }
  31113. const pending = [];
  31114. const extension = materialDef.extensions[ this.name ];
  31115. if ( extension.clearcoatFactor !== undefined ) {
  31116. materialParams.clearcoat = extension.clearcoatFactor;
  31117. }
  31118. if ( extension.clearcoatTexture !== undefined ) {
  31119. pending.push( parser.assignTexture( materialParams, 'clearcoatMap', extension.clearcoatTexture ) );
  31120. }
  31121. if ( extension.clearcoatRoughnessFactor !== undefined ) {
  31122. materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;
  31123. }
  31124. if ( extension.clearcoatRoughnessTexture !== undefined ) {
  31125. pending.push( parser.assignTexture( materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture ) );
  31126. }
  31127. if ( extension.clearcoatNormalTexture !== undefined ) {
  31128. pending.push( parser.assignTexture( materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture ) );
  31129. if ( extension.clearcoatNormalTexture.scale !== undefined ) {
  31130. const scale = extension.clearcoatNormalTexture.scale;
  31131. // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  31132. materialParams.clearcoatNormalScale = new three__WEBPACK_IMPORTED_MODULE_0__.Vector2( scale, - scale );
  31133. }
  31134. }
  31135. return Promise.all( pending );
  31136. }
  31137. }
  31138. /**
  31139. * Transmission Materials Extension
  31140. *
  31141. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission
  31142. * Draft: https://github.com/KhronosGroup/glTF/pull/1698
  31143. */
  31144. class GLTFMaterialsTransmissionExtension {
  31145. constructor( parser ) {
  31146. this.parser = parser;
  31147. this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION;
  31148. }
  31149. getMaterialType( materialIndex ) {
  31150. const parser = this.parser;
  31151. const materialDef = parser.json.materials[ materialIndex ];
  31152. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  31153. return three__WEBPACK_IMPORTED_MODULE_0__.MeshPhysicalMaterial;
  31154. }
  31155. extendMaterialParams( materialIndex, materialParams ) {
  31156. const parser = this.parser;
  31157. const materialDef = parser.json.materials[ materialIndex ];
  31158. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  31159. return Promise.resolve();
  31160. }
  31161. const pending = [];
  31162. const extension = materialDef.extensions[ this.name ];
  31163. if ( extension.transmissionFactor !== undefined ) {
  31164. materialParams.transmission = extension.transmissionFactor;
  31165. }
  31166. if ( extension.transmissionTexture !== undefined ) {
  31167. pending.push( parser.assignTexture( materialParams, 'transmissionMap', extension.transmissionTexture ) );
  31168. }
  31169. return Promise.all( pending );
  31170. }
  31171. }
  31172. /**
  31173. * Materials Volume Extension
  31174. *
  31175. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_volume
  31176. */
  31177. class GLTFMaterialsVolumeExtension {
  31178. constructor( parser ) {
  31179. this.parser = parser;
  31180. this.name = EXTENSIONS.KHR_MATERIALS_VOLUME;
  31181. }
  31182. getMaterialType( materialIndex ) {
  31183. const parser = this.parser;
  31184. const materialDef = parser.json.materials[ materialIndex ];
  31185. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  31186. return three__WEBPACK_IMPORTED_MODULE_0__.MeshPhysicalMaterial;
  31187. }
  31188. extendMaterialParams( materialIndex, materialParams ) {
  31189. const parser = this.parser;
  31190. const materialDef = parser.json.materials[ materialIndex ];
  31191. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  31192. return Promise.resolve();
  31193. }
  31194. const pending = [];
  31195. const extension = materialDef.extensions[ this.name ];
  31196. materialParams.thickness = extension.thicknessFactor !== undefined ? extension.thicknessFactor : 0;
  31197. if ( extension.thicknessTexture !== undefined ) {
  31198. pending.push( parser.assignTexture( materialParams, 'thicknessMap', extension.thicknessTexture ) );
  31199. }
  31200. materialParams.attenuationDistance = extension.attenuationDistance || 0;
  31201. const colorArray = extension.attenuationColor || [ 1, 1, 1 ];
  31202. materialParams.attenuationTint = new three__WEBPACK_IMPORTED_MODULE_0__.Color( colorArray[ 0 ], colorArray[ 1 ], colorArray[ 2 ] );
  31203. return Promise.all( pending );
  31204. }
  31205. }
  31206. /**
  31207. * Materials ior Extension
  31208. *
  31209. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_ior
  31210. */
  31211. class GLTFMaterialsIorExtension {
  31212. constructor( parser ) {
  31213. this.parser = parser;
  31214. this.name = EXTENSIONS.KHR_MATERIALS_IOR;
  31215. }
  31216. getMaterialType( materialIndex ) {
  31217. const parser = this.parser;
  31218. const materialDef = parser.json.materials[ materialIndex ];
  31219. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  31220. return three__WEBPACK_IMPORTED_MODULE_0__.MeshPhysicalMaterial;
  31221. }
  31222. extendMaterialParams( materialIndex, materialParams ) {
  31223. const parser = this.parser;
  31224. const materialDef = parser.json.materials[ materialIndex ];
  31225. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  31226. return Promise.resolve();
  31227. }
  31228. const extension = materialDef.extensions[ this.name ];
  31229. materialParams.ior = extension.ior !== undefined ? extension.ior : 1.5;
  31230. return Promise.resolve();
  31231. }
  31232. }
  31233. /**
  31234. * Materials specular Extension
  31235. *
  31236. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_specular
  31237. */
  31238. class GLTFMaterialsSpecularExtension {
  31239. constructor( parser ) {
  31240. this.parser = parser;
  31241. this.name = EXTENSIONS.KHR_MATERIALS_SPECULAR;
  31242. }
  31243. getMaterialType( materialIndex ) {
  31244. const parser = this.parser;
  31245. const materialDef = parser.json.materials[ materialIndex ];
  31246. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  31247. return three__WEBPACK_IMPORTED_MODULE_0__.MeshPhysicalMaterial;
  31248. }
  31249. extendMaterialParams( materialIndex, materialParams ) {
  31250. const parser = this.parser;
  31251. const materialDef = parser.json.materials[ materialIndex ];
  31252. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  31253. return Promise.resolve();
  31254. }
  31255. const pending = [];
  31256. const extension = materialDef.extensions[ this.name ];
  31257. materialParams.specularIntensity = extension.specularFactor !== undefined ? extension.specularFactor : 1.0;
  31258. if ( extension.specularTexture !== undefined ) {
  31259. pending.push( parser.assignTexture( materialParams, 'specularIntensityMap', extension.specularTexture ) );
  31260. }
  31261. const colorArray = extension.specularColorFactor || [ 1, 1, 1 ];
  31262. materialParams.specularTint = new three__WEBPACK_IMPORTED_MODULE_0__.Color( colorArray[ 0 ], colorArray[ 1 ], colorArray[ 2 ] );
  31263. if ( extension.specularColorTexture !== undefined ) {
  31264. pending.push( parser.assignTexture( materialParams, 'specularTintMap', extension.specularColorTexture ).then( function ( texture ) {
  31265. texture.encoding = three__WEBPACK_IMPORTED_MODULE_0__.sRGBEncoding;
  31266. } ) );
  31267. }
  31268. return Promise.all( pending );
  31269. }
  31270. }
  31271. /**
  31272. * BasisU Texture Extension
  31273. *
  31274. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu
  31275. */
  31276. class GLTFTextureBasisUExtension {
  31277. constructor( parser ) {
  31278. this.parser = parser;
  31279. this.name = EXTENSIONS.KHR_TEXTURE_BASISU;
  31280. }
  31281. loadTexture( textureIndex ) {
  31282. const parser = this.parser;
  31283. const json = parser.json;
  31284. const textureDef = json.textures[ textureIndex ];
  31285. if ( ! textureDef.extensions || ! textureDef.extensions[ this.name ] ) {
  31286. return null;
  31287. }
  31288. const extension = textureDef.extensions[ this.name ];
  31289. const source = json.images[ extension.source ];
  31290. const loader = parser.options.ktx2Loader;
  31291. if ( ! loader ) {
  31292. if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {
  31293. throw new Error( 'THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures' );
  31294. } else {
  31295. // Assumes that the extension is optional and that a fallback texture is present
  31296. return null;
  31297. }
  31298. }
  31299. return parser.loadTextureImage( textureIndex, source, loader );
  31300. }
  31301. }
  31302. /**
  31303. * WebP Texture Extension
  31304. *
  31305. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp
  31306. */
  31307. class GLTFTextureWebPExtension {
  31308. constructor( parser ) {
  31309. this.parser = parser;
  31310. this.name = EXTENSIONS.EXT_TEXTURE_WEBP;
  31311. this.isSupported = null;
  31312. }
  31313. loadTexture( textureIndex ) {
  31314. const name = this.name;
  31315. const parser = this.parser;
  31316. const json = parser.json;
  31317. const textureDef = json.textures[ textureIndex ];
  31318. if ( ! textureDef.extensions || ! textureDef.extensions[ name ] ) {
  31319. return null;
  31320. }
  31321. const extension = textureDef.extensions[ name ];
  31322. const source = json.images[ extension.source ];
  31323. let loader = parser.textureLoader;
  31324. if ( source.uri ) {
  31325. const handler = parser.options.manager.getHandler( source.uri );
  31326. if ( handler !== null ) loader = handler;
  31327. }
  31328. return this.detectSupport().then( function ( isSupported ) {
  31329. if ( isSupported ) return parser.loadTextureImage( textureIndex, source, loader );
  31330. if ( json.extensionsRequired && json.extensionsRequired.indexOf( name ) >= 0 ) {
  31331. throw new Error( 'THREE.GLTFLoader: WebP required by asset but unsupported.' );
  31332. }
  31333. // Fall back to PNG or JPEG.
  31334. return parser.loadTexture( textureIndex );
  31335. } );
  31336. }
  31337. detectSupport() {
  31338. if ( ! this.isSupported ) {
  31339. this.isSupported = new Promise( function ( resolve ) {
  31340. const image = new Image();
  31341. // Lossy test image. Support for lossy images doesn't guarantee support for all
  31342. // WebP images, unfortunately.
  31343. image.src = 'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA';
  31344. image.onload = image.onerror = function () {
  31345. resolve( image.height === 1 );
  31346. };
  31347. } );
  31348. }
  31349. return this.isSupported;
  31350. }
  31351. }
  31352. /**
  31353. * meshopt BufferView Compression Extension
  31354. *
  31355. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_meshopt_compression
  31356. */
  31357. class GLTFMeshoptCompression {
  31358. constructor( parser ) {
  31359. this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION;
  31360. this.parser = parser;
  31361. }
  31362. loadBufferView( index ) {
  31363. const json = this.parser.json;
  31364. const bufferView = json.bufferViews[ index ];
  31365. if ( bufferView.extensions && bufferView.extensions[ this.name ] ) {
  31366. const extensionDef = bufferView.extensions[ this.name ];
  31367. const buffer = this.parser.getDependency( 'buffer', extensionDef.buffer );
  31368. const decoder = this.parser.options.meshoptDecoder;
  31369. if ( ! decoder || ! decoder.supported ) {
  31370. if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {
  31371. throw new Error( 'THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files' );
  31372. } else {
  31373. // Assumes that the extension is optional and that fallback buffer data is present
  31374. return null;
  31375. }
  31376. }
  31377. return Promise.all( [ buffer, decoder.ready ] ).then( function ( res ) {
  31378. const byteOffset = extensionDef.byteOffset || 0;
  31379. const byteLength = extensionDef.byteLength || 0;
  31380. const count = extensionDef.count;
  31381. const stride = extensionDef.byteStride;
  31382. const result = new ArrayBuffer( count * stride );
  31383. const source = new Uint8Array( res[ 0 ], byteOffset, byteLength );
  31384. decoder.decodeGltfBuffer( new Uint8Array( result ), count, stride, source, extensionDef.mode, extensionDef.filter );
  31385. return result;
  31386. } );
  31387. } else {
  31388. return null;
  31389. }
  31390. }
  31391. }
  31392. /* BINARY EXTENSION */
  31393. const BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  31394. const BINARY_EXTENSION_HEADER_LENGTH = 12;
  31395. const BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  31396. class GLTFBinaryExtension {
  31397. constructor( data ) {
  31398. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  31399. this.content = null;
  31400. this.body = null;
  31401. const headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  31402. this.header = {
  31403. magic: three__WEBPACK_IMPORTED_MODULE_0__.LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  31404. version: headerView.getUint32( 4, true ),
  31405. length: headerView.getUint32( 8, true )
  31406. };
  31407. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  31408. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  31409. } else if ( this.header.version < 2.0 ) {
  31410. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected.' );
  31411. }
  31412. const chunkContentsLength = this.header.length - BINARY_EXTENSION_HEADER_LENGTH;
  31413. const chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  31414. let chunkIndex = 0;
  31415. while ( chunkIndex < chunkContentsLength ) {
  31416. const chunkLength = chunkView.getUint32( chunkIndex, true );
  31417. chunkIndex += 4;
  31418. const chunkType = chunkView.getUint32( chunkIndex, true );
  31419. chunkIndex += 4;
  31420. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  31421. const contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  31422. this.content = three__WEBPACK_IMPORTED_MODULE_0__.LoaderUtils.decodeText( contentArray );
  31423. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  31424. const byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  31425. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  31426. }
  31427. // Clients must ignore chunks with unknown types.
  31428. chunkIndex += chunkLength;
  31429. }
  31430. if ( this.content === null ) {
  31431. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  31432. }
  31433. }
  31434. }
  31435. /**
  31436. * DRACO Mesh Compression Extension
  31437. *
  31438. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  31439. */
  31440. class GLTFDracoMeshCompressionExtension {
  31441. constructor( json, dracoLoader ) {
  31442. if ( ! dracoLoader ) {
  31443. throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
  31444. }
  31445. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  31446. this.json = json;
  31447. this.dracoLoader = dracoLoader;
  31448. this.dracoLoader.preload();
  31449. }
  31450. decodePrimitive( primitive, parser ) {
  31451. const json = this.json;
  31452. const dracoLoader = this.dracoLoader;
  31453. const bufferViewIndex = primitive.extensions[ this.name ].bufferView;
  31454. const gltfAttributeMap = primitive.extensions[ this.name ].attributes;
  31455. const threeAttributeMap = {};
  31456. const attributeNormalizedMap = {};
  31457. const attributeTypeMap = {};
  31458. for ( const attributeName in gltfAttributeMap ) {
  31459. const threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  31460. threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ];
  31461. }
  31462. for ( const attributeName in primitive.attributes ) {
  31463. const threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  31464. if ( gltfAttributeMap[ attributeName ] !== undefined ) {
  31465. const accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];
  31466. const componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  31467. attributeTypeMap[ threeAttributeName ] = componentType;
  31468. attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true;
  31469. }
  31470. }
  31471. return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
  31472. return new Promise( function ( resolve ) {
  31473. dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {
  31474. for ( const attributeName in geometry.attributes ) {
  31475. const attribute = geometry.attributes[ attributeName ];
  31476. const normalized = attributeNormalizedMap[ attributeName ];
  31477. if ( normalized !== undefined ) attribute.normalized = normalized;
  31478. }
  31479. resolve( geometry );
  31480. }, threeAttributeMap, attributeTypeMap );
  31481. } );
  31482. } );
  31483. }
  31484. }
  31485. /**
  31486. * Texture Transform Extension
  31487. *
  31488. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  31489. */
  31490. class GLTFTextureTransformExtension {
  31491. constructor() {
  31492. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  31493. }
  31494. extendTexture( texture, transform ) {
  31495. if ( transform.texCoord !== undefined ) {
  31496. console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' );
  31497. }
  31498. if ( transform.offset === undefined && transform.rotation === undefined && transform.scale === undefined ) {
  31499. // See https://github.com/mrdoob/three.js/issues/21819.
  31500. return texture;
  31501. }
  31502. texture = texture.clone();
  31503. if ( transform.offset !== undefined ) {
  31504. texture.offset.fromArray( transform.offset );
  31505. }
  31506. if ( transform.rotation !== undefined ) {
  31507. texture.rotation = transform.rotation;
  31508. }
  31509. if ( transform.scale !== undefined ) {
  31510. texture.repeat.fromArray( transform.scale );
  31511. }
  31512. texture.needsUpdate = true;
  31513. return texture;
  31514. }
  31515. }
  31516. /**
  31517. * Specular-Glossiness Extension
  31518. *
  31519. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  31520. */
  31521. /**
  31522. * A sub class of StandardMaterial with some of the functionality
  31523. * changed via the `onBeforeCompile` callback
  31524. * @pailhead
  31525. */
  31526. class GLTFMeshStandardSGMaterial extends three__WEBPACK_IMPORTED_MODULE_0__.MeshStandardMaterial {
  31527. constructor( params ) {
  31528. super();
  31529. this.isGLTFSpecularGlossinessMaterial = true;
  31530. //various chunks that need replacing
  31531. const specularMapParsFragmentChunk = [
  31532. '#ifdef USE_SPECULARMAP',
  31533. ' uniform sampler2D specularMap;',
  31534. '#endif'
  31535. ].join( '\n' );
  31536. const glossinessMapParsFragmentChunk = [
  31537. '#ifdef USE_GLOSSINESSMAP',
  31538. ' uniform sampler2D glossinessMap;',
  31539. '#endif'
  31540. ].join( '\n' );
  31541. const specularMapFragmentChunk = [
  31542. 'vec3 specularFactor = specular;',
  31543. '#ifdef USE_SPECULARMAP',
  31544. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  31545. ' texelSpecular = sRGBToLinear( texelSpecular );',
  31546. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  31547. ' specularFactor *= texelSpecular.rgb;',
  31548. '#endif'
  31549. ].join( '\n' );
  31550. const glossinessMapFragmentChunk = [
  31551. 'float glossinessFactor = glossiness;',
  31552. '#ifdef USE_GLOSSINESSMAP',
  31553. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  31554. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  31555. ' glossinessFactor *= texelGlossiness.a;',
  31556. '#endif'
  31557. ].join( '\n' );
  31558. const lightPhysicalFragmentChunk = [
  31559. 'PhysicalMaterial material;',
  31560. 'material.diffuseColor = diffuseColor.rgb * ( 1. - max( specularFactor.r, max( specularFactor.g, specularFactor.b ) ) );',
  31561. 'vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );',
  31562. 'float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );',
  31563. 'material.roughness = max( 1.0 - glossinessFactor, 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.',
  31564. 'material.roughness += geometryRoughness;',
  31565. 'material.roughness = min( material.roughness, 1.0 );',
  31566. 'material.specularColor = specularFactor;',
  31567. ].join( '\n' );
  31568. const uniforms = {
  31569. specular: { value: new three__WEBPACK_IMPORTED_MODULE_0__.Color().setHex( 0xffffff ) },
  31570. glossiness: { value: 1 },
  31571. specularMap: { value: null },
  31572. glossinessMap: { value: null }
  31573. };
  31574. this._extraUniforms = uniforms;
  31575. this.onBeforeCompile = function ( shader ) {
  31576. for ( const uniformName in uniforms ) {
  31577. shader.uniforms[ uniformName ] = uniforms[ uniformName ];
  31578. }
  31579. shader.fragmentShader = shader.fragmentShader
  31580. .replace( 'uniform float roughness;', 'uniform vec3 specular;' )
  31581. .replace( 'uniform float metalness;', 'uniform float glossiness;' )
  31582. .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
  31583. .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
  31584. .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
  31585. .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
  31586. .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  31587. };
  31588. Object.defineProperties( this, {
  31589. specular: {
  31590. get: function () {
  31591. return uniforms.specular.value;
  31592. },
  31593. set: function ( v ) {
  31594. uniforms.specular.value = v;
  31595. }
  31596. },
  31597. specularMap: {
  31598. get: function () {
  31599. return uniforms.specularMap.value;
  31600. },
  31601. set: function ( v ) {
  31602. uniforms.specularMap.value = v;
  31603. if ( v ) {
  31604. this.defines.USE_SPECULARMAP = ''; // USE_UV is set by the renderer for specular maps
  31605. } else {
  31606. delete this.defines.USE_SPECULARMAP;
  31607. }
  31608. }
  31609. },
  31610. glossiness: {
  31611. get: function () {
  31612. return uniforms.glossiness.value;
  31613. },
  31614. set: function ( v ) {
  31615. uniforms.glossiness.value = v;
  31616. }
  31617. },
  31618. glossinessMap: {
  31619. get: function () {
  31620. return uniforms.glossinessMap.value;
  31621. },
  31622. set: function ( v ) {
  31623. uniforms.glossinessMap.value = v;
  31624. if ( v ) {
  31625. this.defines.USE_GLOSSINESSMAP = '';
  31626. this.defines.USE_UV = '';
  31627. } else {
  31628. delete this.defines.USE_GLOSSINESSMAP;
  31629. delete this.defines.USE_UV;
  31630. }
  31631. }
  31632. }
  31633. } );
  31634. delete this.metalness;
  31635. delete this.roughness;
  31636. delete this.metalnessMap;
  31637. delete this.roughnessMap;
  31638. this.setValues( params );
  31639. }
  31640. copy( source ) {
  31641. super.copy( source );
  31642. this.specularMap = source.specularMap;
  31643. this.specular.copy( source.specular );
  31644. this.glossinessMap = source.glossinessMap;
  31645. this.glossiness = source.glossiness;
  31646. delete this.metalness;
  31647. delete this.roughness;
  31648. delete this.metalnessMap;
  31649. delete this.roughnessMap;
  31650. return this;
  31651. }
  31652. }
  31653. class GLTFMaterialsPbrSpecularGlossinessExtension {
  31654. constructor() {
  31655. this.name = EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS;
  31656. this.specularGlossinessParams = [
  31657. 'color',
  31658. 'map',
  31659. 'lightMap',
  31660. 'lightMapIntensity',
  31661. 'aoMap',
  31662. 'aoMapIntensity',
  31663. 'emissive',
  31664. 'emissiveIntensity',
  31665. 'emissiveMap',
  31666. 'bumpMap',
  31667. 'bumpScale',
  31668. 'normalMap',
  31669. 'normalMapType',
  31670. 'displacementMap',
  31671. 'displacementScale',
  31672. 'displacementBias',
  31673. 'specularMap',
  31674. 'specular',
  31675. 'glossinessMap',
  31676. 'glossiness',
  31677. 'alphaMap',
  31678. 'envMap',
  31679. 'envMapIntensity',
  31680. 'refractionRatio',
  31681. ];
  31682. }
  31683. getMaterialType() {
  31684. return GLTFMeshStandardSGMaterial;
  31685. }
  31686. extendParams( materialParams, materialDef, parser ) {
  31687. const pbrSpecularGlossiness = materialDef.extensions[ this.name ];
  31688. materialParams.color = new three__WEBPACK_IMPORTED_MODULE_0__.Color( 1.0, 1.0, 1.0 );
  31689. materialParams.opacity = 1.0;
  31690. const pending = [];
  31691. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  31692. const array = pbrSpecularGlossiness.diffuseFactor;
  31693. materialParams.color.fromArray( array );
  31694. materialParams.opacity = array[ 3 ];
  31695. }
  31696. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  31697. pending.push( parser.assignTexture( materialParams, 'map', pbrSpecularGlossiness.diffuseTexture ) );
  31698. }
  31699. materialParams.emissive = new three__WEBPACK_IMPORTED_MODULE_0__.Color( 0.0, 0.0, 0.0 );
  31700. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  31701. materialParams.specular = new three__WEBPACK_IMPORTED_MODULE_0__.Color( 1.0, 1.0, 1.0 );
  31702. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  31703. materialParams.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  31704. }
  31705. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  31706. const specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  31707. pending.push( parser.assignTexture( materialParams, 'glossinessMap', specGlossMapDef ) );
  31708. pending.push( parser.assignTexture( materialParams, 'specularMap', specGlossMapDef ) );
  31709. }
  31710. return Promise.all( pending );
  31711. }
  31712. createMaterial( materialParams ) {
  31713. const material = new GLTFMeshStandardSGMaterial( materialParams );
  31714. material.fog = true;
  31715. material.color = materialParams.color;
  31716. material.map = materialParams.map === undefined ? null : materialParams.map;
  31717. material.lightMap = null;
  31718. material.lightMapIntensity = 1.0;
  31719. material.aoMap = materialParams.aoMap === undefined ? null : materialParams.aoMap;
  31720. material.aoMapIntensity = 1.0;
  31721. material.emissive = materialParams.emissive;
  31722. material.emissiveIntensity = 1.0;
  31723. material.emissiveMap = materialParams.emissiveMap === undefined ? null : materialParams.emissiveMap;
  31724. material.bumpMap = materialParams.bumpMap === undefined ? null : materialParams.bumpMap;
  31725. material.bumpScale = 1;
  31726. material.normalMap = materialParams.normalMap === undefined ? null : materialParams.normalMap;
  31727. material.normalMapType = three__WEBPACK_IMPORTED_MODULE_0__.TangentSpaceNormalMap;
  31728. if ( materialParams.normalScale ) material.normalScale = materialParams.normalScale;
  31729. material.displacementMap = null;
  31730. material.displacementScale = 1;
  31731. material.displacementBias = 0;
  31732. material.specularMap = materialParams.specularMap === undefined ? null : materialParams.specularMap;
  31733. material.specular = materialParams.specular;
  31734. material.glossinessMap = materialParams.glossinessMap === undefined ? null : materialParams.glossinessMap;
  31735. material.glossiness = materialParams.glossiness;
  31736. material.alphaMap = null;
  31737. material.envMap = materialParams.envMap === undefined ? null : materialParams.envMap;
  31738. material.envMapIntensity = 1.0;
  31739. material.refractionRatio = 0.98;
  31740. return material;
  31741. }
  31742. }
  31743. /**
  31744. * Mesh Quantization Extension
  31745. *
  31746. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization
  31747. */
  31748. class GLTFMeshQuantizationExtension {
  31749. constructor() {
  31750. this.name = EXTENSIONS.KHR_MESH_QUANTIZATION;
  31751. }
  31752. }
  31753. /*********************************/
  31754. /********** INTERPOLATION ********/
  31755. /*********************************/
  31756. // Spline Interpolation
  31757. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  31758. class GLTFCubicSplineInterpolant extends three__WEBPACK_IMPORTED_MODULE_0__.Interpolant {
  31759. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31760. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31761. }
  31762. copySampleValue_( index ) {
  31763. // Copies a sample value to the result buffer. See description of glTF
  31764. // CUBICSPLINE values layout in interpolate_() function below.
  31765. const result = this.resultBuffer,
  31766. values = this.sampleValues,
  31767. valueSize = this.valueSize,
  31768. offset = index * valueSize * 3 + valueSize;
  31769. for ( let i = 0; i !== valueSize; i ++ ) {
  31770. result[ i ] = values[ offset + i ];
  31771. }
  31772. return result;
  31773. }
  31774. }
  31775. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  31776. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  31777. GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( i1, t0, t, t1 ) {
  31778. const result = this.resultBuffer;
  31779. const values = this.sampleValues;
  31780. const stride = this.valueSize;
  31781. const stride2 = stride * 2;
  31782. const stride3 = stride * 3;
  31783. const td = t1 - t0;
  31784. const p = ( t - t0 ) / td;
  31785. const pp = p * p;
  31786. const ppp = pp * p;
  31787. const offset1 = i1 * stride3;
  31788. const offset0 = offset1 - stride3;
  31789. const s2 = - 2 * ppp + 3 * pp;
  31790. const s3 = ppp - pp;
  31791. const s0 = 1 - s2;
  31792. const s1 = s3 - pp + p;
  31793. // Layout of keyframe output values for CUBICSPLINE animations:
  31794. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  31795. for ( let i = 0; i !== stride; i ++ ) {
  31796. const p0 = values[ offset0 + i + stride ]; // splineVertex_k
  31797. const m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
  31798. const p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
  31799. const m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
  31800. result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  31801. }
  31802. return result;
  31803. };
  31804. const _q = new three__WEBPACK_IMPORTED_MODULE_0__.Quaternion();
  31805. class GLTFCubicSplineQuaternionInterpolant extends GLTFCubicSplineInterpolant {
  31806. interpolate_( i1, t0, t, t1 ) {
  31807. const result = super.interpolate_( i1, t0, t, t1 );
  31808. _q.fromArray( result ).normalize().toArray( result );
  31809. return result;
  31810. }
  31811. }
  31812. /*********************************/
  31813. /********** INTERNALS ************/
  31814. /*********************************/
  31815. /* CONSTANTS */
  31816. const WEBGL_CONSTANTS = {
  31817. FLOAT: 5126,
  31818. //FLOAT_MAT2: 35674,
  31819. FLOAT_MAT3: 35675,
  31820. FLOAT_MAT4: 35676,
  31821. FLOAT_VEC2: 35664,
  31822. FLOAT_VEC3: 35665,
  31823. FLOAT_VEC4: 35666,
  31824. LINEAR: 9729,
  31825. REPEAT: 10497,
  31826. SAMPLER_2D: 35678,
  31827. POINTS: 0,
  31828. LINES: 1,
  31829. LINE_LOOP: 2,
  31830. LINE_STRIP: 3,
  31831. TRIANGLES: 4,
  31832. TRIANGLE_STRIP: 5,
  31833. TRIANGLE_FAN: 6,
  31834. UNSIGNED_BYTE: 5121,
  31835. UNSIGNED_SHORT: 5123
  31836. };
  31837. const WEBGL_COMPONENT_TYPES = {
  31838. 5120: Int8Array,
  31839. 5121: Uint8Array,
  31840. 5122: Int16Array,
  31841. 5123: Uint16Array,
  31842. 5125: Uint32Array,
  31843. 5126: Float32Array
  31844. };
  31845. const WEBGL_FILTERS = {
  31846. 9728: three__WEBPACK_IMPORTED_MODULE_0__.NearestFilter,
  31847. 9729: three__WEBPACK_IMPORTED_MODULE_0__.LinearFilter,
  31848. 9984: three__WEBPACK_IMPORTED_MODULE_0__.NearestMipmapNearestFilter,
  31849. 9985: three__WEBPACK_IMPORTED_MODULE_0__.LinearMipmapNearestFilter,
  31850. 9986: three__WEBPACK_IMPORTED_MODULE_0__.NearestMipmapLinearFilter,
  31851. 9987: three__WEBPACK_IMPORTED_MODULE_0__.LinearMipmapLinearFilter
  31852. };
  31853. const WEBGL_WRAPPINGS = {
  31854. 33071: three__WEBPACK_IMPORTED_MODULE_0__.ClampToEdgeWrapping,
  31855. 33648: three__WEBPACK_IMPORTED_MODULE_0__.MirroredRepeatWrapping,
  31856. 10497: three__WEBPACK_IMPORTED_MODULE_0__.RepeatWrapping
  31857. };
  31858. const WEBGL_TYPE_SIZES = {
  31859. 'SCALAR': 1,
  31860. 'VEC2': 2,
  31861. 'VEC3': 3,
  31862. 'VEC4': 4,
  31863. 'MAT2': 4,
  31864. 'MAT3': 9,
  31865. 'MAT4': 16
  31866. };
  31867. const ATTRIBUTES = {
  31868. POSITION: 'position',
  31869. NORMAL: 'normal',
  31870. TANGENT: 'tangent',
  31871. TEXCOORD_0: 'uv',
  31872. TEXCOORD_1: 'uv2',
  31873. COLOR_0: 'color',
  31874. WEIGHTS_0: 'skinWeight',
  31875. JOINTS_0: 'skinIndex',
  31876. };
  31877. const PATH_PROPERTIES = {
  31878. scale: 'scale',
  31879. translation: 'position',
  31880. rotation: 'quaternion',
  31881. weights: 'morphTargetInfluences'
  31882. };
  31883. const INTERPOLATION = {
  31884. CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  31885. // keyframe track will be initialized with a default interpolation type, then modified.
  31886. LINEAR: three__WEBPACK_IMPORTED_MODULE_0__.InterpolateLinear,
  31887. STEP: three__WEBPACK_IMPORTED_MODULE_0__.InterpolateDiscrete
  31888. };
  31889. const ALPHA_MODES = {
  31890. OPAQUE: 'OPAQUE',
  31891. MASK: 'MASK',
  31892. BLEND: 'BLEND'
  31893. };
  31894. /* UTILITY FUNCTIONS */
  31895. function resolveURL( url, path ) {
  31896. // Invalid URL
  31897. if ( typeof url !== 'string' || url === '' ) return '';
  31898. // Host Relative URL
  31899. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  31900. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  31901. }
  31902. // Absolute URL http://,https://,//
  31903. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  31904. // Data URI
  31905. if ( /^data:.*,.*$/i.test( url ) ) return url;
  31906. // Blob URL
  31907. if ( /^blob:.*$/i.test( url ) ) return url;
  31908. // Relative URL
  31909. return path + url;
  31910. }
  31911. /**
  31912. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  31913. */
  31914. function createDefaultMaterial( cache ) {
  31915. if ( cache[ 'DefaultMaterial' ] === undefined ) {
  31916. cache[ 'DefaultMaterial' ] = new three__WEBPACK_IMPORTED_MODULE_0__.MeshStandardMaterial( {
  31917. color: 0xFFFFFF,
  31918. emissive: 0x000000,
  31919. metalness: 1,
  31920. roughness: 1,
  31921. transparent: false,
  31922. depthTest: true,
  31923. side: three__WEBPACK_IMPORTED_MODULE_0__.FrontSide
  31924. } );
  31925. }
  31926. return cache[ 'DefaultMaterial' ];
  31927. }
  31928. function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
  31929. // Add unknown glTF extensions to an object's userData.
  31930. for ( const name in objectDef.extensions ) {
  31931. if ( knownExtensions[ name ] === undefined ) {
  31932. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  31933. object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
  31934. }
  31935. }
  31936. }
  31937. /**
  31938. * @param {Object3D|Material|BufferGeometry} object
  31939. * @param {GLTF.definition} gltfDef
  31940. */
  31941. function assignExtrasToUserData( object, gltfDef ) {
  31942. if ( gltfDef.extras !== undefined ) {
  31943. if ( typeof gltfDef.extras === 'object' ) {
  31944. Object.assign( object.userData, gltfDef.extras );
  31945. } else {
  31946. console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
  31947. }
  31948. }
  31949. }
  31950. /**
  31951. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  31952. *
  31953. * @param {BufferGeometry} geometry
  31954. * @param {Array<GLTF.Target>} targets
  31955. * @param {GLTFParser} parser
  31956. * @return {Promise<BufferGeometry>}
  31957. */
  31958. function addMorphTargets( geometry, targets, parser ) {
  31959. let hasMorphPosition = false;
  31960. let hasMorphNormal = false;
  31961. for ( let i = 0, il = targets.length; i < il; i ++ ) {
  31962. const target = targets[ i ];
  31963. if ( target.POSITION !== undefined ) hasMorphPosition = true;
  31964. if ( target.NORMAL !== undefined ) hasMorphNormal = true;
  31965. if ( hasMorphPosition && hasMorphNormal ) break;
  31966. }
  31967. if ( ! hasMorphPosition && ! hasMorphNormal ) return Promise.resolve( geometry );
  31968. const pendingPositionAccessors = [];
  31969. const pendingNormalAccessors = [];
  31970. for ( let i = 0, il = targets.length; i < il; i ++ ) {
  31971. const target = targets[ i ];
  31972. if ( hasMorphPosition ) {
  31973. const pendingAccessor = target.POSITION !== undefined
  31974. ? parser.getDependency( 'accessor', target.POSITION )
  31975. : geometry.attributes.position;
  31976. pendingPositionAccessors.push( pendingAccessor );
  31977. }
  31978. if ( hasMorphNormal ) {
  31979. const pendingAccessor = target.NORMAL !== undefined
  31980. ? parser.getDependency( 'accessor', target.NORMAL )
  31981. : geometry.attributes.normal;
  31982. pendingNormalAccessors.push( pendingAccessor );
  31983. }
  31984. }
  31985. return Promise.all( [
  31986. Promise.all( pendingPositionAccessors ),
  31987. Promise.all( pendingNormalAccessors )
  31988. ] ).then( function ( accessors ) {
  31989. const morphPositions = accessors[ 0 ];
  31990. const morphNormals = accessors[ 1 ];
  31991. if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
  31992. if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
  31993. geometry.morphTargetsRelative = true;
  31994. return geometry;
  31995. } );
  31996. }
  31997. /**
  31998. * @param {Mesh} mesh
  31999. * @param {GLTF.Mesh} meshDef
  32000. */
  32001. function updateMorphTargets( mesh, meshDef ) {
  32002. mesh.updateMorphTargets();
  32003. if ( meshDef.weights !== undefined ) {
  32004. for ( let i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  32005. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  32006. }
  32007. }
  32008. // .extras has user-defined data, so check that .extras.targetNames is an array.
  32009. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
  32010. const targetNames = meshDef.extras.targetNames;
  32011. if ( mesh.morphTargetInfluences.length === targetNames.length ) {
  32012. mesh.morphTargetDictionary = {};
  32013. for ( let i = 0, il = targetNames.length; i < il; i ++ ) {
  32014. mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
  32015. }
  32016. } else {
  32017. console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
  32018. }
  32019. }
  32020. }
  32021. function createPrimitiveKey( primitiveDef ) {
  32022. const dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];
  32023. let geometryKey;
  32024. if ( dracoExtension ) {
  32025. geometryKey = 'draco:' + dracoExtension.bufferView
  32026. + ':' + dracoExtension.indices
  32027. + ':' + createAttributesKey( dracoExtension.attributes );
  32028. } else {
  32029. geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;
  32030. }
  32031. return geometryKey;
  32032. }
  32033. function createAttributesKey( attributes ) {
  32034. let attributesKey = '';
  32035. const keys = Object.keys( attributes ).sort();
  32036. for ( let i = 0, il = keys.length; i < il; i ++ ) {
  32037. attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';
  32038. }
  32039. return attributesKey;
  32040. }
  32041. function getNormalizedComponentScale( constructor ) {
  32042. // Reference:
  32043. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization#encoding-quantized-data
  32044. switch ( constructor ) {
  32045. case Int8Array:
  32046. return 1 / 127;
  32047. case Uint8Array:
  32048. return 1 / 255;
  32049. case Int16Array:
  32050. return 1 / 32767;
  32051. case Uint16Array:
  32052. return 1 / 65535;
  32053. default:
  32054. throw new Error( 'THREE.GLTFLoader: Unsupported normalized accessor component type.' );
  32055. }
  32056. }
  32057. /* GLTF PARSER */
  32058. class GLTFParser {
  32059. constructor( json = {}, options = {} ) {
  32060. this.json = json;
  32061. this.extensions = {};
  32062. this.plugins = {};
  32063. this.options = options;
  32064. // loader object cache
  32065. this.cache = new GLTFRegistry();
  32066. // associations between Three.js objects and glTF elements
  32067. this.associations = new Map();
  32068. // BufferGeometry caching
  32069. this.primitiveCache = {};
  32070. // Object3D instance caches
  32071. this.meshCache = { refs: {}, uses: {} };
  32072. this.cameraCache = { refs: {}, uses: {} };
  32073. this.lightCache = { refs: {}, uses: {} };
  32074. this.textureCache = {};
  32075. // Track node names, to ensure no duplicates
  32076. this.nodeNamesUsed = {};
  32077. // Use an ImageBitmapLoader if imageBitmaps are supported. Moves much of the
  32078. // expensive work of uploading a texture to the GPU off the main thread.
  32079. if ( typeof createImageBitmap !== 'undefined' && /Firefox/.test( navigator.userAgent ) === false ) {
  32080. this.textureLoader = new three__WEBPACK_IMPORTED_MODULE_0__.ImageBitmapLoader( this.options.manager );
  32081. } else {
  32082. this.textureLoader = new three__WEBPACK_IMPORTED_MODULE_0__.TextureLoader( this.options.manager );
  32083. }
  32084. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  32085. this.textureLoader.setRequestHeader( this.options.requestHeader );
  32086. this.fileLoader = new three__WEBPACK_IMPORTED_MODULE_0__.FileLoader( this.options.manager );
  32087. this.fileLoader.setResponseType( 'arraybuffer' );
  32088. if ( this.options.crossOrigin === 'use-credentials' ) {
  32089. this.fileLoader.setWithCredentials( true );
  32090. }
  32091. }
  32092. setExtensions( extensions ) {
  32093. this.extensions = extensions;
  32094. }
  32095. setPlugins( plugins ) {
  32096. this.plugins = plugins;
  32097. }
  32098. parse( onLoad, onError ) {
  32099. const parser = this;
  32100. const json = this.json;
  32101. const extensions = this.extensions;
  32102. // Clear the loader cache
  32103. this.cache.removeAll();
  32104. // Mark the special nodes/meshes in json for efficient parse
  32105. this._invokeAll( function ( ext ) {
  32106. return ext._markDefs && ext._markDefs();
  32107. } );
  32108. Promise.all( this._invokeAll( function ( ext ) {
  32109. return ext.beforeRoot && ext.beforeRoot();
  32110. } ) ).then( function () {
  32111. return Promise.all( [
  32112. parser.getDependencies( 'scene' ),
  32113. parser.getDependencies( 'animation' ),
  32114. parser.getDependencies( 'camera' ),
  32115. ] );
  32116. } ).then( function ( dependencies ) {
  32117. const result = {
  32118. scene: dependencies[ 0 ][ json.scene || 0 ],
  32119. scenes: dependencies[ 0 ],
  32120. animations: dependencies[ 1 ],
  32121. cameras: dependencies[ 2 ],
  32122. asset: json.asset,
  32123. parser: parser,
  32124. userData: {}
  32125. };
  32126. addUnknownExtensionsToUserData( extensions, result, json );
  32127. assignExtrasToUserData( result, json );
  32128. Promise.all( parser._invokeAll( function ( ext ) {
  32129. return ext.afterRoot && ext.afterRoot( result );
  32130. } ) ).then( function () {
  32131. onLoad( result );
  32132. } );
  32133. } ).catch( onError );
  32134. }
  32135. /**
  32136. * Marks the special nodes/meshes in json for efficient parse.
  32137. */
  32138. _markDefs() {
  32139. const nodeDefs = this.json.nodes || [];
  32140. const skinDefs = this.json.skins || [];
  32141. const meshDefs = this.json.meshes || [];
  32142. // Nothing in the node definition indicates whether it is a Bone or an
  32143. // Object3D. Use the skins' joint references to mark bones.
  32144. for ( let skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  32145. const joints = skinDefs[ skinIndex ].joints;
  32146. for ( let i = 0, il = joints.length; i < il; i ++ ) {
  32147. nodeDefs[ joints[ i ] ].isBone = true;
  32148. }
  32149. }
  32150. // Iterate over all nodes, marking references to shared resources,
  32151. // as well as skeleton joints.
  32152. for ( let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  32153. const nodeDef = nodeDefs[ nodeIndex ];
  32154. if ( nodeDef.mesh !== undefined ) {
  32155. this._addNodeRef( this.meshCache, nodeDef.mesh );
  32156. // Nothing in the mesh definition indicates whether it is
  32157. // a SkinnedMesh or Mesh. Use the node's mesh reference
  32158. // to mark SkinnedMesh if node has skin.
  32159. if ( nodeDef.skin !== undefined ) {
  32160. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  32161. }
  32162. }
  32163. if ( nodeDef.camera !== undefined ) {
  32164. this._addNodeRef( this.cameraCache, nodeDef.camera );
  32165. }
  32166. }
  32167. }
  32168. /**
  32169. * Counts references to shared node / Object3D resources. These resources
  32170. * can be reused, or "instantiated", at multiple nodes in the scene
  32171. * hierarchy. Mesh, Camera, and Light instances are instantiated and must
  32172. * be marked. Non-scenegraph resources (like Materials, Geometries, and
  32173. * Textures) can be reused directly and are not marked here.
  32174. *
  32175. * Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  32176. */
  32177. _addNodeRef( cache, index ) {
  32178. if ( index === undefined ) return;
  32179. if ( cache.refs[ index ] === undefined ) {
  32180. cache.refs[ index ] = cache.uses[ index ] = 0;
  32181. }
  32182. cache.refs[ index ] ++;
  32183. }
  32184. /** Returns a reference to a shared resource, cloning it if necessary. */
  32185. _getNodeRef( cache, index, object ) {
  32186. if ( cache.refs[ index ] <= 1 ) return object;
  32187. const ref = object.clone();
  32188. ref.name += '_instance_' + ( cache.uses[ index ] ++ );
  32189. return ref;
  32190. }
  32191. _invokeOne( func ) {
  32192. const extensions = Object.values( this.plugins );
  32193. extensions.push( this );
  32194. for ( let i = 0; i < extensions.length; i ++ ) {
  32195. const result = func( extensions[ i ] );
  32196. if ( result ) return result;
  32197. }
  32198. return null;
  32199. }
  32200. _invokeAll( func ) {
  32201. const extensions = Object.values( this.plugins );
  32202. extensions.unshift( this );
  32203. const pending = [];
  32204. for ( let i = 0; i < extensions.length; i ++ ) {
  32205. const result = func( extensions[ i ] );
  32206. if ( result ) pending.push( result );
  32207. }
  32208. return pending;
  32209. }
  32210. /**
  32211. * Requests the specified dependency asynchronously, with caching.
  32212. * @param {string} type
  32213. * @param {number} index
  32214. * @return {Promise<Object3D|Material|THREE.Texture|AnimationClip|ArrayBuffer|Object>}
  32215. */
  32216. getDependency( type, index ) {
  32217. const cacheKey = type + ':' + index;
  32218. let dependency = this.cache.get( cacheKey );
  32219. if ( ! dependency ) {
  32220. switch ( type ) {
  32221. case 'scene':
  32222. dependency = this.loadScene( index );
  32223. break;
  32224. case 'node':
  32225. dependency = this.loadNode( index );
  32226. break;
  32227. case 'mesh':
  32228. dependency = this._invokeOne( function ( ext ) {
  32229. return ext.loadMesh && ext.loadMesh( index );
  32230. } );
  32231. break;
  32232. case 'accessor':
  32233. dependency = this.loadAccessor( index );
  32234. break;
  32235. case 'bufferView':
  32236. dependency = this._invokeOne( function ( ext ) {
  32237. return ext.loadBufferView && ext.loadBufferView( index );
  32238. } );
  32239. break;
  32240. case 'buffer':
  32241. dependency = this.loadBuffer( index );
  32242. break;
  32243. case 'material':
  32244. dependency = this._invokeOne( function ( ext ) {
  32245. return ext.loadMaterial && ext.loadMaterial( index );
  32246. } );
  32247. break;
  32248. case 'texture':
  32249. dependency = this._invokeOne( function ( ext ) {
  32250. return ext.loadTexture && ext.loadTexture( index );
  32251. } );
  32252. break;
  32253. case 'skin':
  32254. dependency = this.loadSkin( index );
  32255. break;
  32256. case 'animation':
  32257. dependency = this.loadAnimation( index );
  32258. break;
  32259. case 'camera':
  32260. dependency = this.loadCamera( index );
  32261. break;
  32262. default:
  32263. throw new Error( 'Unknown type: ' + type );
  32264. }
  32265. this.cache.add( cacheKey, dependency );
  32266. }
  32267. return dependency;
  32268. }
  32269. /**
  32270. * Requests all dependencies of the specified type asynchronously, with caching.
  32271. * @param {string} type
  32272. * @return {Promise<Array<Object>>}
  32273. */
  32274. getDependencies( type ) {
  32275. let dependencies = this.cache.get( type );
  32276. if ( ! dependencies ) {
  32277. const parser = this;
  32278. const defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  32279. dependencies = Promise.all( defs.map( function ( def, index ) {
  32280. return parser.getDependency( type, index );
  32281. } ) );
  32282. this.cache.add( type, dependencies );
  32283. }
  32284. return dependencies;
  32285. }
  32286. /**
  32287. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  32288. * @param {number} bufferIndex
  32289. * @return {Promise<ArrayBuffer>}
  32290. */
  32291. loadBuffer( bufferIndex ) {
  32292. const bufferDef = this.json.buffers[ bufferIndex ];
  32293. const loader = this.fileLoader;
  32294. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  32295. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  32296. }
  32297. // If present, GLB container is required to be the first buffer.
  32298. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  32299. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  32300. }
  32301. const options = this.options;
  32302. return new Promise( function ( resolve, reject ) {
  32303. loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  32304. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  32305. } );
  32306. } );
  32307. }
  32308. /**
  32309. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  32310. * @param {number} bufferViewIndex
  32311. * @return {Promise<ArrayBuffer>}
  32312. */
  32313. loadBufferView( bufferViewIndex ) {
  32314. const bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  32315. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  32316. const byteLength = bufferViewDef.byteLength || 0;
  32317. const byteOffset = bufferViewDef.byteOffset || 0;
  32318. return buffer.slice( byteOffset, byteOffset + byteLength );
  32319. } );
  32320. }
  32321. /**
  32322. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  32323. * @param {number} accessorIndex
  32324. * @return {Promise<BufferAttribute|InterleavedBufferAttribute>}
  32325. */
  32326. loadAccessor( accessorIndex ) {
  32327. const parser = this;
  32328. const json = this.json;
  32329. const accessorDef = this.json.accessors[ accessorIndex ];
  32330. if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
  32331. // Ignore empty accessors, which may be used to declare runtime
  32332. // information about attributes coming from another source (e.g. Draco
  32333. // compression extension).
  32334. return Promise.resolve( null );
  32335. }
  32336. const pendingBufferViews = [];
  32337. if ( accessorDef.bufferView !== undefined ) {
  32338. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  32339. } else {
  32340. pendingBufferViews.push( null );
  32341. }
  32342. if ( accessorDef.sparse !== undefined ) {
  32343. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  32344. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  32345. }
  32346. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  32347. const bufferView = bufferViews[ 0 ];
  32348. const itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  32349. const TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  32350. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  32351. const elementBytes = TypedArray.BYTES_PER_ELEMENT;
  32352. const itemBytes = elementBytes * itemSize;
  32353. const byteOffset = accessorDef.byteOffset || 0;
  32354. const byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;
  32355. const normalized = accessorDef.normalized === true;
  32356. let array, bufferAttribute;
  32357. // The buffer is not interleaved if the stride is the item size in bytes.
  32358. if ( byteStride && byteStride !== itemBytes ) {
  32359. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  32360. // This makes sure that IBA.count reflects accessor.count properly
  32361. const ibSlice = Math.floor( byteOffset / byteStride );
  32362. const ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  32363. let ib = parser.cache.get( ibCacheKey );
  32364. if ( ! ib ) {
  32365. array = new TypedArray( bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes );
  32366. // Integer parameters to IB/IBA are in array elements, not bytes.
  32367. ib = new three__WEBPACK_IMPORTED_MODULE_0__.InterleavedBuffer( array, byteStride / elementBytes );
  32368. parser.cache.add( ibCacheKey, ib );
  32369. }
  32370. bufferAttribute = new three__WEBPACK_IMPORTED_MODULE_0__.InterleavedBufferAttribute( ib, itemSize, ( byteOffset % byteStride ) / elementBytes, normalized );
  32371. } else {
  32372. if ( bufferView === null ) {
  32373. array = new TypedArray( accessorDef.count * itemSize );
  32374. } else {
  32375. array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
  32376. }
  32377. bufferAttribute = new three__WEBPACK_IMPORTED_MODULE_0__.BufferAttribute( array, itemSize, normalized );
  32378. }
  32379. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  32380. if ( accessorDef.sparse !== undefined ) {
  32381. const itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  32382. const TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  32383. const byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  32384. const byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  32385. const sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  32386. const sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  32387. if ( bufferView !== null ) {
  32388. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  32389. bufferAttribute = new three__WEBPACK_IMPORTED_MODULE_0__.BufferAttribute( bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized );
  32390. }
  32391. for ( let i = 0, il = sparseIndices.length; i < il; i ++ ) {
  32392. const index = sparseIndices[ i ];
  32393. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  32394. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  32395. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  32396. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  32397. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
  32398. }
  32399. }
  32400. return bufferAttribute;
  32401. } );
  32402. }
  32403. /**
  32404. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  32405. * @param {number} textureIndex
  32406. * @return {Promise<THREE.Texture>}
  32407. */
  32408. loadTexture( textureIndex ) {
  32409. const json = this.json;
  32410. const options = this.options;
  32411. const textureDef = json.textures[ textureIndex ];
  32412. const source = json.images[ textureDef.source ];
  32413. let loader = this.textureLoader;
  32414. if ( source.uri ) {
  32415. const handler = options.manager.getHandler( source.uri );
  32416. if ( handler !== null ) loader = handler;
  32417. }
  32418. return this.loadTextureImage( textureIndex, source, loader );
  32419. }
  32420. loadTextureImage( textureIndex, source, loader ) {
  32421. const parser = this;
  32422. const json = this.json;
  32423. const options = this.options;
  32424. const textureDef = json.textures[ textureIndex ];
  32425. const cacheKey = ( source.uri || source.bufferView ) + ':' + textureDef.sampler;
  32426. if ( this.textureCache[ cacheKey ] ) {
  32427. // See https://github.com/mrdoob/three.js/issues/21559.
  32428. return this.textureCache[ cacheKey ];
  32429. }
  32430. const URL = self.URL || self.webkitURL;
  32431. let sourceURI = source.uri || '';
  32432. let isObjectURL = false;
  32433. let hasAlpha = true;
  32434. const isJPEG = sourceURI.search( /\.jpe?g($|\?)/i ) > 0 || sourceURI.search( /^data\:image\/jpeg/ ) === 0;
  32435. if ( source.mimeType === 'image/jpeg' || isJPEG ) hasAlpha = false;
  32436. if ( source.bufferView !== undefined ) {
  32437. // Load binary image data from bufferView, if provided.
  32438. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) {
  32439. if ( source.mimeType === 'image/png' ) {
  32440. // Inspect the PNG 'IHDR' chunk to determine whether the image could have an
  32441. // alpha channel. This check is conservative — the image could have an alpha
  32442. // channel with all values == 1, and the indexed type (colorType == 3) only
  32443. // sometimes contains alpha.
  32444. //
  32445. // https://en.wikipedia.org/wiki/Portable_Network_Graphics#File_header
  32446. const colorType = new DataView( bufferView, 25, 1 ).getUint8( 0, false );
  32447. hasAlpha = colorType === 6 || colorType === 4 || colorType === 3;
  32448. }
  32449. isObjectURL = true;
  32450. const blob = new Blob( [ bufferView ], { type: source.mimeType } );
  32451. sourceURI = URL.createObjectURL( blob );
  32452. return sourceURI;
  32453. } );
  32454. } else if ( source.uri === undefined ) {
  32455. throw new Error( 'THREE.GLTFLoader: Image ' + textureIndex + ' is missing URI and bufferView' );
  32456. }
  32457. const promise = Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  32458. return new Promise( function ( resolve, reject ) {
  32459. let onLoad = resolve;
  32460. if ( loader.isImageBitmapLoader === true ) {
  32461. onLoad = function ( imageBitmap ) {
  32462. const texture = new three__WEBPACK_IMPORTED_MODULE_0__.Texture( imageBitmap );
  32463. texture.needsUpdate = true;
  32464. resolve( texture );
  32465. };
  32466. }
  32467. loader.load( resolveURL( sourceURI, options.path ), onLoad, undefined, reject );
  32468. } );
  32469. } ).then( function ( texture ) {
  32470. // Clean up resources and configure Texture.
  32471. if ( isObjectURL === true ) {
  32472. URL.revokeObjectURL( sourceURI );
  32473. }
  32474. texture.flipY = false;
  32475. if ( textureDef.name ) texture.name = textureDef.name;
  32476. // When there is definitely no alpha channel in the texture, set RGBFormat to save space.
  32477. if ( ! hasAlpha ) texture.format = three__WEBPACK_IMPORTED_MODULE_0__.RGBFormat;
  32478. const samplers = json.samplers || {};
  32479. const sampler = samplers[ textureDef.sampler ] || {};
  32480. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || three__WEBPACK_IMPORTED_MODULE_0__.LinearFilter;
  32481. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || three__WEBPACK_IMPORTED_MODULE_0__.LinearMipmapLinearFilter;
  32482. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || three__WEBPACK_IMPORTED_MODULE_0__.RepeatWrapping;
  32483. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || three__WEBPACK_IMPORTED_MODULE_0__.RepeatWrapping;
  32484. parser.associations.set( texture, {
  32485. type: 'textures',
  32486. index: textureIndex
  32487. } );
  32488. return texture;
  32489. } ).catch( function () {
  32490. console.error( 'THREE.GLTFLoader: Couldn\'t load texture', sourceURI );
  32491. return null;
  32492. } );
  32493. this.textureCache[ cacheKey ] = promise;
  32494. return promise;
  32495. }
  32496. /**
  32497. * Asynchronously assigns a texture to the given material parameters.
  32498. * @param {Object} materialParams
  32499. * @param {string} mapName
  32500. * @param {Object} mapDef
  32501. * @return {Promise<Texture>}
  32502. */
  32503. assignTexture( materialParams, mapName, mapDef ) {
  32504. const parser = this;
  32505. return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) {
  32506. // Materials sample aoMap from UV set 1 and other maps from UV set 0 - this can't be configured
  32507. // However, we will copy UV set 0 to UV set 1 on demand for aoMap
  32508. if ( mapDef.texCoord !== undefined && mapDef.texCoord != 0 && ! ( mapName === 'aoMap' && mapDef.texCoord == 1 ) ) {
  32509. console.warn( 'THREE.GLTFLoader: Custom UV set ' + mapDef.texCoord + ' for texture ' + mapName + ' not yet supported.' );
  32510. }
  32511. if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) {
  32512. const transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined;
  32513. if ( transform ) {
  32514. const gltfReference = parser.associations.get( texture );
  32515. texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform );
  32516. parser.associations.set( texture, gltfReference );
  32517. }
  32518. }
  32519. materialParams[ mapName ] = texture;
  32520. return texture;
  32521. } );
  32522. }
  32523. /**
  32524. * Assigns final material to a Mesh, Line, or Points instance. The instance
  32525. * already has a material (generated from the glTF material options alone)
  32526. * but reuse of the same glTF material may require multiple threejs materials
  32527. * to accommodate different primitive types, defines, etc. New materials will
  32528. * be created if necessary, and reused from a cache.
  32529. * @param {Object3D} mesh Mesh, Line, or Points instance.
  32530. */
  32531. assignFinalMaterial( mesh ) {
  32532. const geometry = mesh.geometry;
  32533. let material = mesh.material;
  32534. const useVertexTangents = geometry.attributes.tangent !== undefined;
  32535. const useVertexColors = geometry.attributes.color !== undefined;
  32536. const useFlatShading = geometry.attributes.normal === undefined;
  32537. if ( mesh.isPoints ) {
  32538. const cacheKey = 'PointsMaterial:' + material.uuid;
  32539. let pointsMaterial = this.cache.get( cacheKey );
  32540. if ( ! pointsMaterial ) {
  32541. pointsMaterial = new three__WEBPACK_IMPORTED_MODULE_0__.PointsMaterial();
  32542. three__WEBPACK_IMPORTED_MODULE_0__.Material.prototype.copy.call( pointsMaterial, material );
  32543. pointsMaterial.color.copy( material.color );
  32544. pointsMaterial.map = material.map;
  32545. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  32546. this.cache.add( cacheKey, pointsMaterial );
  32547. }
  32548. material = pointsMaterial;
  32549. } else if ( mesh.isLine ) {
  32550. const cacheKey = 'LineBasicMaterial:' + material.uuid;
  32551. let lineMaterial = this.cache.get( cacheKey );
  32552. if ( ! lineMaterial ) {
  32553. lineMaterial = new three__WEBPACK_IMPORTED_MODULE_0__.LineBasicMaterial();
  32554. three__WEBPACK_IMPORTED_MODULE_0__.Material.prototype.copy.call( lineMaterial, material );
  32555. lineMaterial.color.copy( material.color );
  32556. this.cache.add( cacheKey, lineMaterial );
  32557. }
  32558. material = lineMaterial;
  32559. }
  32560. // Clone the material if it will be modified
  32561. if ( useVertexTangents || useVertexColors || useFlatShading ) {
  32562. let cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  32563. if ( material.isGLTFSpecularGlossinessMaterial ) cacheKey += 'specular-glossiness:';
  32564. if ( useVertexTangents ) cacheKey += 'vertex-tangents:';
  32565. if ( useVertexColors ) cacheKey += 'vertex-colors:';
  32566. if ( useFlatShading ) cacheKey += 'flat-shading:';
  32567. let cachedMaterial = this.cache.get( cacheKey );
  32568. if ( ! cachedMaterial ) {
  32569. cachedMaterial = material.clone();
  32570. if ( useVertexColors ) cachedMaterial.vertexColors = true;
  32571. if ( useFlatShading ) cachedMaterial.flatShading = true;
  32572. if ( useVertexTangents ) {
  32573. // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  32574. if ( cachedMaterial.normalScale ) cachedMaterial.normalScale.y *= - 1;
  32575. if ( cachedMaterial.clearcoatNormalScale ) cachedMaterial.clearcoatNormalScale.y *= - 1;
  32576. }
  32577. this.cache.add( cacheKey, cachedMaterial );
  32578. this.associations.set( cachedMaterial, this.associations.get( material ) );
  32579. }
  32580. material = cachedMaterial;
  32581. }
  32582. // workarounds for mesh and geometry
  32583. if ( material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined ) {
  32584. geometry.setAttribute( 'uv2', geometry.attributes.uv );
  32585. }
  32586. mesh.material = material;
  32587. }
  32588. getMaterialType( /* materialIndex */ ) {
  32589. return three__WEBPACK_IMPORTED_MODULE_0__.MeshStandardMaterial;
  32590. }
  32591. /**
  32592. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  32593. * @param {number} materialIndex
  32594. * @return {Promise<Material>}
  32595. */
  32596. loadMaterial( materialIndex ) {
  32597. const parser = this;
  32598. const json = this.json;
  32599. const extensions = this.extensions;
  32600. const materialDef = json.materials[ materialIndex ];
  32601. let materialType;
  32602. const materialParams = {};
  32603. const materialExtensions = materialDef.extensions || {};
  32604. const pending = [];
  32605. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  32606. const sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  32607. materialType = sgExtension.getMaterialType();
  32608. pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) );
  32609. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
  32610. const kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
  32611. materialType = kmuExtension.getMaterialType();
  32612. pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
  32613. } else {
  32614. // Specification:
  32615. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  32616. const metallicRoughness = materialDef.pbrMetallicRoughness || {};
  32617. materialParams.color = new three__WEBPACK_IMPORTED_MODULE_0__.Color( 1.0, 1.0, 1.0 );
  32618. materialParams.opacity = 1.0;
  32619. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  32620. const array = metallicRoughness.baseColorFactor;
  32621. materialParams.color.fromArray( array );
  32622. materialParams.opacity = array[ 3 ];
  32623. }
  32624. if ( metallicRoughness.baseColorTexture !== undefined ) {
  32625. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  32626. }
  32627. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  32628. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  32629. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  32630. pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) );
  32631. pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) );
  32632. }
  32633. materialType = this._invokeOne( function ( ext ) {
  32634. return ext.getMaterialType && ext.getMaterialType( materialIndex );
  32635. } );
  32636. pending.push( Promise.all( this._invokeAll( function ( ext ) {
  32637. return ext.extendMaterialParams && ext.extendMaterialParams( materialIndex, materialParams );
  32638. } ) ) );
  32639. }
  32640. if ( materialDef.doubleSided === true ) {
  32641. materialParams.side = three__WEBPACK_IMPORTED_MODULE_0__.DoubleSide;
  32642. }
  32643. const alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  32644. if ( alphaMode === ALPHA_MODES.BLEND ) {
  32645. materialParams.transparent = true;
  32646. // See: https://github.com/mrdoob/three.js/issues/17706
  32647. materialParams.depthWrite = false;
  32648. } else {
  32649. materialParams.format = three__WEBPACK_IMPORTED_MODULE_0__.RGBFormat;
  32650. materialParams.transparent = false;
  32651. if ( alphaMode === ALPHA_MODES.MASK ) {
  32652. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  32653. }
  32654. }
  32655. if ( materialDef.normalTexture !== undefined && materialType !== three__WEBPACK_IMPORTED_MODULE_0__.MeshBasicMaterial ) {
  32656. pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) );
  32657. // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  32658. materialParams.normalScale = new three__WEBPACK_IMPORTED_MODULE_0__.Vector2( 1, - 1 );
  32659. if ( materialDef.normalTexture.scale !== undefined ) {
  32660. materialParams.normalScale.set( materialDef.normalTexture.scale, - materialDef.normalTexture.scale );
  32661. }
  32662. }
  32663. if ( materialDef.occlusionTexture !== undefined && materialType !== three__WEBPACK_IMPORTED_MODULE_0__.MeshBasicMaterial ) {
  32664. pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) );
  32665. if ( materialDef.occlusionTexture.strength !== undefined ) {
  32666. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  32667. }
  32668. }
  32669. if ( materialDef.emissiveFactor !== undefined && materialType !== three__WEBPACK_IMPORTED_MODULE_0__.MeshBasicMaterial ) {
  32670. materialParams.emissive = new three__WEBPACK_IMPORTED_MODULE_0__.Color().fromArray( materialDef.emissiveFactor );
  32671. }
  32672. if ( materialDef.emissiveTexture !== undefined && materialType !== three__WEBPACK_IMPORTED_MODULE_0__.MeshBasicMaterial ) {
  32673. pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture ) );
  32674. }
  32675. return Promise.all( pending ).then( function () {
  32676. let material;
  32677. if ( materialType === GLTFMeshStandardSGMaterial ) {
  32678. material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  32679. } else {
  32680. material = new materialType( materialParams );
  32681. }
  32682. if ( materialDef.name ) material.name = materialDef.name;
  32683. // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  32684. if ( material.map ) material.map.encoding = three__WEBPACK_IMPORTED_MODULE_0__.sRGBEncoding;
  32685. if ( material.emissiveMap ) material.emissiveMap.encoding = three__WEBPACK_IMPORTED_MODULE_0__.sRGBEncoding;
  32686. assignExtrasToUserData( material, materialDef );
  32687. parser.associations.set( material, { type: 'materials', index: materialIndex } );
  32688. if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );
  32689. return material;
  32690. } );
  32691. }
  32692. /** When Object3D instances are targeted by animation, they need unique names. */
  32693. createUniqueName( originalName ) {
  32694. const sanitizedName = three__WEBPACK_IMPORTED_MODULE_0__.PropertyBinding.sanitizeNodeName( originalName || '' );
  32695. let name = sanitizedName;
  32696. for ( let i = 1; this.nodeNamesUsed[ name ]; ++ i ) {
  32697. name = sanitizedName + '_' + i;
  32698. }
  32699. this.nodeNamesUsed[ name ] = true;
  32700. return name;
  32701. }
  32702. /**
  32703. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  32704. *
  32705. * Creates BufferGeometries from primitives.
  32706. *
  32707. * @param {Array<GLTF.Primitive>} primitives
  32708. * @return {Promise<Array<BufferGeometry>>}
  32709. */
  32710. loadGeometries( primitives ) {
  32711. const parser = this;
  32712. const extensions = this.extensions;
  32713. const cache = this.primitiveCache;
  32714. function createDracoPrimitive( primitive ) {
  32715. return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
  32716. .decodePrimitive( primitive, parser )
  32717. .then( function ( geometry ) {
  32718. return addPrimitiveAttributes( geometry, primitive, parser );
  32719. } );
  32720. }
  32721. const pending = [];
  32722. for ( let i = 0, il = primitives.length; i < il; i ++ ) {
  32723. const primitive = primitives[ i ];
  32724. const cacheKey = createPrimitiveKey( primitive );
  32725. // See if we've already created this geometry
  32726. const cached = cache[ cacheKey ];
  32727. if ( cached ) {
  32728. // Use the cached geometry if it exists
  32729. pending.push( cached.promise );
  32730. } else {
  32731. let geometryPromise;
  32732. if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
  32733. // Use DRACO geometry if available
  32734. geometryPromise = createDracoPrimitive( primitive );
  32735. } else {
  32736. // Otherwise create a new geometry
  32737. geometryPromise = addPrimitiveAttributes( new three__WEBPACK_IMPORTED_MODULE_0__.BufferGeometry(), primitive, parser );
  32738. }
  32739. // Cache this geometry
  32740. cache[ cacheKey ] = { primitive: primitive, promise: geometryPromise };
  32741. pending.push( geometryPromise );
  32742. }
  32743. }
  32744. return Promise.all( pending );
  32745. }
  32746. /**
  32747. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  32748. * @param {number} meshIndex
  32749. * @return {Promise<Group|Mesh|SkinnedMesh>}
  32750. */
  32751. loadMesh( meshIndex ) {
  32752. const parser = this;
  32753. const json = this.json;
  32754. const extensions = this.extensions;
  32755. const meshDef = json.meshes[ meshIndex ];
  32756. const primitives = meshDef.primitives;
  32757. const pending = [];
  32758. for ( let i = 0, il = primitives.length; i < il; i ++ ) {
  32759. const material = primitives[ i ].material === undefined
  32760. ? createDefaultMaterial( this.cache )
  32761. : this.getDependency( 'material', primitives[ i ].material );
  32762. pending.push( material );
  32763. }
  32764. pending.push( parser.loadGeometries( primitives ) );
  32765. return Promise.all( pending ).then( function ( results ) {
  32766. const materials = results.slice( 0, results.length - 1 );
  32767. const geometries = results[ results.length - 1 ];
  32768. const meshes = [];
  32769. for ( let i = 0, il = geometries.length; i < il; i ++ ) {
  32770. const geometry = geometries[ i ];
  32771. const primitive = primitives[ i ];
  32772. // 1. create Mesh
  32773. let mesh;
  32774. const material = materials[ i ];
  32775. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  32776. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  32777. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  32778. primitive.mode === undefined ) {
  32779. // .isSkinnedMesh isn't in glTF spec. See ._markDefs()
  32780. mesh = meshDef.isSkinnedMesh === true
  32781. ? new three__WEBPACK_IMPORTED_MODULE_0__.SkinnedMesh( geometry, material )
  32782. : new three__WEBPACK_IMPORTED_MODULE_0__.Mesh( geometry, material );
  32783. if ( mesh.isSkinnedMesh === true && ! mesh.geometry.attributes.skinWeight.normalized ) {
  32784. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  32785. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  32786. mesh.normalizeSkinWeights();
  32787. }
  32788. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  32789. mesh.geometry = toTrianglesDrawMode( mesh.geometry, three__WEBPACK_IMPORTED_MODULE_0__.TriangleStripDrawMode );
  32790. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  32791. mesh.geometry = toTrianglesDrawMode( mesh.geometry, three__WEBPACK_IMPORTED_MODULE_0__.TriangleFanDrawMode );
  32792. }
  32793. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  32794. mesh = new three__WEBPACK_IMPORTED_MODULE_0__.LineSegments( geometry, material );
  32795. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  32796. mesh = new three__WEBPACK_IMPORTED_MODULE_0__.Line( geometry, material );
  32797. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  32798. mesh = new three__WEBPACK_IMPORTED_MODULE_0__.LineLoop( geometry, material );
  32799. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  32800. mesh = new three__WEBPACK_IMPORTED_MODULE_0__.Points( geometry, material );
  32801. } else {
  32802. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  32803. }
  32804. if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {
  32805. updateMorphTargets( mesh, meshDef );
  32806. }
  32807. mesh.name = parser.createUniqueName( meshDef.name || ( 'mesh_' + meshIndex ) );
  32808. assignExtrasToUserData( mesh, meshDef );
  32809. if ( primitive.extensions ) addUnknownExtensionsToUserData( extensions, mesh, primitive );
  32810. parser.assignFinalMaterial( mesh );
  32811. meshes.push( mesh );
  32812. }
  32813. if ( meshes.length === 1 ) {
  32814. return meshes[ 0 ];
  32815. }
  32816. const group = new three__WEBPACK_IMPORTED_MODULE_0__.Group();
  32817. for ( let i = 0, il = meshes.length; i < il; i ++ ) {
  32818. group.add( meshes[ i ] );
  32819. }
  32820. return group;
  32821. } );
  32822. }
  32823. /**
  32824. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  32825. * @param {number} cameraIndex
  32826. * @return {Promise<THREE.Camera>}
  32827. */
  32828. loadCamera( cameraIndex ) {
  32829. let camera;
  32830. const cameraDef = this.json.cameras[ cameraIndex ];
  32831. const params = cameraDef[ cameraDef.type ];
  32832. if ( ! params ) {
  32833. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  32834. return;
  32835. }
  32836. if ( cameraDef.type === 'perspective' ) {
  32837. camera = new three__WEBPACK_IMPORTED_MODULE_0__.PerspectiveCamera( three__WEBPACK_IMPORTED_MODULE_0__.MathUtils.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
  32838. } else if ( cameraDef.type === 'orthographic' ) {
  32839. camera = new three__WEBPACK_IMPORTED_MODULE_0__.OrthographicCamera( - params.xmag, params.xmag, params.ymag, - params.ymag, params.znear, params.zfar );
  32840. }
  32841. if ( cameraDef.name ) camera.name = this.createUniqueName( cameraDef.name );
  32842. assignExtrasToUserData( camera, cameraDef );
  32843. return Promise.resolve( camera );
  32844. }
  32845. /**
  32846. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  32847. * @param {number} skinIndex
  32848. * @return {Promise<Object>}
  32849. */
  32850. loadSkin( skinIndex ) {
  32851. const skinDef = this.json.skins[ skinIndex ];
  32852. const skinEntry = { joints: skinDef.joints };
  32853. if ( skinDef.inverseBindMatrices === undefined ) {
  32854. return Promise.resolve( skinEntry );
  32855. }
  32856. return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) {
  32857. skinEntry.inverseBindMatrices = accessor;
  32858. return skinEntry;
  32859. } );
  32860. }
  32861. /**
  32862. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  32863. * @param {number} animationIndex
  32864. * @return {Promise<AnimationClip>}
  32865. */
  32866. loadAnimation( animationIndex ) {
  32867. const json = this.json;
  32868. const animationDef = json.animations[ animationIndex ];
  32869. const pendingNodes = [];
  32870. const pendingInputAccessors = [];
  32871. const pendingOutputAccessors = [];
  32872. const pendingSamplers = [];
  32873. const pendingTargets = [];
  32874. for ( let i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  32875. const channel = animationDef.channels[ i ];
  32876. const sampler = animationDef.samplers[ channel.sampler ];
  32877. const target = channel.target;
  32878. const name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  32879. const input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  32880. const output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  32881. pendingNodes.push( this.getDependency( 'node', name ) );
  32882. pendingInputAccessors.push( this.getDependency( 'accessor', input ) );
  32883. pendingOutputAccessors.push( this.getDependency( 'accessor', output ) );
  32884. pendingSamplers.push( sampler );
  32885. pendingTargets.push( target );
  32886. }
  32887. return Promise.all( [
  32888. Promise.all( pendingNodes ),
  32889. Promise.all( pendingInputAccessors ),
  32890. Promise.all( pendingOutputAccessors ),
  32891. Promise.all( pendingSamplers ),
  32892. Promise.all( pendingTargets )
  32893. ] ).then( function ( dependencies ) {
  32894. const nodes = dependencies[ 0 ];
  32895. const inputAccessors = dependencies[ 1 ];
  32896. const outputAccessors = dependencies[ 2 ];
  32897. const samplers = dependencies[ 3 ];
  32898. const targets = dependencies[ 4 ];
  32899. const tracks = [];
  32900. for ( let i = 0, il = nodes.length; i < il; i ++ ) {
  32901. const node = nodes[ i ];
  32902. const inputAccessor = inputAccessors[ i ];
  32903. const outputAccessor = outputAccessors[ i ];
  32904. const sampler = samplers[ i ];
  32905. const target = targets[ i ];
  32906. if ( node === undefined ) continue;
  32907. node.updateMatrix();
  32908. node.matrixAutoUpdate = true;
  32909. let TypedKeyframeTrack;
  32910. switch ( PATH_PROPERTIES[ target.path ] ) {
  32911. case PATH_PROPERTIES.weights:
  32912. TypedKeyframeTrack = three__WEBPACK_IMPORTED_MODULE_0__.NumberKeyframeTrack;
  32913. break;
  32914. case PATH_PROPERTIES.rotation:
  32915. TypedKeyframeTrack = three__WEBPACK_IMPORTED_MODULE_0__.QuaternionKeyframeTrack;
  32916. break;
  32917. case PATH_PROPERTIES.position:
  32918. case PATH_PROPERTIES.scale:
  32919. default:
  32920. TypedKeyframeTrack = three__WEBPACK_IMPORTED_MODULE_0__.VectorKeyframeTrack;
  32921. break;
  32922. }
  32923. const targetName = node.name ? node.name : node.uuid;
  32924. const interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : three__WEBPACK_IMPORTED_MODULE_0__.InterpolateLinear;
  32925. const targetNames = [];
  32926. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  32927. // Node may be a Group (glTF mesh with several primitives) or a Mesh.
  32928. node.traverse( function ( object ) {
  32929. if ( object.isMesh === true && object.morphTargetInfluences ) {
  32930. targetNames.push( object.name ? object.name : object.uuid );
  32931. }
  32932. } );
  32933. } else {
  32934. targetNames.push( targetName );
  32935. }
  32936. let outputArray = outputAccessor.array;
  32937. if ( outputAccessor.normalized ) {
  32938. const scale = getNormalizedComponentScale( outputArray.constructor );
  32939. const scaled = new Float32Array( outputArray.length );
  32940. for ( let j = 0, jl = outputArray.length; j < jl; j ++ ) {
  32941. scaled[ j ] = outputArray[ j ] * scale;
  32942. }
  32943. outputArray = scaled;
  32944. }
  32945. for ( let j = 0, jl = targetNames.length; j < jl; j ++ ) {
  32946. const track = new TypedKeyframeTrack(
  32947. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  32948. inputAccessor.array,
  32949. outputArray,
  32950. interpolation
  32951. );
  32952. // Override interpolation with custom factory method.
  32953. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  32954. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
  32955. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  32956. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  32957. // must be divided by three to get the interpolant's sampleSize argument.
  32958. const interpolantType = ( this instanceof three__WEBPACK_IMPORTED_MODULE_0__.QuaternionKeyframeTrack ) ? GLTFCubicSplineQuaternionInterpolant : GLTFCubicSplineInterpolant;
  32959. return new interpolantType( this.times, this.values, this.getValueSize() / 3, result );
  32960. };
  32961. // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  32962. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  32963. }
  32964. tracks.push( track );
  32965. }
  32966. }
  32967. const name = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
  32968. return new three__WEBPACK_IMPORTED_MODULE_0__.AnimationClip( name, undefined, tracks );
  32969. } );
  32970. }
  32971. createNodeMesh( nodeIndex ) {
  32972. const json = this.json;
  32973. const parser = this;
  32974. const nodeDef = json.nodes[ nodeIndex ];
  32975. if ( nodeDef.mesh === undefined ) return null;
  32976. return parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {
  32977. const node = parser._getNodeRef( parser.meshCache, nodeDef.mesh, mesh );
  32978. // if weights are provided on the node, override weights on the mesh.
  32979. if ( nodeDef.weights !== undefined ) {
  32980. node.traverse( function ( o ) {
  32981. if ( ! o.isMesh ) return;
  32982. for ( let i = 0, il = nodeDef.weights.length; i < il; i ++ ) {
  32983. o.morphTargetInfluences[ i ] = nodeDef.weights[ i ];
  32984. }
  32985. } );
  32986. }
  32987. return node;
  32988. } );
  32989. }
  32990. /**
  32991. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  32992. * @param {number} nodeIndex
  32993. * @return {Promise<Object3D>}
  32994. */
  32995. loadNode( nodeIndex ) {
  32996. const json = this.json;
  32997. const extensions = this.extensions;
  32998. const parser = this;
  32999. const nodeDef = json.nodes[ nodeIndex ];
  33000. // reserve node's name before its dependencies, so the root has the intended name.
  33001. const nodeName = nodeDef.name ? parser.createUniqueName( nodeDef.name ) : '';
  33002. return ( function () {
  33003. const pending = [];
  33004. const meshPromise = parser._invokeOne( function ( ext ) {
  33005. return ext.createNodeMesh && ext.createNodeMesh( nodeIndex );
  33006. } );
  33007. if ( meshPromise ) {
  33008. pending.push( meshPromise );
  33009. }
  33010. if ( nodeDef.camera !== undefined ) {
  33011. pending.push( parser.getDependency( 'camera', nodeDef.camera ).then( function ( camera ) {
  33012. return parser._getNodeRef( parser.cameraCache, nodeDef.camera, camera );
  33013. } ) );
  33014. }
  33015. parser._invokeAll( function ( ext ) {
  33016. return ext.createNodeAttachment && ext.createNodeAttachment( nodeIndex );
  33017. } ).forEach( function ( promise ) {
  33018. pending.push( promise );
  33019. } );
  33020. return Promise.all( pending );
  33021. }() ).then( function ( objects ) {
  33022. let node;
  33023. // .isBone isn't in glTF spec. See ._markDefs
  33024. if ( nodeDef.isBone === true ) {
  33025. node = new three__WEBPACK_IMPORTED_MODULE_0__.Bone();
  33026. } else if ( objects.length > 1 ) {
  33027. node = new three__WEBPACK_IMPORTED_MODULE_0__.Group();
  33028. } else if ( objects.length === 1 ) {
  33029. node = objects[ 0 ];
  33030. } else {
  33031. node = new three__WEBPACK_IMPORTED_MODULE_0__.Object3D();
  33032. }
  33033. if ( node !== objects[ 0 ] ) {
  33034. for ( let i = 0, il = objects.length; i < il; i ++ ) {
  33035. node.add( objects[ i ] );
  33036. }
  33037. }
  33038. if ( nodeDef.name ) {
  33039. node.userData.name = nodeDef.name;
  33040. node.name = nodeName;
  33041. }
  33042. assignExtrasToUserData( node, nodeDef );
  33043. if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );
  33044. if ( nodeDef.matrix !== undefined ) {
  33045. const matrix = new three__WEBPACK_IMPORTED_MODULE_0__.Matrix4();
  33046. matrix.fromArray( nodeDef.matrix );
  33047. node.applyMatrix4( matrix );
  33048. } else {
  33049. if ( nodeDef.translation !== undefined ) {
  33050. node.position.fromArray( nodeDef.translation );
  33051. }
  33052. if ( nodeDef.rotation !== undefined ) {
  33053. node.quaternion.fromArray( nodeDef.rotation );
  33054. }
  33055. if ( nodeDef.scale !== undefined ) {
  33056. node.scale.fromArray( nodeDef.scale );
  33057. }
  33058. }
  33059. parser.associations.set( node, { type: 'nodes', index: nodeIndex } );
  33060. return node;
  33061. } );
  33062. }
  33063. /**
  33064. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  33065. * @param {number} sceneIndex
  33066. * @return {Promise<Group>}
  33067. */
  33068. loadScene( sceneIndex ) {
  33069. const json = this.json;
  33070. const extensions = this.extensions;
  33071. const sceneDef = this.json.scenes[ sceneIndex ];
  33072. const parser = this;
  33073. // Loader returns Group, not Scene.
  33074. // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172
  33075. const scene = new three__WEBPACK_IMPORTED_MODULE_0__.Group();
  33076. if ( sceneDef.name ) scene.name = parser.createUniqueName( sceneDef.name );
  33077. assignExtrasToUserData( scene, sceneDef );
  33078. if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );
  33079. const nodeIds = sceneDef.nodes || [];
  33080. const pending = [];
  33081. for ( let i = 0, il = nodeIds.length; i < il; i ++ ) {
  33082. pending.push( buildNodeHierachy( nodeIds[ i ], scene, json, parser ) );
  33083. }
  33084. return Promise.all( pending ).then( function () {
  33085. return scene;
  33086. } );
  33087. }
  33088. }
  33089. function buildNodeHierachy( nodeId, parentObject, json, parser ) {
  33090. const nodeDef = json.nodes[ nodeId ];
  33091. return parser.getDependency( 'node', nodeId ).then( function ( node ) {
  33092. if ( nodeDef.skin === undefined ) return node;
  33093. // build skeleton here as well
  33094. let skinEntry;
  33095. return parser.getDependency( 'skin', nodeDef.skin ).then( function ( skin ) {
  33096. skinEntry = skin;
  33097. const pendingJoints = [];
  33098. for ( let i = 0, il = skinEntry.joints.length; i < il; i ++ ) {
  33099. pendingJoints.push( parser.getDependency( 'node', skinEntry.joints[ i ] ) );
  33100. }
  33101. return Promise.all( pendingJoints );
  33102. } ).then( function ( jointNodes ) {
  33103. node.traverse( function ( mesh ) {
  33104. if ( ! mesh.isMesh ) return;
  33105. const bones = [];
  33106. const boneInverses = [];
  33107. for ( let j = 0, jl = jointNodes.length; j < jl; j ++ ) {
  33108. const jointNode = jointNodes[ j ];
  33109. if ( jointNode ) {
  33110. bones.push( jointNode );
  33111. const mat = new three__WEBPACK_IMPORTED_MODULE_0__.Matrix4();
  33112. if ( skinEntry.inverseBindMatrices !== undefined ) {
  33113. mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );
  33114. }
  33115. boneInverses.push( mat );
  33116. } else {
  33117. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[ j ] );
  33118. }
  33119. }
  33120. mesh.bind( new three__WEBPACK_IMPORTED_MODULE_0__.Skeleton( bones, boneInverses ), mesh.matrixWorld );
  33121. } );
  33122. return node;
  33123. } );
  33124. } ).then( function ( node ) {
  33125. // build node hierachy
  33126. parentObject.add( node );
  33127. const pending = [];
  33128. if ( nodeDef.children ) {
  33129. const children = nodeDef.children;
  33130. for ( let i = 0, il = children.length; i < il; i ++ ) {
  33131. const child = children[ i ];
  33132. pending.push( buildNodeHierachy( child, node, json, parser ) );
  33133. }
  33134. }
  33135. return Promise.all( pending );
  33136. } );
  33137. }
  33138. /**
  33139. * @param {BufferGeometry} geometry
  33140. * @param {GLTF.Primitive} primitiveDef
  33141. * @param {GLTFParser} parser
  33142. */
  33143. function computeBounds( geometry, primitiveDef, parser ) {
  33144. const attributes = primitiveDef.attributes;
  33145. const box = new three__WEBPACK_IMPORTED_MODULE_0__.Box3();
  33146. if ( attributes.POSITION !== undefined ) {
  33147. const accessor = parser.json.accessors[ attributes.POSITION ];
  33148. const min = accessor.min;
  33149. const max = accessor.max;
  33150. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  33151. if ( min !== undefined && max !== undefined ) {
  33152. box.set(
  33153. new three__WEBPACK_IMPORTED_MODULE_0__.Vector3( min[ 0 ], min[ 1 ], min[ 2 ] ),
  33154. new three__WEBPACK_IMPORTED_MODULE_0__.Vector3( max[ 0 ], max[ 1 ], max[ 2 ] )
  33155. );
  33156. if ( accessor.normalized ) {
  33157. const boxScale = getNormalizedComponentScale( WEBGL_COMPONENT_TYPES[ accessor.componentType ] );
  33158. box.min.multiplyScalar( boxScale );
  33159. box.max.multiplyScalar( boxScale );
  33160. }
  33161. } else {
  33162. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  33163. return;
  33164. }
  33165. } else {
  33166. return;
  33167. }
  33168. const targets = primitiveDef.targets;
  33169. if ( targets !== undefined ) {
  33170. const maxDisplacement = new three__WEBPACK_IMPORTED_MODULE_0__.Vector3();
  33171. const vector = new three__WEBPACK_IMPORTED_MODULE_0__.Vector3();
  33172. for ( let i = 0, il = targets.length; i < il; i ++ ) {
  33173. const target = targets[ i ];
  33174. if ( target.POSITION !== undefined ) {
  33175. const accessor = parser.json.accessors[ target.POSITION ];
  33176. const min = accessor.min;
  33177. const max = accessor.max;
  33178. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  33179. if ( min !== undefined && max !== undefined ) {
  33180. // we need to get max of absolute components because target weight is [-1,1]
  33181. vector.setX( Math.max( Math.abs( min[ 0 ] ), Math.abs( max[ 0 ] ) ) );
  33182. vector.setY( Math.max( Math.abs( min[ 1 ] ), Math.abs( max[ 1 ] ) ) );
  33183. vector.setZ( Math.max( Math.abs( min[ 2 ] ), Math.abs( max[ 2 ] ) ) );
  33184. if ( accessor.normalized ) {
  33185. const boxScale = getNormalizedComponentScale( WEBGL_COMPONENT_TYPES[ accessor.componentType ] );
  33186. vector.multiplyScalar( boxScale );
  33187. }
  33188. // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative
  33189. // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets
  33190. // are used to implement key-frame animations and as such only two are active at a time - this results in very large
  33191. // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size.
  33192. maxDisplacement.max( vector );
  33193. } else {
  33194. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  33195. }
  33196. }
  33197. }
  33198. // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets.
  33199. box.expandByVector( maxDisplacement );
  33200. }
  33201. geometry.boundingBox = box;
  33202. const sphere = new three__WEBPACK_IMPORTED_MODULE_0__.Sphere();
  33203. box.getCenter( sphere.center );
  33204. sphere.radius = box.min.distanceTo( box.max ) / 2;
  33205. geometry.boundingSphere = sphere;
  33206. }
  33207. /**
  33208. * @param {BufferGeometry} geometry
  33209. * @param {GLTF.Primitive} primitiveDef
  33210. * @param {GLTFParser} parser
  33211. * @return {Promise<BufferGeometry>}
  33212. */
  33213. function addPrimitiveAttributes( geometry, primitiveDef, parser ) {
  33214. const attributes = primitiveDef.attributes;
  33215. const pending = [];
  33216. function assignAttributeAccessor( accessorIndex, attributeName ) {
  33217. return parser.getDependency( 'accessor', accessorIndex )
  33218. .then( function ( accessor ) {
  33219. geometry.setAttribute( attributeName, accessor );
  33220. } );
  33221. }
  33222. for ( const gltfAttributeName in attributes ) {
  33223. const threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase();
  33224. // Skip attributes already provided by e.g. Draco extension.
  33225. if ( threeAttributeName in geometry.attributes ) continue;
  33226. pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );
  33227. }
  33228. if ( primitiveDef.indices !== undefined && ! geometry.index ) {
  33229. const accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {
  33230. geometry.setIndex( accessor );
  33231. } );
  33232. pending.push( accessor );
  33233. }
  33234. assignExtrasToUserData( geometry, primitiveDef );
  33235. computeBounds( geometry, primitiveDef, parser );
  33236. return Promise.all( pending ).then( function () {
  33237. return primitiveDef.targets !== undefined
  33238. ? addMorphTargets( geometry, primitiveDef.targets, parser )
  33239. : geometry;
  33240. } );
  33241. }
  33242. /**
  33243. * @param {BufferGeometry} geometry
  33244. * @param {Number} drawMode
  33245. * @return {BufferGeometry}
  33246. */
  33247. function toTrianglesDrawMode( geometry, drawMode ) {
  33248. let index = geometry.getIndex();
  33249. // generate index if not present
  33250. if ( index === null ) {
  33251. const indices = [];
  33252. const position = geometry.getAttribute( 'position' );
  33253. if ( position !== undefined ) {
  33254. for ( let i = 0; i < position.count; i ++ ) {
  33255. indices.push( i );
  33256. }
  33257. geometry.setIndex( indices );
  33258. index = geometry.getIndex();
  33259. } else {
  33260. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
  33261. return geometry;
  33262. }
  33263. }
  33264. //
  33265. const numberOfTriangles = index.count - 2;
  33266. const newIndices = [];
  33267. if ( drawMode === three__WEBPACK_IMPORTED_MODULE_0__.TriangleFanDrawMode ) {
  33268. // gl.TRIANGLE_FAN
  33269. for ( let i = 1; i <= numberOfTriangles; i ++ ) {
  33270. newIndices.push( index.getX( 0 ) );
  33271. newIndices.push( index.getX( i ) );
  33272. newIndices.push( index.getX( i + 1 ) );
  33273. }
  33274. } else {
  33275. // gl.TRIANGLE_STRIP
  33276. for ( let i = 0; i < numberOfTriangles; i ++ ) {
  33277. if ( i % 2 === 0 ) {
  33278. newIndices.push( index.getX( i ) );
  33279. newIndices.push( index.getX( i + 1 ) );
  33280. newIndices.push( index.getX( i + 2 ) );
  33281. } else {
  33282. newIndices.push( index.getX( i + 2 ) );
  33283. newIndices.push( index.getX( i + 1 ) );
  33284. newIndices.push( index.getX( i ) );
  33285. }
  33286. }
  33287. }
  33288. if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
  33289. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
  33290. }
  33291. // build final geometry
  33292. const newGeometry = geometry.clone();
  33293. newGeometry.setIndex( newIndices );
  33294. return newGeometry;
  33295. }
  33296. /***/ })
  33297. /******/ });
  33298. /************************************************************************/
  33299. /******/ // The module cache
  33300. /******/ var __webpack_module_cache__ = {};
  33301. /******/
  33302. /******/ // The require function
  33303. /******/ function __webpack_require__(moduleId) {
  33304. /******/ // Check if module is in cache
  33305. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  33306. /******/ if (cachedModule !== undefined) {
  33307. /******/ return cachedModule.exports;
  33308. /******/ }
  33309. /******/ // Create a new module (and put it into the cache)
  33310. /******/ var module = __webpack_module_cache__[moduleId] = {
  33311. /******/ // no module.id needed
  33312. /******/ // no module.loaded needed
  33313. /******/ exports: {}
  33314. /******/ };
  33315. /******/
  33316. /******/ // Execute the module function
  33317. /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
  33318. /******/
  33319. /******/ // Return the exports of the module
  33320. /******/ return module.exports;
  33321. /******/ }
  33322. /******/
  33323. /************************************************************************/
  33324. /******/ /* webpack/runtime/define property getters */
  33325. /******/ (() => {
  33326. /******/ // define getter functions for harmony exports
  33327. /******/ __webpack_require__.d = (exports, definition) => {
  33328. /******/ for(var key in definition) {
  33329. /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
  33330. /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
  33331. /******/ }
  33332. /******/ }
  33333. /******/ };
  33334. /******/ })();
  33335. /******/
  33336. /******/ /* webpack/runtime/hasOwnProperty shorthand */
  33337. /******/ (() => {
  33338. /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
  33339. /******/ })();
  33340. /******/
  33341. /******/ /* webpack/runtime/make namespace object */
  33342. /******/ (() => {
  33343. /******/ // define __esModule on exports
  33344. /******/ __webpack_require__.r = (exports) => {
  33345. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  33346. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  33347. /******/ }
  33348. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  33349. /******/ };
  33350. /******/ })();
  33351. /******/
  33352. /************************************************************************/
  33353. var __webpack_exports__ = {};
  33354. // This entry need to be wrapped in an IIFE because it need to be in strict mode.
  33355. (() => {
  33356. "use strict";
  33357. /*!**********************!*\
  33358. !*** ./src/model.js ***!
  33359. \**********************/
  33360. __webpack_require__.r(__webpack_exports__);
  33361. /* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! three */ "./node_modules/three/build/three.module.js");
  33362. /* harmony import */ var three_examples_jsm_loaders_GLTFLoader_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! three/examples/jsm/loaders/GLTFLoader.js */ "./node_modules/three/examples/jsm/loaders/GLTFLoader.js");
  33363. var main = document.querySelector("#main"); // import GLTFLoader from 'three-gltf-loader';
  33364. var OrbitControls = __webpack_require__(/*! three-orbitcontrols */ "./node_modules/three-orbitcontrols/OrbitControls.js"); // const scene = new THREE.Scene();
  33365. // const camera = new THREE.PerspectiveCamera(75, innerHeight / innerHeight, 0.1, 1000);
  33366. // const light = new THREE.PointLight( 0xffffff, 1, 1000 );
  33367. // light.position.set( 200, 200, 200 );
  33368. // scene.add( light );
  33369. // scene.background = new THREE.Color(0xdddddd);
  33370. // camera.position.set(0, 0, 100);
  33371. // const renderer = new THREE.WebGLRenderer();
  33372. // renderer.setSize(innerWidth, innerHeight)
  33373. // const controlsCamra = new OrbitControls(camera, renderer.domElement)
  33374. // function animate() {
  33375. // controlsCamra.update();
  33376. // requestAnimationFrame(animate);
  33377. // renderer.render(scene, camera);
  33378. // }
  33379. // animate();
  33380. var scene, camera, renderer, hlighit;
  33381. var init = function init() {
  33382. scene = new three__WEBPACK_IMPORTED_MODULE_1__.Scene();
  33383. scene.background = new three__WEBPACK_IMPORTED_MODULE_1__.Color("#e9e9e9");
  33384. camera = new three__WEBPACK_IMPORTED_MODULE_1__.PerspectiveCamera(50, innerWidth / innerHeight, 1, 2000);
  33385. camera.position.set(0, 50, 300);
  33386. var light = new three__WEBPACK_IMPORTED_MODULE_1__.PointLight(0xffffff, 1, 1000);
  33387. light.position.set(200, 200, 200);
  33388. scene.add(light);
  33389. hlighit = new three__WEBPACK_IMPORTED_MODULE_1__.AmbientLight(0x404040, 100);
  33390. scene.add(hlighit);
  33391. renderer = new three__WEBPACK_IMPORTED_MODULE_1__.WebGLRenderer({
  33392. antialias: true
  33393. });
  33394. renderer.setSize(window.innerWidth, window.innerHeight); // document.body.appendChild(renderer.domElement);
  33395. main.appendChild(renderer.domElement);
  33396. var loader = new three_examples_jsm_loaders_GLTFLoader_js__WEBPACK_IMPORTED_MODULE_0__.GLTFLoader();
  33397. loader.load('./model/scene.gltf', function (gltf) {
  33398. scene.add(gltf.scene);
  33399. renderer.render(scene, camera);
  33400. }, undefined, function (error) {
  33401. console.error(error);
  33402. });
  33403. var controlsCamra = new OrbitControls(camera, renderer.domElement);
  33404. function animate() {
  33405. controlsCamra.update();
  33406. requestAnimationFrame(animate);
  33407. renderer.render(scene, camera); // mesh.rotation.y += 0.01;
  33408. }
  33409. animate();
  33410. };
  33411. init();
  33412. })();
  33413. /******/ })()
  33414. ;