GaussianBlurNode.js 9.4 KB

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