PMREMGenerator.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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. const LOD_MIN = 4;
  16. const LOD_MAX = 8;
  17. const 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.
  21. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  22. const TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  23. var _flatCamera = new THREE.OrthographicCamera();
  24. var _blurMaterial = getShader();
  25. var { _lodPlanes, _sizeLods, _sigmas } = createPlanes();
  26. var _pingPongRenderTarget = null;
  27. // Golden Ratio
  28. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  29. const INV_PHI = 1 / PHI;
  30. // Vertices of a dodecahedron (except the opposites, which represent the
  31. // same axis), used as axis directions evenly spread on a sphere.
  32. var _axisDirections = [
  33. new THREE.Vector3( 1, 1, 1 ),
  34. new THREE.Vector3( - 1, 1, 1 ),
  35. new THREE.Vector3( 1, 1, - 1 ),
  36. new THREE.Vector3( - 1, 1, - 1 ),
  37. new THREE.Vector3( 0, PHI, - INV_PHI ),
  38. new THREE.Vector3( INV_PHI, 0, PHI ),
  39. new THREE.Vector3( - INV_PHI, 0, PHI ),
  40. new THREE.Vector3( PHI, INV_PHI, 0 ),
  41. new THREE.Vector3( - PHI, INV_PHI, 0 ) ];
  42. var PMREMGenerator = function ( renderer ) {
  43. this.renderer = renderer;
  44. };
  45. PMREMGenerator.prototype = {
  46. constructor: PMREMGenerator,
  47. /**
  48. * Generates a PMREM from a supplied Scene, which can be faster than using an
  49. * image if networking bandwidth is low. Optional near and far planes ensure
  50. * the scene is rendered in its entirety (the cubeCamera is placed at the
  51. * origin).
  52. */
  53. fromScene: function ( scene, near = 0.1, far = 100 ) {
  54. const dpr = this.renderer.getPixelRatio();
  55. this.renderer.setPixelRatio( 1 );
  56. const cubeUVRenderTarget = allocateTargets();
  57. sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  58. applyPMREM( cubeUVRenderTarget );
  59. _pingPongRenderTarget.dispose();
  60. this.renderer.setPixelRatio( dpr );
  61. return cubeUVRenderTarget;
  62. },
  63. /**
  64. * Generates a PMREM from an equirectangular texture, which can be either LDR
  65. * (RGBFormat) or HDR (RGBEFormat).
  66. */
  67. fromEquirectangular: function ( equirectangular ) {
  68. const dpr = this.renderer.getPixelRatio();
  69. this.renderer.setPixelRatio( 1 );
  70. equirectangular.magFilter = THREE.NearestFilter;
  71. equirectangular.minFilter = THREE.NearestFilter;
  72. equirectangular.generateMipmaps = false;
  73. const cubeUVRenderTarget = allocateTargets( equirectangular );
  74. equirectangularToCubeUV( equirectangular, cubeUVRenderTarget );
  75. applyPMREM( cubeUVRenderTarget );
  76. _pingPongRenderTarget.dispose();
  77. this.renderer.setPixelRatio( dpr );
  78. return cubeUVRenderTarget;
  79. },
  80. };
  81. function createPlanes() {
  82. var _lodPlanes = [];
  83. var _sizeLods = [];
  84. var _sigmas = [];
  85. let lod = LOD_MAX;
  86. for ( let i = 0; i < TOTAL_LODS; i ++ ) {
  87. const sizeLod = Math.pow( 2, lod );
  88. _sizeLods.push( sizeLod );
  89. let sigma = 1.0 / sizeLod;
  90. if ( i > LOD_MAX - LOD_MIN ) {
  91. sigma = EXTRA_LOD_SIGMA[ i - LOD_MAX + LOD_MIN - 1 ];
  92. } else if ( i == 0 ) {
  93. sigma = 0;
  94. }
  95. _sigmas.push( sigma );
  96. const texelSize = 1.0 / ( sizeLod - 1 );
  97. const min = - texelSize / 2;
  98. const max = 1 + texelSize / 2;
  99. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  100. const cubeFaces = 6;
  101. const vertices = 6;
  102. const positionSize = 3;
  103. const uvSize = 2;
  104. const faceIndexSize = 1;
  105. const position = new Float32Array( positionSize * vertices * cubeFaces );
  106. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  107. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  108. for ( let face = 0; face < cubeFaces; face ++ ) {
  109. const x = ( face % 3 ) * 2 / 3 - 1;
  110. const y = face > 2 ? 0 : - 1;
  111. const coordinates = [
  112. [ x, y, 0 ],
  113. [ x + 2 / 3, y, 0 ],
  114. [ x + 2 / 3, y + 1, 0 ],
  115. [ x, y, 0 ],
  116. [ x + 2 / 3, y + 1, 0 ],
  117. [ x, y + 1, 0 ]
  118. ];
  119. position.set( Array.concat( ...coordinates ),
  120. positionSize * vertices * face );
  121. uv.set( uv1, uvSize * vertices * face );
  122. const fill = [ face, face, face, face, face, face ];
  123. faceIndex.set( fill, faceIndexSize * vertices * face );
  124. }
  125. const planes = new THREE.BufferGeometry();
  126. planes.addAttribute(
  127. 'position', new THREE.BufferAttribute( position, positionSize ) );
  128. planes.addAttribute( 'uv', new THREE.BufferAttribute( uv, uvSize ) );
  129. planes.addAttribute(
  130. 'faceIndex', new THREE.BufferAttribute( faceIndex, faceIndexSize ) );
  131. _lodPlanes.push( planes );
  132. if ( lod > LOD_MIN ) {
  133. lod --;
  134. }
  135. }
  136. return { _lodPlanes, _sizeLods, _sigmas };
  137. }
  138. function allocateTargets( equirectangular ) {
  139. const params = {
  140. magFilter: THREE.NearestFilter,
  141. minFilter: THREE.NearestFilter,
  142. generateMipmaps: false,
  143. type: equirectangular ? equirectangular.type : THREE.UnsignedByteType,
  144. format: equirectangular ? equirectangular.format : THREE.RGBEFormat,
  145. encoding: equirectangular ? equirectangular.encoding : THREE.RGBEEncoding,
  146. depthBuffer: false,
  147. stencilBuffer: false
  148. };
  149. const cubeUVRenderTarget = createRenderTarget(
  150. { ...params, depthBuffer: ( equirectangular ? false : true ) } );
  151. _pingPongRenderTarget = createRenderTarget( params );
  152. return cubeUVRenderTarget;
  153. }
  154. function sceneToCubeUV(
  155. scene, near, far,
  156. cubeUVRenderTarget ) {
  157. const fov = 90;
  158. const aspect = 1;
  159. const cubeCamera = new THREE.PerspectiveCamera( fov, aspect, near, far );
  160. const upSign = [ 1, 1, 1, 1, - 1, 1 ];
  161. const forwardSign = [ 1, 1, - 1, - 1, - 1, 1 ];
  162. const gammaOutput = this.renderer.gammaOutput;
  163. const toneMapping = this.renderer.toneMapping;
  164. const toneMappingExposure = this.renderer.toneMappingExposure;
  165. this.renderer.toneMapping = THREE.LinearToneMapping;
  166. this.renderer.toneMappingExposure = 1.0;
  167. this.renderer.gammaOutput = false;
  168. scene.scale.z *= - 1;
  169. this.renderer.setRenderTarget( cubeUVRenderTarget );
  170. for ( let i = 0; i < 6; i ++ ) {
  171. const col = i % 3;
  172. if ( col == 0 ) {
  173. cubeCamera.up.set( 0, upSign[ i ], 0 );
  174. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  175. } else if ( col == 1 ) {
  176. cubeCamera.up.set( 0, 0, upSign[ i ] );
  177. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  178. } else {
  179. cubeCamera.up.set( 0, upSign[ i ], 0 );
  180. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  181. }
  182. this.renderer.setViewport(
  183. col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX );
  184. this.renderer.render( scene, cubeCamera );
  185. }
  186. this.renderer.toneMapping = toneMapping;
  187. this.renderer.toneMappingExposure = toneMappingExposure;
  188. this.renderer.gammaOutput = gammaOutput;
  189. scene.scale.z *= - 1;
  190. }
  191. function equirectangularToCubeUV(
  192. equirectangular, cubeUVRenderTarget ) {
  193. const scene = new THREE.Scene();
  194. scene.add( new THREE.Mesh( _lodPlanes[ 0 ], _blurMaterial ) );
  195. const uniforms = _blurMaterial.uniforms;
  196. uniforms[ 'envMap' ].value = equirectangular;
  197. uniforms[ 'copyEquirectangular' ].value = true;
  198. uniforms[ 'texelSize' ].value.set(
  199. 1.0 / equirectangular.image.width, 1.0 / equirectangular.image.height );
  200. uniforms[ 'inputEncoding' ].value = encodings[ equirectangular.encoding ];
  201. uniforms[ 'outputEncoding' ].value = encodings[ equirectangular.encoding ];
  202. this.renderer.setRenderTarget( cubeUVRenderTarget );
  203. this.renderer.setViewport( 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX );
  204. this.renderer.render( scene, _flatCamera );
  205. }
  206. function createRenderTarget( params ) {
  207. const cubeUVRenderTarget =
  208. new THREE.WebGLRenderTarget( 3 * SIZE_MAX, 3 * SIZE_MAX, params );
  209. cubeUVRenderTarget.texture.mapping = THREE.CubeUVReflectionMapping;
  210. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  211. return cubeUVRenderTarget;
  212. }
  213. function applyPMREM( cubeUVRenderTarget ) {
  214. for ( let i = 1; i < TOTAL_LODS; i ++ ) {
  215. const sigma = Math.sqrt(
  216. _sigmas[ i ] * _sigmas[ i ] -
  217. _sigmas[ i - 1 ] * _sigmas[ i - 1 ] );
  218. const poleAxis =
  219. _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  220. blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  221. }
  222. }
  223. /**
  224. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  225. * vertically and horizontally, but this breaks down on a cube. Here we apply
  226. * the blur latitudinally (around the poles), and then longitudinally (towards
  227. * the poles) to approximate the orthogonally-separable blur. It is least
  228. * accurate at the poles, but still does a decent job.
  229. */
  230. function blur(
  231. cubeUVRenderTarget, lodIn, lodOut,
  232. sigma, poleAxis ) {
  233. halfBlur(
  234. cubeUVRenderTarget,
  235. _pingPongRenderTarget,
  236. lodIn,
  237. lodOut,
  238. sigma,
  239. 'latitudinal',
  240. poleAxis );
  241. halfBlur(
  242. _pingPongRenderTarget,
  243. cubeUVRenderTarget,
  244. lodOut,
  245. lodOut,
  246. sigma,
  247. 'longitudinal',
  248. poleAxis );
  249. }
  250. function halfBlur(
  251. targetIn, targetOut, lodIn,
  252. lodOut, sigmaRadians, direction,
  253. poleAxis ) {
  254. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  255. console.error(
  256. 'blur direction must be either latitudinal or longitudinal!' );
  257. }
  258. // The maximum length of the blur for loop, chosen to equal the number needed
  259. // for GENERATED_SIGMA. Smaller _sigmas will use fewer samples and exit early,
  260. // but not recompile the shader.
  261. const MAX_SAMPLES = 20;
  262. // Number of standard deviations at which to cut off the discrete approximation.
  263. const STANDARD_DEVIATIONS = 3;
  264. const blurScene = new THREE.Scene();
  265. blurScene.add( new THREE.Mesh( _lodPlanes[ lodOut ], _blurMaterial ) );
  266. const blurUniforms = _blurMaterial.uniforms;
  267. const pixels = _sizeLods[ lodIn ] - 1;
  268. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  269. const sigmaPixels = sigmaRadians / radiansPerPixel;
  270. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  271. if ( samples > MAX_SAMPLES ) {
  272. console.warn( `sigmaRadians, ${
  273. sigmaRadians}, is too large and will clip, as it requested ${
  274. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  275. }
  276. let weights = [];
  277. let sum = 0;
  278. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  279. const x = i / sigmaPixels;
  280. const weight = Math.exp( - x * x / 2 );
  281. weights.push( weight );
  282. if ( i == 0 ) {
  283. sum += weight;
  284. } else if ( i < samples ) {
  285. sum += 2 * weight;
  286. }
  287. }
  288. weights = weights.map( w => w / sum );
  289. blurUniforms[ 'envMap' ].value = targetIn.texture;
  290. blurUniforms[ 'copyEquirectangular' ].value = false;
  291. blurUniforms[ 'samples' ].value = samples;
  292. blurUniforms[ 'weights' ].value = weights;
  293. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  294. if ( poleAxis ) {
  295. blurUniforms[ 'poleAxis' ].value = poleAxis;
  296. }
  297. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  298. blurUniforms[ 'mipInt' ].value = LOD_MAX - lodIn;
  299. blurUniforms[ 'inputEncoding' ].value = encodings[ targetIn.texture.encoding ];
  300. blurUniforms[ 'outputEncoding' ].value = encodings[ targetIn.texture.encoding ];
  301. const outputSize = _sizeLods[ lodOut ];
  302. const x = 3 * Math.max( 0, SIZE_MAX - 2 * outputSize );
  303. const y = ( lodOut === 0 ? 0 : 2 * SIZE_MAX ) +
  304. 2 * outputSize *
  305. ( lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0 );
  306. this.renderer.autoClear = false;
  307. this.renderer.setRenderTarget( targetOut );
  308. this.renderer.setViewport( x, y, 3 * outputSize, 2 * outputSize );
  309. this.renderer.render( blurScene, _flatCamera );
  310. }
  311. function getShader( maxSamples ) {
  312. const weights = new Float32Array( maxSamples );
  313. const texelSize = new THREE.Vector2( 1, 1 );
  314. const poleAxis = new THREE.Vector3( 0, 1, 0 );
  315. var shaderMaterial = new THREE.RawShaderMaterial( {
  316. defines: { 'n': maxSamples },
  317. uniforms: {
  318. 'envMap': { value: null },
  319. 'copyEquirectangular': { value: false },
  320. 'texelSize': { value: texelSize },
  321. 'samples': { value: 1 },
  322. 'weights': { value: weights },
  323. 'latitudinal': { value: false },
  324. 'dTheta': { value: 0 },
  325. 'mipInt': { value: 0 },
  326. 'poleAxis': { value: poleAxis },
  327. 'inputEncoding': { value: encodings[ THREE.LinearEncoding ] },
  328. 'outputEncoding': { value: encodings[ THREE.LinearEncoding ] }
  329. },
  330. vertexShader: `
  331. precision mediump float;
  332. precision mediump int;
  333. attribute vec3 position;
  334. attribute vec2 uv;
  335. attribute float faceIndex;
  336. varying vec3 vOutputDirection;
  337. ${getDirectionChunk}
  338. void main() {
  339. vOutputDirection = getDirection(uv, faceIndex);
  340. gl_Position = vec4( position, 1.0 );
  341. }
  342. `,
  343. fragmentShader: `
  344. precision mediump float;
  345. precision mediump int;
  346. varying vec3 vOutputDirection;
  347. uniform sampler2D envMap;
  348. uniform bool copyEquirectangular;
  349. uniform vec2 texelSize;
  350. uniform int samples;
  351. uniform float weights[n];
  352. uniform bool latitudinal;
  353. uniform float dTheta;
  354. uniform float mipInt;
  355. uniform vec3 poleAxis;
  356. #define RECIPROCAL_PI 0.31830988618
  357. #define RECIPROCAL_PI2 0.15915494
  358. ${texelIO}
  359. vec4 envMapTexelToLinear(vec4 color) {
  360. return inputTexelToLinear(color);
  361. }
  362. ${bilinearCubeUVChunk}
  363. void main() {
  364. gl_FragColor = vec4(0.0);
  365. if (copyEquirectangular) {
  366. vec3 direction = normalize(vOutputDirection);
  367. vec2 uv;
  368. uv.y = asin(clamp(direction.y, -1.0, 1.0)) * RECIPROCAL_PI + 0.5;
  369. uv.x = atan(direction.z, direction.x) * RECIPROCAL_PI2 + 0.5;
  370. vec2 f = fract(uv / texelSize - 0.5);
  371. uv -= f * texelSize;
  372. vec3 tl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
  373. uv.x += texelSize.x;
  374. vec3 tr = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
  375. uv.y += texelSize.y;
  376. vec3 br = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
  377. uv.x -= texelSize.x;
  378. vec3 bl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
  379. vec3 tm = mix(tl, tr, f.x);
  380. vec3 bm = mix(bl, br, f.x);
  381. gl_FragColor.rgb = mix(tm, bm, f.y);
  382. } else {
  383. for (int i = 0; i < n; i++) {
  384. if (i >= samples)
  385. break;
  386. for (int dir = -1; dir < 2; dir += 2) {
  387. if (i == 0 && dir == 1)
  388. continue;
  389. vec3 axis = latitudinal ? poleAxis : cross(poleAxis, vOutputDirection);
  390. if (all(equal(axis, vec3(0.0))))
  391. axis = cross(vec3(0.0, 1.0, 0.0), vOutputDirection);
  392. axis = normalize(axis);
  393. float theta = dTheta * float(dir * i);
  394. float cosTheta = cos(theta);
  395. // Rodrigues' axis-angle rotation
  396. vec3 sampleDirection = vOutputDirection * cosTheta
  397. + cross(axis, vOutputDirection) * sin(theta)
  398. + axis * dot(axis, vOutputDirection) * (1.0 - cosTheta);
  399. gl_FragColor.rgb +=
  400. weights[i] * bilinearCubeUV(envMap, sampleDirection, mipInt);
  401. }
  402. }
  403. }
  404. gl_FragColor = linearToOutputTexel(gl_FragColor);
  405. }
  406. `,
  407. blending: THREE.NoBlending,
  408. depthTest: false,
  409. depthWrite: false
  410. } );
  411. shaderMaterial.type = 'SphericalGaussianBlur';
  412. return shaderMaterial;
  413. }
  414. return PMREMGenerator;
  415. } )();
粤ICP备19079148号