DenoiseNode.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. import { DataTexture, RepeatWrapping, Vector2, Vector3, TempNode } from 'three/webgpu';
  2. import { texture, getNormalFromDepth, getViewPosition, convertToTexture, nodeObject, Fn, float, NodeUpdateType, uv, uniform, Loop, luminance, vec2, vec3, vec4, uniformArray, int, dot, max, pow, abs, If, textureSize, sin, cos, mat2, PI } from 'three/tsl';
  3. import { SimplexNoise } from '../../math/SimplexNoise.js';
  4. /** @module DenoiseNode **/
  5. /**
  6. * Post processing node for denoising data like raw screen-space ambient occlusion output.
  7. * Denoise can noticeably improve the quality of ambient occlusion but also add quite some
  8. * overhead to the post processing setup. It's best to make its usage optional (e.g. via
  9. * graphic settings).
  10. *
  11. * Reference: {@link https://openaccess.thecvf.com/content/WACV2021/papers/Khademi_Self-Supervised_Poisson-Gaussian_Denoising_WACV_2021_paper.pdf}.
  12. *
  13. * @augments TempNode
  14. */
  15. class DenoiseNode extends TempNode {
  16. static get type() {
  17. return 'DenoiseNode';
  18. }
  19. /**
  20. * Constructs a new denoise node.
  21. *
  22. * @param {TextureNode} textureNode - The texture node that represents the input of the effect (e.g. AO).
  23. * @param {Node<float>} depthNode - A node that represents the scene's depth.
  24. * @param {Node<vec3>?} normalNode - A node that represents the scene's normals.
  25. * @param {Camera} camera - The camera the scene is rendered with.
  26. */
  27. constructor( textureNode, depthNode, normalNode, camera ) {
  28. super( 'vec4' );
  29. /**
  30. * The texture node that represents the input of the effect (e.g. AO).
  31. *
  32. * @type {TextureNode}
  33. */
  34. this.textureNode = textureNode;
  35. /**
  36. * A node that represents the scene's depth.
  37. *
  38. * @type {Node<float>}
  39. */
  40. this.depthNode = depthNode;
  41. /**
  42. * A node that represents the scene's normals. If no normals are passed to the
  43. * constructor (because MRT is not available), normals can be automatically
  44. * reconstructed from depth values in the shader.
  45. *
  46. * @type {Node<vec3>?}
  47. */
  48. this.normalNode = normalNode;
  49. /**
  50. * The node represents the internal noise texture.
  51. *
  52. * @type {TextureNode}
  53. */
  54. this.noiseNode = texture( generateDefaultNoise() );
  55. /**
  56. * The luma Phi value.
  57. *
  58. * @type {UniformNode<float>}
  59. */
  60. this.lumaPhi = uniform( 5 );
  61. /**
  62. * The depth Phi value.
  63. *
  64. * @type {UniformNode<float>}
  65. */
  66. this.depthPhi = uniform( 5 );
  67. /**
  68. * The normal Phi value.
  69. *
  70. * @type {UniformNode<float>}
  71. */
  72. this.normalPhi = uniform( 5 );
  73. /**
  74. * The radius.
  75. *
  76. * @type {UniformNode<float>}
  77. */
  78. this.radius = uniform( 5 );
  79. /**
  80. * The index.
  81. *
  82. * @type {UniformNode<float>}
  83. */
  84. this.index = uniform( 0 );
  85. /**
  86. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node updates
  87. * its internal uniforms once per frame in `updateBefore()`.
  88. *
  89. * @type {String}
  90. * @default 'frame'
  91. */
  92. this.updateBeforeType = NodeUpdateType.FRAME;
  93. /**
  94. * The resolution of the effect.
  95. *
  96. * @private
  97. * @type {UniformNode<vec2>}
  98. */
  99. this._resolution = uniform( new Vector2() );
  100. /**
  101. * An array of sample vectors.
  102. *
  103. * @private
  104. * @type {UniformArrayNode<vec3>}
  105. */
  106. this._sampleVectors = uniformArray( generateDenoiseSamples( 16, 2, 1 ) );
  107. /**
  108. * Represents the inverse projection matrix of the scene's camera.
  109. *
  110. * @private
  111. * @type {UniformNode<mat4>}
  112. */
  113. this._cameraProjectionMatrixInverse = uniform( camera.projectionMatrixInverse );
  114. }
  115. /**
  116. * This method is used to update internal uniforms once per frame.
  117. *
  118. * @param {NodeFrame} frame - The current node frame.
  119. */
  120. updateBefore() {
  121. const map = this.textureNode.value;
  122. this._resolution.value.set( map.image.width, map.image.height );
  123. }
  124. /**
  125. * This method is used to setup the effect's TSL code.
  126. *
  127. * @param {NodeBuilder} builder - The current node builder.
  128. * @return {ShaderCallNodeInternal}
  129. */
  130. setup( /* builder */ ) {
  131. const uvNode = uv();
  132. const sampleTexture = ( uv ) => this.textureNode.sample( uv );
  133. const sampleDepth = ( uv ) => this.depthNode.sample( uv ).x;
  134. const sampleNormal = ( uv ) => ( this.normalNode !== null ) ? this.normalNode.sample( uv ).rgb.normalize() : getNormalFromDepth( uv, this.depthNode.value, this._cameraProjectionMatrixInverse );
  135. const sampleNoise = ( uv ) => this.noiseNode.sample( uv );
  136. const denoiseSample = Fn( ( [ center, viewNormal, viewPosition, sampleUv ] ) => {
  137. const texel = sampleTexture( sampleUv ).toVar();
  138. const depth = sampleDepth( sampleUv ).toVar();
  139. const normal = sampleNormal( sampleUv ).toVar();
  140. const neighborColor = texel.rgb;
  141. const viewPos = getViewPosition( sampleUv, depth, this._cameraProjectionMatrixInverse ).toVar();
  142. const normalDiff = dot( viewNormal, normal ).toVar();
  143. const normalSimilarity = pow( max( normalDiff, 0 ), this.normalPhi ).toVar();
  144. const lumaDiff = abs( luminance( neighborColor ).sub( luminance( center ) ) ).toVar();
  145. const lumaSimilarity = max( float( 1.0 ).sub( lumaDiff.div( this.lumaPhi ) ), 0 ).toVar();
  146. const depthDiff = abs( dot( viewPosition.sub( viewPos ), viewNormal ) ).toVar();
  147. const depthSimilarity = max( float( 1.0 ).sub( depthDiff.div( this.depthPhi ) ), 0 );
  148. const w = lumaSimilarity.mul( depthSimilarity ).mul( normalSimilarity );
  149. return vec4( neighborColor.mul( w ), w );
  150. } );
  151. const denoise = Fn( ( [ uvNode ] ) => {
  152. const depth = sampleDepth( uvNode ).toVar();
  153. const viewNormal = sampleNormal( uvNode ).toVar();
  154. const texel = sampleTexture( uvNode ).toVar();
  155. If( depth.greaterThanEqual( 1.0 ).or( dot( viewNormal, viewNormal ).equal( 0.0 ) ), () => {
  156. return texel;
  157. } );
  158. const center = vec3( texel.rgb ).toVar();
  159. const viewPosition = getViewPosition( uvNode, depth, this._cameraProjectionMatrixInverse ).toVar();
  160. const noiseResolution = textureSize( this.noiseNode, 0 );
  161. let noiseUv = vec2( uvNode.x, uvNode.y.oneMinus() );
  162. noiseUv = noiseUv.mul( this._resolution.div( noiseResolution ) );
  163. const noiseTexel = sampleNoise( noiseUv ).toVar();
  164. const x = sin( noiseTexel.element( this.index.mod( 4 ).mul( 2 ).mul( PI ) ) ).toVar();
  165. const y = cos( noiseTexel.element( this.index.mod( 4 ).mul( 2 ).mul( PI ) ) ).toVar();
  166. const noiseVec = vec2( x, y ).toVar();
  167. const rotationMatrix = mat2( noiseVec.x, noiseVec.y.negate(), noiseVec.x, noiseVec.y ).toVar();
  168. const totalWeight = float( 1.0 ).toVar();
  169. const denoised = vec3( texel.rgb ).toVar();
  170. Loop( { start: int( 0 ), end: int( 16 ), type: 'int', condition: '<' }, ( { i } ) => {
  171. const sampleDir = this._sampleVectors.element( i ).toVar();
  172. const offset = rotationMatrix.mul( sampleDir.xy.mul( float( 1.0 ).add( sampleDir.z.mul( this.radius.sub( 1 ) ) ) ) ).div( this._resolution ).toVar();
  173. const sampleUv = uvNode.add( offset ).toVar();
  174. const result = denoiseSample( center, viewNormal, viewPosition, sampleUv );
  175. denoised.addAssign( result.xyz );
  176. totalWeight.addAssign( result.w );
  177. } );
  178. If( totalWeight.greaterThan( float( 0 ) ), () => {
  179. denoised.divAssign( totalWeight );
  180. } );
  181. return vec4( denoised, texel.a );
  182. } ).setLayout( {
  183. name: 'denoise',
  184. type: 'vec4',
  185. inputs: [
  186. { name: 'uv', type: 'vec2' }
  187. ]
  188. } );
  189. const output = Fn( () => {
  190. return denoise( uvNode );
  191. } );
  192. const outputNode = output();
  193. return outputNode;
  194. }
  195. }
  196. export default DenoiseNode;
  197. /**
  198. * Generates denoise samples based on the given parameters.
  199. *
  200. * @param {Number} numSamples - The number of samples.
  201. * @param {Number} numRings - The number of rings.
  202. * @param {Number} radiusExponent - The radius exponent.
  203. * @return {Array<Vector3>} The denoise samples.
  204. */
  205. function generateDenoiseSamples( numSamples, numRings, radiusExponent ) {
  206. const samples = [];
  207. for ( let i = 0; i < numSamples; i ++ ) {
  208. const angle = 2 * Math.PI * numRings * i / numSamples;
  209. const radius = Math.pow( i / ( numSamples - 1 ), radiusExponent );
  210. samples.push( new Vector3( Math.cos( angle ), Math.sin( angle ), radius ) );
  211. }
  212. return samples;
  213. }
  214. /**
  215. * Generates a default noise texture for the given size.
  216. *
  217. * @param {Number} [size=64] - The texture size.
  218. * @return {DataTexture} The generated noise texture.
  219. */
  220. function generateDefaultNoise( size = 64 ) {
  221. const simplex = new SimplexNoise();
  222. const arraySize = size * size * 4;
  223. const data = new Uint8Array( arraySize );
  224. for ( let i = 0; i < size; i ++ ) {
  225. for ( let j = 0; j < size; j ++ ) {
  226. const x = i;
  227. const y = j;
  228. data[ ( i * size + j ) * 4 ] = ( simplex.noise( x, y ) * 0.5 + 0.5 ) * 255;
  229. data[ ( i * size + j ) * 4 + 1 ] = ( simplex.noise( x + size, y ) * 0.5 + 0.5 ) * 255;
  230. data[ ( i * size + j ) * 4 + 2 ] = ( simplex.noise( x, y + size ) * 0.5 + 0.5 ) * 255;
  231. data[ ( i * size + j ) * 4 + 3 ] = ( simplex.noise( x + size, y + size ) * 0.5 + 0.5 ) * 255;
  232. }
  233. }
  234. const noiseTexture = new DataTexture( data, size, size );
  235. noiseTexture.wrapS = RepeatWrapping;
  236. noiseTexture.wrapT = RepeatWrapping;
  237. noiseTexture.needsUpdate = true;
  238. return noiseTexture;
  239. }
  240. /**
  241. * TSL function for creating a denoise effect.
  242. *
  243. * @function
  244. * @param {Node} node - The node that represents the input of the effect (e.g. AO).
  245. * @param {Node<float>} depthNode - A node that represents the scene's depth.
  246. * @param {Node<vec3>?} normalNode - A node that represents the scene's normals.
  247. * @param {Camera} camera - The camera the scene is rendered with.
  248. * @returns {DenoiseNode}
  249. */
  250. export const denoise = ( node, depthNode, normalNode, camera ) => nodeObject( new DenoiseNode( convertToTexture( node ), nodeObject( depthNode ), nodeObject( normalNode ), camera ) );
粤ICP备19079148号