PMREMGenerator.js 20 KB

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