TRAANode.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. import { HalfFloatType, Vector2, RenderTarget, RendererUtils, QuadMesh, NodeMaterial, TempNode, NodeUpdateType, Matrix4, DepthTexture } from 'three/webgpu';
  2. import { add, float, If, Loop, int, Fn, min, max, clamp, nodeObject, texture, uniform, uv, vec2, vec4, luminance, convertToTexture, passTexture, velocity, getViewPosition, length } from 'three/tsl';
  3. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  4. const _size = /*@__PURE__*/ new Vector2();
  5. let _rendererState;
  6. /**
  7. * A special node that applies TRAA (Temporal Reprojection Anti-Aliasing).
  8. *
  9. * References:
  10. * - {@link https://alextardif.com/TAA.html}
  11. * - {@link https://www.elopezr.com/temporal-aa-and-the-quest-for-the-holy-trail/}
  12. *
  13. * @augments TempNode
  14. * @three_import import { traa } from 'three/addons/tsl/display/TRAANode.js';
  15. */
  16. class TRAANode extends TempNode {
  17. static get type() {
  18. return 'TRAANode';
  19. }
  20. /**
  21. * Constructs a new TRAA node.
  22. *
  23. * @param {TextureNode} beautyNode - The texture node that represents the input of the effect.
  24. * @param {TextureNode} depthNode - A node that represents the scene's depth.
  25. * @param {TextureNode} velocityNode - A node that represents the scene's velocity.
  26. * @param {Camera} camera - The camera the scene is rendered with.
  27. */
  28. constructor( beautyNode, depthNode, velocityNode, camera ) {
  29. super( 'vec4' );
  30. /**
  31. * This flag can be used for type testing.
  32. *
  33. * @type {boolean}
  34. * @readonly
  35. * @default true
  36. */
  37. this.isTRAANode = true;
  38. /**
  39. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders
  40. * its effect once per frame in `updateBefore()`.
  41. *
  42. * @type {string}
  43. * @default 'frame'
  44. */
  45. this.updateBeforeType = NodeUpdateType.FRAME;
  46. /**
  47. * The texture node that represents the input of the effect.
  48. *
  49. * @type {TextureNode}
  50. */
  51. this.beautyNode = beautyNode;
  52. /**
  53. * A node that represents the scene's velocity.
  54. *
  55. * @type {TextureNode}
  56. */
  57. this.depthNode = depthNode;
  58. /**
  59. * A node that represents the scene's velocity.
  60. *
  61. * @type {TextureNode}
  62. */
  63. this.velocityNode = velocityNode;
  64. /**
  65. * The camera the scene is rendered with.
  66. *
  67. * @type {Camera}
  68. */
  69. this.camera = camera;
  70. /**
  71. * The jitter index selects the current camera offset value.
  72. *
  73. * @private
  74. * @type {number}
  75. * @default 0
  76. */
  77. this._jitterIndex = 0;
  78. /**
  79. * A uniform node holding the inverse resolution value.
  80. *
  81. * @private
  82. * @type {UniformNode<vec2>}
  83. */
  84. this._invSize = uniform( new Vector2() );
  85. /**
  86. * A uniform node holding the camera world matrix.
  87. *
  88. * @private
  89. * @type {UniformNode<mat4>}
  90. */
  91. this._cameraWorldMatrix = uniform( new Matrix4() );
  92. /**
  93. * A uniform node holding the camera projection matrix inverse.
  94. *
  95. * @private
  96. * @type {UniformNode<mat4>}
  97. */
  98. this._cameraProjectionMatrixInverse = uniform( new Matrix4() );
  99. /**
  100. * A uniform node holding the previous frame's view matrix.
  101. *
  102. * @private
  103. * @type {UniformNode<mat4>}
  104. */
  105. this._previousCameraWorldMatrix = uniform( new Matrix4() );
  106. /**
  107. * A uniform node holding the previous frame's projection matrix inverse.
  108. *
  109. * @private
  110. * @type {UniformNode<mat4>}
  111. */
  112. this._previousCameraProjectionMatrixInverse = uniform( new Matrix4() );
  113. /**
  114. * The render target that represents the history of frame data.
  115. *
  116. * @private
  117. * @type {?RenderTarget}
  118. */
  119. this._historyRenderTarget = new RenderTarget( 1, 1, { depthBuffer: false, type: HalfFloatType, depthTexture: new DepthTexture() } );
  120. this._historyRenderTarget.texture.name = 'TRAANode.history';
  121. /**
  122. * The render target for the resolve.
  123. *
  124. * @private
  125. * @type {?RenderTarget}
  126. */
  127. this._resolveRenderTarget = new RenderTarget( 1, 1, { depthBuffer: false, type: HalfFloatType } );
  128. this._resolveRenderTarget.texture.name = 'TRAANode.resolve';
  129. /**
  130. * Material used for the resolve step.
  131. *
  132. * @private
  133. * @type {NodeMaterial}
  134. */
  135. this._resolveMaterial = new NodeMaterial();
  136. this._resolveMaterial.name = 'TRAA.resolve';
  137. /**
  138. * The result of the effect is represented as a separate texture node.
  139. *
  140. * @private
  141. * @type {PassTextureNode}
  142. */
  143. this._textureNode = passTexture( this, this._resolveRenderTarget.texture );
  144. /**
  145. * Used to save the original/unjittered projection matrix.
  146. *
  147. * @private
  148. * @type {Matrix4}
  149. */
  150. this._originalProjectionMatrix = new Matrix4();
  151. /**
  152. * A texture node for the previous depth buffer.
  153. *
  154. * @private
  155. * @type {TextureNode}
  156. */
  157. this._previousDepthNode = texture( new DepthTexture( 1, 1 ) );
  158. /**
  159. * Sync the post processing stack with the TRAA node.
  160. * @private
  161. * @type {boolean}
  162. */
  163. this._needsPostProcessingSync = false;
  164. }
  165. /**
  166. * Returns the result of the effect as a texture node.
  167. *
  168. * @return {PassTextureNode} A texture node that represents the result of the effect.
  169. */
  170. getTextureNode() {
  171. return this._textureNode;
  172. }
  173. /**
  174. * Sets the size of the effect.
  175. *
  176. * @param {number} width - The width of the effect.
  177. * @param {number} height - The height of the effect.
  178. */
  179. setSize( width, height ) {
  180. this._historyRenderTarget.setSize( width, height );
  181. this._resolveRenderTarget.setSize( width, height );
  182. this._invSize.value.set( 1 / width, 1 / height );
  183. }
  184. /**
  185. * Defines the TRAA's current jitter as a view offset
  186. * to the scene's camera.
  187. *
  188. * @param {number} width - The width of the effect.
  189. * @param {number} height - The height of the effect.
  190. */
  191. setViewOffset( width, height ) {
  192. // save original/unjittered projection matrix for velocity pass
  193. this.camera.updateProjectionMatrix();
  194. this._originalProjectionMatrix.copy( this.camera.projectionMatrix );
  195. velocity.setProjectionMatrix( this._originalProjectionMatrix );
  196. //
  197. const viewOffset = {
  198. fullWidth: width,
  199. fullHeight: height,
  200. offsetX: 0,
  201. offsetY: 0,
  202. width: width,
  203. height: height
  204. };
  205. const jitterOffset = _haltonOffsets[ this._jitterIndex ];
  206. this.camera.setViewOffset(
  207. viewOffset.fullWidth, viewOffset.fullHeight,
  208. viewOffset.offsetX + jitterOffset[ 0 ] - 0.5, viewOffset.offsetY + jitterOffset[ 1 ] - 0.5,
  209. viewOffset.width, viewOffset.height
  210. );
  211. }
  212. /**
  213. * Clears the view offset from the scene's camera.
  214. */
  215. clearViewOffset() {
  216. this.camera.clearViewOffset();
  217. velocity.setProjectionMatrix( null );
  218. // update jitter index
  219. this._jitterIndex ++;
  220. this._jitterIndex = this._jitterIndex % ( _haltonOffsets.length - 1 );
  221. }
  222. /**
  223. * This method is used to render the effect once per frame.
  224. *
  225. * @param {NodeFrame} frame - The current node frame.
  226. */
  227. updateBefore( frame ) {
  228. const { renderer } = frame;
  229. // store previous frame matrices before updating current ones
  230. this._previousCameraWorldMatrix.value.copy( this._cameraWorldMatrix.value );
  231. this._previousCameraProjectionMatrixInverse.value.copy( this._cameraProjectionMatrixInverse.value );
  232. // update camera matrices uniforms
  233. this._cameraWorldMatrix.value.copy( this.camera.matrixWorld );
  234. this._cameraProjectionMatrixInverse.value.copy( this.camera.projectionMatrixInverse );
  235. // keep the TRAA in sync with the dimensions of the beauty node
  236. const beautyRenderTarget = ( this.beautyNode.isRTTNode ) ? this.beautyNode.renderTarget : this.beautyNode.passNode.renderTarget;
  237. const width = beautyRenderTarget.texture.width;
  238. const height = beautyRenderTarget.texture.height;
  239. //
  240. if ( this._needsPostProcessingSync === true ) {
  241. this.setViewOffset( width, height );
  242. this._needsPostProcessingSync = false;
  243. }
  244. _rendererState = RendererUtils.resetRendererState( renderer, _rendererState );
  245. //
  246. const needsRestart = this._historyRenderTarget.width !== width || this._historyRenderTarget.height !== height;
  247. this.setSize( width, height );
  248. // every time when the dimensions change we need fresh history data
  249. if ( needsRestart === true ) {
  250. // bind and clear render target to make sure they are initialized after the resize which triggers a dispose()
  251. renderer.setRenderTarget( this._historyRenderTarget );
  252. renderer.clear();
  253. renderer.setRenderTarget( this._resolveRenderTarget );
  254. renderer.clear();
  255. // make sure to reset the history with the contents of the beauty buffer otherwise subsequent frames after the
  256. // resize will fade from a darker color to the correct one because the history was cleared with black.
  257. renderer.copyTextureToTexture( beautyRenderTarget.texture, this._historyRenderTarget.texture );
  258. }
  259. // resolve
  260. renderer.setRenderTarget( this._resolveRenderTarget );
  261. _quadMesh.material = this._resolveMaterial;
  262. _quadMesh.name = 'TRAA';
  263. _quadMesh.render( renderer );
  264. renderer.setRenderTarget( null );
  265. // update history
  266. renderer.copyTextureToTexture( this._resolveRenderTarget.texture, this._historyRenderTarget.texture );
  267. // Copy current depth to previous depth buffer
  268. const size = renderer.getDrawingBufferSize( _size );
  269. // only allow the depth copy if the dimensions of the history render target match with the drawing
  270. // render buffer and thus the depth texture of the scene. For some reasons, there are timing issues
  271. // with WebGPU resulting in different size of the drawing buffer and the beauty render target when
  272. // resizing the browser window. This does not happen with the WebGL backend
  273. if ( this._historyRenderTarget.height === size.height && this._historyRenderTarget.width === size.width ) {
  274. const currentDepth = this.depthNode.value;
  275. renderer.copyTextureToTexture( currentDepth, this._historyRenderTarget.depthTexture );
  276. this._previousDepthNode.value = this._historyRenderTarget.depthTexture;
  277. }
  278. // restore
  279. RendererUtils.restoreRendererState( renderer, _rendererState );
  280. }
  281. /**
  282. * This method is used to setup the effect's render targets and TSL code.
  283. *
  284. * @param {NodeBuilder} builder - The current node builder.
  285. * @return {PassTextureNode}
  286. */
  287. setup( builder ) {
  288. const postProcessing = builder.context.postProcessing;
  289. if ( postProcessing ) {
  290. this._needsPostProcessingSync = true;
  291. postProcessing.context.onBeforePostProcessing = () => {
  292. const size = builder.renderer.getDrawingBufferSize( _size );
  293. this.setViewOffset( size.width, size.height );
  294. };
  295. postProcessing.context.onAfterPostProcessing = () => {
  296. this.clearViewOffset();
  297. };
  298. }
  299. const historyTexture = texture( this._historyRenderTarget.texture );
  300. const sampleTexture = this.beautyNode;
  301. const depthTexture = this.depthNode;
  302. const velocityTexture = this.velocityNode;
  303. const resolve = Fn( () => {
  304. const uvNode = uv();
  305. const minColor = vec4( 10000 ).toVar();
  306. const maxColor = vec4( - 10000 ).toVar();
  307. const closestDepth = float( 1 ).toVar();
  308. const farthestDepth = float( 0 ).toVar();
  309. const closestDepthPixelPosition = vec2( 0 ).toVar();
  310. // sample a 3x3 neighborhood to create a box in color space
  311. // clamping the history color with the resulting min/max colors mitigates ghosting
  312. Loop( { start: int( - 1 ), end: int( 1 ), type: 'int', condition: '<=', name: 'x' }, ( { x } ) => {
  313. Loop( { start: int( - 1 ), end: int( 1 ), type: 'int', condition: '<=', name: 'y' }, ( { y } ) => {
  314. const uvNeighbor = uvNode.add( vec2( float( x ), float( y ) ).mul( this._invSize ) ).toVar();
  315. const colorNeighbor = max( vec4( 0 ), sampleTexture.sample( uvNeighbor ) ).toVar(); // use max() to avoid propagate garbage values
  316. minColor.assign( min( minColor, colorNeighbor ) );
  317. maxColor.assign( max( maxColor, colorNeighbor ) );
  318. const currentDepth = depthTexture.sample( uvNeighbor ).r.toVar();
  319. // find the sample position of the closest depth in the neighborhood (used for velocity)
  320. If( currentDepth.lessThan( closestDepth ), () => {
  321. closestDepth.assign( currentDepth );
  322. closestDepthPixelPosition.assign( uvNeighbor );
  323. } );
  324. // find the farthest depth in the neighborhood (used to preserve edge anti-aliasing)
  325. If( currentDepth.greaterThan( farthestDepth ), () => {
  326. farthestDepth.assign( currentDepth );
  327. } );
  328. } );
  329. } );
  330. // sampling/reprojection
  331. const offset = velocityTexture.sample( closestDepthPixelPosition ).xy.mul( vec2( 0.5, - 0.5 ) ); // NDC to uv offset
  332. const currentColor = sampleTexture.sample( uvNode );
  333. const historyColor = historyTexture.sample( uvNode.sub( offset ) );
  334. // clamping
  335. const clampedHistoryColor = clamp( historyColor, minColor, maxColor );
  336. // calculate current frame world position
  337. const currentDepth = depthTexture.sample( uvNode ).r;
  338. const currentViewPosition = getViewPosition( uvNode, currentDepth, this._cameraProjectionMatrixInverse );
  339. const currentWorldPosition = this._cameraWorldMatrix.mul( vec4( currentViewPosition, 1.0 ) ).xyz;
  340. // calculate previous frame world position from history UV and previous depth
  341. const historyUV = uvNode.sub( offset );
  342. const previousDepth = this._previousDepthNode.sample( historyUV ).r;
  343. const previousViewPosition = getViewPosition( historyUV, previousDepth, this._previousCameraProjectionMatrixInverse );
  344. const previousWorldPosition = this._previousCameraWorldMatrix.mul( vec4( previousViewPosition, 1.0 ) ).xyz;
  345. // calculate difference in world positions
  346. const worldPositionDifference = length( currentWorldPosition.sub( previousWorldPosition ) ).toVar();
  347. worldPositionDifference.assign( min( max( worldPositionDifference.sub( 1.0 ), 0.0 ), 1.0 ) );
  348. // Adaptive blend weights based on velocity magnitude suggested by CLAUDE in #32133
  349. // Higher velocity or position difference = more weight on current frame to reduce ghosting
  350. const velocityMagnitude = length( offset ).toConst();
  351. const motionFactor = max( worldPositionDifference.mul( 0.5 ), velocityMagnitude.mul( 10.0 ) ).toVar();
  352. motionFactor.assign( min( motionFactor, 1.0 ) );
  353. const currentWeight = float( 0.05 ).add( motionFactor.mul( 0.25 ) ).toVar();
  354. const historyWeight = currentWeight.oneMinus().toVar();
  355. // zero out history weight if world positions are different (indicating motion) except on edges.
  356. // note that the constants 0.00001 and 0.5 were suggested by CLAUDE in #32133
  357. const isEdge = farthestDepth.sub( closestDepth ).greaterThan( 0.00001 );
  358. const strongDisocclusion = worldPositionDifference.greaterThan( 0.5 ).and( isEdge.not() );
  359. If( strongDisocclusion, () => {
  360. currentWeight.assign( 1.0 );
  361. historyWeight.assign( 0.0 );
  362. } );
  363. // flicker reduction based on luminance weighing
  364. const compressedCurrent = currentColor.mul( float( 1 ).div( ( max( currentColor.r, currentColor.g, currentColor.b ).add( 1.0 ) ) ) );
  365. const compressedHistory = clampedHistoryColor.mul( float( 1 ).div( ( max( clampedHistoryColor.r, clampedHistoryColor.g, clampedHistoryColor.b ).add( 1.0 ) ) ) );
  366. const luminanceCurrent = luminance( compressedCurrent.rgb );
  367. const luminanceHistory = luminance( compressedHistory.rgb );
  368. currentWeight.mulAssign( float( 1.0 ).div( luminanceCurrent.add( 1 ) ) );
  369. historyWeight.mulAssign( float( 1.0 ).div( luminanceHistory.add( 1 ) ) );
  370. const smoothedOutput = add( currentColor.mul( currentWeight ), clampedHistoryColor.mul( historyWeight ) ).div( max( currentWeight.add( historyWeight ), 0.00001 ) ).toVar();
  371. return smoothedOutput;
  372. } );
  373. // materials
  374. this._resolveMaterial.colorNode = resolve();
  375. return this._textureNode;
  376. }
  377. /**
  378. * Frees internal resources. This method should be called
  379. * when the effect is no longer required.
  380. */
  381. dispose() {
  382. this._historyRenderTarget.dispose();
  383. this._resolveRenderTarget.dispose();
  384. this._resolveMaterial.dispose();
  385. }
  386. }
  387. export default TRAANode;
  388. function _halton( index, base ) {
  389. let fraction = 1;
  390. let result = 0;
  391. while ( index > 0 ) {
  392. fraction /= base;
  393. result += fraction * ( index % base );
  394. index = Math.floor( index / base );
  395. }
  396. return result;
  397. }
  398. const _haltonOffsets = /*@__PURE__*/ Array.from(
  399. { length: 32 },
  400. ( _, index ) => [ _halton( index + 1, 2 ), _halton( index + 1, 3 ) ]
  401. );
  402. /**
  403. * TSL function for creating a TRAA node for Temporal Reprojection Anti-Aliasing.
  404. *
  405. * @tsl
  406. * @function
  407. * @param {TextureNode} beautyNode - The texture node that represents the input of the effect.
  408. * @param {TextureNode} depthNode - A node that represents the scene's depth.
  409. * @param {TextureNode} velocityNode - A node that represents the scene's velocity.
  410. * @param {Camera} camera - The camera the scene is rendered with.
  411. * @returns {TRAANode}
  412. */
  413. export const traa = ( beautyNode, depthNode, velocityNode, camera ) => nodeObject( new TRAANode( convertToTexture( beautyNode ), depthNode, velocityNode, camera ) );
粤ICP备19079148号