UnrealBloomPass.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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. premultipliedAlpha: true,
  151. blending: AdditiveBlending,
  152. depthTest: false,
  153. depthWrite: false,
  154. transparent: true
  155. } );
  156. this._oldClearColor = new Color();
  157. this._oldClearAlpha = 1;
  158. this._basic = new MeshBasicMaterial();
  159. this._fsQuad = new FullScreenQuad( null );
  160. }
  161. /**
  162. * Frees the GPU-related resources allocated by this instance. Call this
  163. * method whenever the pass is no longer used in your app.
  164. */
  165. dispose() {
  166. for ( let i = 0; i < this.renderTargetsHorizontal.length; i ++ ) {
  167. this.renderTargetsHorizontal[ i ].dispose();
  168. }
  169. for ( let i = 0; i < this.renderTargetsVertical.length; i ++ ) {
  170. this.renderTargetsVertical[ i ].dispose();
  171. }
  172. this.renderTargetBright.dispose();
  173. //
  174. for ( let i = 0; i < this.separableBlurMaterials.length; i ++ ) {
  175. this.separableBlurMaterials[ i ].dispose();
  176. }
  177. this.compositeMaterial.dispose();
  178. this.blendMaterial.dispose();
  179. this._basic.dispose();
  180. //
  181. this._fsQuad.dispose();
  182. }
  183. /**
  184. * Sets the size of the pass.
  185. *
  186. * @param {number} width - The width to set.
  187. * @param {number} height - The height to set.
  188. */
  189. setSize( width, height ) {
  190. let resx = Math.round( width / 2 );
  191. let resy = Math.round( height / 2 );
  192. this.renderTargetBright.setSize( resx, resy );
  193. for ( let i = 0; i < this.nMips; i ++ ) {
  194. this.renderTargetsHorizontal[ i ].setSize( resx, resy );
  195. this.renderTargetsVertical[ i ].setSize( resx, resy );
  196. this.separableBlurMaterials[ i ].uniforms[ 'invSize' ].value = new Vector2( 1 / resx, 1 / resy );
  197. resx = Math.round( resx / 2 );
  198. resy = Math.round( resy / 2 );
  199. }
  200. }
  201. /**
  202. * Performs the Bloom pass.
  203. *
  204. * @param {WebGLRenderer} renderer - The renderer.
  205. * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
  206. * destination for the pass.
  207. * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
  208. * previous pass from this buffer.
  209. * @param {number} deltaTime - The delta time in seconds.
  210. * @param {boolean} maskActive - Whether masking is active or not.
  211. */
  212. render( renderer, writeBuffer, readBuffer, deltaTime, maskActive ) {
  213. renderer.getClearColor( this._oldClearColor );
  214. this._oldClearAlpha = renderer.getClearAlpha();
  215. const oldAutoClear = renderer.autoClear;
  216. renderer.autoClear = false;
  217. renderer.setClearColor( this.clearColor, 0 );
  218. if ( maskActive ) renderer.state.buffers.stencil.setTest( false );
  219. // Render input to screen
  220. if ( this.renderToScreen ) {
  221. this._fsQuad.material = this._basic;
  222. this._basic.map = readBuffer.texture;
  223. renderer.setRenderTarget( null );
  224. renderer.clear();
  225. this._fsQuad.render( renderer );
  226. }
  227. // 1. Extract Bright Areas
  228. this.highPassUniforms[ 'tDiffuse' ].value = readBuffer.texture;
  229. this.highPassUniforms[ 'luminosityThreshold' ].value = this.threshold;
  230. this._fsQuad.material = this.materialHighPassFilter;
  231. renderer.setRenderTarget( this.renderTargetBright );
  232. renderer.clear();
  233. this._fsQuad.render( renderer );
  234. // 2. Blur All the mips progressively
  235. let inputRenderTarget = this.renderTargetBright;
  236. for ( let i = 0; i < this.nMips; i ++ ) {
  237. this._fsQuad.material = this.separableBlurMaterials[ i ];
  238. this.separableBlurMaterials[ i ].uniforms[ 'colorTexture' ].value = inputRenderTarget.texture;
  239. this.separableBlurMaterials[ i ].uniforms[ 'direction' ].value = UnrealBloomPass.BlurDirectionX;
  240. renderer.setRenderTarget( this.renderTargetsHorizontal[ i ] );
  241. renderer.clear();
  242. this._fsQuad.render( renderer );
  243. this.separableBlurMaterials[ i ].uniforms[ 'colorTexture' ].value = this.renderTargetsHorizontal[ i ].texture;
  244. this.separableBlurMaterials[ i ].uniforms[ 'direction' ].value = UnrealBloomPass.BlurDirectionY;
  245. renderer.setRenderTarget( this.renderTargetsVertical[ i ] );
  246. renderer.clear();
  247. this._fsQuad.render( renderer );
  248. inputRenderTarget = this.renderTargetsVertical[ i ];
  249. }
  250. // Composite All the mips
  251. this._fsQuad.material = this.compositeMaterial;
  252. this.compositeMaterial.uniforms[ 'bloomStrength' ].value = this.strength;
  253. this.compositeMaterial.uniforms[ 'bloomRadius' ].value = this.radius;
  254. this.compositeMaterial.uniforms[ 'bloomTintColors' ].value = this.bloomTintColors;
  255. renderer.setRenderTarget( this.renderTargetsHorizontal[ 0 ] );
  256. renderer.clear();
  257. this._fsQuad.render( renderer );
  258. // Blend it additively over the input texture
  259. this._fsQuad.material = this.blendMaterial;
  260. this.copyUniforms[ 'tDiffuse' ].value = this.renderTargetsHorizontal[ 0 ].texture;
  261. if ( maskActive ) renderer.state.buffers.stencil.setTest( true );
  262. if ( this.renderToScreen ) {
  263. renderer.setRenderTarget( null );
  264. this._fsQuad.render( renderer );
  265. } else {
  266. renderer.setRenderTarget( readBuffer );
  267. this._fsQuad.render( renderer );
  268. }
  269. // Restore renderer settings
  270. renderer.setClearColor( this._oldClearColor, this._oldClearAlpha );
  271. renderer.autoClear = oldAutoClear;
  272. }
  273. // internals
  274. _getSeparableBlurMaterial( kernelRadius ) {
  275. const coefficients = [];
  276. const sigma = kernelRadius / 3;
  277. for ( let i = 0; i < kernelRadius; i ++ ) {
  278. coefficients.push( 0.39894 * Math.exp( - 0.5 * i * i / ( sigma * sigma ) ) / sigma );
  279. }
  280. return new ShaderMaterial( {
  281. defines: {
  282. 'KERNEL_RADIUS': kernelRadius
  283. },
  284. uniforms: {
  285. 'colorTexture': { value: null },
  286. 'invSize': { value: new Vector2( 0.5, 0.5 ) }, // inverse texture size
  287. 'direction': { value: new Vector2( 0.5, 0.5 ) },
  288. 'gaussianCoefficients': { value: coefficients } // precomputed Gaussian coefficients
  289. },
  290. vertexShader: /* glsl */`
  291. varying vec2 vUv;
  292. void main() {
  293. vUv = uv;
  294. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  295. }`,
  296. fragmentShader: /* glsl */`
  297. #include <common>
  298. varying vec2 vUv;
  299. uniform sampler2D colorTexture;
  300. uniform vec2 invSize;
  301. uniform vec2 direction;
  302. uniform float gaussianCoefficients[KERNEL_RADIUS];
  303. void main() {
  304. float weightSum = gaussianCoefficients[0];
  305. vec3 diffuseSum = texture2D( colorTexture, vUv ).rgb * weightSum;
  306. for ( int i = 1; i < KERNEL_RADIUS; i ++ ) {
  307. float x = float( i );
  308. float w = gaussianCoefficients[i];
  309. vec2 uvOffset = direction * invSize * x;
  310. vec3 sample1 = texture2D( colorTexture, vUv + uvOffset ).rgb;
  311. vec3 sample2 = texture2D( colorTexture, vUv - uvOffset ).rgb;
  312. diffuseSum += ( sample1 + sample2 ) * w;
  313. }
  314. gl_FragColor = vec4( diffuseSum, 1.0 );
  315. }`
  316. } );
  317. }
  318. _getCompositeMaterial( nMips ) {
  319. return new ShaderMaterial( {
  320. defines: {
  321. 'NUM_MIPS': nMips
  322. },
  323. uniforms: {
  324. 'blurTexture1': { value: null },
  325. 'blurTexture2': { value: null },
  326. 'blurTexture3': { value: null },
  327. 'blurTexture4': { value: null },
  328. 'blurTexture5': { value: null },
  329. 'bloomStrength': { value: 1.0 },
  330. 'bloomFactors': { value: null },
  331. 'bloomTintColors': { value: null },
  332. 'bloomRadius': { value: 0.0 }
  333. },
  334. vertexShader: /* glsl */`
  335. varying vec2 vUv;
  336. void main() {
  337. vUv = uv;
  338. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  339. }`,
  340. fragmentShader: /* glsl */`
  341. varying vec2 vUv;
  342. uniform sampler2D blurTexture1;
  343. uniform sampler2D blurTexture2;
  344. uniform sampler2D blurTexture3;
  345. uniform sampler2D blurTexture4;
  346. uniform sampler2D blurTexture5;
  347. uniform float bloomStrength;
  348. uniform float bloomRadius;
  349. uniform float bloomFactors[NUM_MIPS];
  350. uniform vec3 bloomTintColors[NUM_MIPS];
  351. float lerpBloomFactor( const in float factor ) {
  352. float mirrorFactor = 1.2 - factor;
  353. return mix( factor, mirrorFactor, bloomRadius );
  354. }
  355. void main() {
  356. // 3.0 for backwards compatibility with previous alpha-based intensity
  357. vec3 bloom = 3.0 * bloomStrength * (
  358. lerpBloomFactor( bloomFactors[ 0 ] ) * bloomTintColors[ 0 ] * texture2D( blurTexture1, vUv ).rgb +
  359. lerpBloomFactor( bloomFactors[ 1 ] ) * bloomTintColors[ 1 ] * texture2D( blurTexture2, vUv ).rgb +
  360. lerpBloomFactor( bloomFactors[ 2 ] ) * bloomTintColors[ 2 ] * texture2D( blurTexture3, vUv ).rgb +
  361. lerpBloomFactor( bloomFactors[ 3 ] ) * bloomTintColors[ 3 ] * texture2D( blurTexture4, vUv ).rgb +
  362. lerpBloomFactor( bloomFactors[ 4 ] ) * bloomTintColors[ 4 ] * texture2D( blurTexture5, vUv ).rgb
  363. );
  364. float bloomAlpha = max( bloom.r, max( bloom.g, bloom.b ) );
  365. gl_FragColor = vec4( bloom, bloomAlpha );
  366. }`
  367. } );
  368. }
  369. }
  370. UnrealBloomPass.BlurDirectionX = new Vector2( 1.0, 0.0 );
  371. UnrealBloomPass.BlurDirectionY = new Vector2( 0.0, 1.0 );
  372. export { UnrealBloomPass };
粤ICP备19079148号