PMREMGenerator.js 21 KB

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