GaussianBlurNode.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. import { RenderTarget, Vector2, NodeMaterial, RendererUtils, QuadMesh, TempNode, NodeUpdateType } from 'three/webgpu';
  2. import { nodeObject, Fn, If, float, uv, uniform, convertToTexture, vec2, vec4, passTexture, mul } from 'three/tsl';
  3. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  4. let _rendererState;
  5. const premult = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6. return vec4( color.rgb.mul( color.a ), color.a );
  7. } ).setLayout( {
  8. name: 'premult',
  9. type: 'vec4',
  10. inputs: [
  11. { name: 'color', type: 'vec4' }
  12. ]
  13. } );
  14. const unpremult = /*@__PURE__*/ Fn( ( [ color ] ) => {
  15. If( color.a.equal( 0.0 ), () => vec4( 0.0 ) );
  16. return vec4( color.rgb.div( color.a ), color.a );
  17. } ).setLayout( {
  18. name: 'unpremult',
  19. type: 'vec4',
  20. inputs: [
  21. { name: 'color', type: 'vec4' }
  22. ]
  23. } );
  24. /**
  25. * Post processing node for creating a gaussian blur effect.
  26. *
  27. * @augments TempNode
  28. * @three_import import { gaussianBlur, premultipliedGaussianBlur } from 'three/addons/tsl/display/GaussianBlurNode.js';
  29. */
  30. class GaussianBlurNode extends TempNode {
  31. static get type() {
  32. return 'GaussianBlurNode';
  33. }
  34. /**
  35. * Constructs a new gaussian blur node.
  36. *
  37. * @param {TextureNode} textureNode - The texture node that represents the input of the effect.
  38. * @param {Node<vec2|float>} directionNode - Defines the direction and radius of the blur.
  39. * @param {number} sigma - Controls the kernel of the blur filter. Higher values mean a wider blur radius.
  40. */
  41. constructor( textureNode, directionNode = null, sigma = 2 ) {
  42. super( 'vec4' );
  43. /**
  44. * The texture node that represents the input of the effect.
  45. *
  46. * @type {TextureNode}
  47. */
  48. this.textureNode = textureNode;
  49. /**
  50. * Defines the direction and radius of the blur.
  51. *
  52. * @type {Node<vec2|float>}
  53. */
  54. this.directionNode = directionNode;
  55. /**
  56. * Controls the kernel of the blur filter. Higher values mean a wider blur radius.
  57. *
  58. * @type {number}
  59. */
  60. this.sigma = sigma;
  61. /**
  62. * A uniform node holding the inverse resolution value.
  63. *
  64. * @private
  65. * @type {UniformNode<vec2>}
  66. */
  67. this._invSize = uniform( new Vector2() );
  68. /**
  69. * Gaussian blur is applied in two passes (horizontal, vertical).
  70. * This node controls the direction of each pass.
  71. *
  72. * @private
  73. * @type {UniformNode<vec2>}
  74. */
  75. this._passDirection = uniform( new Vector2() );
  76. /**
  77. * The render target used for the horizontal pass.
  78. *
  79. * @private
  80. * @type {RenderTarget}
  81. */
  82. this._horizontalRT = new RenderTarget( 1, 1, { depthBuffer: false } );
  83. this._horizontalRT.texture.name = 'GaussianBlurNode.horizontal';
  84. /**
  85. * The render target used for the vertical pass.
  86. *
  87. * @private
  88. * @type {RenderTarget}
  89. */
  90. this._verticalRT = new RenderTarget( 1, 1, { depthBuffer: false } );
  91. this._verticalRT.texture.name = 'GaussianBlurNode.vertical';
  92. /**
  93. * The result of the effect is represented as a separate texture node.
  94. *
  95. * @private
  96. * @type {PassTextureNode}
  97. */
  98. this._textureNode = passTexture( this, this._verticalRT.texture );
  99. this._textureNode.uvNode = textureNode.uvNode;
  100. /**
  101. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders
  102. * its effect once per frame in `updateBefore()`.
  103. *
  104. * @type {string}
  105. * @default 'frame'
  106. */
  107. this.updateBeforeType = NodeUpdateType.FRAME;
  108. /**
  109. * Controls the resolution of the effect.
  110. *
  111. * @type {Vector2}
  112. * @default (1,1)
  113. */
  114. this.resolution = new Vector2( 1, 1 );
  115. /**
  116. * Whether the effect should use premultiplied alpha or not. Set this to `true`
  117. * if you are going to blur texture input with transparency.
  118. *
  119. * @type {boolean}
  120. * @default false
  121. */
  122. this.premultipliedAlpha = false;
  123. }
  124. /**
  125. * Sets the given premultiplied alpha value.
  126. *
  127. * @param {boolean} value - Whether the effect should use premultiplied alpha or not.
  128. * @return {GaussianBlurNode} height - A reference to this node.
  129. */
  130. setPremultipliedAlpha( value ) {
  131. this.premultipliedAlpha = value;
  132. return this;
  133. }
  134. /**
  135. * Returns the premultiplied alpha value.
  136. *
  137. * @return {boolean} Whether the effect should use premultiplied alpha or not.
  138. */
  139. getPremultipliedAlpha() {
  140. return this.premultipliedAlpha;
  141. }
  142. /**
  143. * Sets the size of the effect.
  144. *
  145. * @param {number} width - The width of the effect.
  146. * @param {number} height - The height of the effect.
  147. */
  148. setSize( width, height ) {
  149. width = Math.max( Math.round( width * this.resolution.x ), 1 );
  150. height = Math.max( Math.round( height * this.resolution.y ), 1 );
  151. this._invSize.value.set( 1 / width, 1 / height );
  152. this._horizontalRT.setSize( width, height );
  153. this._verticalRT.setSize( width, height );
  154. }
  155. /**
  156. * This method is used to render the effect once per frame.
  157. *
  158. * @param {NodeFrame} frame - The current node frame.
  159. */
  160. updateBefore( frame ) {
  161. const { renderer } = frame;
  162. _rendererState = RendererUtils.resetRendererState( renderer, _rendererState );
  163. //
  164. const textureNode = this.textureNode;
  165. const map = textureNode.value;
  166. const currentTexture = textureNode.value;
  167. _quadMesh.material = this._material;
  168. this.setSize( map.image.width, map.image.height );
  169. const textureType = map.type;
  170. this._horizontalRT.texture.type = textureType;
  171. this._verticalRT.texture.type = textureType;
  172. // horizontal
  173. renderer.setRenderTarget( this._horizontalRT );
  174. this._passDirection.value.set( 1, 0 );
  175. _quadMesh.render( renderer );
  176. // vertical
  177. textureNode.value = this._horizontalRT.texture;
  178. renderer.setRenderTarget( this._verticalRT );
  179. this._passDirection.value.set( 0, 1 );
  180. _quadMesh.render( renderer );
  181. // restore
  182. textureNode.value = currentTexture;
  183. RendererUtils.restoreRendererState( renderer, _rendererState );
  184. }
  185. /**
  186. * Returns the result of the effect as a texture node.
  187. *
  188. * @return {PassTextureNode} A texture node that represents the result of the effect.
  189. */
  190. getTextureNode() {
  191. return this._textureNode;
  192. }
  193. /**
  194. * This method is used to setup the effect's TSL code.
  195. *
  196. * @param {NodeBuilder} builder - The current node builder.
  197. * @return {PassTextureNode}
  198. */
  199. setup( builder ) {
  200. const textureNode = this.textureNode;
  201. //
  202. const uvNode = uv();
  203. const directionNode = vec2( this.directionNode || 1 );
  204. let sampleTexture, output;
  205. if ( this.premultipliedAlpha ) {
  206. // https://lisyarus.github.io/blog/posts/blur-coefficients-generator.html
  207. sampleTexture = ( uv ) => premult( textureNode.sample( uv ) );
  208. output = ( color ) => unpremult( color );
  209. } else {
  210. sampleTexture = ( uv ) => textureNode.sample( uv );
  211. output = ( color ) => color;
  212. }
  213. const blur = Fn( () => {
  214. const kernelSize = 3 + ( 2 * this.sigma );
  215. const gaussianCoefficients = this._getCoefficients( kernelSize );
  216. const invSize = this._invSize;
  217. const direction = directionNode.mul( this._passDirection );
  218. const weightSum = float( gaussianCoefficients[ 0 ] ).toVar();
  219. const diffuseSum = vec4( sampleTexture( uvNode ).mul( weightSum ) ).toVar();
  220. for ( let i = 1; i < kernelSize; i ++ ) {
  221. const x = float( i );
  222. const w = float( gaussianCoefficients[ i ] );
  223. const uvOffset = vec2( direction.mul( invSize.mul( x ) ) ).toVar();
  224. const sample1 = sampleTexture( uvNode.add( uvOffset ) );
  225. const sample2 = sampleTexture( uvNode.sub( uvOffset ) );
  226. diffuseSum.addAssign( sample1.add( sample2 ).mul( w ) );
  227. weightSum.addAssign( mul( 2.0, w ) );
  228. }
  229. return output( diffuseSum.div( weightSum ) );
  230. } );
  231. //
  232. const material = this._material || ( this._material = new NodeMaterial() );
  233. material.fragmentNode = blur().context( builder.getSharedContext() );
  234. material.name = 'Gaussian_blur';
  235. material.needsUpdate = true;
  236. //
  237. const properties = builder.getNodeProperties( this );
  238. properties.textureNode = textureNode;
  239. //
  240. return this._textureNode;
  241. }
  242. /**
  243. * Frees internal resources. This method should be called
  244. * when the effect is no longer required.
  245. */
  246. dispose() {
  247. this._horizontalRT.dispose();
  248. this._verticalRT.dispose();
  249. }
  250. /**
  251. * Computes gaussian coefficients depending on the given kernel radius.
  252. *
  253. * @private
  254. * @param {number} kernelRadius - The kernel radius.
  255. * @return {Array<number>}
  256. */
  257. _getCoefficients( kernelRadius ) {
  258. const coefficients = [];
  259. for ( let i = 0; i < kernelRadius; i ++ ) {
  260. coefficients.push( 0.39894 * Math.exp( - 0.5 * i * i / ( kernelRadius * kernelRadius ) ) / kernelRadius );
  261. }
  262. return coefficients;
  263. }
  264. }
  265. export default GaussianBlurNode;
  266. /**
  267. * TSL function for creating a gaussian blur node for post processing.
  268. *
  269. * @tsl
  270. * @function
  271. * @param {Node<vec4>} node - The node that represents the input of the effect.
  272. * @param {Node<vec2|float>} directionNode - Defines the direction and radius of the blur.
  273. * @param {number} sigma - Controls the kernel of the blur filter. Higher values mean a wider blur radius.
  274. * @returns {GaussianBlurNode}
  275. */
  276. export const gaussianBlur = ( node, directionNode, sigma ) => nodeObject( new GaussianBlurNode( convertToTexture( node ), directionNode, sigma ) );
  277. /**
  278. * TSL function for creating a gaussian blur node for post processing with enabled premultiplied alpha.
  279. *
  280. * @tsl
  281. * @function
  282. * @param {Node<vec4>} node - The node that represents the input of the effect.
  283. * @param {Node<vec2|float>} directionNode - Defines the direction and radius of the blur.
  284. * @param {number} sigma - Controls the kernel of the blur filter. Higher values mean a wider blur radius.
  285. * @returns {GaussianBlurNode}
  286. */
  287. export const premultipliedGaussianBlur = ( node, directionNode, sigma ) => nodeObject( new GaussianBlurNode( convertToTexture( node ), directionNode, sigma ).setPremultipliedAlpha( true ) );