PMREMGenerator.js 23 KB

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