UnrealBloomPass.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. import {
  2. AdditiveBlending,
  3. Color,
  4. HalfFloatType,
  5. MeshBasicMaterial,
  6. ShaderMaterial,
  7. UniformsUtils,
  8. Vector2,
  9. Vector3,
  10. WebGLRenderTarget
  11. } from 'three';
  12. import { Pass, FullScreenQuad } from './Pass.js';
  13. import { CopyShader } from '../shaders/CopyShader.js';
  14. import { LuminosityHighPassShader } from '../shaders/LuminosityHighPassShader.js';
  15. /**
  16. * This pass is inspired by the bloom pass of Unreal Engine. It creates a
  17. * mip map chain of bloom textures and blurs them with different radii. Because
  18. * of the weighted combination of mips, and because larger blurs are done on
  19. * higher mips, this effect provides good quality and performance.
  20. *
  21. * When using this pass, tone mapping must be enabled in the renderer settings.
  22. *
  23. * Reference:
  24. * - [Bloom in Unreal Engine](https://docs.unrealengine.com/latest/INT/Engine/Rendering/PostProcessEffects/Bloom/)
  25. *
  26. * ```js
  27. * const resolution = new THREE.Vector2( window.innerWidth, window.innerHeight );
  28. * const bloomPass = new UnrealBloomPass( resolution, 1.5, 0.4, 0.85 );
  29. * composer.addPass( bloomPass );
  30. * ```
  31. *
  32. * @augments Pass
  33. * @three_import import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
  34. */
  35. class UnrealBloomPass extends Pass {
  36. /**
  37. * Constructs a new Unreal Bloom pass.
  38. *
  39. * @param {Vector2} [resolution] - The effect's resolution.
  40. * @param {number} [strength=1] - The Bloom strength.
  41. * @param {number} radius - The Bloom radius.
  42. * @param {number} threshold - The luminance threshold limits which bright areas contribute to the Bloom effect.
  43. */
  44. constructor( resolution, strength = 1, radius, threshold ) {
  45. super();
  46. /**
  47. * The Bloom strength.
  48. *
  49. * @type {number}
  50. * @default 1
  51. */
  52. this.strength = strength;
  53. /**
  54. * The Bloom radius. Must be in the range `[0,1]`.
  55. *
  56. * @type {number}
  57. */
  58. this.radius = radius;
  59. /**
  60. * The luminance threshold limits which bright areas contribute to the Bloom effect.
  61. *
  62. * @type {number}
  63. */
  64. this.threshold = threshold;
  65. /**
  66. * The effect's resolution.
  67. *
  68. * @type {Vector2}
  69. * @default (256,256)
  70. */
  71. this.resolution = ( resolution !== undefined ) ? new Vector2( resolution.x, resolution.y ) : new Vector2( 256, 256 );
  72. /**
  73. * The effect's clear color
  74. *
  75. * @type {Color}
  76. * @default (0,0,0)
  77. */
  78. this.clearColor = new Color( 0, 0, 0 );
  79. /**
  80. * Overwritten to disable the swap.
  81. *
  82. * @type {boolean}
  83. * @default false
  84. */
  85. this.needsSwap = false;
  86. // internals
  87. // render targets
  88. this.renderTargetsHorizontal = [];
  89. this.renderTargetsVertical = [];
  90. this.nMips = 5;
  91. let resx = Math.round( this.resolution.x / 2 );
  92. let resy = Math.round( this.resolution.y / 2 );
  93. this.renderTargetBright = new WebGLRenderTarget( resx, resy, { type: HalfFloatType } );
  94. this.renderTargetBright.texture.name = 'UnrealBloomPass.bright';
  95. this.renderTargetBright.texture.generateMipmaps = false;
  96. for ( let i = 0; i < this.nMips; i ++ ) {
  97. const renderTargetHorizontal = new WebGLRenderTarget( resx, resy, { type: HalfFloatType } );
  98. renderTargetHorizontal.texture.name = 'UnrealBloomPass.h' + i;
  99. renderTargetHorizontal.texture.generateMipmaps = false;
  100. this.renderTargetsHorizontal.push( renderTargetHorizontal );
  101. const renderTargetVertical = new WebGLRenderTarget( resx, resy, { type: HalfFloatType } );
  102. renderTargetVertical.texture.name = 'UnrealBloomPass.v' + i;
  103. renderTargetVertical.texture.generateMipmaps = false;
  104. this.renderTargetsVertical.push( renderTargetVertical );
  105. resx = Math.round( resx / 2 );
  106. resy = Math.round( resy / 2 );
  107. }
  108. // luminosity high pass material
  109. const highPassShader = LuminosityHighPassShader;
  110. this.highPassUniforms = UniformsUtils.clone( highPassShader.uniforms );
  111. this.highPassUniforms[ 'luminosityThreshold' ].value = threshold;
  112. this.highPassUniforms[ 'smoothWidth' ].value = 0.01;
  113. this.materialHighPassFilter = new ShaderMaterial( {
  114. uniforms: this.highPassUniforms,
  115. vertexShader: highPassShader.vertexShader,
  116. fragmentShader: highPassShader.fragmentShader
  117. } );
  118. // gaussian blur materials
  119. this.separableBlurMaterials = [];
  120. // These sizes have been changed to account for the altered coefficients-calculation to avoid blockiness,
  121. // while retaining the same blur-strength. For details see https://github.com/mrdoob/three.js/pull/31528
  122. const kernelSizeArray = [ 6, 10, 14, 18, 22 ];
  123. resx = Math.round( this.resolution.x / 2 );
  124. resy = Math.round( this.resolution.y / 2 );
  125. for ( let i = 0; i < this.nMips; i ++ ) {
  126. this.separableBlurMaterials.push( this._getSeparableBlurMaterial( kernelSizeArray[ i ] ) );
  127. this.separableBlurMaterials[ i ].uniforms[ 'invSize' ].value = new Vector2( 1 / resx, 1 / resy );
  128. resx = Math.round( resx / 2 );
  129. resy = Math.round( resy / 2 );
  130. }
  131. // composite material
  132. this.compositeMaterial = this._getCompositeMaterial( this.nMips );
  133. this.compositeMaterial.uniforms[ 'blurTexture1' ].value = this.renderTargetsVertical[ 0 ].texture;
  134. this.compositeMaterial.uniforms[ 'blurTexture2' ].value = this.renderTargetsVertical[ 1 ].texture;
  135. this.compositeMaterial.uniforms[ 'blurTexture3' ].value = this.renderTargetsVertical[ 2 ].texture;
  136. this.compositeMaterial.uniforms[ 'blurTexture4' ].value = this.renderTargetsVertical[ 3 ].texture;
  137. this.compositeMaterial.uniforms[ 'blurTexture5' ].value = this.renderTargetsVertical[ 4 ].texture;
  138. this.compositeMaterial.uniforms[ 'bloomStrength' ].value = strength;
  139. this.compositeMaterial.uniforms[ 'bloomRadius' ].value = 0.1;
  140. const bloomFactors = [ 1.0, 0.8, 0.6, 0.4, 0.2 ];
  141. this.compositeMaterial.uniforms[ 'bloomFactors' ].value = bloomFactors;
  142. this.bloomTintColors = [ new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ) ];
  143. this.compositeMaterial.uniforms[ 'bloomTintColors' ].value = this.bloomTintColors;
  144. // blend material
  145. this.copyUniforms = UniformsUtils.clone( CopyShader.uniforms );
  146. this.blendMaterial = new ShaderMaterial( {
  147. uniforms: this.copyUniforms,
  148. vertexShader: CopyShader.vertexShader,
  149. fragmentShader: CopyShader.fragmentShader,
  150. blending: AdditiveBlending,
  151. depthTest: false,
  152. depthWrite: false,
  153. transparent: true
  154. } );
  155. this._oldClearColor = new Color();
  156. this._oldClearAlpha = 1;
  157. this._basic = new MeshBasicMaterial();
  158. this._fsQuad = new FullScreenQuad( null );
  159. }
  160. /**
  161. * Frees the GPU-related resources allocated by this instance. Call this
  162. * method whenever the pass is no longer used in your app.
  163. */
  164. dispose() {
  165. for ( let i = 0; i < this.renderTargetsHorizontal.length; i ++ ) {
  166. this.renderTargetsHorizontal[ i ].dispose();
  167. }
  168. for ( let i = 0; i < this.renderTargetsVertical.length; i ++ ) {
  169. this.renderTargetsVertical[ i ].dispose();
  170. }
  171. this.renderTargetBright.dispose();
  172. //
  173. for ( let i = 0; i < this.separableBlurMaterials.length; i ++ ) {
  174. this.separableBlurMaterials[ i ].dispose();
  175. }
  176. this.compositeMaterial.dispose();
  177. this.blendMaterial.dispose();
  178. this._basic.dispose();
  179. //
  180. this._fsQuad.dispose();
  181. }
  182. /**
  183. * Sets the size of the pass.
  184. *
  185. * @param {number} width - The width to set.
  186. * @param {number} height - The height to set.
  187. */
  188. setSize( width, height ) {
  189. let resx = Math.round( width / 2 );
  190. let resy = Math.round( height / 2 );
  191. this.renderTargetBright.setSize( resx, resy );
  192. for ( let i = 0; i < this.nMips; i ++ ) {
  193. this.renderTargetsHorizontal[ i ].setSize( resx, resy );
  194. this.renderTargetsVertical[ i ].setSize( resx, resy );
  195. this.separableBlurMaterials[ i ].uniforms[ 'invSize' ].value = new Vector2( 1 / resx, 1 / resy );
  196. resx = Math.round( resx / 2 );
  197. resy = Math.round( resy / 2 );
  198. }
  199. }
  200. /**
  201. * Performs the Bloom pass.
  202. *
  203. * @param {WebGLRenderer} renderer - The renderer.
  204. * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
  205. * destination for the pass.
  206. * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
  207. * previous pass from this buffer.
  208. * @param {number} deltaTime - The delta time in seconds.
  209. * @param {boolean} maskActive - Whether masking is active or not.
  210. */
  211. render( renderer, writeBuffer, readBuffer, deltaTime, maskActive ) {
  212. renderer.getClearColor( this._oldClearColor );
  213. this._oldClearAlpha = renderer.getClearAlpha();
  214. const oldAutoClear = renderer.autoClear;
  215. renderer.autoClear = false;
  216. renderer.setClearColor( this.clearColor, 0 );
  217. if ( maskActive ) renderer.state.buffers.stencil.setTest( false );
  218. // Render input to screen
  219. if ( this.renderToScreen ) {
  220. this._fsQuad.material = this._basic;
  221. this._basic.map = readBuffer.texture;
  222. renderer.setRenderTarget( null );
  223. renderer.clear();
  224. this._fsQuad.render( renderer );
  225. }
  226. // 1. Extract Bright Areas
  227. this.highPassUniforms[ 'tDiffuse' ].value = readBuffer.texture;
  228. this.highPassUniforms[ 'luminosityThreshold' ].value = this.threshold;
  229. this._fsQuad.material = this.materialHighPassFilter;
  230. renderer.setRenderTarget( this.renderTargetBright );
  231. renderer.clear();
  232. this._fsQuad.render( renderer );
  233. // 2. Blur All the mips progressively
  234. let inputRenderTarget = this.renderTargetBright;
  235. for ( let i = 0; i < this.nMips; i ++ ) {
  236. this._fsQuad.material = this.separableBlurMaterials[ i ];
  237. this.separableBlurMaterials[ i ].uniforms[ 'colorTexture' ].value = inputRenderTarget.texture;
  238. this.separableBlurMaterials[ i ].uniforms[ 'direction' ].value = UnrealBloomPass.BlurDirectionX;
  239. renderer.setRenderTarget( this.renderTargetsHorizontal[ i ] );
  240. renderer.clear();
  241. this._fsQuad.render( renderer );
  242. this.separableBlurMaterials[ i ].uniforms[ 'colorTexture' ].value = this.renderTargetsHorizontal[ i ].texture;
  243. this.separableBlurMaterials[ i ].uniforms[ 'direction' ].value = UnrealBloomPass.BlurDirectionY;
  244. renderer.setRenderTarget( this.renderTargetsVertical[ i ] );
  245. renderer.clear();
  246. this._fsQuad.render( renderer );
  247. inputRenderTarget = this.renderTargetsVertical[ i ];
  248. }
  249. // Composite All the mips
  250. this._fsQuad.material = this.compositeMaterial;
  251. this.compositeMaterial.uniforms[ 'bloomStrength' ].value = this.strength;
  252. this.compositeMaterial.uniforms[ 'bloomRadius' ].value = this.radius;
  253. this.compositeMaterial.uniforms[ 'bloomTintColors' ].value = this.bloomTintColors;
  254. renderer.setRenderTarget( this.renderTargetsHorizontal[ 0 ] );
  255. renderer.clear();
  256. this._fsQuad.render( renderer );
  257. // Blend it additively over the input texture
  258. this._fsQuad.material = this.blendMaterial;
  259. this.copyUniforms[ 'tDiffuse' ].value = this.renderTargetsHorizontal[ 0 ].texture;
  260. if ( maskActive ) renderer.state.buffers.stencil.setTest( true );
  261. if ( this.renderToScreen ) {
  262. renderer.setRenderTarget( null );
  263. this._fsQuad.render( renderer );
  264. } else {
  265. renderer.setRenderTarget( readBuffer );
  266. this._fsQuad.render( renderer );
  267. }
  268. // Restore renderer settings
  269. renderer.setClearColor( this._oldClearColor, this._oldClearAlpha );
  270. renderer.autoClear = oldAutoClear;
  271. }
  272. // internals
  273. _getSeparableBlurMaterial( kernelRadius ) {
  274. const coefficients = [];
  275. const sigma = kernelRadius / 3;
  276. for ( let i = 0; i < kernelRadius; i ++ ) {
  277. coefficients.push( 0.39894 * Math.exp( - 0.5 * i * i / ( sigma * sigma ) ) / sigma );
  278. }
  279. return new ShaderMaterial( {
  280. defines: {
  281. 'KERNEL_RADIUS': kernelRadius
  282. },
  283. uniforms: {
  284. 'colorTexture': { value: null },
  285. 'invSize': { value: new Vector2( 0.5, 0.5 ) }, // inverse texture size
  286. 'direction': { value: new Vector2( 0.5, 0.5 ) },
  287. 'gaussianCoefficients': { value: coefficients } // precomputed Gaussian coefficients
  288. },
  289. vertexShader:
  290. `varying vec2 vUv;
  291. void main() {
  292. vUv = uv;
  293. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  294. }`,
  295. fragmentShader:
  296. `#include <common>
  297. varying vec2 vUv;
  298. uniform sampler2D colorTexture;
  299. uniform vec2 invSize;
  300. uniform vec2 direction;
  301. uniform float gaussianCoefficients[KERNEL_RADIUS];
  302. void main() {
  303. float weightSum = gaussianCoefficients[0];
  304. vec3 diffuseSum = texture2D( colorTexture, vUv ).rgb * weightSum;
  305. for( int i = 1; i < KERNEL_RADIUS; i ++ ) {
  306. float x = float(i);
  307. float w = gaussianCoefficients[i];
  308. vec2 uvOffset = direction * invSize * x;
  309. vec3 sample1 = texture2D( colorTexture, vUv + uvOffset ).rgb;
  310. vec3 sample2 = texture2D( colorTexture, vUv - uvOffset ).rgb;
  311. diffuseSum += ( sample1 + sample2 ) * w;
  312. }
  313. gl_FragColor = vec4( diffuseSum, 1.0 );
  314. }`
  315. } );
  316. }
  317. _getCompositeMaterial( nMips ) {
  318. return new ShaderMaterial( {
  319. defines: {
  320. 'NUM_MIPS': nMips
  321. },
  322. uniforms: {
  323. 'blurTexture1': { value: null },
  324. 'blurTexture2': { value: null },
  325. 'blurTexture3': { value: null },
  326. 'blurTexture4': { value: null },
  327. 'blurTexture5': { value: null },
  328. 'bloomStrength': { value: 1.0 },
  329. 'bloomFactors': { value: null },
  330. 'bloomTintColors': { value: null },
  331. 'bloomRadius': { value: 0.0 }
  332. },
  333. vertexShader:
  334. `varying vec2 vUv;
  335. void main() {
  336. vUv = uv;
  337. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  338. }`,
  339. fragmentShader:
  340. `varying vec2 vUv;
  341. uniform sampler2D blurTexture1;
  342. uniform sampler2D blurTexture2;
  343. uniform sampler2D blurTexture3;
  344. uniform sampler2D blurTexture4;
  345. uniform sampler2D blurTexture5;
  346. uniform float bloomStrength;
  347. uniform float bloomRadius;
  348. uniform float bloomFactors[NUM_MIPS];
  349. uniform vec3 bloomTintColors[NUM_MIPS];
  350. float lerpBloomFactor(const in float factor) {
  351. float mirrorFactor = 1.2 - factor;
  352. return mix(factor, mirrorFactor, bloomRadius);
  353. }
  354. void main() {
  355. gl_FragColor = bloomStrength * ( lerpBloomFactor(bloomFactors[0]) * vec4(bloomTintColors[0], 1.0) * texture2D(blurTexture1, vUv) +
  356. lerpBloomFactor(bloomFactors[1]) * vec4(bloomTintColors[1], 1.0) * texture2D(blurTexture2, vUv) +
  357. lerpBloomFactor(bloomFactors[2]) * vec4(bloomTintColors[2], 1.0) * texture2D(blurTexture3, vUv) +
  358. lerpBloomFactor(bloomFactors[3]) * vec4(bloomTintColors[3], 1.0) * texture2D(blurTexture4, vUv) +
  359. lerpBloomFactor(bloomFactors[4]) * vec4(bloomTintColors[4], 1.0) * texture2D(blurTexture5, vUv) );
  360. }`
  361. } );
  362. }
  363. }
  364. UnrealBloomPass.BlurDirectionX = new Vector2( 1.0, 0.0 );
  365. UnrealBloomPass.BlurDirectionY = new Vector2( 0.0, 1.0 );
  366. export { UnrealBloomPass };
粤ICP备19079148号