PMREMGenerator.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  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. return cubeUVRenderTarget;
  105. },
  106. /**
  107. * Generates a PMREM from an equirectangular texture, which can be either LDR
  108. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  109. * as this matches best with the 256 x 256 cubemap output.
  110. */
  111. fromEquirectangular: function ( equirectangular ) {
  112. equirectangular.magFilter = NearestFilter;
  113. equirectangular.minFilter = NearestFilter;
  114. equirectangular.generateMipmaps = false;
  115. return this.fromCubemap( equirectangular );
  116. },
  117. /**
  118. * Generates a PMREM from an cubemap texture, which can be either LDR
  119. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  120. * as this matches best with the 256 x 256 cubemap output.
  121. */
  122. fromCubemap: function ( cubemap ) {
  123. var cubeUVRenderTarget = _allocateTargets( cubemap );
  124. _textureToCubeUV( cubemap, cubeUVRenderTarget );
  125. _applyPMREM( cubeUVRenderTarget );
  126. _cleanup();
  127. return cubeUVRenderTarget;
  128. },
  129. /**
  130. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  131. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  132. * one of them will cause any others to also become unusable.
  133. */
  134. dispose: function () {
  135. _blurMaterial.dispose();
  136. if ( _cubemapShader != null ) _cubemapShader.dispose();
  137. if ( _equirectShader != null ) _equirectShader.dispose();
  138. var plane;
  139. for ( plane of _lodPlanes ) {
  140. plane.dispose();
  141. }
  142. },
  143. };
  144. function _createPlanes() {
  145. var _lodPlanes = [];
  146. var _sizeLods = [];
  147. var _sigmas = [];
  148. var lod = LOD_MAX;
  149. for ( var i = 0; i < TOTAL_LODS; i ++ ) {
  150. var sizeLod = Math.pow( 2, lod );
  151. _sizeLods.push( sizeLod );
  152. var sigma = 1.0 / sizeLod;
  153. if ( i > LOD_MAX - LOD_MIN ) {
  154. sigma = EXTRA_LOD_SIGMA[ i - LOD_MAX + LOD_MIN - 1 ];
  155. } else if ( i == 0 ) {
  156. sigma = 0;
  157. }
  158. _sigmas.push( sigma );
  159. var texelSize = 1.0 / ( sizeLod - 1 );
  160. var min = - texelSize / 2;
  161. var max = 1 + texelSize / 2;
  162. var uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  163. var cubeFaces = 6;
  164. var vertices = 6;
  165. var positionSize = 3;
  166. var uvSize = 2;
  167. var faceIndexSize = 1;
  168. var position = new Float32Array( positionSize * vertices * cubeFaces );
  169. var uv = new Float32Array( uvSize * vertices * cubeFaces );
  170. var faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  171. for ( var face = 0; face < cubeFaces; face ++ ) {
  172. var x = ( face % 3 ) * 2 / 3 - 1;
  173. var y = face > 2 ? 0 : - 1;
  174. var coordinates = [
  175. [ x, y, 0 ],
  176. [ x + 2 / 3, y, 0 ],
  177. [ x + 2 / 3, y + 1, 0 ],
  178. [ x, y, 0 ],
  179. [ x + 2 / 3, y + 1, 0 ],
  180. [ x, y + 1, 0 ]
  181. ];
  182. position.set( [].concat( ...coordinates ),
  183. positionSize * vertices * face );
  184. uv.set( uv1, uvSize * vertices * face );
  185. var fill = [ face, face, face, face, face, face ];
  186. faceIndex.set( fill, faceIndexSize * vertices * face );
  187. }
  188. var planes = new BufferGeometry();
  189. planes.setAttribute(
  190. 'position', new BufferAttribute( position, positionSize ) );
  191. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  192. planes.setAttribute(
  193. 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  194. _lodPlanes.push( planes );
  195. if ( lod > LOD_MIN ) {
  196. lod --;
  197. }
  198. }
  199. return { _lodPlanes, _sizeLods, _sigmas };
  200. }
  201. function _allocateTargets( equirectangular ) {
  202. var params = {
  203. magFilter: NearestFilter,
  204. minFilter: NearestFilter,
  205. generateMipmaps: false,
  206. type: equirectangular ? equirectangular.type : UnsignedByteType,
  207. format: equirectangular ? equirectangular.format : RGBEFormat,
  208. encoding: equirectangular ? equirectangular.encoding : RGBEEncoding,
  209. depthBuffer: false,
  210. stencilBuffer: false
  211. };
  212. var cubeUVRenderTarget = _createRenderTarget(
  213. { ...params, depthBuffer: ( equirectangular ? false : true ) } );
  214. _pingPongRenderTarget = _createRenderTarget( params );
  215. return cubeUVRenderTarget;
  216. }
  217. function _cleanup() {
  218. _pingPongRenderTarget.dispose();
  219. _renderer.setRenderTarget( null );
  220. var size = _renderer.getSize( new Vector2() );
  221. _renderer.setViewport( 0, 0, size.x, size.y );
  222. }
  223. function _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  224. var fov = 90;
  225. var aspect = 1;
  226. var cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  227. var upSign = [ 1, 1, 1, 1, - 1, 1 ];
  228. var forwardSign = [ 1, 1, - 1, - 1, - 1, 1 ];
  229. var gammaOutput = _renderer.gammaOutput;
  230. var toneMapping = _renderer.toneMapping;
  231. var toneMappingExposure = _renderer.toneMappingExposure;
  232. var clearColor = _renderer.getClearColor();
  233. var clearAlpha = _renderer.getClearAlpha();
  234. _renderer.toneMapping = LinearToneMapping;
  235. _renderer.toneMappingExposure = 1.0;
  236. _renderer.gammaOutput = false;
  237. scene.scale.z *= - 1;
  238. var background = scene.background;
  239. if ( background && background.isColor ) {
  240. background.convertSRGBToLinear();
  241. // Convert linear to RGBE
  242. var maxComponent = Math.max( background.r, background.g, background.b );
  243. var fExp = Math.min( Math.max( Math.ceil( Math.log2( maxComponent ) ), - 128.0 ), 127.0 );
  244. background = background.multiplyScalar( Math.pow( 2.0, - fExp ) );
  245. var alpha = ( fExp + 128.0 ) / 255.0;
  246. _renderer.setClearColor( background, alpha );
  247. scene.background = null;
  248. }
  249. _renderer.setRenderTarget( cubeUVRenderTarget );
  250. for ( var i = 0; i < 6; i ++ ) {
  251. var col = i % 3;
  252. if ( col == 0 ) {
  253. cubeCamera.up.set( 0, upSign[ i ], 0 );
  254. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  255. } else if ( col == 1 ) {
  256. cubeCamera.up.set( 0, 0, upSign[ i ] );
  257. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  258. } else {
  259. cubeCamera.up.set( 0, upSign[ i ], 0 );
  260. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  261. }
  262. _setViewport(
  263. col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX );
  264. _renderer.render( scene, cubeCamera );
  265. }
  266. _renderer.toneMapping = toneMapping;
  267. _renderer.toneMappingExposure = toneMappingExposure;
  268. _renderer.gammaOutput = gammaOutput;
  269. _renderer.setClearColor( clearColor, clearAlpha );
  270. scene.scale.z *= - 1;
  271. }
  272. function _textureToCubeUV( texture, cubeUVRenderTarget ) {
  273. var scene = new Scene();
  274. if ( texture.isCubeTexture ) {
  275. if ( _cubemapShader == null ) {
  276. _cubemapShader = _getCubemapShader();
  277. }
  278. } else {
  279. if ( _equirectShader == null ) {
  280. _equirectShader = _getEquirectShader();
  281. }
  282. }
  283. var material = texture.isCubeTexture ? _cubemapShader : _equirectShader;
  284. scene.add( new Mesh( _lodPlanes[ 0 ], material ) );
  285. var uniforms = material.uniforms;
  286. uniforms[ 'envMap' ].value = texture;
  287. if ( ! texture.isCubeTexture ) {
  288. uniforms[ 'texelSize' ].value.set( 1.0 / texture.image.width, 1.0 / texture.image.height );
  289. }
  290. uniforms[ 'inputEncoding' ].value = ENCODINGS[ texture.encoding ];
  291. uniforms[ 'outputEncoding' ].value = ENCODINGS[ texture.encoding ];
  292. _renderer.setRenderTarget( cubeUVRenderTarget );
  293. _setViewport( 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX );
  294. _renderer.render( scene, _flatCamera );
  295. }
  296. function _createRenderTarget( params ) {
  297. var cubeUVRenderTarget =
  298. new WebGLRenderTarget( 3 * SIZE_MAX, 3 * SIZE_MAX, params );
  299. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  300. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  301. return cubeUVRenderTarget;
  302. }
  303. function _setViewport( x, y, width, height ) {
  304. var dpr = _renderer.getPixelRatio();
  305. _renderer.setViewport( x / dpr, y / dpr, width / dpr, height / dpr );
  306. }
  307. function _applyPMREM( cubeUVRenderTarget ) {
  308. var autoClear = _renderer.autoClear;
  309. _renderer.autoClear = false;
  310. for ( var i = 1; i < TOTAL_LODS; i ++ ) {
  311. var sigma = Math.sqrt(
  312. _sigmas[ i ] * _sigmas[ i ] -
  313. _sigmas[ i - 1 ] * _sigmas[ i - 1 ] );
  314. var poleAxis =
  315. _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  316. _blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  317. }
  318. _renderer.autoClear = autoClear;
  319. }
  320. /**
  321. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  322. * vertically and horizontally, but this breaks down on a cube. Here we apply
  323. * the blur latitudinally (around the poles), and then longitudinally (towards
  324. * the poles) to approximate the orthogonally-separable blur. It is least
  325. * accurate at the poles, but still does a decent job.
  326. */
  327. function _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  328. _halfBlur(
  329. cubeUVRenderTarget,
  330. _pingPongRenderTarget,
  331. lodIn,
  332. lodOut,
  333. sigma,
  334. 'latitudinal',
  335. poleAxis );
  336. _halfBlur(
  337. _pingPongRenderTarget,
  338. cubeUVRenderTarget,
  339. lodOut,
  340. lodOut,
  341. sigma,
  342. 'longitudinal',
  343. poleAxis );
  344. }
  345. function _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  346. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  347. console.error(
  348. 'blur direction must be either latitudinal or longitudinal!' );
  349. }
  350. // Number of standard deviations at which to cut off the discrete approximation.
  351. var STANDARD_DEVIATIONS = 3;
  352. var blurScene = new Scene();
  353. blurScene.add( new Mesh( _lodPlanes[ lodOut ], _blurMaterial ) );
  354. var blurUniforms = _blurMaterial.uniforms;
  355. var pixels = _sizeLods[ lodIn ] - 1;
  356. var radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  357. var sigmaPixels = sigmaRadians / radiansPerPixel;
  358. var samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  359. if ( samples > MAX_SAMPLES ) {
  360. console.warn( `sigmaRadians, ${
  361. sigmaRadians}, is too large and will clip, as it requested ${
  362. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  363. }
  364. var weights = [];
  365. var sum = 0;
  366. for ( var i = 0; i < MAX_SAMPLES; ++ i ) {
  367. var x = i / sigmaPixels;
  368. var weight = Math.exp( - x * x / 2 );
  369. weights.push( weight );
  370. if ( i == 0 ) {
  371. sum += weight;
  372. } else if ( i < samples ) {
  373. sum += 2 * weight;
  374. }
  375. }
  376. weights = weights.map( w => w / sum );
  377. blurUniforms[ 'envMap' ].value = targetIn.texture;
  378. blurUniforms[ 'samples' ].value = samples;
  379. blurUniforms[ 'weights' ].value = weights;
  380. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  381. if ( poleAxis ) {
  382. blurUniforms[ 'poleAxis' ].value = poleAxis;
  383. }
  384. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  385. blurUniforms[ 'mipInt' ].value = LOD_MAX - lodIn;
  386. blurUniforms[ 'inputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
  387. blurUniforms[ 'outputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
  388. var outputSize = _sizeLods[ lodOut ];
  389. var x = 3 * Math.max( 0, SIZE_MAX - 2 * outputSize );
  390. var y = ( lodOut === 0 ? 0 : 2 * SIZE_MAX ) +
  391. 2 * outputSize *
  392. ( lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0 );
  393. _renderer.setRenderTarget( targetOut );
  394. _setViewport( x, y, 3 * outputSize, 2 * outputSize );
  395. _renderer.render( blurScene, _flatCamera );
  396. }
  397. function _getBlurShader( maxSamples ) {
  398. var weights = new Float32Array( maxSamples );
  399. var poleAxis = new Vector3( 0, 1, 0 );
  400. var shaderMaterial = new RawShaderMaterial( {
  401. defines: { 'n': maxSamples },
  402. uniforms: {
  403. 'envMap': { value: null },
  404. 'samples': { value: 1 },
  405. 'weights': { value: weights },
  406. 'latitudinal': { value: false },
  407. 'dTheta': { value: 0 },
  408. 'mipInt': { value: 0 },
  409. 'poleAxis': { value: poleAxis },
  410. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  411. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  412. },
  413. vertexShader: _getCommonVertexShader(),
  414. fragmentShader: `
  415. precision mediump float;
  416. precision mediump int;
  417. varying vec3 vOutputDirection;
  418. uniform sampler2D envMap;
  419. uniform int samples;
  420. uniform float weights[n];
  421. uniform bool latitudinal;
  422. uniform float dTheta;
  423. uniform float mipInt;
  424. uniform vec3 poleAxis;
  425. ${_getEncodings()}
  426. #define ENVMAP_TYPE_CUBE_UV
  427. #include <cube_uv_reflection_fragment>
  428. void main() {
  429. gl_FragColor = vec4(0.0);
  430. for (int i = 0; i < n; i++) {
  431. if (i >= samples)
  432. break;
  433. for (int dir = -1; dir < 2; dir += 2) {
  434. if (i == 0 && dir == 1)
  435. continue;
  436. vec3 axis = latitudinal ? poleAxis : cross(poleAxis, vOutputDirection);
  437. if (all(equal(axis, vec3(0.0))))
  438. axis = cross(vec3(0.0, 1.0, 0.0), vOutputDirection);
  439. axis = normalize(axis);
  440. float theta = dTheta * float(dir * i);
  441. float cosTheta = cos(theta);
  442. // Rodrigues' axis-angle rotation
  443. vec3 sampleDirection = vOutputDirection * cosTheta
  444. + cross(axis, vOutputDirection) * sin(theta)
  445. + axis * dot(axis, vOutputDirection) * (1.0 - cosTheta);
  446. gl_FragColor.rgb +=
  447. weights[i] * bilinearCubeUV(envMap, sampleDirection, mipInt);
  448. }
  449. }
  450. gl_FragColor = linearToOutputTexel(gl_FragColor);
  451. }
  452. `,
  453. blending: NoBlending,
  454. depthTest: false,
  455. depthWrite: false
  456. } );
  457. shaderMaterial.type = 'SphericalGaussianBlur';
  458. return shaderMaterial;
  459. }
  460. function _getEquirectShader() {
  461. var texelSize = new Vector2( 1, 1 );
  462. var shaderMaterial = new RawShaderMaterial( {
  463. uniforms: {
  464. 'envMap': { value: null },
  465. 'texelSize': { value: texelSize },
  466. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  467. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  468. },
  469. vertexShader: _getCommonVertexShader(),
  470. fragmentShader: `
  471. precision mediump float;
  472. precision mediump int;
  473. varying vec3 vOutputDirection;
  474. uniform sampler2D envMap;
  475. uniform vec2 texelSize;
  476. ${_getEncodings()}
  477. #define RECIPROCAL_PI 0.31830988618
  478. #define RECIPROCAL_PI2 0.15915494
  479. void main() {
  480. gl_FragColor = vec4(0.0);
  481. vec3 outputDirection = normalize(vOutputDirection);
  482. vec2 uv;
  483. uv.y = asin(clamp(outputDirection.y, -1.0, 1.0)) * RECIPROCAL_PI + 0.5;
  484. uv.x = atan(outputDirection.z, outputDirection.x) * RECIPROCAL_PI2 + 0.5;
  485. vec2 f = fract(uv / texelSize - 0.5);
  486. uv -= f * texelSize;
  487. vec3 tl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
  488. uv.x += texelSize.x;
  489. vec3 tr = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
  490. uv.y += texelSize.y;
  491. vec3 br = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
  492. uv.x -= texelSize.x;
  493. vec3 bl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
  494. vec3 tm = mix(tl, tr, f.x);
  495. vec3 bm = mix(bl, br, f.x);
  496. gl_FragColor.rgb = mix(tm, bm, f.y);
  497. gl_FragColor = linearToOutputTexel(gl_FragColor);
  498. }
  499. `,
  500. blending: NoBlending,
  501. depthTest: false,
  502. depthWrite: false
  503. } );
  504. shaderMaterial.type = 'EquirectangularToCubeUV';
  505. return shaderMaterial;
  506. }
  507. function _getCubemapShader() {
  508. var shaderMaterial = new RawShaderMaterial( {
  509. uniforms: {
  510. 'envMap': { value: null },
  511. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  512. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  513. },
  514. vertexShader: _getCommonVertexShader(),
  515. fragmentShader: `
  516. precision mediump float;
  517. precision mediump int;
  518. varying vec3 vOutputDirection;
  519. uniform samplerCube envMap;
  520. ${_getEncodings()}
  521. void main() {
  522. gl_FragColor = vec4(0.0);
  523. gl_FragColor.rgb = envMapTexelToLinear(textureCube(envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ))).rgb;
  524. gl_FragColor = linearToOutputTexel(gl_FragColor);
  525. }
  526. `,
  527. blending: NoBlending,
  528. depthTest: false,
  529. depthWrite: false
  530. } );
  531. shaderMaterial.type = 'CubemapToCubeUV';
  532. return shaderMaterial;
  533. }
  534. function _getCommonVertexShader() {
  535. return `
  536. precision mediump float;
  537. precision mediump int;
  538. attribute vec3 position;
  539. attribute vec2 uv;
  540. attribute float faceIndex;
  541. varying vec3 vOutputDirection;
  542. vec3 getDirection(vec2 uv, float face) {
  543. uv = 2.0 * uv - 1.0;
  544. vec3 direction = vec3(uv, 1.0);
  545. if (face == 0.0) {
  546. direction = direction.zyx;
  547. direction.z *= -1.0;
  548. } else if (face == 1.0) {
  549. direction = direction.xzy;
  550. direction.z *= -1.0;
  551. } else if (face == 3.0) {
  552. direction = direction.zyx;
  553. direction.x *= -1.0;
  554. } else if (face == 4.0) {
  555. direction = direction.xzy;
  556. direction.y *= -1.0;
  557. } else if (face == 5.0) {
  558. direction.xz *= -1.0;
  559. }
  560. return direction;
  561. }
  562. void main() {
  563. vOutputDirection = getDirection(uv, faceIndex);
  564. gl_Position = vec4( position, 1.0 );
  565. }
  566. `;
  567. }
  568. function _getEncodings() {
  569. return `
  570. uniform int inputEncoding;
  571. uniform int outputEncoding;
  572. #include <encodings_pars_fragment>
  573. vec4 inputTexelToLinear(vec4 value){
  574. if(inputEncoding == 0){
  575. return value;
  576. }else if(inputEncoding == 1){
  577. return sRGBToLinear(value);
  578. }else if(inputEncoding == 2){
  579. return RGBEToLinear(value);
  580. }else if(inputEncoding == 3){
  581. return RGBMToLinear(value, 7.0);
  582. }else if(inputEncoding == 4){
  583. return RGBMToLinear(value, 16.0);
  584. }else if(inputEncoding == 5){
  585. return RGBDToLinear(value, 256.0);
  586. }else{
  587. return GammaToLinear(value, 2.2);
  588. }
  589. }
  590. vec4 linearToOutputTexel(vec4 value){
  591. if(outputEncoding == 0){
  592. return value;
  593. }else if(outputEncoding == 1){
  594. return LinearTosRGB(value);
  595. }else if(outputEncoding == 2){
  596. return LinearToRGBE(value);
  597. }else if(outputEncoding == 3){
  598. return LinearToRGBM(value, 7.0);
  599. }else if(outputEncoding == 4){
  600. return LinearToRGBM(value, 16.0);
  601. }else if(outputEncoding == 5){
  602. return LinearToRGBD(value, 256.0);
  603. }else{
  604. return LinearToGamma(value, 2.2);
  605. }
  606. }
  607. vec4 envMapTexelToLinear(vec4 color) {
  608. return inputTexelToLinear(color);
  609. }
  610. `;
  611. }
  612. return PMREMGenerator;
  613. } )();
  614. export { PMREMGenerator };