PMREMGenerator.js 22 KB

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