File size: 9,460 Bytes
a28eca3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
import { Vector2, TempNode } from 'three/webgpu';
import { nodeObject, Fn, uniformArray, select, float, NodeUpdateType, uv, dot, clamp, uniform, convertToTexture, smoothstep, bool, vec2, vec3, If, Loop, max, min, Break, abs } from 'three/tsl';

/** @module FXAANode **/

/**
 * Post processing node for applying FXAA. This node requires sRGB input
 * so tone mapping and color space conversion must happen before the anti-aliasing.
 *
 * @augments TempNode
 */
class FXAANode extends TempNode {

	static get type() {

		return 'FXAANode';

	}

	/**
	 * Constructs a new FXAA node.
	 *
	 * @param {TextureNode} textureNode - The texture node that represents the input of the effect.
	 */
	constructor( textureNode ) {

		super( 'vec4' );

		/**
		 * The texture node that represents the input of the effect.
		 *
		 * @type {TextureNode}
		 */
		this.textureNode = textureNode;

		/**
		 * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node updates
		 * its internal uniforms once per frame in `updateBefore()`.
		 *
		 * @type {String}
		 * @default 'frame'
		 */
		this.updateBeforeType = NodeUpdateType.FRAME;

		/**
		 * A uniform node holding the inverse resolution value.
		 *
		 * @private
		 * @type {UniformNode<vec2>}
		 */
		this._invSize = uniform( new Vector2() );

	}

	/**
	 * This method is used to update the effect's uniforms once per frame.
	 *
	 * @param {NodeFrame} frame - The current node frame.
	 */
	updateBefore( /* frame */ ) {

		const map = this.textureNode.value;

		this._invSize.value.set( 1 / map.image.width, 1 / map.image.height );

	}

	/**
	 * This method is used to setup the effect's TSL code.
	 *
	 * @param {NodeBuilder} builder - The current node builder.
	 * @return {ShaderCallNodeInternal}
	 */
	setup( /* builder */ ) {

		const textureNode = this.textureNode.bias( - 100 );
		const uvNode = textureNode.uvNode || uv();

		const EDGE_STEP_COUNT = float( 6 );
		const EDGE_GUESS = float( 8.0 );
		const EDGE_STEPS = uniformArray( [ 1.0, 1.5, 2.0, 2.0, 2.0, 4.0 ] );

		const _ContrastThreshold = float( 0.0312 );
		const _RelativeThreshold = float( 0.063 );
		const _SubpixelBlending = float( 1.0 );

		const Sample = Fn( ( [ uv ] ) => {

			return textureNode.sample( uv );

		} );

		const SampleLuminance = Fn( ( [ uv ] ) => {

			return dot( Sample( uv ).rgb, vec3( 0.3, 0.59, 0.11 ) );

		} );

		const SampleLuminanceOffset = Fn( ( [ texSize, uv, uOffset, vOffset ] ) => {

			const shiftedUv = uv.add( texSize.mul( vec2( uOffset, vOffset ) ) );
			return SampleLuminance( shiftedUv );

		} );

		const ShouldSkipPixel = ( l ) => {

			const threshold = max( _ContrastThreshold, _RelativeThreshold.mul( l.highest ) );
			return l.contrast.lessThan( threshold );

		};

		const SampleLuminanceNeighborhood = ( texSize, uv ) => {

			const m = SampleLuminance( uv );

			const n = SampleLuminanceOffset( texSize, uv, 0.0, - 1.0 );
			const e = SampleLuminanceOffset( texSize, uv, 1.0, 0.0 );
			const s = SampleLuminanceOffset( texSize, uv, 0.0, 1.0 );
			const w = SampleLuminanceOffset( texSize, uv, - 1.0, 0.0 );

			const ne = SampleLuminanceOffset( texSize, uv, 1.0, - 1.0 );
			const nw = SampleLuminanceOffset( texSize, uv, - 1.0, - 1.0 );
			const se = SampleLuminanceOffset( texSize, uv, 1.0, 1.0 );
			const sw = SampleLuminanceOffset( texSize, uv, - 1.0, 1.0 );

			const highest = max( max( max( max( s, e ), n ), w ), m );
			const lowest = min( min( min( min( s, e ), n ), w ), m );
			const contrast = highest.sub( lowest );

			return { m, n, e, s, w, ne, nw, se, sw, highest, lowest, contrast };

		};

		const DeterminePixelBlendFactor = ( l ) => {

			let f = float( 2.0 ).mul( l.s.add( l.e ).add( l.n ).add( l.w ) );
			f = f.add( l.se.add( l.sw ).add( l.ne ).add( l.nw ) );
			f = f.mul( 1.0 / 12.0 );
			f = abs( f.sub( l.m ) );
			f = clamp( f.div( max( l.contrast, 0 ) ), 0.0, 1.0 );

			const blendFactor = smoothstep( 0.0, 1.0, f );
			return blendFactor.mul( blendFactor ).mul( _SubpixelBlending );

		};

		const DetermineEdge = ( texSize, l ) => {

			const horizontal =
				abs( l.s.add( l.n ).sub( l.m.mul( 2.0 ) ) ).mul( 2.0 ).add(
					abs( l.se.add( l.ne ).sub( l.e.mul( 2.0 ) ) ).add(
						abs( l.sw.add( l.nw ).sub( l.w.mul( 2.0 ) ) )
					)
				);

			const vertical =
				abs( l.e.add( l.w ).sub( l.m.mul( 2.0 ) ) ).mul( 2.0 ).add(
					abs( l.se.add( l.sw ).sub( l.s.mul( 2.0 ) ) ).add(
						abs( l.ne.add( l.nw ).sub( l.n.mul( 2.0 ) ) )
					)
				);

			const isHorizontal = horizontal.greaterThanEqual( vertical );

			const pLuminance = select( isHorizontal, l.s, l.e );
			const nLuminance = select( isHorizontal, l.n, l.w );
			const pGradient = abs( pLuminance.sub( l.m ) );
			const nGradient = abs( nLuminance.sub( l.m ) );

			const pixelStep = select( isHorizontal, texSize.y, texSize.x ).toVar();
			const oppositeLuminance = float().toVar();
			const gradient = float().toVar();

			If( pGradient.lessThan( nGradient ), () => {

				pixelStep.assign( pixelStep.negate() );
				oppositeLuminance.assign( nLuminance );
				gradient.assign( nGradient );

			} ).Else( () => {

				oppositeLuminance.assign( pLuminance );
				gradient.assign( pGradient );

			} );

			return { isHorizontal, pixelStep, oppositeLuminance, gradient };

		};

		const DetermineEdgeBlendFactor = ( texSize, l, e, uv ) => {

			const uvEdge = uv.toVar();
			const edgeStep = vec2().toVar();
			If( e.isHorizontal, () => {

				uvEdge.y.addAssign( e.pixelStep.mul( 0.5 ) );
				edgeStep.assign( vec2( texSize.x, 0.0 ) );

			} ).Else( () => {

				uvEdge.x.addAssign( e.pixelStep.mul( 0.5 ) );
				edgeStep.assign( vec2( 0.0, texSize.y ) );

			} );

			const edgeLuminance = l.m.add( e.oppositeLuminance ).mul( 0.5 );
			const gradientThreshold = e.gradient.mul( 0.25 );

			const puv = uvEdge.add( edgeStep.mul( EDGE_STEPS.element( 0 ) ) ).toVar();
			const pLuminanceDelta = SampleLuminance( puv ).sub( edgeLuminance ).toVar();
			const pAtEnd = abs( pLuminanceDelta ).greaterThanEqual( gradientThreshold ).toVar();

			Loop( { start: 1, end: EDGE_STEP_COUNT }, ( { i } ) => {

				If( pAtEnd, () => {

					Break();

				} );

				puv.addAssign( edgeStep.mul( EDGE_STEPS.element( i ) ) );
				pLuminanceDelta.assign( SampleLuminance( puv ).sub( edgeLuminance ) );
				pAtEnd.assign( abs( pLuminanceDelta ).greaterThanEqual( gradientThreshold ) );

			} );

			If( pAtEnd.not(), () => {

				puv.addAssign( edgeStep.mul( EDGE_GUESS ) );

			} );

			const nuv = uvEdge.sub( edgeStep.mul( EDGE_STEPS.element( 0 ) ) ).toVar();
			const nLuminanceDelta = SampleLuminance( nuv ).sub( edgeLuminance ).toVar();
			const nAtEnd = abs( nLuminanceDelta ).greaterThanEqual( gradientThreshold ).toVar();

			Loop( { start: 1, end: EDGE_STEP_COUNT }, ( { i } ) => {

				If( nAtEnd, () => {

					Break();

				} );

				nuv.subAssign( edgeStep.mul( EDGE_STEPS.element( i ) ) );
				nLuminanceDelta.assign( SampleLuminance( nuv ).sub( edgeLuminance ) );
				nAtEnd.assign( abs( nLuminanceDelta ).greaterThanEqual( gradientThreshold ) );

			} );

			If( nAtEnd.not(), () => {

				nuv.subAssign( edgeStep.mul( EDGE_GUESS ) );

			} );

			const pDistance = float().toVar();
			const nDistance = float().toVar();

			If( e.isHorizontal, () => {

				pDistance.assign( puv.x.sub( uv.x ) );
				nDistance.assign( uv.x.sub( nuv.x ) );

			} ).Else( () => {

				pDistance.assign( puv.y.sub( uv.y ) );
				nDistance.assign( uv.y.sub( nuv.y ) );

			} );

			const shortestDistance = float().toVar();
			const deltaSign = bool().toVar();

			If( pDistance.lessThanEqual( nDistance ), () => {

				shortestDistance.assign( pDistance );
				deltaSign.assign( pLuminanceDelta.greaterThanEqual( 0.0 ) );

			} ).Else( () => {

				shortestDistance.assign( nDistance );
				deltaSign.assign( nLuminanceDelta.greaterThanEqual( 0.0 ) );

			} );

			const blendFactor = float().toVar();

			If( deltaSign.equal( l.m.sub( edgeLuminance ).greaterThanEqual( 0.0 ) ), () => {

				blendFactor.assign( 0.0 );

			} ).Else( () => {

				blendFactor.assign( float( 0.5 ).sub( shortestDistance.div( pDistance.add( nDistance ) ) ) );

			} );

			return blendFactor;

		};

		const ApplyFXAA = Fn( ( [ uv, texSize ] ) => {

			const luminance = SampleLuminanceNeighborhood( texSize, uv );
			If( ShouldSkipPixel( luminance ), () => {

				return Sample( uv );

			} );

			const pixelBlend = DeterminePixelBlendFactor( luminance );
			const edge = DetermineEdge( texSize, luminance );
			const edgeBlend = DetermineEdgeBlendFactor( texSize, luminance, edge, uv );

			const finalBlend = max( pixelBlend, edgeBlend );
			const finalUv = uv.toVar();

			If( edge.isHorizontal, () => {

				finalUv.y.addAssign( edge.pixelStep.mul( finalBlend ) );

			} ).Else( () => {

				finalUv.x.addAssign( edge.pixelStep.mul( finalBlend ) );

			} );

			return Sample( finalUv );

		} ).setLayout( {
			name: 'FxaaPixelShader',
			type: 'vec4',
			inputs: [
				{ name: 'uv', type: 'vec2' },
				{ name: 'texSize', type: 'vec2' },
			]
		} );

		const fxaa = Fn( () => {

			return ApplyFXAA( uvNode, this._invSize );

		} );

		const outputNode = fxaa();

		return outputNode;

	}

}

export default FXAANode;

/**
 * TSL function for creating a FXAA node for anti-aliasing via post processing.
 *
 * @function
 * @param {Node<vec4>} node - The node that represents the input of the effect.
 * @returns {FXAANode}
 */
export const fxaa = ( node ) => nodeObject( new FXAANode( convertToTexture( node ) ) );