Three Blocks

Screen-space smoke / source

Open preview
webgl_postprocessing_smoke/source.jsPlain text ↗
import * as THREE from 'three/webgpu';
import WebGPU from 'three/addons/capabilities/WebGPU.js';
import { registerDevtools } from 'three-blocks/devtools';
import { createExampleGui } from '../helpers/exampleGui.js';
import { frameCameraForAspect, isMobileViewport } from '../helpers/mobile.js';
import { pass, uniform, uv } from 'three/tsl';
import { smoke } from 'three-blocks/smoke';
import { smokeRTT } from 'three-blocks/smoke';

let container;
let renderer;
let devtools;
let scene;
let mesh;
let instancedMesh;
let camera;
let postProcessing;
let scenePass;
let fluid;
let gui;
let animateScene = true;

const CUBE_COUNT = 160;
const CUBE_SPREAD = 6;
const SMOKE_QUALITY_PRESETS = Object.freeze( {
	high: Object.freeze( { simRes: 128, dyeRes: 512, iterations: 3, densityDissipation: 0.97, radius: 0.1, pointerScale: 45 } ),
	low: Object.freeze( { simRes: 64, dyeRes: 128, iterations: 1, densityDissipation: 0.97, radius: 0.1, pointerScale: 45 } ),
	mobile: Object.freeze( { simRes: 96, dyeRes: 256, iterations: 2, densityDissipation: 0.96, radius: 0.075, pointerScale: 30 } ),
} );
const cubeDummy = new THREE.Object3D();
const fluidPointer = new THREE.Vector2();
const params = {
	speedFactor: 1,
	simRes: SMOKE_QUALITY_PRESETS.high.simRes,
	dyeRes: SMOKE_QUALITY_PRESETS.high.dyeRes,
	iterations: SMOKE_QUALITY_PRESETS.high.iterations,
	densityDissipation: 0.97,
	velocityDissipation: 0.98,
	pressureDissipation: 0.8,
	curlStrength: 20,
	radius: 0.1,
	pressureFactor: 0.2,
	useBoundaries: true,
	pointerScale: 45,
	useInteraction: true,
};
const fxParams = {
	distortionStrength: 0.015,
	fluidMix: 0.65,
	fluidTint: 0.45,
	splitPoint: 0.5,
};
const fxUniforms = {
	distortionStrength: uniform( fxParams.distortionStrength ).setName( 'distortionStrength' ),
	fluidMix: uniform( fxParams.fluidMix ).setName( 'fluidMix' ),
	fluidTint: uniform( fxParams.fluidTint ).setName( 'fluidTint' ),
	splitPoint: uniform( fxParams.splitPoint ).setName( 'splitPoint' ),
};

export async function mount( containerElement, {
	animate = true,
	quality = 'high',
	randomSeed,
	reducedWorkload = false,
} = {} ) {

	container = containerElement;
	animateScene = animate;
	const selectedQuality = isMobileViewport()
		? 'mobile'
		: reducedWorkload || quality === 'low' || quality === 'reduced' ? 'low' : 'high';
	Object.assign( params, SMOKE_QUALITY_PRESETS[ selectedQuality ] );

	await init( randomSeed );
	return { dispose: unmount };

}

async function init( randomSeed ) {

	camera = new THREE.PerspectiveCamera( 35, window.innerWidth / window.innerHeight, 0.1, 1000 );
	camera.position.set( 0, 1.5, 8 );
	camera.lookAt( 0, 0, 0 );

	scene = new THREE.Scene();

	mesh = new THREE.Group();

	const heroCube = new THREE.Mesh( new THREE.BoxGeometry( 1.5, 1.5, 1.5 ), new THREE.MeshNormalNodeMaterial() );
	mesh.add( heroCube );

	instancedMesh = createInstancedCubes( randomSeed );
	mesh.add( instancedMesh );

	scene.add( mesh );

	scene.background = new THREE.Color( 0xffffff );

	renderer = new THREE.WebGPURenderer( { antialias: false } );
	devtools = registerDevtools( { renderer, container } );
	renderer.setPixelRatio( window.devicePixelRatio );
	renderer.domElement.style.touchAction = 'none';
	onResize();
	container.appendChild( renderer.domElement );
	await renderer.init();


	// Postprocessing chain: scene pass -> fluid
	postProcessing = new THREE.RenderPipeline( renderer );
	scenePass = pass( scene, camera );

	fluid = smokeRTT(
		fluidPointer,
		params.simRes,
		params.dyeRes,
		params.iterations,
		params.densityDissipation,
		params.velocityDissipation,
		params.pressureDissipation,
		params.curlStrength,
		params.pressureFactor,
		params.radius,
		params.useBoundaries,
		params.pointerScale,
		1,
		params.speedFactor
	);

	setupPostProcessingOutput();

	setupGUI();
	applyFluidParams();
	updateFxUniforms();

	renderer.setAnimationLoop( render );
	window.addEventListener( 'resize', onResize );
	renderer.domElement.addEventListener( 'pointermove', onPointerMove );

}

function onPointerMove( e ) {

	if ( ! params.useInteraction || e.isPrimary === false ) return;
	const bounds = renderer.domElement.getBoundingClientRect();
	const x = ( ( e.clientX - bounds.left ) / Math.max( 1, bounds.width ) ) * 2 - 1;
	const y = - ( ( e.clientY - bounds.top ) / Math.max( 1, bounds.height ) ) * 2 + 1;
	fluidPointer.set( x, y );

}

function onResize() {

	const w = Math.max( 1, window.innerWidth );
	const h = Math.max( 1, window.innerHeight );
	renderer.setSize( w, h );
	camera.aspect = w / h;
	camera.updateProjectionMatrix();
	frameCameraForAspect( camera, mesh.position );

}

function render() {

	if ( animateScene ) {

		mesh.rotation.x -= 0.0015;
		mesh.rotation.y -= 0.0015;

	}
	postProcessing.render();

}

function setupGUI() {

	gui = createExampleGui( 'Fluid Postprocessing' );
	const isMobile = window.innerWidth < 512;
	if ( isMobile ) gui.close();

	const onChange = () => {

		applyFluidParams();

	};

	gui.add( params, 'speedFactor', 0.1, 5, 0.05 ).name( 'Speed Factor' ).onChange( onChange );
	gui.add( params, 'simRes', 16, 1024, 16 ).name( 'Sim Resolution' ).onChange( onChange );
	gui.add( params, 'dyeRes', 32, 1024, 16 ).name( 'Dye Resolution' ).onChange( onChange );
	gui.add( params, 'iterations', 1, 20, 1 ).name( 'Pressure Iterations' ).onChange( onChange );
	gui.add( params, 'densityDissipation', 0.85, 1, 0.001 ).name( 'Density Dissipation' ).onChange( onChange );
	gui.add( params, 'velocityDissipation', 0.9, 1, 0.001 ).name( 'Velocity Dissipation' ).onChange( onChange );
	gui.add( params, 'pressureDissipation', 0, 0.99, 0.001 ).name( 'Pressure Dissipation' ).onChange( onChange );
	gui.add( params, 'pressureFactor', 0, 0.25, 0.001 ).name( 'Pressure Factor' ).onChange( onChange );
	gui.add( params, 'curlStrength', 0, 40, 1 ).name( 'Curl Strength' ).onChange( onChange );
	gui.add( params, 'radius', 0.1, 1, 0.001 ).name( 'Splat Radius' ).onChange( onChange );
	gui.add( params, 'pointerScale', 0, 200, 1 ).name( 'Pointer Scale' ).onChange( onChange );
	gui.add( params, 'useBoundaries' ).name( 'Use Boundaries' ).onChange( onChange );

	const fxFolder = gui.addFolder( 'Post FX' );
	const onFxChange = () => {

		updateFxUniforms();

	};

	fxFolder.add( fxParams, 'distortionStrength', 0.005, 0.02, 0.001 ).name( 'Distortion' ).onChange( onFxChange );
	fxFolder.add( fxParams, 'fluidMix', 0, 1, 0.01 ).name( 'Fluid Blend' ).onChange( onFxChange );
	fxFolder.add( fxParams, 'fluidTint', 0, 1, 0.01 ).name( 'Fluid Tint' ).onChange( onFxChange );
	fxFolder.add( fxParams, 'splitPoint', 0.05, 0.95, 0.01 ).name( 'Split Position' ).onChange( onFxChange );

}

function applyFluidParams() {

	if ( ! fluid ) return;

	const simRes = Math.max( 8, Math.round( params.simRes ) );
	const dyeRes = Math.max( 8, Math.round( params.dyeRes ) );
	params.simRes = simRes;
	params.dyeRes = dyeRes;

	fluid.simRes.value.set( simRes, simRes );
	fluid.dyeRes.value.set( dyeRes, dyeRes );
	fluid.setSize( renderer.domElement.width, renderer.domElement.height );

	const baseIterations = Math.max( 1, Math.round( params.iterations ) );
	params.iterations = baseIterations;
	fluid.setPressureIterations( baseIterations );
	fluid.setSpeedFactor( params.speedFactor );

	fluid.densityDissipation = params.densityDissipation;
	fluid.velocityDissipation = params.velocityDissipation;
	fluid.pressureDissipation.value = params.pressureDissipation;
	fluid.pressureFactor.value = params.pressureFactor;
	fluid.curlStrength.value = params.curlStrength;
	fluid.radius.value = params.radius;
	fluid.useBoundaries = !! params.useBoundaries;
	fluid.setPointerScale( params.pointerScale );

	postProcessing.needsUpdate = true;
	// Refresh the lil-gui controls after applying a preset.
	if ( typeof gui?.controllersRecursive === 'function' ) {

		gui.controllersRecursive().forEach( ( controller ) => controller.updateDisplay?.() );

	}

}

function createInstancedCubes( randomSeed ) {

	const geometry = new THREE.BoxGeometry( 0.35, 0.35, 0.35 );
	const material = new THREE.MeshNormalNodeMaterial();
	const instances = new THREE.InstancedMesh( geometry, material, CUBE_COUNT );
	let seed = randomSeed;
	const random = Number.isInteger( seed )
		? () => THREE.MathUtils.seededRandom( seed ++ )
		: Math.random;

	for ( let i = 0; i < CUBE_COUNT; i ++ ) {

		cubeDummy.position.set(
			( random() - 0.5 ) * CUBE_SPREAD,
			( random() - 0.5 ) * CUBE_SPREAD,
			( random() - 0.5 ) * CUBE_SPREAD
		);

		cubeDummy.rotation.set(
			random() * Math.PI * 2,
			random() * Math.PI * 2,
			random() * Math.PI * 2
		);

		const scale = random() * 0.4 + 0.1;
		cubeDummy.scale.setScalar( scale );
		cubeDummy.updateMatrix();

		instances.setMatrixAt( i, cubeDummy.matrix );

	}

	instances.instanceMatrix.needsUpdate = true;
	instances.frustumCulled = false;

	return instances;

}

function setupPostProcessingOutput() {

	if ( ! scenePass || ! fluid ) return;

	const fluidTexture = fluid.getTextureNode();
	const sceneTexture = scenePass.getTextureNode();
	const uvNode = uv();
	const distortedScene = sceneTexture.sample(
		uvNode.sub( fluidTexture.xy.mul( fxUniforms.distortionStrength ).mul( 0.01 ) )
	);

	const fluidTinted = fluidTexture.rgb.mul( fxUniforms.fluidTint ).add( 0.35 );
	const fluidBlend = distortedScene.mix( fluidTinted, fxUniforms.fluidMix );

	postProcessing.outputNode = uvNode.x.lessThan( fxUniforms.splitPoint ).select( distortedScene, fluidBlend );
	postProcessing.needsUpdate = true;

}

function updateFxUniforms() {

	if ( ! postProcessing ) return;

	fxUniforms.distortionStrength.value = fxParams.distortionStrength;
	fxUniforms.fluidMix.value = fxParams.fluidMix;
	fxUniforms.fluidTint.value = fxParams.fluidTint;
	fxUniforms.splitPoint.value = fxParams.splitPoint;

	postProcessing.needsUpdate = true;

}

export function unmount() {

	renderer?.setAnimationLoop( null );
	window.removeEventListener( 'resize', onResize );
	renderer?.domElement?.removeEventListener( 'pointermove', onPointerMove );
	gui?.destroy?.();
	devtools?.dispose();
	devtools = null;
	renderer?.dispose();
	renderer?.domElement?.remove();
	renderer = null;
	gui = null;
	fluid = null;
	scenePass = null;
	postProcessing = null;
	instancedMesh = null;
	mesh = null;
	scene = null;
	camera = null;
	container = null;

}