first commit

This commit is contained in:
rafaeldpsilva
2025-12-10 12:32:12 +00:00
commit adbbf6bf50
3442 changed files with 2725681 additions and 0 deletions

View File

@@ -0,0 +1,155 @@
import { RenderTarget, Vector2, PostProcessingUtils } from 'three';
import { TempNode, nodeObject, Fn, float, vec4, NodeUpdateType, uv, texture, passTexture, uniform, sign, max, convertToTexture, QuadMesh, NodeMaterial } from 'three/tsl';
const _size = /*@__PURE__*/ new Vector2();
const _quadMeshComp = /*@__PURE__*/ new QuadMesh();
let _rendererState;
class AfterImageNode extends TempNode {
static get type() {
return 'AfterImageNode';
}
constructor( textureNode, damp = 0.96 ) {
super( textureNode );
this.textureNode = textureNode;
this.textureNodeOld = texture();
this.damp = uniform( damp );
this._compRT = new RenderTarget( 1, 1, { depthBuffer: false } );
this._compRT.texture.name = 'AfterImageNode.comp';
this._oldRT = new RenderTarget( 1, 1, { depthBuffer: false } );
this._oldRT.texture.name = 'AfterImageNode.old';
this._textureNode = passTexture( this, this._compRT.texture );
this.updateBeforeType = NodeUpdateType.FRAME;
}
getTextureNode() {
return this._textureNode;
}
setSize( width, height ) {
this._compRT.setSize( width, height );
this._oldRT.setSize( width, height );
}
updateBefore( frame ) {
const { renderer } = frame;
_rendererState = PostProcessingUtils.resetRendererState( renderer, _rendererState );
//
const textureNode = this.textureNode;
const map = textureNode.value;
const textureType = map.type;
this._compRT.texture.type = textureType;
this._oldRT.texture.type = textureType;
renderer.getDrawingBufferSize( _size );
this.setSize( _size.x, _size.y );
const currentTexture = textureNode.value;
this.textureNodeOld.value = this._oldRT.texture;
// comp
renderer.setRenderTarget( this._compRT );
_quadMeshComp.render( renderer );
// Swap the textures
const temp = this._oldRT;
this._oldRT = this._compRT;
this._compRT = temp;
//
textureNode.value = currentTexture;
PostProcessingUtils.restoreRendererState( renderer, _rendererState );
}
setup( builder ) {
const textureNode = this.textureNode;
const textureNodeOld = this.textureNodeOld;
//
const uvNode = textureNode.uvNode || uv();
textureNodeOld.uvNode = uvNode;
const sampleTexture = ( uv ) => textureNode.uv( uv );
const when_gt = Fn( ( [ x_immutable, y_immutable ] ) => {
const y = float( y_immutable ).toVar();
const x = vec4( x_immutable ).toVar();
return max( sign( x.sub( y ) ), 0.0 );
} );
const afterImg = Fn( () => {
const texelOld = vec4( textureNodeOld );
const texelNew = vec4( sampleTexture( uvNode ) );
texelOld.mulAssign( this.damp.mul( when_gt( texelOld, 0.1 ) ) );
return max( texelNew, texelOld );
} );
//
const materialComposed = this._materialComposed || ( this._materialComposed = new NodeMaterial() );
materialComposed.name = 'AfterImage';
materialComposed.fragmentNode = afterImg();
_quadMeshComp.material = materialComposed;
//
const properties = builder.getNodeProperties( this );
properties.textureNode = textureNode;
//
return this._textureNode;
}
dispose() {
this._compRT.dispose();
this._oldRT.dispose();
}
}
export const afterImage = ( node, damp ) => nodeObject( new AfterImageNode( convertToTexture( node ), damp ) );
export default AfterImageNode;

View File

@@ -0,0 +1,63 @@
import { Matrix3 } from 'three';
import { clamp, nodeObject, Fn, vec4, uv, uniform, max, NodeMaterial } from 'three/tsl';
import StereoCompositePassNode from './StereoCompositePassNode.js';
class AnaglyphPassNode extends StereoCompositePassNode {
static get type() {
return 'AnaglyphPassNode';
}
constructor( scene, camera ) {
super( scene, camera );
this.isAnaglyphPassNode = true;
// Dubois matrices from https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.7.6968&rep=rep1&type=pdf#page=4
this._colorMatrixLeft = uniform( new Matrix3().fromArray( [
0.456100, - 0.0400822, - 0.0152161,
0.500484, - 0.0378246, - 0.0205971,
0.176381, - 0.0157589, - 0.00546856
] ) );
this._colorMatrixRight = uniform( new Matrix3().fromArray( [
- 0.0434706, 0.378476, - 0.0721527,
- 0.0879388, 0.73364, - 0.112961,
- 0.00155529, - 0.0184503, 1.2264
] ) );
}
setup( builder ) {
const uvNode = uv();
const anaglyph = Fn( () => {
const colorL = this._mapLeft.uv( uvNode );
const colorR = this._mapRight.uv( uvNode );
const color = clamp( this._colorMatrixLeft.mul( colorL.rgb ).add( this._colorMatrixRight.mul( colorR.rgb ) ) );
return vec4( color.rgb, max( colorL.a, colorR.a ) );
} );
const material = this._material || ( this._material = new NodeMaterial() );
material.fragmentNode = anaglyph().context( builder.getSharedContext() );
material.name = 'Anaglyph';
material.needsUpdate = true;
return super.setup( builder );
}
}
export default AnaglyphPassNode;
export const anaglyphPass = ( scene, camera ) => nodeObject( new AnaglyphPassNode( scene, camera ) );

View File

@@ -0,0 +1,145 @@
import { RenderTarget, Vector2, PostProcessingUtils } from 'three';
import { TempNode, nodeObject, Fn, float, NodeUpdateType, uv, passTexture, uniform, convertToTexture, QuadMesh, NodeMaterial, vec2, vec3, Loop, threshold } from 'three/tsl';
const _quadMesh = /*@__PURE__*/ new QuadMesh();
let _rendererState;
class AnamorphicNode extends TempNode {
static get type() {
return 'AnamorphicNode';
}
constructor( textureNode, tresholdNode, scaleNode, samples ) {
super( 'vec4' );
this.textureNode = textureNode;
this.tresholdNode = tresholdNode;
this.scaleNode = scaleNode;
this.colorNode = vec3( 0.1, 0.0, 1.0 );
this.samples = samples;
this.resolution = new Vector2( 1, 1 );
this._renderTarget = new RenderTarget( 1, 1, { depthBuffer: false } );
this._renderTarget.texture.name = 'anamorphic';
this._invSize = uniform( new Vector2() );
this._textureNode = passTexture( this, this._renderTarget.texture );
this.updateBeforeType = NodeUpdateType.FRAME;
}
getTextureNode() {
return this._textureNode;
}
setSize( width, height ) {
this._invSize.value.set( 1 / width, 1 / height );
width = Math.max( Math.round( width * this.resolution.x ), 1 );
height = Math.max( Math.round( height * this.resolution.y ), 1 );
this._renderTarget.setSize( width, height );
}
updateBefore( frame ) {
const { renderer } = frame;
_rendererState = PostProcessingUtils.resetRendererState( renderer, _rendererState );
//
const textureNode = this.textureNode;
const map = textureNode.value;
this._renderTarget.texture.type = map.type;
const currentTexture = textureNode.value;
_quadMesh.material = this._material;
this.setSize( map.image.width, map.image.height );
// render
renderer.setRenderTarget( this._renderTarget );
_quadMesh.render( renderer );
// restore
textureNode.value = currentTexture;
PostProcessingUtils.restoreRendererState( renderer, _rendererState );
}
setup( builder ) {
const textureNode = this.textureNode;
const uvNode = textureNode.uvNode || uv();
const sampleTexture = ( uv ) => textureNode.uv( uv );
const anamorph = Fn( () => {
const samples = this.samples;
const halfSamples = Math.floor( samples / 2 );
const total = vec3( 0 ).toVar();
Loop( { start: - halfSamples, end: halfSamples }, ( { i } ) => {
const softness = float( i ).abs().div( halfSamples ).oneMinus();
const uv = vec2( uvNode.x.add( this._invSize.x.mul( i ).mul( this.scaleNode ) ), uvNode.y );
const color = sampleTexture( uv );
const pass = threshold( color, this.tresholdNode ).mul( softness );
total.addAssign( pass );
} );
return total.mul( this.colorNode );
} );
//
const material = this._material || ( this._material = new NodeMaterial() );
material.name = 'Anamorphic';
material.fragmentNode = anamorph();
//
const properties = builder.getNodeProperties( this );
properties.textureNode = textureNode;
//
return this._textureNode;
}
dispose() {
this._renderTarget.dispose();
}
}
export const anamorphic = ( node, threshold = .9, scale = 3, samples = 32 ) => nodeObject( new AnamorphicNode( convertToTexture( node ), nodeObject( threshold ), nodeObject( scale ), samples ) );
export default AnamorphicNode;

View File

@@ -0,0 +1,24 @@
import { float, Fn, vec3, vec4, min, max, mix, luminance } from 'three/tsl';
export const bleach = /*@__PURE__*/ Fn( ( [ color, opacity = 1 ] ) => {
const base = color;
const lum = luminance( base.rgb );
const blend = vec3( lum );
const L = min( 1.0, max( 0.0, float( 10.0 ).mul( lum.sub( 0.45 ) ) ) );
const result1 = blend.mul( base.rgb ).mul( 2.0 );
const result2 = float( 2.0 ).mul( blend.oneMinus() ).mul( base.rgb.oneMinus() ).oneMinus();
const newColor = mix( result1, result2, L );
const A2 = base.a.mul( opacity );
const mixRGB = A2.mul( newColor.rgb );
mixRGB.addAssign( base.rgb.mul( A2.oneMinus() ) );
return vec4( mixRGB, base.a );
} );

View File

@@ -0,0 +1,312 @@
import { HalfFloatType, RenderTarget, Vector2, Vector3, PostProcessingUtils } from 'three';
import { TempNode, nodeObject, Fn, float, NodeUpdateType, uv, passTexture, uniform, QuadMesh, NodeMaterial, Loop, texture, luminance, smoothstep, mix, vec4, uniformArray, add, int } from 'three/tsl';
const _quadMesh = /*@__PURE__*/ new QuadMesh();
const _size = /*@__PURE__*/ new Vector2();
const _BlurDirectionX = /*@__PURE__*/ new Vector2( 1.0, 0.0 );
const _BlurDirectionY = /*@__PURE__*/ new Vector2( 0.0, 1.0 );
let _rendererState;
class BloomNode extends TempNode {
static get type() {
return 'BloomNode';
}
constructor( inputNode, strength = 1, radius = 0, threshold = 0 ) {
super();
this.inputNode = inputNode;
this.strength = uniform( strength );
this.radius = uniform( radius );
this.threshold = uniform( threshold );
this.smoothWidth = uniform( 0.01 );
//
this._renderTargetsHorizontal = [];
this._renderTargetsVertical = [];
this._nMips = 5;
// render targets
this._renderTargetBright = new RenderTarget( 1, 1, { depthBuffer: false, type: HalfFloatType } );
this._renderTargetBright.texture.name = 'UnrealBloomPass.bright';
this._renderTargetBright.texture.generateMipmaps = false;
for ( let i = 0; i < this._nMips; i ++ ) {
const renderTargetHorizontal = new RenderTarget( 1, 1, { depthBuffer: false, type: HalfFloatType } );
renderTargetHorizontal.texture.name = 'UnrealBloomPass.h' + i;
renderTargetHorizontal.texture.generateMipmaps = false;
this._renderTargetsHorizontal.push( renderTargetHorizontal );
const renderTargetVertical = new RenderTarget( 1, 1, { depthBuffer: false, type: HalfFloatType } );
renderTargetVertical.texture.name = 'UnrealBloomPass.v' + i;
renderTargetVertical.texture.generateMipmaps = false;
this._renderTargetsVertical.push( renderTargetVertical );
}
// materials
this._compositeMaterial = null;
this._highPassFilterMaterial = null;
this._separableBlurMaterials = [];
// pass and texture nodes
this._textureNodeBright = texture( this._renderTargetBright.texture );
this._textureNodeBlur0 = texture( this._renderTargetsVertical[ 0 ].texture );
this._textureNodeBlur1 = texture( this._renderTargetsVertical[ 1 ].texture );
this._textureNodeBlur2 = texture( this._renderTargetsVertical[ 2 ].texture );
this._textureNodeBlur3 = texture( this._renderTargetsVertical[ 3 ].texture );
this._textureNodeBlur4 = texture( this._renderTargetsVertical[ 4 ].texture );
this._textureOutput = passTexture( this, this._renderTargetsHorizontal[ 0 ].texture );
this.updateBeforeType = NodeUpdateType.FRAME;
}
getTextureNode() {
return this._textureOutput;
}
setSize( width, height ) {
let resx = Math.round( width / 2 );
let resy = Math.round( height / 2 );
this._renderTargetBright.setSize( resx, resy );
for ( let i = 0; i < this._nMips; i ++ ) {
this._renderTargetsHorizontal[ i ].setSize( resx, resy );
this._renderTargetsVertical[ i ].setSize( resx, resy );
this._separableBlurMaterials[ i ].invSize.value.set( 1 / resx, 1 / resy );
resx = Math.round( resx / 2 );
resy = Math.round( resy / 2 );
}
}
updateBefore( frame ) {
const { renderer } = frame;
_rendererState = PostProcessingUtils.resetRendererState( renderer, _rendererState );
//
const size = renderer.getDrawingBufferSize( _size );
this.setSize( size.width, size.height );
// 1. Extract Bright Areas
renderer.setRenderTarget( this._renderTargetBright );
_quadMesh.material = this._highPassFilterMaterial;
_quadMesh.render( renderer );
// 2. Blur All the mips progressively
let inputRenderTarget = this._renderTargetBright;
for ( let i = 0; i < this._nMips; i ++ ) {
_quadMesh.material = this._separableBlurMaterials[ i ];
this._separableBlurMaterials[ i ].colorTexture.value = inputRenderTarget.texture;
this._separableBlurMaterials[ i ].direction.value = _BlurDirectionX;
renderer.setRenderTarget( this._renderTargetsHorizontal[ i ] );
_quadMesh.render( renderer );
this._separableBlurMaterials[ i ].colorTexture.value = this._renderTargetsHorizontal[ i ].texture;
this._separableBlurMaterials[ i ].direction.value = _BlurDirectionY;
renderer.setRenderTarget( this._renderTargetsVertical[ i ] );
_quadMesh.render( renderer );
inputRenderTarget = this._renderTargetsVertical[ i ];
}
// 3. Composite All the mips
renderer.setRenderTarget( this._renderTargetsHorizontal[ 0 ] );
_quadMesh.material = this._compositeMaterial;
_quadMesh.render( renderer );
// restore
PostProcessingUtils.restoreRendererState( renderer, _rendererState );
}
setup( builder ) {
// luminosity high pass material
const luminosityHighPass = Fn( () => {
const texel = this.inputNode;
const v = luminance( texel.rgb );
const alpha = smoothstep( this.threshold, this.threshold.add( this.smoothWidth ), v );
return mix( vec4( 0 ), texel, alpha );
} );
this._highPassFilterMaterial = this._highPassFilterMaterial || new NodeMaterial();
this._highPassFilterMaterial.fragmentNode = luminosityHighPass().context( builder.getSharedContext() );
this._highPassFilterMaterial.name = 'Bloom_highPass';
this._highPassFilterMaterial.needsUpdate = true;
// gaussian blur materials
const kernelSizeArray = [ 3, 5, 7, 9, 11 ];
for ( let i = 0; i < this._nMips; i ++ ) {
this._separableBlurMaterials.push( this._getSeperableBlurMaterial( builder, kernelSizeArray[ i ] ) );
}
// composite material
const bloomFactors = uniformArray( [ 1.0, 0.8, 0.6, 0.4, 0.2 ] );
const bloomTintColors = uniformArray( [ new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ) ] );
const lerpBloomFactor = Fn( ( [ factor, radius ] ) => {
const mirrorFactor = float( 1.2 ).sub( factor );
return mix( factor, mirrorFactor, radius );
} ).setLayout( {
name: 'lerpBloomFactor',
type: 'float',
inputs: [
{ name: 'factor', type: 'float' },
{ name: 'radius', type: 'float' },
]
} );
const compositePass = Fn( () => {
const color0 = lerpBloomFactor( bloomFactors.element( 0 ), this.radius ).mul( vec4( bloomTintColors.element( 0 ), 1.0 ) ).mul( this._textureNodeBlur0 );
const color1 = lerpBloomFactor( bloomFactors.element( 1 ), this.radius ).mul( vec4( bloomTintColors.element( 1 ), 1.0 ) ).mul( this._textureNodeBlur1 );
const color2 = lerpBloomFactor( bloomFactors.element( 2 ), this.radius ).mul( vec4( bloomTintColors.element( 2 ), 1.0 ) ).mul( this._textureNodeBlur2 );
const color3 = lerpBloomFactor( bloomFactors.element( 3 ), this.radius ).mul( vec4( bloomTintColors.element( 3 ), 1.0 ) ).mul( this._textureNodeBlur3 );
const color4 = lerpBloomFactor( bloomFactors.element( 4 ), this.radius ).mul( vec4( bloomTintColors.element( 4 ), 1.0 ) ).mul( this._textureNodeBlur4 );
const sum = color0.add( color1 ).add( color2 ).add( color3 ).add( color4 );
return sum.mul( this.strength );
} );
this._compositeMaterial = this._compositeMaterial || new NodeMaterial();
this._compositeMaterial.fragmentNode = compositePass().context( builder.getSharedContext() );
this._compositeMaterial.name = 'Bloom_comp';
this._compositeMaterial.needsUpdate = true;
//
return this._textureOutput;
}
dispose() {
for ( let i = 0; i < this._renderTargetsHorizontal.length; i ++ ) {
this._renderTargetsHorizontal[ i ].dispose();
}
for ( let i = 0; i < this._renderTargetsVertical.length; i ++ ) {
this._renderTargetsVertical[ i ].dispose();
}
this._renderTargetBright.dispose();
}
_getSeperableBlurMaterial( builder, kernelRadius ) {
const coefficients = [];
for ( let i = 0; i < kernelRadius; i ++ ) {
coefficients.push( 0.39894 * Math.exp( - 0.5 * i * i / ( kernelRadius * kernelRadius ) ) / kernelRadius );
}
//
const colorTexture = texture();
const gaussianCoefficients = uniformArray( coefficients );
const invSize = uniform( new Vector2() );
const direction = uniform( new Vector2( 0.5, 0.5 ) );
const uvNode = uv();
const sampleTexel = ( uv ) => colorTexture.uv( uv );
const seperableBlurPass = Fn( () => {
const weightSum = gaussianCoefficients.element( 0 ).toVar();
const diffuseSum = sampleTexel( uvNode ).rgb.mul( weightSum ).toVar();
Loop( { start: int( 1 ), end: int( kernelRadius ), type: 'int', condition: '<' }, ( { i } ) => {
const x = float( i );
const w = gaussianCoefficients.element( i );
const uvOffset = direction.mul( invSize ).mul( x );
const sample1 = sampleTexel( uvNode.add( uvOffset ) ).rgb;
const sample2 = sampleTexel( uvNode.sub( uvOffset ) ).rgb;
diffuseSum.addAssign( add( sample1, sample2 ).mul( w ) );
weightSum.addAssign( float( 2.0 ).mul( w ) );
} );
return vec4( diffuseSum.div( weightSum ), 1.0 );
} );
const seperableBlurMaterial = new NodeMaterial();
seperableBlurMaterial.fragmentNode = seperableBlurPass().context( builder.getSharedContext() );
seperableBlurMaterial.name = 'Bloom_seperable';
seperableBlurMaterial.needsUpdate = true;
// uniforms
seperableBlurMaterial.colorTexture = colorTexture;
seperableBlurMaterial.direction = direction;
seperableBlurMaterial.invSize = invSize;
return seperableBlurMaterial;
}
}
export const bloom = ( node, strength, radius, threshold ) => nodeObject( new BloomNode( nodeObject( node ), strength, radius, threshold ) );
export default BloomNode;

View File

@@ -0,0 +1,181 @@
import { Vector2, Vector3 } from 'three';
import { getNormalFromDepth, getViewPosition, convertToTexture, TempNode, 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';
class DenoiseNode extends TempNode {
static get type() {
return 'DenoiseNode';
}
constructor( textureNode, depthNode, normalNode, noiseNode, camera ) {
super();
this.textureNode = textureNode;
this.depthNode = depthNode;
this.normalNode = normalNode;
this.noiseNode = noiseNode;
this.cameraProjectionMatrixInverse = uniform( camera.projectionMatrixInverse );
this.lumaPhi = uniform( 5 );
this.depthPhi = uniform( 5 );
this.normalPhi = uniform( 5 );
this.radius = uniform( 5 );
this.index = uniform( 0 );
this._resolution = uniform( new Vector2() );
this._sampleVectors = uniformArray( generatePdSamplePointInitializer( 16, 2, 1 ) );
this.updateBeforeType = NodeUpdateType.FRAME;
}
updateBefore() {
const map = this.textureNode.value;
this._resolution.value.set( map.image.width, map.image.height );
}
setup() {
const uvNode = uv();
const sampleTexture = ( uv ) => this.textureNode.uv( uv );
const sampleDepth = ( uv ) => this.depthNode.uv( uv ).x;
const sampleNormal = ( uv ) => ( this.normalNode !== null ) ? this.normalNode.uv( uv ).rgb.normalize() : getNormalFromDepth( uv, this.depthNode.value, this.cameraProjectionMatrixInverse );
const sampleNoise = ( uv ) => this.noiseNode.uv( uv );
const denoiseSample = Fn( ( [ center, viewNormal, viewPosition, sampleUv ] ) => {
const texel = sampleTexture( sampleUv ).toVar();
const depth = sampleDepth( sampleUv ).toVar();
const normal = sampleNormal( sampleUv ).toVar();
const neighborColor = texel.rgb;
const viewPos = getViewPosition( sampleUv, depth, this.cameraProjectionMatrixInverse ).toVar();
const normalDiff = dot( viewNormal, normal ).toVar();
const normalSimilarity = pow( max( normalDiff, 0 ), this.normalPhi ).toVar();
const lumaDiff = abs( luminance( neighborColor ).sub( luminance( center ) ) ).toVar();
const lumaSimilarity = max( float( 1.0 ).sub( lumaDiff.div( this.lumaPhi ) ), 0 ).toVar();
const depthDiff = abs( dot( viewPosition.sub( viewPos ), viewNormal ) ).toVar();
const depthSimilarity = max( float( 1.0 ).sub( depthDiff.div( this.depthPhi ) ), 0 );
const w = lumaSimilarity.mul( depthSimilarity ).mul( normalSimilarity );
return vec4( neighborColor.mul( w ), w );
} );
const denoise = Fn( ( [ uvNode ] ) => {
const depth = sampleDepth( uvNode ).toVar();
const viewNormal = sampleNormal( uvNode ).toVar();
const texel = sampleTexture( uvNode ).toVar();
If( depth.greaterThanEqual( 1.0 ).or( dot( viewNormal, viewNormal ).equal( 0.0 ) ), () => {
return texel;
} );
const center = vec3( texel.rgb ).toVar();
const viewPosition = getViewPosition( uvNode, depth, this.cameraProjectionMatrixInverse ).toVar();
const noiseResolution = textureSize( this.noiseNode, 0 );
let noiseUv = vec2( uvNode.x, uvNode.y.oneMinus() );
noiseUv = noiseUv.mul( this._resolution.div( noiseResolution ) );
const noiseTexel = sampleNoise( noiseUv ).toVar();
const x = sin( noiseTexel.element( this.index.mod( 4 ).mul( 2 ).mul( PI ) ) ).toVar();
const y = cos( noiseTexel.element( this.index.mod( 4 ).mul( 2 ).mul( PI ) ) ).toVar();
const noiseVec = vec2( x, y ).toVar();
const rotationMatrix = mat2( noiseVec.x, noiseVec.y.negate(), noiseVec.x, noiseVec.y ).toVar();
const totalWeight = float( 1.0 ).toVar();
const denoised = vec3( texel.rgb ).toVar();
Loop( { start: int( 0 ), end: int( 16 ), type: 'int', condition: '<' }, ( { i } ) => {
const sampleDir = this._sampleVectors.element( i ).toVar();
const offset = rotationMatrix.mul( sampleDir.xy.mul( float( 1.0 ).add( sampleDir.z.mul( this.radius.sub( 1 ) ) ) ) ).div( this._resolution ).toVar();
const sampleUv = uvNode.add( offset ).toVar();
const result = denoiseSample( center, viewNormal, viewPosition, sampleUv );
denoised.addAssign( result.xyz );
totalWeight.addAssign( result.w );
} );
If( totalWeight.greaterThan( float( 0 ) ), () => {
denoised.divAssign( totalWeight );
} );
return vec4( denoised, texel.a );
} ).setLayout( {
name: 'denoise',
type: 'vec4',
inputs: [
{ name: 'uv', type: 'vec2' }
]
} );
const output = Fn( () => {
return denoise( uvNode );
} );
const outputNode = output();
return outputNode;
}
}
export default DenoiseNode;
function generatePdSamplePointInitializer( samples, rings, radiusExponent ) {
const poissonDisk = generateDenoiseSamples( samples, rings, radiusExponent );
const array = [];
for ( let i = 0; i < samples; i ++ ) {
const sample = poissonDisk[ i ];
array.push( sample );
}
return array;
}
function generateDenoiseSamples( numSamples, numRings, radiusExponent ) {
const samples = [];
for ( let i = 0; i < numSamples; i ++ ) {
const angle = 2 * Math.PI * numRings * i / numSamples;
const radius = Math.pow( i / ( numSamples - 1 ), radiusExponent );
samples.push( new Vector3( Math.cos( angle ), Math.sin( angle ), radius ) );
}
return samples;
}
export const denoise = ( node, depthNode, normalNode, noiseNode, camera ) => nodeObject( new DenoiseNode( convertToTexture( node ), nodeObject( depthNode ), nodeObject( normalNode ), nodeObject( noiseNode ), camera ) );

View File

@@ -0,0 +1,118 @@
import { convertToTexture, TempNode, nodeObject, Fn, NodeUpdateType, uv, uniform, vec2, vec4, clamp } from 'three/tsl';
class DepthOfFieldNode extends TempNode {
static get type() {
return 'DepthOfFieldNode';
}
constructor( textureNode, viewZNode, focusNode, apertureNode, maxblurNode ) {
super();
this.textureNode = textureNode;
this.viewZNode = viewZNode;
this.focusNode = focusNode;
this.apertureNode = apertureNode;
this.maxblurNode = maxblurNode;
this._aspect = uniform( 0 );
this.updateBeforeType = NodeUpdateType.FRAME;
}
updateBefore() {
const map = this.textureNode.value;
this._aspect.value = map.image.width / map.image.height;
}
setup() {
const textureNode = this.textureNode;
const uvNode = textureNode.uvNode || uv();
const sampleTexture = ( uv ) => textureNode.uv( uv );
const dof = Fn( () => {
const aspectcorrect = vec2( 1.0, this._aspect );
const factor = this.focusNode.add( this.viewZNode );
const dofblur = vec2( clamp( factor.mul( this.apertureNode ), this.maxblurNode.negate(), this.maxblurNode ) );
const dofblur9 = dofblur.mul( 0.9 );
const dofblur7 = dofblur.mul( 0.7 );
const dofblur4 = dofblur.mul( 0.4 );
let col = vec4( 0.0 );
col = col.add( sampleTexture( uvNode ) );
col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( 0.40, 0.0 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( 0.40, 0.0 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
col = col.div( 41 );
col.a = 1;
return vec4( col );
} );
const outputNode = dof();
return outputNode;
}
}
export default DepthOfFieldNode;
export const dof = ( node, viewZNode, focus = 1, aperture = 0.025, maxblur = 1 ) => nodeObject( new DepthOfFieldNode( convertToTexture( node ), nodeObject( viewZNode ), nodeObject( focus ), nodeObject( aperture ), nodeObject( maxblur ) ) );

View File

@@ -0,0 +1,59 @@
import { Vector2 } from 'three';
import { TempNode, nodeObject, Fn, uv, uniform, vec2, vec3, sin, cos, add, vec4, screenSize } from 'three/tsl';
class DotScreenNode extends TempNode {
static get type() {
return 'DotScreenNode';
}
constructor( inputNode, center = new Vector2( 0.5, 0.5 ), angle = 1.57, scale = 1 ) {
super( 'vec4' );
this.inputNode = inputNode;
this.center = uniform( center );
this.angle = uniform( angle );
this.scale = uniform( scale );
}
setup() {
const inputNode = this.inputNode;
const pattern = Fn( () => {
const s = sin( this.angle );
const c = cos( this.angle );
const tex = uv().mul( screenSize ).sub( this.center );
const point = vec2( c.mul( tex.x ).sub( s.mul( tex.y ) ), s.mul( tex.x ).add( c.mul( tex.y ) ) ).mul( this.scale );
return sin( point.x ).mul( sin( point.y ) ).mul( 4 );
} );
const dotScreen = Fn( () => {
const color = inputNode;
const average = add( color.r, color.g, color.b ).div( 3 );
return vec4( vec3( average.mul( 10 ).sub( 5 ).add( pattern() ) ), color.a );
} );
const outputNode = dotScreen();
return outputNode;
}
}
export default DotScreenNode;
export const dotScreen = ( node, center, angle, scale ) => nodeObject( new DotScreenNode( nodeObject( node ), center, angle, scale ) );

View File

@@ -0,0 +1,316 @@
import { Vector2 } from 'three';
import { TempNode, nodeObject, Fn, uniformArray, select, float, NodeUpdateType, uv, dot, clamp, uniform, convertToTexture, smoothstep, bool, vec2, vec3, If, Loop, max, min, Break, abs } from 'three/tsl';
class FXAANode extends TempNode {
static get type() {
return 'FXAANode';
}
constructor( textureNode ) {
super();
this.textureNode = textureNode;
this.updateBeforeType = NodeUpdateType.FRAME;
this._invSize = uniform( new Vector2() );
}
updateBefore() {
const map = this.textureNode.value;
this._invSize.value.set( 1 / map.image.width, 1 / map.image.height );
}
setup() {
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.uv( 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;
export const fxaa = ( node ) => nodeObject( new FXAANode( convertToTexture( node ) ) );

View File

@@ -0,0 +1,52 @@
import { TempNode, rand, Fn, fract, time, uv, clamp, mix, vec4, nodeProxy } from 'three/tsl';
class FilmNode extends TempNode {
static get type() {
return 'FilmNode';
}
constructor( inputNode, intensityNode = null, uvNode = null ) {
super();
this.inputNode = inputNode;
this.intensityNode = intensityNode;
this.uvNode = uvNode;
}
setup() {
const uvNode = this.uvNode || uv();
const film = Fn( () => {
const base = this.inputNode.rgb;
const noise = rand( fract( uvNode.add( time ) ) );
let color = base.add( base.mul( clamp( noise.add( 0.1 ), 0, 1 ) ) );
if ( this.intensityNode !== null ) {
color = mix( base, color, this.intensityNode );
}
return vec4( color, this.inputNode.a );
} );
const outputNode = film();
return outputNode;
}
}
export default FilmNode;
export const film = /*@__PURE__*/ nodeProxy( FilmNode );

View File

@@ -0,0 +1,291 @@
import { DataTexture, RenderTarget, RepeatWrapping, Vector2, Vector3, PostProcessingUtils } from 'three';
import { getNormalFromDepth, getScreenPosition, getViewPosition, QuadMesh, TempNode, nodeObject, Fn, float, NodeUpdateType, uv, uniform, Loop, vec2, vec3, vec4, int, dot, max, pow, abs, If, textureSize, sin, cos, PI, texture, passTexture, mat3, add, normalize, mul, cross, div, mix, sqrt, sub, acos, clamp, NodeMaterial } from 'three/tsl';
const _quadMesh = /*@__PURE__*/ new QuadMesh();
const _size = /*@__PURE__*/ new Vector2();
let _rendererState;
class GTAONode extends TempNode {
static get type() {
return 'GTAONode';
}
constructor( depthNode, normalNode, camera ) {
super();
this.depthNode = depthNode;
this.normalNode = normalNode;
this.radius = uniform( 0.25 );
this.resolution = uniform( new Vector2() );
this.thickness = uniform( 1 );
this.distanceExponent = uniform( 1 );
this.distanceFallOff = uniform( 1 );
this.scale = uniform( 1 );
this.noiseNode = texture( generateMagicSquareNoise() );
this.cameraProjectionMatrix = uniform( camera.projectionMatrix );
this.cameraProjectionMatrixInverse = uniform( camera.projectionMatrixInverse );
this.SAMPLES = uniform( 16 );
this._aoRenderTarget = new RenderTarget( 1, 1, { depthBuffer: false } );
this._aoRenderTarget.texture.name = 'GTAONode.AO';
this._material = null;
this._textureNode = passTexture( this, this._aoRenderTarget.texture );
this.updateBeforeType = NodeUpdateType.FRAME;
}
getTextureNode() {
return this._textureNode;
}
setSize( width, height ) {
this.resolution.value.set( width, height );
this._aoRenderTarget.setSize( width, height );
}
updateBefore( frame ) {
const { renderer } = frame;
_rendererState = PostProcessingUtils.resetRendererState( renderer, _rendererState );
//
const size = renderer.getDrawingBufferSize( _size );
this.setSize( size.width, size.height );
_quadMesh.material = this._material;
// clear
renderer.setClearColor( 0xffffff, 1 );
// ao
renderer.setRenderTarget( this._aoRenderTarget );
_quadMesh.render( renderer );
// restore
PostProcessingUtils.restoreRendererState( renderer, _rendererState );
}
setup( builder ) {
const uvNode = uv();
const sampleDepth = ( uv ) => this.depthNode.uv( uv ).x;
const sampleNoise = ( uv ) => this.noiseNode.uv( uv );
const sampleNormal = ( uv ) => ( this.normalNode !== null ) ? this.normalNode.uv( uv ).rgb.normalize() : getNormalFromDepth( uv, this.depthNode.value, this.cameraProjectionMatrixInverse );
const ao = Fn( () => {
const depth = sampleDepth( uvNode ).toVar();
depth.greaterThanEqual( 1.0 ).discard();
const viewPosition = getViewPosition( uvNode, depth, this.cameraProjectionMatrixInverse ).toVar();
const viewNormal = sampleNormal( uvNode ).toVar();
const radiusToUse = this.radius;
const noiseResolution = textureSize( this.noiseNode, 0 );
let noiseUv = vec2( uvNode.x, uvNode.y.oneMinus() );
noiseUv = noiseUv.mul( this.resolution.div( noiseResolution ) );
const noiseTexel = sampleNoise( noiseUv );
const randomVec = noiseTexel.xyz.mul( 2.0 ).sub( 1.0 );
const tangent = vec3( randomVec.xy, 0.0 ).normalize();
const bitangent = vec3( tangent.y.mul( - 1.0 ), tangent.x, 0.0 );
const kernelMatrix = mat3( tangent, bitangent, vec3( 0.0, 0.0, 1.0 ) );
const DIRECTIONS = this.SAMPLES.lessThan( 30 ).select( 3, 5 ).toVar();
const STEPS = add( this.SAMPLES, DIRECTIONS.sub( 1 ) ).div( DIRECTIONS ).toVar();
const ao = float( 0 ).toVar();
Loop( { start: int( 0 ), end: DIRECTIONS, type: 'int', condition: '<' }, ( { i } ) => {
const angle = float( i ).div( float( DIRECTIONS ) ).mul( PI ).toVar();
const sampleDir = vec4( cos( angle ), sin( angle ), 0., add( 0.5, mul( 0.5, noiseTexel.w ) ) );
sampleDir.xyz = normalize( kernelMatrix.mul( sampleDir.xyz ) );
const viewDir = normalize( viewPosition.xyz.negate() ).toVar();
const sliceBitangent = normalize( cross( sampleDir.xyz, viewDir ) ).toVar();
const sliceTangent = cross( sliceBitangent, viewDir );
const normalInSlice = normalize( viewNormal.sub( sliceBitangent.mul( dot( viewNormal, sliceBitangent ) ) ) );
const tangentToNormalInSlice = cross( normalInSlice, sliceBitangent ).toVar();
const cosHorizons = vec2( dot( viewDir, tangentToNormalInSlice ), dot( viewDir, tangentToNormalInSlice.negate() ) ).toVar();
Loop( { end: STEPS, type: 'int', name: 'j', condition: '<' }, ( { j } ) => {
const sampleViewOffset = sampleDir.xyz.mul( radiusToUse ).mul( sampleDir.w ).mul( pow( div( float( j ).add( 1.0 ), float( STEPS ) ), this.distanceExponent ) );
// x
const sampleScreenPositionX = getScreenPosition( viewPosition.add( sampleViewOffset ), this.cameraProjectionMatrix ).toVar();
const sampleDepthX = sampleDepth( sampleScreenPositionX ).toVar();
const sampleSceneViewPositionX = getViewPosition( sampleScreenPositionX, sampleDepthX, this.cameraProjectionMatrixInverse ).toVar();
const viewDeltaX = sampleSceneViewPositionX.sub( viewPosition ).toVar();
If( abs( viewDeltaX.z ).lessThan( this.thickness ), () => {
const sampleCosHorizon = dot( viewDir, normalize( viewDeltaX ) );
cosHorizons.x.addAssign( max( 0, mul( sampleCosHorizon.sub( cosHorizons.x ), mix( 1.0, float( 2.0 ).div( float( j ).add( 2 ) ), this.distanceFallOff ) ) ) );
} );
// y
const sampleScreenPositionY = getScreenPosition( viewPosition.sub( sampleViewOffset ), this.cameraProjectionMatrix ).toVar();
const sampleDepthY = sampleDepth( sampleScreenPositionY ).toVar();
const sampleSceneViewPositionY = getViewPosition( sampleScreenPositionY, sampleDepthY, this.cameraProjectionMatrixInverse ).toVar();
const viewDeltaY = sampleSceneViewPositionY.sub( viewPosition ).toVar();
If( abs( viewDeltaY.z ).lessThan( this.thickness ), () => {
const sampleCosHorizon = dot( viewDir, normalize( viewDeltaY ) );
cosHorizons.y.addAssign( max( 0, mul( sampleCosHorizon.sub( cosHorizons.y ), mix( 1.0, float( 2.0 ).div( float( j ).add( 2 ) ), this.distanceFallOff ) ) ) );
} );
} );
const sinHorizons = sqrt( sub( 1.0, cosHorizons.mul( cosHorizons ) ) ).toVar();
const nx = dot( normalInSlice, sliceTangent );
const ny = dot( normalInSlice, viewDir );
const nxb = mul( 0.5, acos( cosHorizons.y ).sub( acos( cosHorizons.x ) ).add( sinHorizons.x.mul( cosHorizons.x ).sub( sinHorizons.y.mul( cosHorizons.y ) ) ) );
const nyb = mul( 0.5, sub( 2.0, cosHorizons.x.mul( cosHorizons.x ) ).sub( cosHorizons.y.mul( cosHorizons.y ) ) );
const occlusion = nx.mul( nxb ).add( ny.mul( nyb ) );
ao.addAssign( occlusion );
} );
ao.assign( clamp( ao.div( DIRECTIONS ), 0, 1 ) );
ao.assign( pow( ao, this.scale ) );
return vec4( vec3( ao ), 1.0 );
} );
const material = this._material || ( this._material = new NodeMaterial() );
material.fragmentNode = ao().context( builder.getSharedContext() );
material.name = 'GTAO';
material.needsUpdate = true;
//
return this._textureNode;
}
dispose() {
this._aoRenderTarget.dispose();
}
}
export default GTAONode;
function generateMagicSquareNoise( size = 5 ) {
const noiseSize = Math.floor( size ) % 2 === 0 ? Math.floor( size ) + 1 : Math.floor( size );
const magicSquare = generateMagicSquare( noiseSize );
const noiseSquareSize = magicSquare.length;
const data = new Uint8Array( noiseSquareSize * 4 );
for ( let inx = 0; inx < noiseSquareSize; ++ inx ) {
const iAng = magicSquare[ inx ];
const angle = ( 2 * Math.PI * iAng ) / noiseSquareSize;
const randomVec = new Vector3(
Math.cos( angle ),
Math.sin( angle ),
0
).normalize();
data[ inx * 4 ] = ( randomVec.x * 0.5 + 0.5 ) * 255;
data[ inx * 4 + 1 ] = ( randomVec.y * 0.5 + 0.5 ) * 255;
data[ inx * 4 + 2 ] = 127;
data[ inx * 4 + 3 ] = 255;
}
const noiseTexture = new DataTexture( data, noiseSize, noiseSize );
noiseTexture.wrapS = RepeatWrapping;
noiseTexture.wrapT = RepeatWrapping;
noiseTexture.needsUpdate = true;
return noiseTexture;
}
function generateMagicSquare( size ) {
const noiseSize = Math.floor( size ) % 2 === 0 ? Math.floor( size ) + 1 : Math.floor( size );
const noiseSquareSize = noiseSize * noiseSize;
const magicSquare = Array( noiseSquareSize ).fill( 0 );
let i = Math.floor( noiseSize / 2 );
let j = noiseSize - 1;
for ( let num = 1; num <= noiseSquareSize; ) {
if ( i === - 1 && j === noiseSize ) {
j = noiseSize - 2;
i = 0;
} else {
if ( j === noiseSize ) {
j = 0;
}
if ( i < 0 ) {
i = noiseSize - 1;
}
}
if ( magicSquare[ i * noiseSize + j ] !== 0 ) {
j -= 2;
i ++;
continue;
} else {
magicSquare[ i * noiseSize + j ] = num ++;
}
j ++;
i --;
}
return magicSquare;
}
export const ao = ( depthNode, normalNode, camera ) => nodeObject( new GTAONode( nodeObject( depthNode ), nodeObject( normalNode ), camera ) );

View File

@@ -0,0 +1,251 @@
import { RenderTarget, Vector2, PostProcessingUtils } from 'three';
import { TempNode, nodeObject, Fn, If, float, NodeUpdateType, uv, uniform, convertToTexture, vec2, vec4, QuadMesh, passTexture, mul, NodeMaterial } from 'three/tsl';
// WebGPU: The use of a single QuadMesh for both gaussian blur passes results in a single RenderObject with a SampledTexture binding that
// alternates between source textures and triggers creation of new BindGroups and BindGroupLayouts every frame.
const _quadMesh1 = /*@__PURE__*/ new QuadMesh();
const _quadMesh2 = /*@__PURE__*/ new QuadMesh();
let _rendererState;
const premult = /*@__PURE__*/ Fn( ( [ color ] ) => {
return vec4( color.rgb.mul( color.a ), color.a );
} ).setLayout( {
name: 'premult',
type: 'vec4',
inputs: [
{ name: 'color', type: 'vec4' }
]
} );
const unpremult = /*@__PURE__*/ Fn( ( [ color ] ) => {
If( color.a.equal( 0.0 ), () => vec4( 0.0 ) );
return vec4( color.rgb.div( color.a ), color.a );
} ).setLayout( {
name: 'unpremult',
type: 'vec4',
inputs: [
{ name: 'color', type: 'vec4' }
]
} );
class GaussianBlurNode extends TempNode {
static get type() {
return 'GaussianBlurNode';
}
constructor( textureNode, directionNode = null, sigma = 2 ) {
super( 'vec4' );
this.textureNode = textureNode;
this.directionNode = directionNode;
this.sigma = sigma;
this._invSize = uniform( new Vector2() );
this._passDirection = uniform( new Vector2() );
this._horizontalRT = new RenderTarget( 1, 1, { depthBuffer: false } );
this._horizontalRT.texture.name = 'GaussianBlurNode.horizontal';
this._verticalRT = new RenderTarget( 1, 1, { depthBuffer: false } );
this._verticalRT.texture.name = 'GaussianBlurNode.vertical';
this._textureNode = passTexture( this, this._verticalRT.texture );
this._textureNode.uvNode = textureNode.uvNode;
this.updateBeforeType = NodeUpdateType.FRAME;
this.resolution = new Vector2( 1, 1 );
this.premultipliedAlpha = false;
}
setPremultipliedAlpha( value ) {
this.premultipliedAlpha = value;
return this;
}
getPremultipliedAlpha() {
return this.premultipliedAlpha;
}
setSize( width, height ) {
width = Math.max( Math.round( width * this.resolution.x ), 1 );
height = Math.max( Math.round( height * this.resolution.y ), 1 );
this._invSize.value.set( 1 / width, 1 / height );
this._horizontalRT.setSize( width, height );
this._verticalRT.setSize( width, height );
}
updateBefore( frame ) {
const { renderer } = frame;
_rendererState = PostProcessingUtils.resetRendererState( renderer, _rendererState );
//
const textureNode = this.textureNode;
const map = textureNode.value;
const currentTexture = textureNode.value;
_quadMesh1.material = this._material;
_quadMesh2.material = this._material;
this.setSize( map.image.width, map.image.height );
const textureType = map.type;
this._horizontalRT.texture.type = textureType;
this._verticalRT.texture.type = textureType;
// horizontal
renderer.setRenderTarget( this._horizontalRT );
this._passDirection.value.set( 1, 0 );
_quadMesh1.render( renderer );
// vertical
textureNode.value = this._horizontalRT.texture;
renderer.setRenderTarget( this._verticalRT );
this._passDirection.value.set( 0, 1 );
_quadMesh2.render( renderer );
// restore
textureNode.value = currentTexture;
PostProcessingUtils.restoreRendererState( renderer, _rendererState );
}
getTextureNode() {
return this._textureNode;
}
setup( builder ) {
const textureNode = this.textureNode;
//
const uvNode = textureNode.uvNode || uv();
const directionNode = vec2( this.directionNode || 1 );
let sampleTexture, output;
if ( this.premultipliedAlpha ) {
// https://lisyarus.github.io/blog/posts/blur-coefficients-generator.html
sampleTexture = ( uv ) => premult( textureNode.uv( uv ) );
output = ( color ) => unpremult( color );
} else {
sampleTexture = ( uv ) => textureNode.uv( uv );
output = ( color ) => color;
}
const blur = Fn( () => {
const kernelSize = 3 + ( 2 * this.sigma );
const gaussianCoefficients = this._getCoefficients( kernelSize );
const invSize = this._invSize;
const direction = directionNode.mul( this._passDirection );
const weightSum = float( gaussianCoefficients[ 0 ] ).toVar();
const diffuseSum = vec4( sampleTexture( uvNode ).mul( weightSum ) ).toVar();
for ( let i = 1; i < kernelSize; i ++ ) {
const x = float( i );
const w = float( gaussianCoefficients[ i ] );
const uvOffset = vec2( direction.mul( invSize.mul( x ) ) ).toVar();
const sample1 = sampleTexture( uvNode.add( uvOffset ) );
const sample2 = sampleTexture( uvNode.sub( uvOffset ) );
diffuseSum.addAssign( sample1.add( sample2 ).mul( w ) );
weightSum.addAssign( mul( 2.0, w ) );
}
return output( diffuseSum.div( weightSum ) );
} );
//
const material = this._material || ( this._material = new NodeMaterial() );
material.fragmentNode = blur().context( builder.getSharedContext() );
material.name = 'Gaussian_blur';
material.needsUpdate = true;
//
const properties = builder.getNodeProperties( this );
properties.textureNode = textureNode;
//
return this._textureNode;
}
dispose() {
this._horizontalRT.dispose();
this._verticalRT.dispose();
}
_getCoefficients( kernelRadius ) {
const coefficients = [];
for ( let i = 0; i < kernelRadius; i ++ ) {
coefficients.push( 0.39894 * Math.exp( - 0.5 * i * i / ( kernelRadius * kernelRadius ) ) / kernelRadius );
}
return coefficients;
}
}
export default GaussianBlurNode;
export const gaussianBlur = ( node, directionNode, sigma ) => nodeObject( new GaussianBlurNode( convertToTexture( node ), directionNode, sigma ) );
export const premultipliedGaussianBlur = ( node, directionNode, sigma ) => nodeObject( new GaussianBlurNode( convertToTexture( node ), directionNode, sigma ).setPremultipliedAlpha( true ) );

View File

@@ -0,0 +1,161 @@
import { RenderTarget, Vector2 } from 'three';
import { convertToTexture, TempNode, nodeObject, Fn, NodeUpdateType, QuadMesh, PostProcessingUtils, NodeMaterial, passTexture, uv, vec2, vec3, vec4, max, float, sub, int, Loop, fract, pow, distance } from 'three/tsl';
const _quadMesh = /*@__PURE__*/ new QuadMesh();
const _size = /*@__PURE__*/ new Vector2();
let _rendererState;
/**
* References:
* https://john-chapman-graphics.blogspot.com/2013/02/pseudo-lens-flare.html
* https://john-chapman.github.io/2017/11/05/pseudo-lens-flare.html
*/
class LensflareNode extends TempNode {
static get type() {
return 'LensflareNode';
}
constructor( textureNode, params = {} ) {
super();
this.textureNode = textureNode;
const {
ghostTint = vec3( 1, 1, 1 ),
threshold = float( 0.5 ),
ghostSamples = float( 4 ),
ghostSpacing = float( 0.25 ),
ghostAttenuationFactor = float( 25 ),
downSampleRatio = 4
} = params;
this.ghostTintNode = nodeObject( ghostTint );
this.thresholdNode = nodeObject( threshold );
this.ghostSamplesNode = nodeObject( ghostSamples );
this.ghostSpacingNode = nodeObject( ghostSpacing );
this.ghostAttenuationFactorNode = nodeObject( ghostAttenuationFactor );
this.downSampleRatio = downSampleRatio;
this.updateBeforeType = NodeUpdateType.FRAME;
// render targets
this._renderTarget = new RenderTarget( 1, 1, { depthBuffer: false } );
this._renderTarget.texture.name = 'LensflareNode';
// materials
this._material = new NodeMaterial();
this._material.name = 'LensflareNode';
//
this._textureNode = passTexture( this, this._renderTarget.texture );
}
getTextureNode() {
return this._textureNode;
}
setSize( width, height ) {
const resx = Math.round( width / this.downSampleRatio );
const resy = Math.round( height / this.downSampleRatio );
this._renderTarget.setSize( resx, resy );
}
updateBefore( frame ) {
const { renderer } = frame;
const size = renderer.getDrawingBufferSize( _size );
this.setSize( size.width, size.height );
_rendererState = PostProcessingUtils.resetRendererState( renderer, _rendererState );
_quadMesh.material = this._material;
// clear
renderer.setMRT( null );
// lensflare
renderer.setRenderTarget( this._renderTarget );
_quadMesh.render( renderer );
// restore
PostProcessingUtils.restoreRendererState( renderer, _rendererState );
}
setup( builder ) {
const lensflare = Fn( () => {
// flip uvs so lens flare pivot around the image center
const texCoord = uv().oneMinus().toVar();
// ghosts are positioned along this vector
const ghostVec = sub( vec2( 0.5 ), texCoord ).mul( this.ghostSpacingNode ).toVar();
// sample ghosts
const result = vec4().toVar();
Loop( { start: int( 0 ), end: int( this.ghostSamplesNode ), type: 'int', condition: '<' }, ( { i } ) => {
// use fract() to ensure that the texture coordinates wrap around
const sampleUv = fract( texCoord.add( ghostVec.mul( float( i ) ) ) ).toVar();
// reduce contributions from samples at the screen edge
const d = distance( sampleUv, vec2( 0.5 ) );
const weight = pow( d.oneMinus(), this.ghostAttenuationFactorNode );
// accumulate
let sample = this.textureNode.uv( sampleUv ).rgb;
sample = max( sample.sub( this.thresholdNode ), vec3( 0 ) ).mul( this.ghostTintNode );
result.addAssign( sample.mul( weight ) );
} );
return result;
} );
this._material.fragmentNode = lensflare().context( builder.getSharedContext() );
this._material.needsUpdate = true;
return this._textureNode;
}
dispose() {
this._renderTarget.dispose();
this._material.dispose();
}
}
export default LensflareNode;
export const lensflare = ( inputNode, params ) => nodeObject( new LensflareNode( convertToTexture( inputNode ), params ) );

View File

@@ -0,0 +1,54 @@
import { TempNode, nodeObject, Fn, float, uniform, vec3, vec4, mix } from 'three/tsl';
class Lut3DNode extends TempNode {
static get type() {
return 'Lut3DNode';
}
constructor( inputNode, lutNode, size, intensityNode ) {
super();
this.inputNode = inputNode;
this.lutNode = lutNode;
this.size = uniform( size );
this.intensityNode = intensityNode;
}
setup() {
const { inputNode, lutNode } = this;
const sampleLut = ( uv ) => lutNode.uv( uv );
const lut3D = Fn( () => {
const base = inputNode;
// pull the sample in by half a pixel so the sample begins at the center of the edge pixels.
const pixelWidth = float( 1.0 ).div( this.size );
const halfPixelWidth = float( 0.5 ).div( this.size );
const uvw = vec3( halfPixelWidth ).add( base.rgb.mul( float( 1.0 ).sub( pixelWidth ) ) );
const lutValue = vec4( sampleLut( uvw ).rgb, base.a );
return vec4( mix( base, lutValue, this.intensityNode ) );
} );
const outputNode = lut3D();
return outputNode;
}
}
export default Lut3DNode;
export const lut3D = ( node, lut, size, intensity ) => nodeObject( new Lut3DNode( nodeObject( node ), nodeObject( lut ), size, nodeObject( intensity ) ) );

View File

@@ -0,0 +1,24 @@
import { Fn, float, uv, Loop, int } from 'three/tsl';
export const motionBlur = /*@__PURE__*/ Fn( ( [ inputNode, velocity, numSamples = int( 16 ) ] ) => {
const sampleColor = ( uv ) => inputNode.uv( uv );
const uvs = uv();
const colorResult = sampleColor( uvs ).toVar();
const fSamples = float( numSamples );
Loop( { start: int( 1 ), end: numSamples, type: 'int', condition: '<=' }, ( { i } ) => {
const offset = velocity.mul( float( i ).div( fSamples.sub( 1 ) ).sub( 0.5 ) );
colorResult.addAssign( sampleColor( uvs.add( offset ) ) );
} );
colorResult.divAssign( fSamples );
return colorResult;
} );

View File

@@ -0,0 +1,434 @@
import { Color, DepthTexture, FloatType, RenderTarget, Vector2, PostProcessingUtils } from 'three';
import { Loop, int, exp, min, float, mul, uv, vec2, vec3, Fn, textureSize, orthographicDepthToViewZ, QuadMesh, screenUV, TempNode, nodeObject, NodeUpdateType, uniform, vec4, NodeMaterial, passTexture, texture, perspectiveDepthToViewZ, positionView } from 'three/tsl';
const _quadMesh = /*@__PURE__*/ new QuadMesh();
const _size = /*@__PURE__*/ new Vector2();
const _BLUR_DIRECTION_X = /*@__PURE__*/ new Vector2( 1.0, 0.0 );
const _BLUR_DIRECTION_Y = /*@__PURE__*/ new Vector2( 0.0, 1.0 );
let _rendererState;
class OutlineNode extends TempNode {
static get type() {
return 'OutlineNode';
}
constructor( scene, camera, params = {} ) {
super( 'vec4' );
const {
selectedObjects = [],
edgeThickness = float( 1 ),
edgeGlow = float( 0 ),
downSampleRatio = 2
} = params;
this.scene = scene;
this.camera = camera;
this.selectedObjects = selectedObjects;
this.edgeThicknessNode = nodeObject( edgeThickness );
this.edgeGlowNode = nodeObject( edgeGlow );
this.downSampleRatio = downSampleRatio;
this.updateBeforeType = NodeUpdateType.FRAME;
// render targets
this._renderTargetDepthBuffer = new RenderTarget();
this._renderTargetDepthBuffer.depthTexture = new DepthTexture();
this._renderTargetDepthBuffer.depthTexture.type = FloatType;
this._renderTargetMaskBuffer = new RenderTarget();
this._renderTargetMaskDownSampleBuffer = new RenderTarget( 1, 1, { depthBuffer: false } );
this._renderTargetEdgeBuffer1 = new RenderTarget( 1, 1, { depthBuffer: false } );
this._renderTargetEdgeBuffer2 = new RenderTarget( 1, 1, { depthBuffer: false } );
this._renderTargetBlurBuffer1 = new RenderTarget( 1, 1, { depthBuffer: false } );
this._renderTargetBlurBuffer2 = new RenderTarget( 1, 1, { depthBuffer: false } );
this._renderTargetComposite = new RenderTarget( 1, 1, { depthBuffer: false } );
// uniforms
this._cameraNear = uniform( camera.near );
this._cameraFar = uniform( camera.far );
this._blurDirection = uniform( new Vector2() );
this._depthTextureUniform = texture( this._renderTargetDepthBuffer.depthTexture );
this._maskTextureUniform = texture( this._renderTargetMaskBuffer.texture );
this._maskTextureDownsSampleUniform = texture( this._renderTargetMaskDownSampleBuffer.texture );
this._edge1TextureUniform = texture( this._renderTargetEdgeBuffer1.texture );
this._edge2TextureUniform = texture( this._renderTargetEdgeBuffer2.texture );
this._blurColorTextureUniform = texture( this._renderTargetEdgeBuffer1.texture );
// constants
this._visibleEdgeColor = vec3( 1, 0, 0 );
this._hiddenEdgeColor = vec3( 0, 1, 0 );
// materials
this._depthMaterial = new NodeMaterial();
this._depthMaterial.fragmentNode = vec4( 0, 0, 0, 1 );
this._depthMaterial.name = 'OutlineNode.depth';
this._prepareMaskMaterial = new NodeMaterial();
this._prepareMaskMaterial.name = 'OutlineNode.prepareMask';
this._materialCopy = new NodeMaterial();
this._materialCopy.name = 'OutlineNode.copy';
this._edgeDetectionMaterial = new NodeMaterial();
this._edgeDetectionMaterial.name = 'OutlineNode.edgeDetection';
this._separableBlurMaterial = new NodeMaterial();
this._separableBlurMaterial.name = 'OutlineNode.separableBlur';
this._separableBlurMaterial2 = new NodeMaterial();
this._separableBlurMaterial2.name = 'OutlineNode.separableBlur2';
this._compositeMaterial = new NodeMaterial();
this._compositeMaterial.name = 'OutlineNode.composite';
//
this._selectionCache = new Set();
this._tempPulseColor1 = new Color();
this._tempPulseColor2 = new Color();
//
this._textureNode = passTexture( this, this._renderTargetComposite.texture );
}
get visibleEdge() {
return this.r;
}
get hiddenEdge() {
return this.g;
}
getTextureNode() {
return this._textureNode;
}
setSize( width, height ) {
this._renderTargetDepthBuffer.setSize( width, height );
this._renderTargetMaskBuffer.setSize( width, height );
this._renderTargetComposite.setSize( width, height );
// downsample 1
let resx = Math.round( width / this.downSampleRatio );
let resy = Math.round( height / this.downSampleRatio );
this._renderTargetMaskDownSampleBuffer.setSize( resx, resy );
this._renderTargetEdgeBuffer1.setSize( resx, resy );
this._renderTargetBlurBuffer1.setSize( resx, resy );
// downsample 2
resx = Math.round( resx / 2 );
resy = Math.round( resy / 2 );
this._renderTargetEdgeBuffer2.setSize( resx, resy );
this._renderTargetBlurBuffer2.setSize( resx, resy );
}
updateBefore( frame ) {
const { renderer } = frame;
const { camera, scene } = this;
_rendererState = PostProcessingUtils.resetRendererAndSceneState( renderer, scene, _rendererState );
//
const size = renderer.getDrawingBufferSize( _size );
this.setSize( size.width, size.height );
//
renderer.setClearColor( 0xffffff, 1 );
this._updateSelectionCache();
// 1. Draw non-selected objects in the depth buffer
scene.overrideMaterial = this._depthMaterial;
renderer.setRenderTarget( this._renderTargetDepthBuffer );
renderer.setRenderObjectFunction( ( object, ...params ) => {
if ( this._selectionCache.has( object ) === false ) {
renderer.renderObject( object, ...params );
}
} );
renderer.render( scene, camera );
// 2. Draw only the selected objects by comparing the depth buffer of non-selected objects
scene.overrideMaterial = this._prepareMaskMaterial;
renderer.setRenderTarget( this._renderTargetMaskBuffer );
renderer.setRenderObjectFunction( ( object, ...params ) => {
if ( this._selectionCache.has( object ) === true ) {
renderer.renderObject( object, ...params );
}
} );
renderer.render( scene, camera );
//
renderer.setRenderObjectFunction( _rendererState.renderObjectFunction );
this._selectionCache.clear();
// 3. Downsample to (at least) half resolution
_quadMesh.material = this._materialCopy;
renderer.setRenderTarget( this._renderTargetMaskDownSampleBuffer );
_quadMesh.render( renderer );
// 4. Perform edge detection (half resolution)
_quadMesh.material = this._edgeDetectionMaterial;
renderer.setRenderTarget( this._renderTargetEdgeBuffer1 );
_quadMesh.render( renderer );
// 5. Apply blur (half resolution)
this._blurColorTextureUniform.value = this._renderTargetEdgeBuffer1.texture;
this._blurDirection.value.copy( _BLUR_DIRECTION_X );
_quadMesh.material = this._separableBlurMaterial;
renderer.setRenderTarget( this._renderTargetBlurBuffer1 );
_quadMesh.render( renderer );
this._blurColorTextureUniform.value = this._renderTargetBlurBuffer1.texture;
this._blurDirection.value.copy( _BLUR_DIRECTION_Y );
renderer.setRenderTarget( this._renderTargetEdgeBuffer1 );
_quadMesh.render( renderer );
// 6. Apply blur (quarter resolution)
this._blurColorTextureUniform.value = this._renderTargetEdgeBuffer1.texture;
this._blurDirection.value.copy( _BLUR_DIRECTION_X );
_quadMesh.material = this._separableBlurMaterial2;
renderer.setRenderTarget( this._renderTargetBlurBuffer2 );
_quadMesh.render( renderer );
this._blurColorTextureUniform.value = this._renderTargetBlurBuffer2.texture;
this._blurDirection.value.copy( _BLUR_DIRECTION_Y );
renderer.setRenderTarget( this._renderTargetEdgeBuffer2 );
_quadMesh.render( renderer );
// 7. Composite
_quadMesh.material = this._compositeMaterial;
renderer.setRenderTarget( this._renderTargetComposite );
_quadMesh.render( renderer );
// restore
PostProcessingUtils.restoreRendererAndSceneState( renderer, scene, _rendererState );
}
setup() {
// prepare mask material
const prepareMask = () => {
const depth = this._depthTextureUniform.uv( screenUV );
let viewZNode;
if ( this.camera.isPerspectiveCamera ) {
viewZNode = perspectiveDepthToViewZ( depth, this._cameraNear, this._cameraFar );
} else {
viewZNode = orthographicDepthToViewZ( depth, this._cameraNear, this._cameraFar );
}
const depthTest = positionView.z.lessThanEqual( viewZNode ).select( 1, 0 );
return vec4( 0.0, depthTest, 1.0, 1.0 );
};
this._prepareMaskMaterial.fragmentNode = prepareMask();
this._prepareMaskMaterial.needsUpdate = true;
// copy material
this._materialCopy.fragmentNode = this._maskTextureUniform;
this._materialCopy.needsUpdate = true;
// edge detection material
const edgeDetection = Fn( () => {
const resolution = textureSize( this._maskTextureDownsSampleUniform );
const invSize = vec2( 1 ).div( resolution ).toVar();
const uvOffset = vec4( 1.0, 0.0, 0.0, 1.0 ).mul( vec4( invSize, invSize ) );
const uvNode = uv();
const c1 = this._maskTextureDownsSampleUniform.uv( uvNode.add( uvOffset.xy ) ).toVar();
const c2 = this._maskTextureDownsSampleUniform.uv( uvNode.sub( uvOffset.xy ) ).toVar();
const c3 = this._maskTextureDownsSampleUniform.uv( uvNode.add( uvOffset.yw ) ).toVar();
const c4 = this._maskTextureDownsSampleUniform.uv( uvNode.sub( uvOffset.yw ) ).toVar();
const diff1 = mul( c1.r.sub( c2.r ), 0.5 );
const diff2 = mul( c3.r.sub( c4.r ), 0.5 );
const d = vec2( diff1, diff2 ).length();
const a1 = min( c1.g, c2.g );
const a2 = min( c3.g, c4.g );
const visibilityFactor = min( a1, a2 );
const edgeColor = visibilityFactor.oneMinus().greaterThan( 0.001 ).select( this._visibleEdgeColor, this._hiddenEdgeColor );
return vec4( edgeColor, 1 ).mul( d );
} );
this._edgeDetectionMaterial.fragmentNode = edgeDetection();
this._edgeDetectionMaterial.needsUpdate = true;
// seperable blur material
const MAX_RADIUS = 4;
const gaussianPdf = Fn( ( [ x, sigma ] ) => {
return float( 0.39894 ).mul( exp( float( - 0.5 ).mul( x ).mul( x ).div( sigma.mul( sigma ) ) ).div( sigma ) );
} );
const seperableBlur = Fn( ( [ kernelRadius ] ) => {
const resolution = textureSize( this._maskTextureDownsSampleUniform );
const invSize = vec2( 1 ).div( resolution ).toVar();
const uvNode = uv();
const sigma = kernelRadius.div( 2 ).toVar();
const weightSum = gaussianPdf( 0, sigma ).toVar();
const diffuseSum = this._blurColorTextureUniform.uv( uvNode ).mul( weightSum ).toVar();
const delta = this._blurDirection.mul( invSize ).mul( kernelRadius ).div( MAX_RADIUS ).toVar();
const uvOffset = delta.toVar();
Loop( { start: int( 1 ), end: int( MAX_RADIUS ), type: 'int', condition: '<=' }, ( { i } ) => {
const x = kernelRadius.mul( float( i ) ).div( MAX_RADIUS );
const w = gaussianPdf( x, sigma );
const sample1 = this._blurColorTextureUniform.uv( uvNode.add( uvOffset ) );
const sample2 = this._blurColorTextureUniform.uv( uvNode.sub( uvOffset ) );
diffuseSum.addAssign( sample1.add( sample2 ).mul( w ) );
weightSum.addAssign( w.mul( 2 ) );
uvOffset.addAssign( delta );
} );
return diffuseSum.div( weightSum );
} );
this._separableBlurMaterial.fragmentNode = seperableBlur( this.edgeThicknessNode );
this._separableBlurMaterial.needsUpdate = true;
this._separableBlurMaterial2.fragmentNode = seperableBlur( MAX_RADIUS );
this._separableBlurMaterial2.needsUpdate = true;
// composite material
const composite = Fn( () => {
const edgeValue1 = this._edge1TextureUniform;
const edgeValue2 = this._edge2TextureUniform;
const maskColor = this._maskTextureUniform;
const edgeValue = edgeValue1.add( edgeValue2.mul( this.edgeGlowNode ) );
return maskColor.r.mul( edgeValue );
} );
this._compositeMaterial.fragmentNode = composite();
this._compositeMaterial.needsUpdate = true;
return this._textureNode;
}
dispose() {
this.selectedObjects.length = 0;
this._renderTargetDepthBuffer.dispose();
this._renderTargetMaskBuffer.dispose();
this._renderTargetMaskDownSampleBuffer.dispose();
this._renderTargetEdgeBuffer1.dispose();
this._renderTargetEdgeBuffer2.dispose();
this._renderTargetBlurBuffer1.dispose();
this._renderTargetBlurBuffer2.dispose();
this._renderTargetComposite.dispose();
this._depthMaterial.dispose();
this._prepareMaskMaterial.dispose();
this._materialCopy.dispose();
this._edgeDetectionMaterial.dispose();
this._separableBlurMaterial.dispose();
this._separableBlurMaterial2.dispose();
this._compositeMaterial.dispose();
}
//
_updateSelectionCache() {
for ( let i = 0; i < this.selectedObjects.length; i ++ ) {
const selectedObject = this.selectedObjects[ i ];
selectedObject.traverse( ( object ) => {
if ( object.isMesh ) this._selectionCache.add( object );
} );
}
}
}
export default OutlineNode;
export const outline = ( scene, camera, params ) => nodeObject( new OutlineNode( scene, camera, params ) );

View File

@@ -0,0 +1,54 @@
import { nodeObject, Fn, vec4, uv, NodeMaterial, If, mod, screenCoordinate } from 'three/tsl';
import StereoCompositePassNode from './StereoCompositePassNode.js';
class ParallaxBarrierPassNode extends StereoCompositePassNode {
static get type() {
return 'ParallaxBarrierPassNode';
}
constructor( scene, camera ) {
super( scene, camera );
this.isParallaxBarrierPassNode = true;
}
setup( builder ) {
const uvNode = uv();
const parallaxBarrier = Fn( () => {
const color = vec4().toVar();
If( mod( screenCoordinate.y, 2 ).greaterThan( 1 ), () => {
color.assign( this._mapLeft.uv( uvNode ) );
} ).Else( () => {
color.assign( this._mapRight.uv( uvNode ) );
} );
return color;
} );
const material = this._material || ( this._material = new NodeMaterial() );
material.fragmentNode = parallaxBarrier().context( builder.getSharedContext() );
material.needsUpdate = true;
return super.setup( builder );
}
}
export default ParallaxBarrierPassNode;
export const parallaxBarrierPass = ( scene, camera ) => nodeObject( new ParallaxBarrierPassNode( scene, camera ) );

View File

@@ -0,0 +1,201 @@
import { NearestFilter, Vector4 } from 'three';
import { TempNode, nodeObject, Fn, float, NodeUpdateType, uv, uniform, convertToTexture, vec2, vec3, clamp, floor, dot, smoothstep, If, sign, step, mrt, output, normalView, PassNode, property } from 'three/tsl';
class PixelationNode extends TempNode {
static get type() {
return 'PixelationNode';
}
constructor( textureNode, depthNode, normalNode, pixelSize, normalEdgeStrength, depthEdgeStrength ) {
super();
// Input textures
this.textureNode = textureNode;
this.depthNode = depthNode;
this.normalNode = normalNode;
// Input uniforms
this.pixelSize = pixelSize;
this.normalEdgeStrength = normalEdgeStrength;
this.depthEdgeStrength = depthEdgeStrength;
// Private uniforms
this._resolution = uniform( new Vector4() );
this.updateBeforeType = NodeUpdateType.FRAME;
}
updateBefore() {
const map = this.textureNode.value;
const width = map.image.width;
const height = map.image.height;
this._resolution.value.set( width, height, 1 / width, 1 / height );
}
setup() {
const { textureNode, depthNode, normalNode } = this;
const uvNodeTexture = textureNode.uvNode || uv();
const uvNodeDepth = depthNode.uvNode || uv();
const uvNodeNormal = normalNode.uvNode || uv();
const sampleTexture = () => textureNode.uv( uvNodeTexture );
const sampleDepth = ( x, y ) => depthNode.uv( uvNodeDepth.add( vec2( x, y ).mul( this._resolution.zw ) ) ).r;
const sampleNormal = ( x, y ) => normalNode.uv( uvNodeNormal.add( vec2( x, y ).mul( this._resolution.zw ) ) ).rgb.normalize();
const depthEdgeIndicator = ( depth ) => {
const diff = property( 'float', 'diff' );
diff.addAssign( clamp( sampleDepth( 1, 0 ).sub( depth ) ) );
diff.addAssign( clamp( sampleDepth( - 1, 0 ).sub( depth ) ) );
diff.addAssign( clamp( sampleDepth( 0, 1 ).sub( depth ) ) );
diff.addAssign( clamp( sampleDepth( 0, - 1 ).sub( depth ) ) );
return floor( smoothstep( 0.01, 0.02, diff ).mul( 2 ) ).div( 2 );
};
const neighborNormalEdgeIndicator = ( x, y, depth, normal ) => {
const depthDiff = sampleDepth( x, y ).sub( depth );
const neighborNormal = sampleNormal( x, y );
// Edge pixels should yield to faces who's normals are closer to the bias normal.
const normalEdgeBias = vec3( 1, 1, 1 ); // This should probably be a parameter.
const normalDiff = dot( normal.sub( neighborNormal ), normalEdgeBias );
const normalIndicator = clamp( smoothstep( - 0.01, 0.01, normalDiff ), 0.0, 1.0 );
// Only the shallower pixel should detect the normal edge.
const depthIndicator = clamp( sign( depthDiff.mul( .25 ).add( .0025 ) ), 0.0, 1.0 );
return float( 1.0 ).sub( dot( normal, neighborNormal ) ).mul( depthIndicator ).mul( normalIndicator );
};
const normalEdgeIndicator = ( depth, normal ) => {
const indicator = property( 'float', 'indicator' );
indicator.addAssign( neighborNormalEdgeIndicator( 0, - 1, depth, normal ) );
indicator.addAssign( neighborNormalEdgeIndicator( 0, 1, depth, normal ) );
indicator.addAssign( neighborNormalEdgeIndicator( - 1, 0, depth, normal ) );
indicator.addAssign( neighborNormalEdgeIndicator( 1, 0, depth, normal ) );
return step( 0.1, indicator );
};
const pixelation = Fn( () => {
const texel = sampleTexture();
const depth = property( 'float', 'depth' );
const normal = property( 'vec3', 'normal' );
If( this.depthEdgeStrength.greaterThan( 0.0 ).or( this.normalEdgeStrength.greaterThan( 0.0 ) ), () => {
depth.assign( sampleDepth( 0, 0 ) );
normal.assign( sampleNormal( 0, 0 ) );
} );
const dei = property( 'float', 'dei' );
If( this.depthEdgeStrength.greaterThan( 0.0 ), () => {
dei.assign( depthEdgeIndicator( depth ) );
} );
const nei = property( 'float', 'nei' );
If( this.normalEdgeStrength.greaterThan( 0.0 ), () => {
nei.assign( normalEdgeIndicator( depth, normal ) );
} );
const strength = dei.greaterThan( 0 ).select( float( 1.0 ).sub( dei.mul( this.depthEdgeStrength ) ), nei.mul( this.normalEdgeStrength ).add( 1 ) );
return texel.mul( strength );
} );
const outputNode = pixelation();
return outputNode;
}
}
const pixelation = ( node, depthNode, normalNode, pixelSize = 6, normalEdgeStrength = 0.3, depthEdgeStrength = 0.4 ) => nodeObject( new PixelationNode( convertToTexture( node ), convertToTexture( depthNode ), convertToTexture( normalNode ), nodeObject( pixelSize ), nodeObject( normalEdgeStrength ), nodeObject( depthEdgeStrength ) ) );
class PixelationPassNode extends PassNode {
static get type() {
return 'PixelationPassNode';
}
constructor( scene, camera, pixelSize = 6, normalEdgeStrength = 0.3, depthEdgeStrength = 0.4 ) {
super( 'color', scene, camera, { minFilter: NearestFilter, magFilter: NearestFilter } );
this.pixelSize = pixelSize;
this.normalEdgeStrength = normalEdgeStrength;
this.depthEdgeStrength = depthEdgeStrength;
this.isPixelationPassNode = true;
this._mrt = mrt( {
output: output,
normal: normalView
} );
}
setSize( width, height ) {
const pixelSize = this.pixelSize.value ? this.pixelSize.value : this.pixelSize;
const adjustedWidth = Math.floor( width / pixelSize );
const adjustedHeight = Math.floor( height / pixelSize );
super.setSize( adjustedWidth, adjustedHeight );
}
setup() {
const color = super.getTextureNode( 'output' );
const depth = super.getTextureNode( 'depth' );
const normal = super.getTextureNode( 'normal' );
return pixelation( color, depth, normal, this.pixelSize, this.normalEdgeStrength, this.depthEdgeStrength );
}
}
export const pixelationPass = ( scene, camera, pixelSize, normalEdgeStrength, depthEdgeStrength ) => nodeObject( new PixelationPassNode( scene, camera, pixelSize, normalEdgeStrength, depthEdgeStrength ) );
export default PixelationPassNode;

View File

@@ -0,0 +1,48 @@
import { TempNode, nodeObject, Fn, uv, uniform, vec2, sin, cos, vec4, convertToTexture } from 'three/tsl';
class RGBShiftNode extends TempNode {
static get type() {
return 'RGBShiftNode';
}
constructor( textureNode, amount = 0.005, angle = 0 ) {
super( 'vec4' );
this.textureNode = textureNode;
this.amount = uniform( amount );
this.angle = uniform( angle );
}
setup() {
const { textureNode } = this;
const uvNode = textureNode.uvNode || uv();
const sampleTexture = ( uv ) => textureNode.uv( uv );
const rgbShift = Fn( () => {
const offset = vec2( cos( this.angle ), sin( this.angle ) ).mul( this.amount );
const cr = sampleTexture( uvNode.add( offset ) );
const cga = sampleTexture( uvNode );
const cb = sampleTexture( uvNode.sub( offset ) );
return vec4( cr.r, cga.g, cb.b, cga.a );
} );
return rgbShift();
}
}
export default RGBShiftNode;
export const rgbShift = ( node, amount, angle ) => nodeObject( new RGBShiftNode( convertToTexture( node ), amount, angle ) );

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,272 @@
import { AdditiveBlending, Color, Vector2, PostProcessingUtils } from 'three';
import { nodeObject, uniform, mrt, PassNode, QuadMesh, texture, NodeMaterial, getTextureIndex } from 'three/tsl';
const _size = /*@__PURE__*/ new Vector2();
let _rendererState;
/**
*
* Supersample Anti-Aliasing Render Pass
*
* This manual approach to SSAA re-renders the scene ones for each sample with camera jitter and accumulates the results.
*
* References: https://en.wikipedia.org/wiki/Supersampling
*
*/
class SSAAPassNode extends PassNode {
static get type() {
return 'SSAAPassNode';
}
constructor( scene, camera ) {
super( PassNode.COLOR, scene, camera );
this.isSSAAPassNode = true;
this.sampleLevel = 4; // specified as n, where the number of samples is 2^n, so sampleLevel = 4, is 2^4 samples, 16.
this.unbiased = true;
this.clearColor = new Color( 0x000000 );
this.clearAlpha = 0;
this.sampleWeight = uniform( 1 );
this.sampleRenderTarget = null;
this._quadMesh = new QuadMesh();
}
updateBefore( frame ) {
const { renderer } = frame;
const { scene, camera } = this;
_rendererState = PostProcessingUtils.resetRendererAndSceneState( renderer, scene, _rendererState );
//
this._pixelRatio = renderer.getPixelRatio();
const size = renderer.getSize( _size );
this.setSize( size.width, size.height );
this.sampleRenderTarget.setSize( this.renderTarget.width, this.renderTarget.height );
//
this._cameraNear.value = camera.near;
this._cameraFar.value = camera.far;
renderer.setMRT( this.getMRT() );
renderer.autoClear = false;
const jitterOffsets = _JitterVectors[ Math.max( 0, Math.min( this.sampleLevel, 5 ) ) ];
const baseSampleWeight = 1.0 / jitterOffsets.length;
const roundingRange = 1 / 32;
const viewOffset = {
fullWidth: this.renderTarget.width,
fullHeight: this.renderTarget.height,
offsetX: 0,
offsetY: 0,
width: this.renderTarget.width,
height: this.renderTarget.height
};
const originalViewOffset = Object.assign( {}, camera.view );
if ( originalViewOffset.enabled ) Object.assign( viewOffset, originalViewOffset );
// render the scene multiple times, each slightly jitter offset from the last and accumulate the results.
for ( let i = 0; i < jitterOffsets.length; i ++ ) {
const jitterOffset = jitterOffsets[ i ];
if ( camera.setViewOffset ) {
camera.setViewOffset(
viewOffset.fullWidth, viewOffset.fullHeight,
viewOffset.offsetX + jitterOffset[ 0 ] * 0.0625, viewOffset.offsetY + jitterOffset[ 1 ] * 0.0625, // 0.0625 = 1 / 16
viewOffset.width, viewOffset.height
);
}
this.sampleWeight.value = baseSampleWeight;
if ( this.unbiased ) {
// the theory is that equal weights for each sample lead to an accumulation of rounding errors.
// The following equation varies the sampleWeight per sample so that it is uniformly distributed
// across a range of values whose rounding errors cancel each other out.
const uniformCenteredDistribution = ( - 0.5 + ( i + 0.5 ) / jitterOffsets.length );
this.sampleWeight.value += roundingRange * uniformCenteredDistribution;
}
renderer.setClearColor( this.clearColor, this.clearAlpha );
renderer.setRenderTarget( this.sampleRenderTarget );
renderer.clear();
renderer.render( scene, camera );
// accumulation
renderer.setRenderTarget( this.renderTarget );
if ( i === 0 ) {
renderer.setClearColor( 0x000000, 0.0 );
renderer.clear();
}
this._quadMesh.render( renderer );
}
renderer.copyTextureToTexture( this.sampleRenderTarget.depthTexture, this.renderTarget.depthTexture );
// restore
if ( camera.setViewOffset && originalViewOffset.enabled ) {
camera.setViewOffset(
originalViewOffset.fullWidth, originalViewOffset.fullHeight,
originalViewOffset.offsetX, originalViewOffset.offsetY,
originalViewOffset.width, originalViewOffset.height
);
} else if ( camera.clearViewOffset ) {
camera.clearViewOffset();
}
//
PostProcessingUtils.restoreRendererAndSceneState( renderer, scene, _rendererState );
}
setup( builder ) {
if ( this.sampleRenderTarget === null ) {
this.sampleRenderTarget = this.renderTarget.clone();
}
let sampleTexture;
const passMRT = this.getMRT();
if ( passMRT !== null ) {
const outputs = {};
for ( const name in passMRT.outputNodes ) {
const index = getTextureIndex( this.sampleRenderTarget.textures, name );
if ( index >= 0 ) {
outputs[ name ] = texture( this.sampleRenderTarget.textures[ index ] ).mul( this.sampleWeight );
}
}
sampleTexture = mrt( outputs );
} else {
sampleTexture = texture( this.sampleRenderTarget.texture ).mul( this.sampleWeight );
}
this._quadMesh.material = new NodeMaterial();
this._quadMesh.material.fragmentNode = sampleTexture;
this._quadMesh.material.transparent = true;
this._quadMesh.material.depthTest = false;
this._quadMesh.material.depthWrite = false;
this._quadMesh.material.premultipliedAlpha = true;
this._quadMesh.material.blending = AdditiveBlending;
this._quadMesh.material.name = 'SSAA';
return super.setup( builder );
}
dispose() {
super.dispose();
if ( this.sampleRenderTarget !== null ) {
this.sampleRenderTarget.dispose();
}
}
}
export default SSAAPassNode;
// These jitter vectors are specified in integers because it is easier.
// I am assuming a [-8,8) integer grid, but it needs to be mapped onto [-0.5,0.5)
// before being used, thus these integers need to be scaled by 1/16.
//
// Sample patterns reference: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476218%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
const _JitterVectors = [
[
[ 0, 0 ]
],
[
[ 4, 4 ], [ - 4, - 4 ]
],
[
[ - 2, - 6 ], [ 6, - 2 ], [ - 6, 2 ], [ 2, 6 ]
],
[
[ 1, - 3 ], [ - 1, 3 ], [ 5, 1 ], [ - 3, - 5 ],
[ - 5, 5 ], [ - 7, - 1 ], [ 3, 7 ], [ 7, - 7 ]
],
[
[ 1, 1 ], [ - 1, - 3 ], [ - 3, 2 ], [ 4, - 1 ],
[ - 5, - 2 ], [ 2, 5 ], [ 5, 3 ], [ 3, - 5 ],
[ - 2, 6 ], [ 0, - 7 ], [ - 4, - 6 ], [ - 6, 4 ],
[ - 8, 0 ], [ 7, - 4 ], [ 6, 7 ], [ - 7, - 8 ]
],
[
[ - 4, - 7 ], [ - 7, - 5 ], [ - 3, - 5 ], [ - 5, - 4 ],
[ - 1, - 4 ], [ - 2, - 2 ], [ - 6, - 1 ], [ - 4, 0 ],
[ - 7, 1 ], [ - 1, 2 ], [ - 6, 3 ], [ - 3, 3 ],
[ - 7, 6 ], [ - 3, 6 ], [ - 5, 7 ], [ - 1, 7 ],
[ 5, - 7 ], [ 1, - 6 ], [ 6, - 5 ], [ 4, - 4 ],
[ 2, - 3 ], [ 7, - 2 ], [ 1, - 1 ], [ 4, - 1 ],
[ 2, 1 ], [ 6, 2 ], [ 0, 4 ], [ 4, 4 ],
[ 2, 5 ], [ 7, 5 ], [ 5, 6 ], [ 3, 7 ]
]
];
export const ssaaPass = ( scene, camera ) => nodeObject( new SSAAPassNode( scene, camera ) );

View File

@@ -0,0 +1,343 @@
import { NearestFilter, RenderTarget, Vector2, PostProcessingUtils } from 'three';
import { getScreenPosition, getViewPosition, sqrt, mul, div, cross, float, Continue, Break, Loop, int, max, abs, sub, If, dot, reflect, normalize, screenCoordinate, QuadMesh, TempNode, nodeObject, Fn, NodeUpdateType, passTexture, NodeMaterial, uv, uniform, perspectiveDepthToViewZ, orthographicDepthToViewZ, vec2, vec3, vec4 } from 'three/tsl';
const _quadMesh = /*@__PURE__*/ new QuadMesh();
const _size = /*@__PURE__*/ new Vector2();
let _rendererState;
/**
* References:
* https://lettier.github.io/3d-game-shaders-for-beginners/screen-space-reflection.html
*/
class SSRNode extends TempNode {
static get type() {
return 'SSRNode';
}
constructor( colorNode, depthNode, normalNode, metalnessNode, camera ) {
super();
this.colorNode = colorNode;
this.depthNode = depthNode;
this.normalNode = normalNode;
this.metalnessNode = metalnessNode;
this.camera = camera;
this.resolutionScale = 0.5;
this.updateBeforeType = NodeUpdateType.FRAME;
// render targets
this._ssrRenderTarget = new RenderTarget( 1, 1, { depthBuffer: false, minFilter: NearestFilter, magFilter: NearestFilter } );
this._ssrRenderTarget.texture.name = 'SSRNode.SSR';
// uniforms
this.maxDistance = uniform( 1 ); // controls how far a fragment can reflect
this.thickness = uniform( 0.1 ); // controls the cutoff between what counts as a possible reflection hit and what does not
this.opacity = uniform( 1 ); // controls the transparency of the reflected colors
this._cameraNear = uniform( camera.near );
this._cameraFar = uniform( camera.far );
this._cameraProjectionMatrix = uniform( camera.projectionMatrix );
this._cameraProjectionMatrixInverse = uniform( camera.projectionMatrixInverse );
this._isPerspectiveCamera = uniform( camera.isPerspectiveCamera ? 1 : 0 );
this._resolution = uniform( new Vector2() );
this._maxStep = uniform( 0 );
// materials
this._material = new NodeMaterial();
this._material.name = 'SSRNode.SSR';
//
this._textureNode = passTexture( this, this._ssrRenderTarget.texture );
}
getTextureNode() {
return this._textureNode;
}
setSize( width, height ) {
width = Math.round( this.resolutionScale * width );
height = Math.round( this.resolutionScale * height );
this._resolution.value.set( width, height );
this._maxStep.value = Math.round( Math.sqrt( width * width + height * height ) );
this._ssrRenderTarget.setSize( width, height );
}
updateBefore( frame ) {
const { renderer } = frame;
_rendererState = PostProcessingUtils.resetRendererState( renderer, _rendererState );
const size = renderer.getDrawingBufferSize( _size );
_quadMesh.material = this._material;
this.setSize( size.width, size.height );
// clear
renderer.setMRT( null );
renderer.setClearColor( 0x000000, 0 );
// ssr
renderer.setRenderTarget( this._ssrRenderTarget );
_quadMesh.render( renderer );
// restore
PostProcessingUtils.restoreRendererState( renderer, _rendererState );
}
setup( builder ) {
const uvNode = uv();
const pointToLineDistance = Fn( ( [ point, linePointA, linePointB ] )=> {
// https://mathworld.wolfram.com/Point-LineDistance3-Dimensional.html
return cross( point.sub( linePointA ), point.sub( linePointB ) ).length().div( linePointB.sub( linePointA ).length() );
} );
const pointPlaneDistance = Fn( ( [ point, planePoint, planeNormal ] )=> {
// https://mathworld.wolfram.com/Point-PlaneDistance.html
// https://en.wikipedia.org/wiki/Plane_(geometry)
// http://paulbourke.net/geometry/pointlineplane/
const d = mul( planeNormal.x, planePoint.x ).add( mul( planeNormal.y, planePoint.y ) ).add( mul( planeNormal.z, planePoint.z ) ).negate().toVar();
const denominator = sqrt( mul( planeNormal.x, planeNormal.x, ).add( mul( planeNormal.y, planeNormal.y ) ).add( mul( planeNormal.z, planeNormal.z ) ) ).toVar();
const distance = div( mul( planeNormal.x, point.x ).add( mul( planeNormal.y, point.y ) ).add( mul( planeNormal.z, point.z ) ).add( d ), denominator );
return distance;
} );
const getViewZ = Fn( ( [ depth ] ) => {
let viewZNode;
if ( this.camera.isPerspectiveCamera ) {
viewZNode = perspectiveDepthToViewZ( depth, this._cameraNear, this._cameraFar );
} else {
viewZNode = orthographicDepthToViewZ( depth, this._cameraNear, this._cameraFar );
}
return viewZNode;
} );
const ssr = Fn( () => {
const metalness = this.metalnessNode.uv( uvNode ).r;
// fragments with no metalness do not reflect their environment
metalness.equal( 0.0 ).discard();
// compute some standard FX entities
const depth = this.depthNode.uv( uvNode ).r.toVar();
const viewPosition = getViewPosition( uvNode, depth, this._cameraProjectionMatrixInverse ).toVar();
const viewNormal = this.normalNode.rgb.normalize().toVar();
// compute the direction from the position in view space to the camera
const viewIncidentDir = ( ( this.camera.isPerspectiveCamera ) ? normalize( viewPosition ) : vec3( 0, 0, - 1 ) ).toVar();
// compute the direction in which the light is reflected on the surface
const viewReflectDir = reflect( viewIncidentDir, viewNormal ).toVar();
// adapt maximum distance to the local geometry (see https://www.mathsisfun.com/algebra/vectors-dot-product.html)
const maxReflectRayLen = this.maxDistance.div( dot( viewIncidentDir.negate(), viewNormal ) ).toVar();
// compute the maximum point of the reflection ray in view space
const d1viewPosition = viewPosition.add( viewReflectDir.mul( maxReflectRayLen ) ).toVar();
// check if d1viewPosition lies behind the camera near plane
If( this._isPerspectiveCamera.equal( float( 1 ) ).and( d1viewPosition.z.greaterThan( this._cameraNear.negate() ) ), () => {
// if so, ensure d1viewPosition is clamped on the near plane.
// this prevents artifacts during the ray marching process
const t = sub( this._cameraNear.negate(), viewPosition.z ).div( viewReflectDir.z );
d1viewPosition.assign( viewPosition.add( viewReflectDir.mul( t ) ) );
} );
// d0 and d1 are the start and maximum points of the reflection ray in screen space
const d0 = screenCoordinate.xy.toVar();
const d1 = getScreenPosition( d1viewPosition, this._cameraProjectionMatrix ).mul( this._resolution ).toVar();
// below variables are used to control the raymarching process
// total length of the ray
const totalLen = d1.sub( d0 ).length().toVar();
// offset in x and y direction
const xLen = d1.x.sub( d0.x ).toVar();
const yLen = d1.y.sub( d0.y ).toVar();
// determine the larger delta
// The larger difference will help to determine how much to travel in the X and Y direction each iteration and
// how many iterations are needed to travel the entire ray
const totalStep = max( abs( xLen ), abs( yLen ) ).toVar();
// step sizes in the x and y directions
const xSpan = xLen.div( totalStep ).toVar();
const ySpan = yLen.div( totalStep ).toVar();
const output = vec4( 0 ).toVar();
// the actual ray marching loop
// starting from d0, the code gradually travels along the ray and looks for an intersection with the geometry.
// it does not exceed d1 (the maximum ray extend)
Loop( { start: int( 0 ), end: int( this._maxStep ), type: 'int', condition: '<' }, ( { i } ) => {
// stop if the maximum number of steps is reached for this specific ray
If( float( i ).greaterThanEqual( totalStep ), () => {
Break();
} );
// advance on the ray by computing a new position in screen space
const xy = vec2( d0.x.add( xSpan.mul( float( i ) ) ), d0.y.add( ySpan.mul( float( i ) ) ) ).toVar();
// stop processing if the new position lies outside of the screen
If( xy.x.lessThan( 0 ).or( xy.x.greaterThan( this._resolution.x ) ).or( xy.y.lessThan( 0 ) ).or( xy.y.greaterThan( this._resolution.y ) ), () => {
Break();
} );
// compute new uv, depth, viewZ and viewPosition for the new location on the ray
const uvNode = xy.div( this._resolution );
const d = this.depthNode.uv( uvNode ).r.toVar();
const vZ = getViewZ( d ).toVar();
const vP = getViewPosition( uvNode, d, this._cameraProjectionMatrixInverse ).toVar();
const viewReflectRayZ = float( 0 ).toVar();
// normalized distance between the current position xy and the starting point d0
const s = xy.sub( d0 ).length().div( totalLen );
// depending on the camera type, we now compute the z-coordinate of the reflected ray at the current step in view space
If( this._isPerspectiveCamera.equal( float( 1 ) ), () => {
const recipVPZ = float( 1 ).div( viewPosition.z ).toVar();
viewReflectRayZ.assign( float( 1 ).div( recipVPZ.add( s.mul( float( 1 ).div( d1viewPosition.z ).sub( recipVPZ ) ) ) ) );
} ).Else( () => {
viewReflectRayZ.assign( viewPosition.z.add( s.mul( d1viewPosition.z.sub( viewPosition.z ) ) ) );
} );
// if viewReflectRayZ is less or equal than the real z-coordinate at this place, it potentially intersects the geometry
If( viewReflectRayZ.lessThanEqual( vZ ), () => {
// compute the distance of the new location to the ray in view space
// to clarify vP is the fragment's view position which is not an exact point on the ray
const away = pointToLineDistance( vP, viewPosition, d1viewPosition ).toVar();
// compute the minimum thickness between the current fragment and its neighbor in the x-direction.
const xyNeighbor = vec2( xy.x.add( 1 ), xy.y ).toVar(); // move one pixel
const uvNeighbor = xyNeighbor.div( this._resolution );
const vPNeighbor = getViewPosition( uvNeighbor, d, this._cameraProjectionMatrixInverse ).toVar();
const minThickness = vPNeighbor.x.sub( vP.x ).toVar();
minThickness.mulAssign( 3 ); // expand a bit to avoid errors
const tk = max( minThickness, this.thickness ).toVar();
If( away.lessThanEqual( tk ), () => { // hit
const vN = this.normalNode.uv( uvNode ).rgb.normalize().toVar();
If( dot( viewReflectDir, vN ).greaterThanEqual( 0 ), () => {
// the reflected ray is pointing towards the same side as the fragment's normal (current ray position),
// which means it wouldn't reflect off the surface. The loop continues to the next step for the next ray sample.
Continue();
} );
// this distance represents the depth of the intersection point between the reflected ray and the scene.
const distance = pointPlaneDistance( vP, viewPosition, viewNormal ).toVar();
If( distance.greaterThan( this.maxDistance ), () => {
// Distance exceeding limit: The reflection is potentially too far away and
// might not contribute significantly to the final color
Break();
} );
const op = this.opacity.mul( metalness ).toVar();
// distance attenuation (the reflection should fade out the farther it is away from the surface)
const ratio = float( 1 ).sub( distance.div( this.maxDistance ) ).toVar();
const attenuation = ratio.mul( ratio );
op.mulAssign( attenuation );
// fresnel (reflect more light on surfaces that are viewed at grazing angles)
const fresnelCoe = div( dot( viewIncidentDir, viewReflectDir ).add( 1 ), 2 );
op.mulAssign( fresnelCoe );
// output
const reflectColor = this.colorNode.uv( uvNode );
output.assign( vec4( reflectColor.rgb, op ) );
Break();
} );
} );
} );
return output;
} );
this._material.fragmentNode = ssr().context( builder.getSharedContext() );
this._material.needsUpdate = true;
//
return this._textureNode;
}
dispose() {
this._ssrRenderTarget.dispose();
this._material.dispose();
}
}
export default SSRNode;
export const ssr = ( colorNode, depthNode, normalNode, metalnessNode, camera ) => nodeObject( new SSRNode( nodeObject( colorNode ), nodeObject( depthNode ), nodeObject( normalNode ), nodeObject( metalnessNode ), camera ) );

View File

@@ -0,0 +1,16 @@
import { dot, Fn, vec3, vec4 } from 'three/tsl';
export const sepia = /*@__PURE__*/ Fn( ( [ color ] ) => {
const c = vec3( color );
// https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/sepia.js
return vec4(
dot( c, vec3( 0.393, 0.769, 0.189 ) ),
dot( c, vec3( 0.349, 0.686, 0.168 ) ),
dot( c, vec3( 0.272, 0.534, 0.131 ) ),
color.a
);
} );

View File

@@ -0,0 +1,118 @@
import { Vector2 } from 'three';
import { TempNode, nodeObject, Fn, NodeUpdateType, uv, uniform, convertToTexture, vec2, vec3, vec4, mat3, luminance, add } from 'three/tsl';
class SobelOperatorNode extends TempNode {
static get type() {
return 'SobelOperatorNode';
}
constructor( textureNode ) {
super();
this.textureNode = textureNode;
this.updateBeforeType = NodeUpdateType.FRAME;
this._invSize = uniform( new Vector2() );
}
updateBefore() {
const map = this.textureNode.value;
this._invSize.value.set( 1 / map.image.width, 1 / map.image.height );
}
setup() {
const { textureNode } = this;
const uvNode = textureNode.uvNode || uv();
const sampleTexture = ( uv ) => textureNode.uv( uv );
const sobel = Fn( () => {
// Sobel Edge Detection (see https://youtu.be/uihBwtPIBxM)
const texel = this._invSize;
// kernel definition (in glsl matrices are filled in column-major order)
const Gx = mat3( - 1, - 2, - 1, 0, 0, 0, 1, 2, 1 ); // x direction kernel
const Gy = mat3( - 1, 0, 1, - 2, 0, 2, - 1, 0, 1 ); // y direction kernel
// fetch the 3x3 neighbourhood of a fragment
// first column
const tx0y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, - 1 ) ) ) ).xyz );
const tx0y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, 0 ) ) ) ).xyz );
const tx0y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, 1 ) ) ) ).xyz );
// second column
const tx1y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, - 1 ) ) ) ).xyz );
const tx1y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, 0 ) ) ) ).xyz );
const tx1y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, 1 ) ) ) ).xyz );
// third column
const tx2y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, - 1 ) ) ) ).xyz );
const tx2y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, 0 ) ) ) ).xyz );
const tx2y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, 1 ) ) ) ).xyz );
// gradient value in x direction
const valueGx = add(
Gx[ 0 ][ 0 ].mul( tx0y0 ),
Gx[ 1 ][ 0 ].mul( tx1y0 ),
Gx[ 2 ][ 0 ].mul( tx2y0 ),
Gx[ 0 ][ 1 ].mul( tx0y1 ),
Gx[ 1 ][ 1 ].mul( tx1y1 ),
Gx[ 2 ][ 1 ].mul( tx2y1 ),
Gx[ 0 ][ 2 ].mul( tx0y2 ),
Gx[ 1 ][ 2 ].mul( tx1y2 ),
Gx[ 2 ][ 2 ].mul( tx2y2 )
);
// gradient value in y direction
const valueGy = add(
Gy[ 0 ][ 0 ].mul( tx0y0 ),
Gy[ 1 ][ 0 ].mul( tx1y0 ),
Gy[ 2 ][ 0 ].mul( tx2y0 ),
Gy[ 0 ][ 1 ].mul( tx0y1 ),
Gy[ 1 ][ 1 ].mul( tx1y1 ),
Gy[ 2 ][ 1 ].mul( tx2y1 ),
Gy[ 0 ][ 2 ].mul( tx0y2 ),
Gy[ 1 ][ 2 ].mul( tx1y2 ),
Gy[ 2 ][ 2 ].mul( tx2y2 )
);
// magnitute of the total gradient
const G = valueGx.mul( valueGx ).add( valueGy.mul( valueGy ) ).sqrt();
return vec4( vec3( G ), 1 );
} );
const outputNode = sobel();
return outputNode;
}
}
export default SobelOperatorNode;
export const sobel = ( node ) => nodeObject( new SobelOperatorNode( convertToTexture( node ) ) );

View File

@@ -0,0 +1,108 @@
import { RenderTarget, StereoCamera, HalfFloatType, LinearFilter, NearestFilter, Vector2, PostProcessingUtils } from 'three';
import { PassNode, QuadMesh, texture } from 'three/tsl';
const _size = /*@__PURE__*/ new Vector2();
const _quadMesh = /*@__PURE__*/ new QuadMesh();
let _rendererState;
class StereoCompositePassNode extends PassNode {
static get type() {
return 'StereoCompositePassNode';
}
constructor( scene, camera ) {
super( PassNode.COLOR, scene, camera );
this.isStereoCompositePassNode = true;
this.stereo = new StereoCamera();
const _params = { minFilter: LinearFilter, magFilter: NearestFilter, type: HalfFloatType };
this._renderTargetL = new RenderTarget( 1, 1, _params );
this._renderTargetR = new RenderTarget( 1, 1, _params );
this._mapLeft = texture( this._renderTargetL.texture );
this._mapRight = texture( this._renderTargetR.texture );
this._material = null;
}
updateStereoCamera( coordinateSystem ) {
this.stereo.cameraL.coordinateSystem = coordinateSystem;
this.stereo.cameraR.coordinateSystem = coordinateSystem;
this.stereo.update( this.camera );
}
setSize( width, height ) {
super.setSize( width, height );
this._renderTargetL.setSize( this.renderTarget.width, this.renderTarget.height );
this._renderTargetR.setSize( this.renderTarget.width, this.renderTarget.height );
}
updateBefore( frame ) {
const { renderer } = frame;
const { scene, stereo, renderTarget } = this;
_rendererState = PostProcessingUtils.resetRendererAndSceneState( renderer, scene, _rendererState );
//
this._pixelRatio = renderer.getPixelRatio();
this.updateStereoCamera( renderer.coordinateSystem );
const size = renderer.getSize( _size );
this.setSize( size.width, size.height );
// left
renderer.setRenderTarget( this._renderTargetL );
renderer.render( scene, stereo.cameraL );
// right
renderer.setRenderTarget( this._renderTargetR );
renderer.render( scene, stereo.cameraR );
// composite
renderer.setRenderTarget( renderTarget );
_quadMesh.material = this._material;
_quadMesh.render( renderer );
// restore
PostProcessingUtils.restoreRendererState( renderer, scene, _rendererState );
}
dispose() {
super.dispose();
this._renderTargetL.dispose();
this._renderTargetR.dispose();
if ( this._material !== null ) {
this._material.dispose();
}
}
}
export default StereoCompositePassNode;

View File

@@ -0,0 +1,82 @@
import { StereoCamera, Vector2, PostProcessingUtils } from 'three';
import { PassNode, nodeObject } from 'three/tsl';
const _size = /*@__PURE__*/ new Vector2();
let _rendererState;
class StereoPassNode extends PassNode {
static get type() {
return 'StereoPassNode';
}
constructor( scene, camera ) {
super( PassNode.COLOR, scene, camera );
this.isStereoPassNode = true;
this.stereo = new StereoCamera();
this.stereo.aspect = 0.5;
}
updateBefore( frame ) {
const { renderer } = frame;
const { scene, camera, stereo, renderTarget } = this;
_rendererState = PostProcessingUtils.resetRendererState( renderer, _rendererState );
//
this._pixelRatio = renderer.getPixelRatio();
stereo.cameraL.coordinateSystem = renderer.coordinateSystem;
stereo.cameraR.coordinateSystem = renderer.coordinateSystem;
stereo.update( camera );
const size = renderer.getSize( _size );
this.setSize( size.width, size.height );
renderer.autoClear = false;
this._cameraNear.value = camera.near;
this._cameraFar.value = camera.far;
for ( const name in this._previousTextures ) {
this.toggleTexture( name );
}
renderer.setRenderTarget( renderTarget );
renderer.setMRT( this._mrt );
renderer.clear();
renderTarget.scissorTest = true;
renderTarget.scissor.set( 0, 0, renderTarget.width / 2, renderTarget.height );
renderTarget.viewport.set( 0, 0, renderTarget.width / 2, renderTarget.height );
renderer.render( scene, stereo.cameraL );
renderTarget.scissor.set( renderTarget.width / 2, 0, renderTarget.width / 2, renderTarget.height );
renderTarget.viewport.set( renderTarget.width / 2, 0, renderTarget.width / 2, renderTarget.height );
renderer.render( scene, stereo.cameraR );
renderTarget.scissorTest = false;
// restore
PostProcessingUtils.restoreRendererState( renderer, _rendererState );
}
}
export default StereoPassNode;
export const stereoPass = ( scene, camera ) => nodeObject( new StereoPassNode( scene, camera ) );

View File

@@ -0,0 +1,355 @@
import { Color, Vector2, PostProcessingUtils, NearestFilter, Matrix4 } from 'three';
import { add, float, If, Loop, int, Fn, min, max, clamp, nodeObject, PassNode, QuadMesh, texture, NodeMaterial, uniform, uv, vec2, vec4, luminance } from 'three/tsl';
const _quadMesh = /*@__PURE__*/ new QuadMesh();
const _size = /*@__PURE__*/ new Vector2();
let _rendererState;
/**
* Temporal Reprojection Anti-Aliasing (TRAA).
*
* References:
* https://alextardif.com/TAA.html
* https://www.elopezr.com/temporal-aa-and-the-quest-for-the-holy-trail/
*
*/
class TRAAPassNode extends PassNode {
static get type() {
return 'TRAAPassNode';
}
constructor( scene, camera ) {
super( PassNode.COLOR, scene, camera );
this.isTRAAPassNode = true;
this.clearColor = new Color( 0x000000 );
this.clearAlpha = 0;
this._jitterIndex = 0;
this._originalProjectionMatrix = new Matrix4();
// uniforms
this._invSize = uniform( new Vector2() );
// render targets
this._sampleRenderTarget = null;
this._historyRenderTarget = null;
// materials
this._resolveMaterial = new NodeMaterial();
this._resolveMaterial.name = 'TRAA.Resolve';
}
setSize( width, height ) {
super.setSize( width, height );
let needsRestart = false;
if ( this.renderTarget.width !== this._sampleRenderTarget.width || this.renderTarget.height !== this._sampleRenderTarget.height ) {
this._sampleRenderTarget.setSize( this.renderTarget.width, this.renderTarget.height );
this._historyRenderTarget.setSize( this.renderTarget.width, this.renderTarget.height );
this._invSize.value.set( 1 / this.renderTarget.width, 1 / this.renderTarget.height );
needsRestart = true;
}
return needsRestart;
}
updateBefore( frame ) {
const { renderer } = frame;
const { scene, camera } = this;
_rendererState = PostProcessingUtils.resetRendererAndSceneState( renderer, scene, _rendererState );
//
this._pixelRatio = renderer.getPixelRatio();
const size = renderer.getSize( _size );
const needsRestart = this.setSize( size.width, size.height );
// save original/unjittered projection matrix for velocity pass
camera.updateProjectionMatrix();
this._originalProjectionMatrix.copy( camera.projectionMatrix );
// camera configuration
this._cameraNear.value = camera.near;
this._cameraFar.value = camera.far;
// configure jitter as view offset
const viewOffset = {
fullWidth: this.renderTarget.width,
fullHeight: this.renderTarget.height,
offsetX: 0,
offsetY: 0,
width: this.renderTarget.width,
height: this.renderTarget.height
};
const originalViewOffset = Object.assign( {}, camera.view );
if ( originalViewOffset.enabled ) Object.assign( viewOffset, originalViewOffset );
const jitterOffset = _JitterVectors[ this._jitterIndex ];
camera.setViewOffset(
viewOffset.fullWidth, viewOffset.fullHeight,
viewOffset.offsetX + jitterOffset[ 0 ] * 0.0625, viewOffset.offsetY + jitterOffset[ 1 ] * 0.0625, // 0.0625 = 1 / 16
viewOffset.width, viewOffset.height
);
// configure velocity
const mrt = this.getMRT();
const velocityOutput = mrt.get( 'velocity' );
if ( velocityOutput !== undefined ) {
velocityOutput.setProjectionMatrix( this._originalProjectionMatrix );
} else {
throw new Error( 'THREE:TRAAPassNode: Missing velocity output in MRT configuration.' );
}
// render sample
renderer.setMRT( mrt );
renderer.setClearColor( this.clearColor, this.clearAlpha );
renderer.setRenderTarget( this._sampleRenderTarget );
renderer.render( scene, camera );
renderer.setRenderTarget( null );
renderer.setMRT( null );
// every time when the dimensions change we need fresh history data. Copy the sample
// into the history and final render target (no AA happens at that point).
if ( needsRestart === true ) {
// bind and clear render target to make sure they are initialized after the resize which triggers a dispose()
renderer.setRenderTarget( this._historyRenderTarget );
renderer.clear();
renderer.setRenderTarget( this.renderTarget );
renderer.clear();
renderer.setRenderTarget( null );
renderer.copyTextureToTexture( this._sampleRenderTarget.texture, this._historyRenderTarget.texture );
renderer.copyTextureToTexture( this._sampleRenderTarget.texture, this.renderTarget.texture );
} else {
// resolve
renderer.setRenderTarget( this.renderTarget );
_quadMesh.material = this._resolveMaterial;
_quadMesh.render( renderer );
renderer.setRenderTarget( null );
// update history
renderer.copyTextureToTexture( this.renderTarget.texture, this._historyRenderTarget.texture );
}
// copy depth
renderer.copyTextureToTexture( this._sampleRenderTarget.depthTexture, this.renderTarget.depthTexture );
// update jitter index
this._jitterIndex ++;
this._jitterIndex = this._jitterIndex % ( _JitterVectors.length - 1 );
// restore
if ( originalViewOffset.enabled ) {
camera.setViewOffset(
originalViewOffset.fullWidth, originalViewOffset.fullHeight,
originalViewOffset.offsetX, originalViewOffset.offsetY,
originalViewOffset.width, originalViewOffset.height
);
} else {
camera.clearViewOffset();
}
velocityOutput.setProjectionMatrix( null );
PostProcessingUtils.restoreRendererAndSceneState( renderer, scene, _rendererState );
}
setup( builder ) {
if ( this._sampleRenderTarget === null ) {
this._sampleRenderTarget = this.renderTarget.clone();
this._historyRenderTarget = this.renderTarget.clone();
this._sampleRenderTarget.texture.minFiler = NearestFilter;
this._sampleRenderTarget.texture.magFilter = NearestFilter;
const velocityTarget = this._sampleRenderTarget.texture.clone();
velocityTarget.isRenderTargetTexture = true;
velocityTarget.name = 'velocity';
this._sampleRenderTarget.textures.push( velocityTarget ); // for MRT
}
// textures
const historyTexture = texture( this._historyRenderTarget.texture );
const sampleTexture = texture( this._sampleRenderTarget.textures[ 0 ] );
const velocityTexture = texture( this._sampleRenderTarget.textures[ 1 ] );
const depthTexture = texture( this._sampleRenderTarget.depthTexture );
const resolve = Fn( () => {
const uvNode = uv();
const minColor = vec4( 10000 ).toVar();
const maxColor = vec4( - 10000 ).toVar();
const closestDepth = float( 1 ).toVar();
const closestDepthPixelPosition = vec2( 0 ).toVar();
// sample a 3x3 neighborhood to create a box in color space
// clamping the history color with the resulting min/max colors mitigates ghosting
Loop( { start: int( - 1 ), end: int( 1 ), type: 'int', condition: '<=', name: 'x' }, ( { x } ) => {
Loop( { start: int( - 1 ), end: int( 1 ), type: 'int', condition: '<=', name: 'y' }, ( { y } ) => {
const uvNeighbor = uvNode.add( vec2( float( x ), float( y ) ).mul( this._invSize ) ).toVar();
const colorNeighbor = max( vec4( 0 ), sampleTexture.uv( uvNeighbor ) ).toVar(); // use max() to avoid propagate garbage values
minColor.assign( min( minColor, colorNeighbor ) );
maxColor.assign( max( maxColor, colorNeighbor ) );
const currentDepth = depthTexture.uv( uvNeighbor ).r.toVar();
// find the sample position of the closest depth in the neighborhood (used for velocity)
If( currentDepth.lessThan( closestDepth ), () => {
closestDepth.assign( currentDepth );
closestDepthPixelPosition.assign( uvNeighbor );
} );
} );
} );
// sampling/reprojection
const offset = velocityTexture.uv( closestDepthPixelPosition ).xy.mul( vec2( 0.5, - 0.5 ) ); // NDC to uv offset
const currentColor = sampleTexture.uv( uvNode );
const historyColor = historyTexture.uv( uvNode.sub( offset ) );
// clamping
const clampedHistoryColor = clamp( historyColor, minColor, maxColor );
// flicker reduction based on luminance weighing
const currentWeight = float( 0.05 ).toVar();
const historyWeight = currentWeight.oneMinus().toVar();
const compressedCurrent = currentColor.mul( float( 1 ).div( ( max( max( currentColor.r, currentColor.g ), currentColor.b ).add( 1.0 ) ) ) );
const compressedHistory = clampedHistoryColor.mul( float( 1 ).div( ( max( max( clampedHistoryColor.r, clampedHistoryColor.g ), clampedHistoryColor.b ).add( 1.0 ) ) ) );
const luminanceCurrent = luminance( compressedCurrent.rgb );
const luminanceHistory = luminance( compressedHistory.rgb );
currentWeight.mulAssign( float( 1.0 ).div( luminanceCurrent.add( 1 ) ) );
historyWeight.mulAssign( float( 1.0 ).div( luminanceHistory.add( 1 ) ) );
return add( currentColor.mul( currentWeight ), clampedHistoryColor.mul( historyWeight ) ).div( max( currentWeight.add( historyWeight ), 0.00001 ) );
} );
// materials
this._resolveMaterial.fragmentNode = resolve();
return super.setup( builder );
}
dispose() {
super.dispose();
if ( this._sampleRenderTarget !== null ) {
this._sampleRenderTarget.dispose();
this._historyRenderTarget.dispose();
}
this._resolveMaterial.dispose();
}
}
export default TRAAPassNode;
// These jitter vectors are specified in integers because it is easier.
// I am assuming a [-8,8) integer grid, but it needs to be mapped onto [-0.5,0.5)
// before being used, thus these integers need to be scaled by 1/16.
//
// Sample patterns reference: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476218%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
const _JitterVectors = [
[ - 4, - 7 ], [ - 7, - 5 ], [ - 3, - 5 ], [ - 5, - 4 ],
[ - 1, - 4 ], [ - 2, - 2 ], [ - 6, - 1 ], [ - 4, 0 ],
[ - 7, 1 ], [ - 1, 2 ], [ - 6, 3 ], [ - 3, 3 ],
[ - 7, 6 ], [ - 3, 6 ], [ - 5, 7 ], [ - 1, 7 ],
[ 5, - 7 ], [ 1, - 6 ], [ 6, - 5 ], [ 4, - 4 ],
[ 2, - 3 ], [ 7, - 2 ], [ 1, - 1 ], [ 4, - 1 ],
[ 2, 1 ], [ 6, 2 ], [ 0, 4 ], [ 4, 4 ],
[ 2, 5 ], [ 7, 5 ], [ 5, 6 ], [ 3, 7 ]
];
export const traaPass = ( scene, camera ) => nodeObject( new TRAAPassNode( scene, camera ) );

View File

@@ -0,0 +1,75 @@
import { TempNode, nodeObject, Fn, float, uv, convertToTexture, vec4, If, int, clamp, sub, mix } from 'three/tsl';
class TransitionNode extends TempNode {
static get type() {
return 'TransitionNode';
}
constructor( textureNodeA, textureNodeB, mixTextureNode, mixRatioNode, thresholdNode, useTextureNode ) {
super();
// Input textures
this.textureNodeA = textureNodeA;
this.textureNodeB = textureNodeB;
this.mixTextureNode = mixTextureNode;
// Uniforms
this.mixRatioNode = mixRatioNode;
this.thresholdNode = thresholdNode;
this.useTextureNode = useTextureNode;
}
setup() {
const { textureNodeA, textureNodeB, mixTextureNode, mixRatioNode, thresholdNode, useTextureNode } = this;
const sampleTexture = ( textureNode ) => {
const uvNodeTexture = textureNode.uvNode || uv();
return textureNode.uv( uvNodeTexture );
};
const transition = Fn( () => {
const texelOne = sampleTexture( textureNodeA );
const texelTwo = sampleTexture( textureNodeB );
const color = vec4().toVar();
If( useTextureNode.equal( int( 1 ) ), () => {
const transitionTexel = sampleTexture( mixTextureNode );
const r = mixRatioNode.mul( thresholdNode.mul( 2.0 ).add( 1.0 ) ).sub( thresholdNode );
const mixf = clamp( sub( transitionTexel.r, r ).mul( float( 1.0 ).div( thresholdNode ) ), 0.0, 1.0 );
color.assign( mix( texelOne, texelTwo, mixf ) );
} ).Else( () => {
color.assign( mix( texelTwo, texelOne, mixRatioNode ) );
} );
return color;
} );
const outputNode = transition();
return outputNode;
}
}
export default TransitionNode;
export const transition = ( nodeA, nodeB, mixTexture, mixRatio = 0.0, threshold = 0.1, useTexture = 0 ) => nodeObject( new TransitionNode( convertToTexture( nodeA ), convertToTexture( nodeB ), convertToTexture( mixTexture ), nodeObject( mixRatio ), nodeObject( threshold ), nodeObject( useTexture ) ) );

View File

@@ -0,0 +1,24 @@
import { float, Fn, vec2, uv, sin, rand, degrees, cos, Loop, vec4 } from 'three/tsl';
// https://www.shadertoy.com/view/4lXXWn
export const hashBlur = /*#__PURE__*/ Fn( ( [ textureNode, bluramount = float( 0.1 ), repeats = float( 45 ) ] ) => {
const draw = ( uv ) => textureNode.uv( uv );
const targetUV = textureNode.uvNode || uv();
const blurred_image = vec4( 0. ).toVar();
Loop( { start: 0., end: repeats, type: 'float' }, ( { i } ) => {
const q = vec2( vec2( cos( degrees( i.div( repeats ).mul( 360. ) ) ), sin( degrees( i.div( repeats ).mul( 360. ) ) ) ).mul( rand( vec2( i, targetUV.x.add( targetUV.y ) ) ).add( bluramount ) ) );
const uv2 = vec2( targetUV.add( q.mul( bluramount ) ) );
blurred_image.addAssign( draw( uv2 ) );
} );
blurred_image.divAssign( repeats );
return blurred_image;
} );

View File

@@ -0,0 +1,392 @@
import {
storageObject, nodeProxy, int, float, vec2, ivec2, ivec4, uniform, Break, Loop,
Fn, If, Return, textureLoad, instanceIndex, screenCoordinate, directPointLight
} from 'three/tsl';
import { DataTexture, FloatType, LightsNode, NodeUpdateType, RGBAFormat, StorageBufferAttribute, Vector2, Vector3 } from 'three';
export const circleIntersectsAABB = /*@__PURE__*/ Fn( ( [ circleCenter, radius, minBounds, maxBounds ] ) => {
// Find the closest point on the AABB to the circle's center using method chaining
const closestX = minBounds.x.max( circleCenter.x.min( maxBounds.x ) );
const closestY = minBounds.y.max( circleCenter.y.min( maxBounds.y ) );
// Compute the distance between the circle's center and the closest point
const distX = circleCenter.x.sub( closestX );
const distY = circleCenter.y.sub( closestY );
// Calculate the squared distance
const distSquared = distX.mul( distX ).add( distY.mul( distY ) );
return distSquared.lessThanEqual( radius.mul( radius ) );
} ).setLayout( {
name: 'circleIntersectsAABB',
type: 'bool',
inputs: [
{ name: 'circleCenter', type: 'vec2' },
{ name: 'radius', type: 'float' },
{ name: 'minBounds', type: 'vec2' },
{ name: 'maxBounds', type: 'vec2' }
]
} );
const _vector3 = /*@__PURE__*/ new Vector3();
const _size = /*@__PURE__*/ new Vector2();
class TiledLightsNode extends LightsNode {
static get type() {
return 'TiledLightsNode';
}
constructor( maxLights = 1024, tileSize = 32 ) {
super();
this.materialLights = [];
this.tiledLights = [];
this.maxLights = maxLights;
this.tileSize = tileSize;
this.bufferSize = null;
this.lightIndexes = null;
this.screenTileIndex = null;
this.compute = null;
this.lightsTexture = null;
this.lightsCount = uniform( 0, 'int' );
this.tileLightCount = 8;
this.screenSize = uniform( new Vector2() );
this.cameraProjectionMatrix = uniform( 'mat4' );
this.cameraViewMatrix = uniform( 'mat4' );
this.updateBeforeType = NodeUpdateType.RENDER;
}
updateLightsTexture() {
const { lightsTexture, tiledLights } = this;
const data = lightsTexture.image.data;
const lineSize = lightsTexture.image.width * 4;
this.lightsCount.value = tiledLights.length;
for ( let i = 0; i < tiledLights.length; i ++ ) {
const light = tiledLights[ i ];
// world position
_vector3.setFromMatrixPosition( light.matrixWorld );
// store data
const offset = i * 4;
data[ offset + 0 ] = _vector3.x;
data[ offset + 1 ] = _vector3.y;
data[ offset + 2 ] = _vector3.z;
data[ offset + 3 ] = light.distance;
data[ lineSize + offset + 0 ] = light.color.r * light.intensity;
data[ lineSize + offset + 1 ] = light.color.g * light.intensity;
data[ lineSize + offset + 2 ] = light.color.b * light.intensity;
data[ lineSize + offset + 3 ] = light.decay;
}
lightsTexture.needsUpdate = true;
}
updateBefore( frame ) {
const { renderer, camera } = frame;
this.updateProgram( renderer );
this.updateLightsTexture( camera );
this.cameraProjectionMatrix.value = camera.projectionMatrix;
this.cameraViewMatrix.value = camera.matrixWorldInverse;
renderer.getDrawingBufferSize( _size );
this.screenSize.value.copy( _size );
renderer.compute( this.compute );
}
setLights( lights ) {
const { tiledLights, materialLights } = this;
let materialindex = 0;
let tiledIndex = 0;
for ( const light of lights ) {
if ( light.isPointLight === true ) {
tiledLights[ tiledIndex ++ ] = light;
} else {
materialLights[ materialindex ++ ] = light;
}
}
materialLights.length = materialindex;
tiledLights.length = tiledIndex;
return super.setLights( materialLights );
}
getBlock( block = 0 ) {
return this.lightIndexes.element( this.screenTileIndex.mul( int( 2 ).add( int( block ) ) ) );
}
getTile( element ) {
element = int( element );
const stride = int( 4 );
const tileOffset = element.div( stride );
const tileIndex = this.screenTileIndex.mul( int( 2 ) ).add( tileOffset );
return this.lightIndexes.element( tileIndex ).element( element.modInt( stride ) );
}
getLightData( index ) {
index = int( index );
const dataA = textureLoad( this.lightsTexture, ivec2( index, 0 ) );
const dataB = textureLoad( this.lightsTexture, ivec2( index, 1 ) );
const position = dataA.xyz;
const viewPosition = this.cameraViewMatrix.mul( position );
const distance = dataA.w;
const color = dataB.rgb;
const decay = dataB.w;
return {
position,
viewPosition,
distance,
color,
decay
};
}
setupLights( builder, lightNodes ) {
this.updateProgram( builder.renderer );
//
const lightingModel = builder.context.reflectedLight;
// force declaration order, before of the loop
lightingModel.directDiffuse.append();
lightingModel.directSpecular.append();
Fn( () => {
Loop( this.tileLightCount, ( { i } ) => {
const lightIndex = this.getTile( i );
If( lightIndex.equal( int( 0 ) ), () => {
Break();
} );
const { color, decay, viewPosition, distance } = this.getLightData( lightIndex.sub( 1 ) );
directPointLight( {
color,
lightViewPosition: viewPosition,
cutoffDistance: distance,
decayExponent: decay
} ).append();
} );
} )().append();
// others lights
super.setupLights( builder, lightNodes );
}
getBufferFitSize( value ) {
const multiple = this.tileSize;
return Math.ceil( value / multiple ) * multiple;
}
setSize( width, height ) {
width = this.getBufferFitSize( width );
height = this.getBufferFitSize( height );
if ( ! this.bufferSize || this.bufferSize.width !== width || this.bufferSize.height !== height ) {
this.create( width, height );
}
return this;
}
updateProgram( renderer ) {
renderer.getDrawingBufferSize( _size );
const width = this.getBufferFitSize( _size.width );
const height = this.getBufferFitSize( _size.height );
if ( this.bufferSize === null ) {
this.create( width, height );
} else if ( this.bufferSize.width !== width || this.bufferSize.height !== height ) {
this.create( width, height );
}
}
create( width, height ) {
const { tileSize, maxLights } = this;
const bufferSize = new Vector2( width, height );
const lineSize = Math.floor( bufferSize.width / tileSize );
const count = Math.floor( ( bufferSize.width * bufferSize.height ) / tileSize );
// buffers
const lightsData = new Float32Array( maxLights * 4 * 2 ); // 2048 lights, 4 elements(rgba), 2 components, 1 component per line (position, distance, color, decay)
const lightsTexture = new DataTexture( lightsData, lightsData.length / 8, 2, RGBAFormat, FloatType );
const lightIndexesArray = new Int32Array( count * 4 * 2 );
const lightIndexesAttribute = new StorageBufferAttribute( lightIndexesArray, 4 );
const lightIndexes = storageObject( lightIndexesAttribute, 'ivec4', lightIndexesAttribute.count ).label( 'lightIndexes' );
// compute
const getBlock = ( index ) => {
const tileIndex = instanceIndex.mul( int( 2 ) ).add( int( index ) );
return lightIndexes.element( tileIndex );
};
const getTile = ( elementIndex ) => {
elementIndex = int( elementIndex );
const stride = int( 4 );
const tileOffset = elementIndex.div( stride );
const tileIndex = instanceIndex.mul( int( 2 ) ).add( tileOffset );
return lightIndexes.element( tileIndex ).element( elementIndex.modInt( stride ) );
};
const compute = Fn( () => {
const { cameraProjectionMatrix, bufferSize, screenSize } = this;
const tiledBufferSize = bufferSize.clone().divideScalar( tileSize ).floor();
const tileScreen = vec2(
instanceIndex.modInt( tiledBufferSize.width ),
instanceIndex.div( tiledBufferSize.width )
).mul( tileSize ).div( screenSize );
const blockSize = float( tileSize ).div( screenSize );
const minBounds = tileScreen;
const maxBounds = minBounds.add( blockSize );
const index = int( 0 ).toVar();
getBlock( 0 ).assign( ivec4( 0 ) );
getBlock( 1 ).assign( ivec4( 0 ) );
Loop( this.maxLights, ( { i } ) => {
If( index.greaterThanEqual( this.tileLightCount ).or( int( i ).greaterThanEqual( int( this.lightsCount ) ) ), () => {
Return();
} );
const { viewPosition, distance } = this.getLightData( i );
const projectedPosition = cameraProjectionMatrix.mul( viewPosition );
const ndc = projectedPosition.div( projectedPosition.w );
const screenPosition = ndc.xy.mul( 0.5 ).add( 0.5 ).flipY();
const distanceFromCamera = viewPosition.z;
const pointRadius = distance.div( distanceFromCamera );
If( circleIntersectsAABB( screenPosition, pointRadius, minBounds, maxBounds ), () => {
getTile( index ).assign( i.add( int( 1 ) ) );
index.addAssign( int( 1 ) );
} );
} );
} )().compute( count );
// screen coordinate lighting indexes
const screenTile = screenCoordinate.div( tileSize ).floor().toVar();
const screenTileIndex = screenTile.x.add( screenTile.y.mul( lineSize ) );
// assigns
this.bufferSize = bufferSize;
this.lightIndexes = lightIndexes;
this.screenTileIndex = screenTileIndex;
this.compute = compute;
this.lightsTexture = lightsTexture;
}
get hasLights() {
return super.hasLights || this.tiledLights.length > 0;
}
}
export default TiledLightsNode;
export const tiledLights = /*@__PURE__*/ nodeProxy( TiledLightsNode );