PMREMGenerator.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  1. /**
  2. * @author Emmett Lalish / elalish
  3. *
  4. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  5. * (PMREM) from a cubeMap environment texture. This allows different levels of
  6. * blur to be quickly accessed based on material roughness. It is packed into a
  7. * special CubeUV format that allows us to perform custom interpolation so that
  8. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  10. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  11. * higher roughness levels. In this way we maintain resolution to smoothly
  12. * interpolate diffuse lighting while limiting sampling computation.
  13. */
  14. import {
  15. BufferAttribute,
  16. BufferGeometry,
  17. CubeUVReflectionMapping,
  18. GammaEncoding,
  19. LinearEncoding,
  20. LinearToneMapping,
  21. Mesh,
  22. NearestFilter,
  23. NoBlending,
  24. OrthographicCamera,
  25. PerspectiveCamera,
  26. RGBDEncoding,
  27. RGBEEncoding,
  28. RGBEFormat,
  29. RGBM16Encoding,
  30. RGBM7Encoding,
  31. RawShaderMaterial,
  32. Scene,
  33. UnsignedByteType,
  34. Vector2,
  35. Vector3,
  36. WebGLRenderTarget,
  37. sRGBEncoding
  38. } from "../../../build/three.module.js";
  39. var PMREMGenerator = ( function () {
  40. var LOD_MIN = 4;
  41. var LOD_MAX = 8;
  42. var SIZE_MAX = Math.pow( 2, LOD_MAX );
  43. // The standard deviations (radians) associated with the extra mips. These are
  44. // chosen to approximate a Trowbridge-Reitz distribution function times the
  45. // geometric shadowing function. These sigma values squared must match the
  46. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  47. var EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  48. var TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  49. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  50. // samples and exit early, but not recompile the shader.
  51. var MAX_SAMPLES = 20;
  52. var ENCODINGS = {
  53. [ LinearEncoding ]: 0,
  54. [ sRGBEncoding ]: 1,
  55. [ RGBEEncoding ]: 2,
  56. [ RGBM7Encoding ]: 3,
  57. [ RGBM16Encoding ]: 4,
  58. [ RGBDEncoding ]: 5,
  59. [ GammaEncoding ]: 6
  60. };
  61. var _flatCamera = new OrthographicCamera();
  62. var _blurMaterial = _getBlurShader( MAX_SAMPLES );
  63. var _equirectShader = null;
  64. var _cubemapShader = null;
  65. var { _lodPlanes, _sizeLods, _sigmas } = _createPlanes();
  66. var _pingPongRenderTarget = null;
  67. var _renderer = null;
  68. // Golden Ratio
  69. var PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  70. var INV_PHI = 1 / PHI;
  71. // Vertices of a dodecahedron (except the opposites, which represent the
  72. // same axis), used as axis directions evenly spread on a sphere.
  73. var _axisDirections = [
  74. new Vector3( 1, 1, 1 ),
  75. new Vector3( - 1, 1, 1 ),
  76. new Vector3( 1, 1, - 1 ),
  77. new Vector3( - 1, 1, - 1 ),
  78. new Vector3( 0, PHI, INV_PHI ),
  79. new Vector3( 0, PHI, - INV_PHI ),
  80. new Vector3( INV_PHI, 0, PHI ),
  81. new Vector3( - INV_PHI, 0, PHI ),
  82. new Vector3( PHI, INV_PHI, 0 ),
  83. new Vector3( - PHI, INV_PHI, 0 ) ];
  84. var PMREMGenerator = function ( renderer ) {
  85. _renderer = renderer;
  86. };
  87. PMREMGenerator.prototype = {
  88. constructor: PMREMGenerator,
  89. /**
  90. * Generates a PMREM from a supplied Scene, which can be faster than using an
  91. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  92. * in radians to be applied to the scene before PMREM generation. Optional near
  93. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  94. * is placed at the origin).
  95. */
  96. fromScene: function ( scene, sigma = 0, near = 0.1, far = 100 ) {
  97. var cubeUVRenderTarget = _allocateTargets();
  98. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  99. if ( sigma > 0 ) {
  100. _blur( cubeUVRenderTarget, 0, 0, sigma );
  101. }
  102. _applyPMREM( cubeUVRenderTarget );
  103. _cleanup();
  104. cubeUVRenderTarget.scissorTest = false;
  105. return cubeUVRenderTarget;
  106. },
  107. /**
  108. * Generates a PMREM from an equirectangular texture, which can be either LDR
  109. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  110. * as this matches best with the 256 x 256 cubemap output.
  111. */
  112. fromEquirectangular: function ( equirectangular ) {
  113. equirectangular.magFilter = NearestFilter;
  114. equirectangular.minFilter = NearestFilter;
  115. equirectangular.generateMipmaps = false;
  116. return this.fromCubemap( equirectangular );
  117. },
  118. /**
  119. * Generates a PMREM from an cubemap texture, which can be either LDR
  120. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  121. * as this matches best with the 256 x 256 cubemap output.
  122. */
  123. fromCubemap: function ( cubemap ) {
  124. var cubeUVRenderTarget = _allocateTargets( cubemap );
  125. _textureToCubeUV( cubemap, cubeUVRenderTarget );
  126. _applyPMREM( cubeUVRenderTarget );
  127. _cleanup();
  128. cubeUVRenderTarget.scissorTest = false;
  129. return cubeUVRenderTarget;
  130. },
  131. /**
  132. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  133. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  134. * one of them will cause any others to also become unusable.
  135. */
  136. dispose: function () {
  137. _blurMaterial.dispose();
  138. if ( _cubemapShader != null ) _cubemapShader.dispose();
  139. if ( _equirectShader != null ) _equirectShader.dispose();
  140. var plane;
  141. for ( plane of _lodPlanes ) {
  142. plane.dispose();
  143. }
  144. },
  145. };
  146. function _createPlanes() {
  147. var _lodPlanes = [];
  148. var _sizeLods = [];
  149. var _sigmas = [];
  150. var lod = LOD_MAX;
  151. for ( var i = 0; i < TOTAL_LODS; i ++ ) {
  152. var sizeLod = Math.pow( 2, lod );
  153. _sizeLods.push( sizeLod );
  154. var sigma = 1.0 / sizeLod;
  155. if ( i > LOD_MAX - LOD_MIN ) {
  156. sigma = EXTRA_LOD_SIGMA[ i - LOD_MAX + LOD_MIN - 1 ];
  157. } else if ( i == 0 ) {
  158. sigma = 0;
  159. }
  160. _sigmas.push( sigma );
  161. var texelSize = 1.0 / ( sizeLod - 1 );
  162. var min = - texelSize / 2;
  163. var max = 1 + texelSize / 2;
  164. var uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  165. var cubeFaces = 6;
  166. var vertices = 6;
  167. var positionSize = 3;
  168. var uvSize = 2;
  169. var faceIndexSize = 1;
  170. var position = new Float32Array( positionSize * vertices * cubeFaces );
  171. var uv = new Float32Array( uvSize * vertices * cubeFaces );
  172. var faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  173. for ( var face = 0; face < cubeFaces; face ++ ) {
  174. var x = ( face % 3 ) * 2 / 3 - 1;
  175. var y = face > 2 ? 0 : - 1;
  176. var coordinates = [
  177. [ x, y, 0 ],
  178. [ x + 2 / 3, y, 0 ],
  179. [ x + 2 / 3, y + 1, 0 ],
  180. [ x, y, 0 ],
  181. [ x + 2 / 3, y + 1, 0 ],
  182. [ x, y + 1, 0 ]
  183. ];
  184. position.set( [].concat( ...coordinates ),
  185. positionSize * vertices * face );
  186. uv.set( uv1, uvSize * vertices * face );
  187. var fill = [ face, face, face, face, face, face ];
  188. faceIndex.set( fill, faceIndexSize * vertices * face );
  189. }
  190. var planes = new BufferGeometry();
  191. planes.setAttribute(
  192. 'position', new BufferAttribute( position, positionSize ) );
  193. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  194. planes.setAttribute(
  195. 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  196. _lodPlanes.push( planes );
  197. if ( lod > LOD_MIN ) {
  198. lod --;
  199. }
  200. }
  201. return { _lodPlanes, _sizeLods, _sigmas };
  202. }
  203. function _allocateTargets( equirectangular ) {
  204. var params = {
  205. magFilter: NearestFilter,
  206. minFilter: NearestFilter,
  207. generateMipmaps: false,
  208. type: equirectangular ? equirectangular.type : UnsignedByteType,
  209. format: equirectangular ? equirectangular.format : RGBEFormat,
  210. encoding: equirectangular ? equirectangular.encoding : RGBEEncoding,
  211. depthBuffer: false,
  212. stencilBuffer: false
  213. };
  214. var cubeUVRenderTarget = _createRenderTarget(
  215. { ...params, depthBuffer: ( equirectangular ? false : true ) } );
  216. _pingPongRenderTarget = _createRenderTarget( params );
  217. return cubeUVRenderTarget;
  218. }
  219. function _cleanup() {
  220. _pingPongRenderTarget.dispose();
  221. _renderer.setRenderTarget( null );
  222. var size = _renderer.getSize( new Vector2() );
  223. _renderer.setViewport( 0, 0, size.x, size.y );
  224. }
  225. function _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  226. var fov = 90;
  227. var aspect = 1;
  228. var cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  229. var upSign = [ 1, 1, 1, 1, - 1, 1 ];
  230. var forwardSign = [ 1, 1, - 1, - 1, - 1, 1 ];
  231. var gammaOutput = _renderer.gammaOutput;
  232. var toneMapping = _renderer.toneMapping;
  233. var toneMappingExposure = _renderer.toneMappingExposure;
  234. var clearColor = _renderer.getClearColor();
  235. var clearAlpha = _renderer.getClearAlpha();
  236. _renderer.toneMapping = LinearToneMapping;
  237. _renderer.toneMappingExposure = 1.0;
  238. _renderer.gammaOutput = false;
  239. scene.scale.z *= - 1;
  240. var background = scene.background;
  241. if ( background && background.isColor ) {
  242. background.convertSRGBToLinear();
  243. // Convert linear to RGBE
  244. var maxComponent = Math.max( background.r, background.g, background.b );
  245. var fExp = Math.min( Math.max( Math.ceil( Math.log2( maxComponent ) ), - 128.0 ), 127.0 );
  246. background = background.multiplyScalar( Math.pow( 2.0, - fExp ) );
  247. var alpha = ( fExp + 128.0 ) / 255.0;
  248. _renderer.setClearColor( background, alpha );
  249. scene.background = null;
  250. }
  251. _renderer.setRenderTarget( cubeUVRenderTarget );
  252. for ( var i = 0; i < 6; i ++ ) {
  253. var col = i % 3;
  254. if ( col == 0 ) {
  255. cubeCamera.up.set( 0, upSign[ i ], 0 );
  256. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  257. } else if ( col == 1 ) {
  258. cubeCamera.up.set( 0, 0, upSign[ i ] );
  259. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  260. } else {
  261. cubeCamera.up.set( 0, upSign[ i ], 0 );
  262. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  263. }
  264. _setViewport(
  265. col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX );
  266. _renderer.render( scene, cubeCamera );
  267. }
  268. _renderer.toneMapping = toneMapping;
  269. _renderer.toneMappingExposure = toneMappingExposure;
  270. _renderer.gammaOutput = gammaOutput;
  271. _renderer.setClearColor( clearColor, clearAlpha );
  272. scene.scale.z *= - 1;
  273. }
  274. function _textureToCubeUV( texture, cubeUVRenderTarget ) {
  275. var scene = new Scene();
  276. if ( texture.isCubeTexture ) {
  277. if ( _cubemapShader == null ) {
  278. _cubemapShader = _getCubemapShader();
  279. }
  280. } else {
  281. if ( _equirectShader == null ) {
  282. _equirectShader = _getEquirectShader();
  283. }
  284. }
  285. var material = texture.isCubeTexture ? _cubemapShader : _equirectShader;
  286. scene.add( new Mesh( _lodPlanes[ 0 ], material ) );
  287. var uniforms = material.uniforms;
  288. uniforms[ 'envMap' ].value = texture;
  289. if ( ! texture.isCubeTexture ) {
  290. uniforms[ 'texelSize' ].value.set( 1.0 / texture.image.width, 1.0 / texture.image.height );
  291. }
  292. uniforms[ 'inputEncoding' ].value = ENCODINGS[ texture.encoding ];
  293. uniforms[ 'outputEncoding' ].value = ENCODINGS[ texture.encoding ];
  294. _renderer.setRenderTarget( cubeUVRenderTarget );
  295. _setViewport( 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX );
  296. _renderer.render( scene, _flatCamera );
  297. }
  298. function _createRenderTarget( params ) {
  299. var cubeUVRenderTarget =
  300. new WebGLRenderTarget( 3 * SIZE_MAX, 3 * SIZE_MAX, params );
  301. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  302. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  303. cubeUVRenderTarget.scissorTest = true;
  304. return cubeUVRenderTarget;
  305. }
  306. function _setViewport( x, y, width, height ) {
  307. var invDpr = 1.0 / _renderer.getPixelRatio();
  308. x *= invDpr;
  309. y *= invDpr;
  310. width *= invDpr;
  311. height *= invDpr;
  312. _renderer.setViewport( x, y, width, height );
  313. _renderer.setScissor( x, y, width, height );
  314. }
  315. function _applyPMREM( cubeUVRenderTarget ) {
  316. var autoClear = _renderer.autoClear;
  317. _renderer.autoClear = false;
  318. for ( var i = 1; i < TOTAL_LODS; i ++ ) {
  319. var sigma = Math.sqrt(
  320. _sigmas[ i ] * _sigmas[ i ] -
  321. _sigmas[ i - 1 ] * _sigmas[ i - 1 ] );
  322. var poleAxis =
  323. _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  324. _blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  325. }
  326. _renderer.autoClear = autoClear;
  327. }
  328. /**
  329. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  330. * vertically and horizontally, but this breaks down on a cube. Here we apply
  331. * the blur latitudinally (around the poles), and then longitudinally (towards
  332. * the poles) to approximate the orthogonally-separable blur. It is least
  333. * accurate at the poles, but still does a decent job.
  334. */
  335. function _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  336. _halfBlur(
  337. cubeUVRenderTarget,
  338. _pingPongRenderTarget,
  339. lodIn,
  340. lodOut,
  341. sigma,
  342. 'latitudinal',
  343. poleAxis );
  344. _halfBlur(
  345. _pingPongRenderTarget,
  346. cubeUVRenderTarget,
  347. lodOut,
  348. lodOut,
  349. sigma,
  350. 'longitudinal',
  351. poleAxis );
  352. }
  353. function _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  354. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  355. console.error(
  356. 'blur direction must be either latitudinal or longitudinal!' );
  357. }
  358. // Number of standard deviations at which to cut off the discrete approximation.
  359. var STANDARD_DEVIATIONS = 3;
  360. var blurScene = new Scene();
  361. blurScene.add( new Mesh( _lodPlanes[ lodOut ], _blurMaterial ) );
  362. var blurUniforms = _blurMaterial.uniforms;
  363. var pixels = _sizeLods[ lodIn ] - 1;
  364. var radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  365. var sigmaPixels = sigmaRadians / radiansPerPixel;
  366. var samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  367. if ( samples > MAX_SAMPLES ) {
  368. console.warn( `sigmaRadians, ${
  369. sigmaRadians}, is too large and will clip, as it requested ${
  370. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  371. }
  372. var weights = [];
  373. var sum = 0;
  374. for ( var i = 0; i < MAX_SAMPLES; ++ i ) {
  375. var x = i / sigmaPixels;
  376. var weight = Math.exp( - x * x / 2 );
  377. weights.push( weight );
  378. if ( i == 0 ) {
  379. sum += weight;
  380. } else if ( i < samples ) {
  381. sum += 2 * weight;
  382. }
  383. }
  384. weights = weights.map( w => w / sum );
  385. blurUniforms[ 'envMap' ].value = targetIn.texture;
  386. blurUniforms[ 'samples' ].value = samples;
  387. blurUniforms[ 'weights' ].value = weights;
  388. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  389. if ( poleAxis ) {
  390. blurUniforms[ 'poleAxis' ].value = poleAxis;
  391. }
  392. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  393. blurUniforms[ 'mipInt' ].value = LOD_MAX - lodIn;
  394. blurUniforms[ 'inputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
  395. blurUniforms[ 'outputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
  396. var outputSize = _sizeLods[ lodOut ];
  397. var x = 3 * Math.max( 0, SIZE_MAX - 2 * outputSize );
  398. var y = ( lodOut === 0 ? 0 : 2 * SIZE_MAX ) +
  399. 2 * outputSize *
  400. ( lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0 );
  401. _renderer.setRenderTarget( targetOut );
  402. _setViewport( x, y, 3 * outputSize, 2 * outputSize );
  403. _renderer.render( blurScene, _flatCamera );
  404. }
  405. function _getBlurShader( maxSamples ) {
  406. var weights = new Float32Array( maxSamples );
  407. var poleAxis = new Vector3( 0, 1, 0 );
  408. var shaderMaterial = new RawShaderMaterial( {
  409. defines: { 'n': maxSamples },
  410. uniforms: {
  411. 'envMap': { value: null },
  412. 'samples': { value: 1 },
  413. 'weights': { value: weights },
  414. 'latitudinal': { value: false },
  415. 'dTheta': { value: 0 },
  416. 'mipInt': { value: 0 },
  417. 'poleAxis': { value: poleAxis },
  418. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  419. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  420. },
  421. vertexShader: _getCommonVertexShader(),
  422. fragmentShader: `
  423. precision mediump float;
  424. precision mediump int;
  425. varying vec3 vOutputDirection;
  426. uniform sampler2D envMap;
  427. uniform int samples;
  428. uniform float weights[n];
  429. uniform bool latitudinal;
  430. uniform float dTheta;
  431. uniform float mipInt;
  432. uniform vec3 poleAxis;
  433. ${_getEncodings()}
  434. #define ENVMAP_TYPE_CUBE_UV
  435. #include <cube_uv_reflection_fragment>
  436. void main() {
  437. gl_FragColor = vec4(0.0);
  438. for (int i = 0; i < n; i++) {
  439. if (i >= samples)
  440. break;
  441. for (int dir = -1; dir < 2; dir += 2) {
  442. if (i == 0 && dir == 1)
  443. continue;
  444. vec3 axis = latitudinal ? poleAxis : cross(poleAxis, vOutputDirection);
  445. if (all(equal(axis, vec3(0.0))))
  446. axis = cross(vec3(0.0, 1.0, 0.0), vOutputDirection);
  447. axis = normalize(axis);
  448. float theta = dTheta * float(dir * i);
  449. float cosTheta = cos(theta);
  450. // Rodrigues' axis-angle rotation
  451. vec3 sampleDirection = vOutputDirection * cosTheta
  452. + cross(axis, vOutputDirection) * sin(theta)
  453. + axis * dot(axis, vOutputDirection) * (1.0 - cosTheta);
  454. gl_FragColor.rgb +=
  455. weights[i] * bilinearCubeUV(envMap, sampleDirection, mipInt);
  456. }
  457. }
  458. gl_FragColor = linearToOutputTexel(gl_FragColor);
  459. }
  460. `,
  461. blending: NoBlending,
  462. depthTest: false,
  463. depthWrite: false
  464. } );
  465. shaderMaterial.type = 'SphericalGaussianBlur';
  466. return shaderMaterial;
  467. }
  468. function _getEquirectShader() {
  469. var texelSize = new Vector2( 1, 1 );
  470. var shaderMaterial = new RawShaderMaterial( {
  471. uniforms: {
  472. 'envMap': { value: null },
  473. 'texelSize': { value: texelSize },
  474. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  475. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  476. },
  477. vertexShader: _getCommonVertexShader(),
  478. fragmentShader: `
  479. precision mediump float;
  480. precision mediump int;
  481. varying vec3 vOutputDirection;
  482. uniform sampler2D envMap;
  483. uniform vec2 texelSize;
  484. ${_getEncodings()}
  485. #define RECIPROCAL_PI 0.31830988618
  486. #define RECIPROCAL_PI2 0.15915494
  487. void main() {
  488. gl_FragColor = vec4(0.0);
  489. vec3 outputDirection = normalize(vOutputDirection);
  490. vec2 uv;
  491. uv.y = asin(clamp(outputDirection.y, -1.0, 1.0)) * RECIPROCAL_PI + 0.5;
  492. uv.x = atan(outputDirection.z, outputDirection.x) * RECIPROCAL_PI2 + 0.5;
  493. vec2 f = fract(uv / texelSize - 0.5);
  494. uv -= f * texelSize;
  495. vec3 tl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
  496. uv.x += texelSize.x;
  497. vec3 tr = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
  498. uv.y += texelSize.y;
  499. vec3 br = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
  500. uv.x -= texelSize.x;
  501. vec3 bl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
  502. vec3 tm = mix(tl, tr, f.x);
  503. vec3 bm = mix(bl, br, f.x);
  504. gl_FragColor.rgb = mix(tm, bm, f.y);
  505. gl_FragColor = linearToOutputTexel(gl_FragColor);
  506. }
  507. `,
  508. blending: NoBlending,
  509. depthTest: false,
  510. depthWrite: false
  511. } );
  512. shaderMaterial.type = 'EquirectangularToCubeUV';
  513. return shaderMaterial;
  514. }
  515. function _getCubemapShader() {
  516. var shaderMaterial = new RawShaderMaterial( {
  517. uniforms: {
  518. 'envMap': { value: null },
  519. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  520. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  521. },
  522. vertexShader: _getCommonVertexShader(),
  523. fragmentShader: `
  524. precision mediump float;
  525. precision mediump int;
  526. varying vec3 vOutputDirection;
  527. uniform samplerCube envMap;
  528. ${_getEncodings()}
  529. void main() {
  530. gl_FragColor = vec4(0.0);
  531. gl_FragColor.rgb = envMapTexelToLinear(textureCube(envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ))).rgb;
  532. gl_FragColor = linearToOutputTexel(gl_FragColor);
  533. }
  534. `,
  535. blending: NoBlending,
  536. depthTest: false,
  537. depthWrite: false
  538. } );
  539. shaderMaterial.type = 'CubemapToCubeUV';
  540. return shaderMaterial;
  541. }
  542. function _getCommonVertexShader() {
  543. return `
  544. precision mediump float;
  545. precision mediump int;
  546. attribute vec3 position;
  547. attribute vec2 uv;
  548. attribute float faceIndex;
  549. varying vec3 vOutputDirection;
  550. vec3 getDirection(vec2 uv, float face) {
  551. uv = 2.0 * uv - 1.0;
  552. vec3 direction = vec3(uv, 1.0);
  553. if (face == 0.0) {
  554. direction = direction.zyx;
  555. direction.z *= -1.0;
  556. } else if (face == 1.0) {
  557. direction = direction.xzy;
  558. direction.z *= -1.0;
  559. } else if (face == 3.0) {
  560. direction = direction.zyx;
  561. direction.x *= -1.0;
  562. } else if (face == 4.0) {
  563. direction = direction.xzy;
  564. direction.y *= -1.0;
  565. } else if (face == 5.0) {
  566. direction.xz *= -1.0;
  567. }
  568. return direction;
  569. }
  570. void main() {
  571. vOutputDirection = getDirection(uv, faceIndex);
  572. gl_Position = vec4( position, 1.0 );
  573. }
  574. `;
  575. }
  576. function _getEncodings() {
  577. return `
  578. uniform int inputEncoding;
  579. uniform int outputEncoding;
  580. #include <encodings_pars_fragment>
  581. vec4 inputTexelToLinear(vec4 value){
  582. if(inputEncoding == 0){
  583. return value;
  584. }else if(inputEncoding == 1){
  585. return sRGBToLinear(value);
  586. }else if(inputEncoding == 2){
  587. return RGBEToLinear(value);
  588. }else if(inputEncoding == 3){
  589. return RGBMToLinear(value, 7.0);
  590. }else if(inputEncoding == 4){
  591. return RGBMToLinear(value, 16.0);
  592. }else if(inputEncoding == 5){
  593. return RGBDToLinear(value, 256.0);
  594. }else{
  595. return GammaToLinear(value, 2.2);
  596. }
  597. }
  598. vec4 linearToOutputTexel(vec4 value){
  599. if(outputEncoding == 0){
  600. return value;
  601. }else if(outputEncoding == 1){
  602. return LinearTosRGB(value);
  603. }else if(outputEncoding == 2){
  604. return LinearToRGBE(value);
  605. }else if(outputEncoding == 3){
  606. return LinearToRGBM(value, 7.0);
  607. }else if(outputEncoding == 4){
  608. return LinearToRGBM(value, 16.0);
  609. }else if(outputEncoding == 5){
  610. return LinearToRGBD(value, 256.0);
  611. }else{
  612. return LinearToGamma(value, 2.2);
  613. }
  614. }
  615. vec4 envMapTexelToLinear(vec4 color) {
  616. return inputTexelToLinear(color);
  617. }
  618. `;
  619. }
  620. return PMREMGenerator;
  621. } )();
  622. export { PMREMGenerator };