/**
* Body of Fire — Michelle dances inside a GPU smoke simulation that burns from her skin.
*
* Every frame the SkinnedMeshSDF block rebuilds a signed-distance + surface-velocity field
* from the posed skeleton. Two small compute kernels then walk the smoke grids and, in a thin
* shell around the surface (|distance| < fireShell), blend in density, heat, upward lift, and
* the limb's own motion. Buoyancy, vorticity, and turbulence do the rest; the volume renders
* through the smoke material's blackbody emission into the linear HDR post graph (bloom, ACES).
*
* A second render mode, "Screen flames", is a port of onepiece-meramera's fire: the dancer's
* screen-space silhouette re-lights a half-resolution semi-Lagrangian heat field (buoyancy +
* curl-noise swirl), the heat is torn into tongues through a blackbody ramp, and the picture is
* composited with heat-haze refraction, a warmed skin, a white-hot rim, bloom, and sparks. Less
* noisy and more literal than the volume; the smoke simulation idles while it is shown.
*/
import * as THREE from 'three/webgpu';
import WebGPU from 'three/addons/capabilities/WebGPU.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { bloom } from 'three/addons/tsl/display/BloomNode.js';
import { Fn, abs, clamp, color, dot, exp, float, floor, fract, globalId, ivec3, int, length, max, min, mix, mx_fractal_noise_float, mx_noise_float, pass, positionLocal, renderOutput, screenUV, sin, smoothstep, step, texture, texture3D, textureLoad, textureStore, uniform, uv, uvec3, vec2, vec3, vec4 } from 'three/tsl';
import { fresnel } from 'three-blocks';
import { registerDevtools } from 'three-blocks/devtools';
import { SkinnedMeshSDF } from 'three-blocks/sdf-raymarching';
import { shaderCache } from 'three-blocks/shaders';
import { SmokeVolume, VolumeSmokeNodeMaterial, VolumeSmokeRenderCompositor } from 'three-blocks/smoke';
import { createExampleGui } from '../helpers/exampleGui.js';
import { withAssetLoader } from '../helpers/LoadingManager.js';
let container;
let renderer;
let devtools;
let scene;
let camera;
let controls;
let gui;
let fluid;
let mesh;
let material;
let volumeCompositor;
let renderPipeline;
let scenePass;
let sceneColorNode;
let sceneDepthNode;
let bloomPassNode;
let flames;
let keyLight;
let fireLight;
let dancerRoot;
let skinnedMesh;
let hipsBone;
let mixer;
let action;
let bodySDF;
let fireKernels;
let uiState;
let raycaster;
let mouse;
let volumeResolutionScale = 0.5;
let volumeDepthSigma = 96;
const tmpSplatVelocity = new THREE.Vector3();
const tmpEmitterPosition = new THREE.Vector3();
const tmpEmitterVelocity = new THREE.Vector3();
const tmpCameraLocal = new THREE.Vector3();
const tmpSDFCenter = new THREE.Vector3();
const tmpDomainMatrix = new THREE.Matrix4();
const sharedFogColor = uniform( new THREE.Color( 0x050405 ) );
const sharedFogDensity = uniform( 0.035 );
const postFrame = uniform( 0 );
const postVignetteStrength = uniform( 0.42 );
// Fire shell: metres around the skin that ignite, and what the shell blends the grids toward.
const fireShell = uniform( 0.08 );
const fireDensity = uniform( 0.55 );
const fireHeat = uniform( 1.35 );
const fireBlend = uniform( 0.4 );
const fireLift = uniform( 1.5 );
const fireDrag = uniform( 0.85 );
const fireVelocityBlend = uniform( 0.28 );
const worldToVolumeVelocity = uniform( new THREE.Matrix3(), 'mat3' );
const VOLUME_LAYER = 1;
const DANCER_LAYER = 2;
const OPAQUE_SCENE_LAYERS = new THREE.Layers();
OPAQUE_SCENE_LAYERS.set( 0 );
// Metric stage: Michelle is normalised to 1.72 m, the smoke box wraps her with headroom.
const DANCER_HEIGHT = 1.72;
const DOMAIN_SCALE = new THREE.Vector3( 3.4, 5.2, 3.4 );
const DOMAIN_CENTER = new THREE.Vector3( 0, 2.55, 0 );
const SDF_DOMAIN = new THREE.Vector3( 2.4, 2.3, 2.4 );
const SDF_CENTER_RANGE = 0.5;
const CAMERA_POSITION = new THREE.Vector3( 2.1, 1.35, 2.6 );
const CAMERA_TARGET = new THREE.Vector3( 0, 1.05, 0 );
const IDLE_ORBIT_SPEED = 0.35;
// Candela: the pool it throws on the floor a metre below is the scene's only warm light.
const FIRE_LIGHT_INTENSITY = 14;
// Screen flames (onepiece-meramera look). Distances in height units (the frame is 1 high),
// speeds in height units per second, rates per second.
const FLAME_LOOK = {
rise: 0.38,
riseHot: 0.5,
swirl: 0.18,
swirlScale: 4.2,
cool: 3.8,
coolFloor: 0.5,
hazeCool: 1.6,
edgeBand: 0.011,
interiorFloor: 0.14,
interiorPeak: 0.78,
fireLight: 0.6,
refract: 0.012,
shimmer: 0.003,
// meramera tone-maps through a plain ACES curve; three's ACESFilmic output runs
// exposure/0.6, so the fire terms are scaled down to land on the same look.
exposure: 0.5,
bloom: 0.25,
sparks: 1,
};
const FLAME_SIM_SCALE = 0.5;
const SIMULATION_FIXED_DELTA = 1 / 60;
const MAX_SIMULATION_SUBSTEPS = 2;
const REDUCED_MOTION = window.matchMedia( '(prefers-reduced-motion: reduce)' ).matches;
// Frame cost ∝ smoke pixels × raymarch steps; the tetrahedral gradient taps are the billowy
// look, so only LOW drops them.
const QUALITY_TIERS = {
LOW: { simRes: 64, dyeRes: 96, sdfRes: 48, volumeScale: 0.35, steps: 40, flowDetail: false, gradientLighting: false, highFrequencyDetail: false, temporal: false },
MED: { simRes: 80, dyeRes: 128, sdfRes: 64, volumeScale: 0.42, steps: 48, flowDetail: true, gradientLighting: true, highFrequencyDetail: false, temporal: false },
HIGH: { simRes: 96, dyeRes: 160, sdfRes: 80, volumeScale: 0.5, steps: 64, flowDetail: true, gradientLighting: true, highFrequencyDetail: false, temporal: false },
ULTRA: { simRes: 96, dyeRes: 192, sdfRes: 96, volumeScale: 0.65, steps: 128, flowDetail: true, gradientLighting: true, highFrequencyDetail: true, temporal: false },
};
const QUALITY_ORDER = [ 'LOW', 'MED', 'HIGH', 'ULTRA' ];
let activeQualityTier = 'HIGH';
let activeQuality = QUALITY_TIERS[ activeQualityTier ];
let qualityProbeElapsed = 0;
let qualityProbeFrames = 0;
let qualityProbeCooldown = 2;
let requestedQualityTier;
let autoQualityEnabled = true;
let debugGui = false;
let autoStart = true;
let initializationSteps = 240;
let gridSettings;
let danceTime = 0;
let flameClock = 0;
let flameDelta = 0;
let previousFrameTime;
let simulationAccumulator = 0;
let activeAssets;
const sharedVolumeFogNode = Fn( ( [ , cameraDistance ] ) => {
const extinction = cameraDistance.mul( sharedFogDensity ).toVar( 'sharedFogExtinction' );
const transmittance = extinction.mul( extinction ).negate().exp().toVar( 'sharedFogTransmittance' );
return vec4( sharedFogColor.mul( transmittance.oneMinus() ), transmittance );
} );
function requireAsset( assets, key ) {
const asset = assets?.[ key ];
if ( asset instanceof URL ) return asset.href;
if ( typeof asset === 'string' && asset.length > 0 ) return asset;
throw new Error( `Body of Fire requires assets.${key}.` );
}
export async function mount( containerElement, {
assets = {},
quality,
autoQuality = true,
autoStart: shouldAutoStart = true,
initializationSteps: warmupSteps = 240,
debug = false,
grid = {},
} = {} ) {
container = containerElement;
activeAssets = { characterModel: requireAsset( assets, 'characterModel' ) };
requestedQualityTier = typeof quality === 'string' ? quality.toUpperCase() : undefined;
autoQualityEnabled = autoQuality !== false;
debugGui = debug === true;
autoStart = shouldAutoStart !== false;
initializationSteps = THREE.MathUtils.clamp( Math.round( Number( warmupSteps ) || 0 ), 0, 480 );
const automaticTier = window.matchMedia( '(pointer: coarse)' ).matches || window.innerWidth < 720 ? 'LOW' : 'HIGH';
activeQualityTier = Object.hasOwn( QUALITY_TIERS, requestedQualityTier ) ? requestedQualityTier : automaticTier;
activeQuality = QUALITY_TIERS[ activeQualityTier ];
qualityProbeElapsed = 0;
qualityProbeFrames = 0;
qualityProbeCooldown = 2;
danceTime = 0;
flameClock = 0;
flameDelta = 0;
simulationAccumulator = 0;
volumeResolutionScale = activeQuality.volumeScale;
const finiteGridOption = ( name, fallback, min, max ) => {
const value = Number( grid[ name ] );
return Number.isFinite( value ) ? THREE.MathUtils.clamp( value, min, max ) : fallback;
};
gridSettings = {
simRes: Math.round( finiteGridOption( 'simRes', activeQuality.simRes, 8, 256 ) ),
dyeRes: Math.round( finiteGridOption( 'dyeRes', activeQuality.dyeRes, 8, 256 ) ),
sdfRes: Math.round( finiteGridOption( 'sdfRes', activeQuality.sdfRes, 16, 128 ) ),
lightRes: Math.round( finiteGridOption( 'lightRes', 64, 4, 128 ) ),
maxSplatSources: Math.round( finiteGridOption( 'maxSplatSources', 64, 1, 256 ) ),
};
if ( WebGPU.isAvailable() === false ) {
container.appendChild( WebGPU.getErrorMessage() );
throw new Error( 'No WebGPU support' );
}
const handle = await init();
return { ...handle, dispose: unmount };
}
async function init() {
container.style.position = 'relative';
container.style.overflow = 'hidden';
container.style.touchAction = 'none';
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 0.05, 100 );
camera.position.copy( CAMERA_POSITION );
renderer = new THREE.WebGPURenderer( { antialias: true } );
devtools = registerDevtools( { renderer, container } );
renderer.setPixelRatio( Math.min( window.devicePixelRatio, 2 ) );
renderer.setSize( window.innerWidth, window.innerHeight );
// Scene pass, volume target, and bloom stay linear HDR; ACES runs once at the end.
renderer.toneMapping = THREE.NoToneMapping;
renderer.toneMappingExposure = 1.1;
renderer.domElement.setAttribute( 'role', 'img' );
renderer.domElement.setAttribute( 'aria-label', 'A dancer wrapped in simulated fire and smoke on a dark stage.' );
container.appendChild( renderer.domElement );
await renderer.init();
createStage();
controls = new OrbitControls( camera, renderer.domElement );
controls.target.copy( CAMERA_TARGET );
controls.enableDamping = true;
controls.dampingFactor = 0.06;
controls.autoRotate = ! REDUCED_MOTION;
controls.autoRotateSpeed = IDLE_ORBIT_SPEED;
controls.enablePan = false;
controls.minDistance = 1.6;
controls.maxDistance = 9;
controls.maxPolarAngle = Math.PI * 0.55;
controls.update();
renderer.domElement.addEventListener( 'pointerdown', () => controls.autoRotate = false );
await withAssetLoader( container, [ 'Dancer' ], manager => manager.load( 'Dancer', loadDancer ) );
scenePass = pass( scene, camera );
scenePass.setLayers( OPAQUE_SCENE_LAYERS );
sceneColorNode = texture( scenePass.getTexture( 'output' ) );
sceneDepthNode = scenePass.getTextureNode( 'depth' );
fluid = new SmokeVolume( {
simRes: gridSettings.simRes,
dyeRes: gridSettings.dyeRes,
lightRes: gridSettings.lightRes,
maxSplatSources: gridSettings.maxSplatSources,
iterations: 12,
pressureSolver: 'sor',
splatMode: 'batched',
// Heat dies fast and smoke a little slower: flames live on the skin, the wisps above
// cool to grey and thin out before they reach the top of the box.
densityDissipation: 0.982,
temperatureDissipation: 0.93,
densityDiffusion: 0.002,
densityAdvectionCorrection: 0.2,
velocityDissipation: 0.985,
pressureDissipation: 0,
curlStrength: 10,
turbulenceStrength: 2.2,
turbulenceFrequency: 2.1,
turbulenceSpeed: 0.2,
turbulenceOctaves: 2,
turbulenceDensityScale: 0.5,
turbulenceThermalBoost: 0.6,
turbulenceUpdateInterval: 3,
pressureFactor: 1 / 6,
radius: 0.07,
useBoundaries: true,
boundaryFade: 0.05,
neighborStride: 1,
buoyancyStrength: 2.2,
densityWeight: 0.02,
lightSteps: 24,
enableOccupancyCache: true,
enableLightOpticalDepthCache: true,
} );
shaderCache.container( 'smoke/volume', fluid );
fluid.initialize( renderer );
fluid.setLightDirection( keyLight.position.clone().normalize() );
const dyeTexelSize = uniform( new THREE.Vector3( 1 / fluid.dyeRes, 1 / fluid.dyeRes, 1 / fluid.dyeRes ), 'vec3' );
material = new VolumeSmokeNodeMaterial( {
densityTexture: fluid.getDensityTexture3D(),
velocityTexture: fluid.getVelocityTexture3D(),
curlTexture: fluid.getCurlTexture3D(),
pressureTexture: fluid.getPressureTexture3D(),
divergenceTexture: fluid.getDivergenceTexture3D(),
occupancyTexture: fluid.getOccupancyTexture3D(),
occupancyGridSize: fluid.getOccupancyGridSize(),
lightOpticalDepthTexture: fluid.getLightOpticalDepthTexture3D(),
sceneDepthNode,
fogNode: sharedVolumeFogNode,
sceneShadowNode: null,
useLightCacheVisibility: false,
useGradientLighting: activeQuality.gradientLighting !== false,
useFlowDetail: activeQuality.flowDetail,
useHighFrequencyDetail: activeQuality.highFrequencyDetail,
useMacrocellSkipping: true,
outputMode: 'unclamped-hdr',
dyeTexelSize,
lightDir: fluid.lightDirection,
steps: activeQuality.steps,
temporalJitter: activeQuality.temporal ? 1 : 0,
baseColor: new THREE.Color( 0x4c4744 ),
skyColor: new THREE.Color( 0x2b3140 ),
groundColor: new THREE.Color( 0x0d0b0a ),
highlightColor: new THREE.Color( 0x8e949e ),
lightColor: new THREE.Color( 0xb9c8dd ),
ambientLight: 0.26,
lightStrength: 1.5,
rimStrength: 0.08,
densityBoost: 2.6,
absorption: 2.4,
brightness: 1.15,
anisotropy: 0.55,
phaseBack: - 0.18,
phaseForwardWeight: 0.7,
scatteringAlbedo: 0.8,
shadowIntensity: 0.6,
rayJitterStrength: 0.85,
curlInfluence: 0.45,
detailWarpStrength: 2.2,
detailWarpMix: 0.7,
detailNoiseScale: 5.5,
detailNoiseStrength: 0.26,
detailNoiseSpeed: 0.02,
adaptiveStepThreshold: 0.0015,
densitySmoothing: 0.2,
gradientLighting: 0.12,
surfaceLighting: 0.02,
multipleScattering: 0.5,
multipleScatteringOctaves: 3,
multipleScatteringAttenuation: 0.32,
multipleScatteringContribution: 0.45,
multipleScatteringAnisotropy: 0.7,
powderStrength: 0.3,
ambientGradient: 0.5,
ambientOcclusion: 0.8,
fireColor: new THREE.Color( 0xff5a1e ),
fireColorHot: new THREE.Color( 0xffc070 ),
// Emission only where the shell is genuinely hot: the blackbody core hugs the skin.
fireIntensity: 0.95,
firePower: 3,
fireTemperatureScale: 0.66,
fireBlackbody: 1,
pointLightColor: new THREE.Color( 0xff8a3c ),
pointLightRadius: 1.1,
} );
material.side = THREE.FrontSide;
material.useSmokeOutput();
mesh = new THREE.Mesh( new THREE.BoxGeometry( 1, 1, 1 ), material );
mesh.scale.copy( DOMAIN_SCALE );
mesh.position.copy( DOMAIN_CENTER );
mesh.frustumCulled = false;
mesh.layers.set( VOLUME_LAYER );
scene.add( mesh );
fluid.setDomainFromObject( mesh );
tmpDomainMatrix.copy( mesh.matrixWorld ).invert();
createBodySDF( gridSettings.sdfRes );
setupVolumeCompositor();
setupRenderPipeline();
installPointerStir();
uiState = {
qualityTier: activeQualityTier,
autoStep: false,
fireMode: 'volume',
dance: ! REDUCED_MOTION,
dancePace: 0.9,
fire: 1,
pointerDensityRate: 0.05,
pointerTemperatureRate: 0.6,
splatStrength: 4,
volumeResolutionScale,
volumeRenderTarget: '',
};
createScreenFlames();
createGui();
window.addEventListener( 'resize', onResize );
onResize();
await initializeSimulation();
previousFrameTime = performance.now();
renderer.setAnimationLoop( animate );
return createControls();
}
function createStage() {
scene.fog = new THREE.FogExp2( sharedFogColor.value.getHex(), sharedFogDensity.value );
const glowDistance = screenUV.sub( vec2( 0.5, 0.42 ) ).mul( vec2( 0.9, 1.2 ) ).length();
const stageGlow = smoothstep( 0.78, 0.05, glowDistance ).pow( 1.4 );
scene.backgroundNode = mix( color( 0x040304 ), color( 0x1a110c ), stageGlow.mul( 0.7 ) );
keyLight = new THREE.DirectionalLight( 0xb9c8dd, 1.1 );
keyLight.position.set( - 2.2, 4.5, 2.6 );
scene.add( keyLight );
scene.add( new THREE.HemisphereLight( 0x2b3140, 0x0d0b0a, 0.5 ) );
// One warm point light lives where the fire is: it lights the floor pool and the dancer,
// and doubles as the smoke material's in-volume point light.
fireLight = new THREE.PointLight( 0xff8a3c, FIRE_LIGHT_INTENSITY, 0, 2 );
fireLight.position.set( 0, 1.1, 0 );
scene.add( fireLight );
// The floor fades into the void on its own; no scene fog is needed for that.
const floorMaterial = new THREE.MeshStandardNodeMaterial( { roughness: 0.92, metalness: 0.04 } );
floorMaterial.colorNode = color( 0x1a181f ).mul( smoothstep( 6, 1.5, positionLocal.xy.length() ) );
const floor = new THREE.Mesh( new THREE.CircleGeometry( 7, 96 ), floorMaterial );
floor.rotation.x = - Math.PI * 0.5;
scene.add( floor );
}
async function loadDancer( onProgress ) {
const gltf = await new GLTFLoader().loadAsync( activeAssets.characterModel, onProgress );
dancerRoot = gltf.scene;
skinnedMesh = null;
dancerRoot.traverse( child => {
if ( ! skinnedMesh && child.isSkinnedMesh ) skinnedMesh = child;
} );
if ( ! skinnedMesh ) throw new Error( 'Michelle.glb does not contain a skinned mesh.' );
// Normalise the bind pose to a metric dancer standing on the floor.
dancerRoot.updateMatrixWorld( true );
const bounds = new THREE.Box3().setFromObject( dancerRoot );
const height = Math.max( 1e-4, bounds.max.y - bounds.min.y );
dancerRoot.scale.setScalar( DANCER_HEIGHT / height );
dancerRoot.position.y = - bounds.min.y * ( DANCER_HEIGHT / height );
dancerRoot.updateMatrixWorld( true );
scene.add( dancerRoot );
// Charred skin with embers under it: dark dielectric, hot fresnel rim that breathes.
skinnedMesh.material?.dispose?.();
const skin = new THREE.MeshPhysicalNodeMaterial( {
color: 0x100c0b,
metalness: 0.1,
roughness: 0.58,
clearcoat: 0.35,
clearcoatRoughness: 0.5,
} );
skin.emissiveNode = color( 0xff4a14 ).mul( fresnel( 2.4, 1.3 ).mul( 0.9 ).add( 0.03 ) );
skinnedMesh.material = skin;
skinnedMesh.frustumCulled = false;
skinnedMesh.layers.enable( DANCER_LAYER );
hipsBone = skinnedMesh.skeleton.bones.find( bone => /hips/iu.test( bone.name ) ) ?? skinnedMesh.skeleton.bones[ 0 ];
mixer = new THREE.AnimationMixer( dancerRoot );
const clip = gltf.animations.find( candidate => candidate.name === 'SambaDance' ) ?? gltf.animations[ 0 ];
if ( clip ) {
action = mixer.clipAction( clip );
action.play();
mixer.update( 0 );
}
}
function createBodySDF( resolution ) {
bodySDF?.dispose();
bodySDF = new SkinnedMeshSDF( skinnedMesh, { resolution, domain: SDF_DOMAIN, far: 4 } );
shaderCache.container( 'smoke/body-sdf', bodySDF );
fireKernels = null;
}
// The shell kernels mirror the library's own splat passes: read the current grid, write the
// other half of the ping-pong, swap.
// ponytail: reaches into fluid._density3D/_velocity3D (the pair is not public API); replace
// with a SmokeVolume source hook once one exists.
function createFireKernels() {
const volumeToWorld = uniform( fluid.volumeToWorldMatrix, 'mat4' );
const workgroup = [ 4, 4, 4 ];
const dispatch = res => [ Math.ceil( res / 4 ), Math.ceil( res / 4 ), Math.ceil( res / 4 ) ];
const shellWeight = ( gridDim ) => {
const uvw = vec3( globalId ).add( 0.5 ).div( vec3( gridDim ) );
const world = volumeToWorld.mul( vec4( uvw, 1 ) ).xyz.toVar( 'fireWorld' );
const distance = bodySDF.distance( world ).toVar( 'fireDistance' );
// One-sided: flames live in the layer just outside the skin, so the charred body stays
// visible through them instead of being filled solid.
const weight = smoothstep( float( - 0.025 ), 0, distance ).mul( smoothstep( 0, fireShell, distance ).oneMinus() ).toVar( 'fireShellWeight' );
return { world, weight };
};
const densityGrid = uvec3( fluid.dyeRes, fluid.dyeRes, fluid.dyeRes );
const densityKernel = ( readTexture, writeTexture, name ) => {
const readTex = texture3D( readTexture );
return Fn( () => {
const { weight } = shellWeight( densityGrid );
const base = textureLoad( readTex, ivec3( globalId ), int( 0 ) ).xy.toVar( 'fireBase' );
const blend = weight.mul( fireBlend ).saturate();
const amount = mix( base.x, max( base.x, fireDensity ), blend );
const heat = mix( base.y, max( base.y, fireHeat ), blend );
textureStore( writeTexture, globalId, vec4( amount, heat, 0, 1 ) );
} )().compute( dispatch( fluid.dyeRes ), workgroup ).setName( name );
};
const velocityGrid = uvec3( fluid.simRes, fluid.simRes, fluid.simRes );
const velocityKernel = ( readTexture, writeTexture, name ) => {
const readTex = texture3D( readTexture );
return Fn( () => {
const { world, weight } = shellWeight( velocityGrid );
const current = textureLoad( readTex, ivec3( globalId ), int( 0 ) ).xyz;
// The flame rises and is dragged along by the limb it burns on (m/s → grid cells/s).
const targetWorld = bodySDF.surfaceVelocity( world ).mul( fireDrag ).add( vec3( 0, fireLift, 0 ) );
const target = worldToVolumeVelocity.mul( targetWorld );
const next = mix( current, target, weight.mul( fireVelocityBlend ).saturate() );
textureStore( writeTexture, globalId, vec4( next, 1 ) );
} )().compute( dispatch( fluid.simRes ), workgroup ).setName( name );
};
const density = fluid._density3D;
const velocity = fluid._velocity3D;
fireKernels = {
density,
velocity,
densityRead: densityKernel( density.read, density.write, 'computeBodyFireDensityRead' ),
densityWrite: densityKernel( density.write, density.read, 'computeBodyFireDensityWrite' ),
velocityRead: velocityKernel( velocity.read, velocity.write, 'computeBodyFireVelocityRead' ),
velocityWrite: velocityKernel( velocity.write, velocity.read, 'computeBodyFireVelocityWrite' ),
};
}
function emitBodyFire() {
if ( ! fireKernels ) createFireKernels();
worldToVolumeVelocity.value.setFromMatrix4( fluid.worldToVolumeMatrix ).multiplyScalar( fluid.simRes );
const { density, velocity } = fireKernels;
renderer.compute( [
density.phase ? fireKernels.densityRead : fireKernels.densityWrite,
velocity.phase ? fireKernels.velocityRead : fireKernels.velocityWrite,
] );
density.swap();
velocity.swap();
}
function advanceDance( delta ) {
if ( mixer ) mixer.update( delta );
danceTime += delta;
dancerRoot.updateMatrixWorld( true );
hipsBone.getWorldPosition( tmpSDFCenter );
tmpSDFCenter.set(
THREE.MathUtils.clamp( tmpSDFCenter.x, - SDF_CENTER_RANGE, SDF_CENTER_RANGE ),
SDF_DOMAIN.y * 0.5,
THREE.MathUtils.clamp( tmpSDFCenter.z, - SDF_CENTER_RANGE, SDF_CENTER_RANGE )
);
fireLight.position.set( tmpSDFCenter.x, 1.05, tmpSDFCenter.z );
if ( uiState.fireMode !== 'volume' ) return;
bodySDF.update( delta, tmpSDFCenter );
bodySDF.dispatch( renderer );
}
function simulationStep( { refreshRenderCaches = true } = {} ) {
emitBodyFire();
fluid.step( renderer, SIMULATION_FIXED_DELTA, { refreshRenderCaches } );
}
async function initializeSimulation() {
const paceScale = uiState.dance ? uiState.dancePace : 0;
for ( let index = 0; index < initializationSteps; index ++ ) {
advanceDance( SIMULATION_FIXED_DELTA * paceScale );
simulationStep( { refreshRenderCaches: index === initializationSteps - 1 } );
}
if ( initializationSteps === 0 ) advanceDance( 0 );
syncVolumeTextures();
renderFrame();
await renderer.backend?.device?.queue?.onSubmittedWorkDone?.();
previousFrameTime = performance.now();
uiState.autoStep = autoStart;
}
function installPointerStir() {
raycaster = new THREE.Raycaster();
mouse = new THREE.Vector2();
const previousPointer = new THREE.Vector2();
const localPointerRay = new THREE.Ray();
const localPointerOrigin = new THREE.Vector3();
const localPointerDirection = new THREE.Vector3();
const localPointerPoint = new THREE.Vector3();
const cameraRight = new THREE.Vector3();
const cameraUp = new THREE.Vector3();
let previousPointerReady = false;
const rayBoxSegment = ( ray ) => {
let near = - Infinity;
let far = Infinity;
for ( const axis of [ 'x', 'y', 'z' ] ) {
const origin = ray.origin[ axis ];
const direction = ray.direction[ axis ];
if ( Math.abs( direction ) < 1e-6 ) {
if ( origin < - 0.5 || origin > 0.5 ) return null;
continue;
}
let first = ( - 0.5 - origin ) / direction;
let second = ( 0.5 - origin ) / direction;
if ( first > second ) [ first, second ] = [ second, first ];
near = Math.max( near, first );
far = Math.min( far, second );
if ( far < near ) return null;
}
return far >= Math.max( near, 0 ) ? [ Math.max( near, 0 ), far ] : null;
};
const onPointerMove = ( e ) => {
if ( e.isPrimary === false ) return;
const rect = renderer.domElement.getBoundingClientRect();
mouse.x = ( ( e.clientX - rect.left ) / rect.width ) * 2 - 1;
mouse.y = - ( ( e.clientY - rect.top ) / rect.height ) * 2 + 1;
if ( ! previousPointerReady ) {
previousPointer.set( e.clientX, e.clientY );
previousPointerReady = true;
return;
}
const deltaX = ( e.clientX - previousPointer.x ) / Math.max( rect.width, 1 );
const deltaY = ( e.clientY - previousPointer.y ) / Math.max( rect.height, 1 );
previousPointer.set( e.clientX, e.clientY );
// Touch has no hover state, so let its drag stir while pressed mouse
// movement remains reserved for OrbitControls.
if ( ( e.pointerType !== 'touch' && e.buttons !== 0 ) || ! mesh || ! fluid ) return;
raycaster.setFromCamera( mouse, camera );
mesh.updateMatrixWorld();
localPointerOrigin.copy( raycaster.ray.origin );
mesh.worldToLocal( localPointerOrigin );
localPointerDirection.copy( raycaster.ray.direction ).transformDirection( tmpDomainMatrix );
localPointerRay.set( localPointerOrigin, localPointerDirection );
const segment = rayBoxSegment( localPointerRay );
if ( ! segment || Math.abs( deltaX ) + Math.abs( deltaY ) < 0.0001 ) return;
cameraRight.setFromMatrixColumn( camera.matrixWorld, 0 );
cameraUp.setFromMatrixColumn( camera.matrixWorld, 1 );
tmpSplatVelocity.copy( cameraRight ).multiplyScalar( deltaX )
.addScaledVector( cameraUp, - deltaY )
.normalize()
.multiplyScalar( uiState.splatStrength );
const sampleCount = 4;
for ( let index = 0; index < sampleCount; index ++ ) {
const distance = THREE.MathUtils.lerp( segment[ 0 ], segment[ 1 ], ( index + 0.5 ) / sampleCount );
localPointerRay.at( distance, localPointerPoint );
mesh.localToWorld( localPointerPoint );
fluid.addWorldSplat( localPointerPoint, tmpSplatVelocity, uiState.pointerDensityRate / sampleCount, {
temperatureAmount: uiState.pointerTemperatureRate / sampleCount,
velocityMode: 'add',
velocityBlend: 1,
densityMode: 'add',
densityBlend: 1,
radius: fluid.radius.value * 1.35,
} );
}
};
renderer.domElement.addEventListener( 'pointermove', onPointerMove );
renderer.domElement.addEventListener( 'pointerdown', ( e ) => {
previousPointer.set( e.clientX, e.clientY );
previousPointerReady = true;
} );
renderer.domElement.addEventListener( 'pointerup', ( e ) => previousPointer.set( e.clientX, e.clientY ) );
const resetPointer = () => previousPointerReady = false;
renderer.domElement.addEventListener( 'pointerleave', resetPointer );
renderer.domElement.addEventListener( 'pointercancel', resetPointer );
}
function stirPlume() {
tmpEmitterPosition.set( 0, 1.3, 0 );
tmpEmitterVelocity.set( 1.4, 0.3, - 0.8 );
fluid.addWorldSplat( tmpEmitterPosition, tmpEmitterVelocity, 0, {
temperatureAmount: 0,
velocityMode: 'add',
velocityBlend: 1,
densityMode: 'add',
densityBlend: 1,
radius: fluid.radius.value * 2.2,
} );
}
function createGui() {
gui = createExampleGui( 'Body of Fire' );
if ( window.innerWidth < 512 ) gui.close();
gui.add( uiState, 'fireMode', { 'Volumetric smoke': 'volume', 'Screen flames': 'flames' } ).name( 'Fire' ).onChange( setFireMode ).listen();
gui.add( uiState, 'qualityTier', QUALITY_ORDER ).name( 'Quality' ).onChange( setQualityTier ).listen();
gui.add( uiState, 'dance' ).name( 'Dance' );
gui.add( uiState, 'dancePace', 0.1, 1.6, 0.01 ).name( 'Dance pace' );
gui.add( uiState, 'fire', 0, 2, 0.01 ).name( 'Fire' ).onChange( applyFireAmount );
gui.add( controls, 'autoRotate' ).name( 'Auto rotate' ).listen();
gui.add( { resetView }, 'resetView' ).name( 'Reset view' );
if ( ! debugGui ) return;
const engineering = gui.addFolder( 'Engineering' );
engineering.add( fireShell, 'value', 0.01, 0.2, 0.005 ).name( 'Shell (m)' );
engineering.add( fireBlend, 'value', 0, 1, 0.01 ).name( 'Shell blend' );
engineering.add( fireVelocityBlend, 'value', 0, 1, 0.01 ).name( 'Velocity blend' );
engineering.add( fireLift, 'value', 0, 4, 0.05 ).name( 'Lift (m/s)' );
engineering.add( fireDrag, 'value', 0, 1.5, 0.05 ).name( 'Limb drag' );
engineering.add( fluid.buoyancyStrength, 'value', 0, 8, 0.05 ).name( 'Buoyancy' );
engineering.add( fluid.curlStrength, 'value', 0, 30, 0.25 ).name( 'Vorticity' );
engineering.add( fluid.turbulenceStrength, 'value', 0, 8, 0.05 ).name( 'Turbulence' );
engineering.add( fluid.densityDissipation, 'value', 0.9, 1, 0.001 ).name( 'Density dissipation' );
engineering.add( fluid.temperatureDissipation, 'value', 0.8, 1, 0.001 ).name( 'Heat dissipation' );
const smoke = material.smokeUniforms;
engineering.add( smoke.fireIntensity, 'value', 0, 6, 0.05 ).name( 'Fire glow' );
engineering.add( smoke.firePower, 'value', 0.5, 4, 0.05 ).name( 'Fire falloff' );
engineering.add( smoke.densityBoost, 'value', 0.2, 8, 0.05 ).name( 'Density boost' );
engineering.add( smoke.absorption, 'value', 0.1, 8, 0.05 ).name( 'Absorption' );
engineering.add( uiState, 'volumeResolutionScale', 0.25, 1, 0.05 ).name( 'Render scale' ).onChange( value => {
volumeResolutionScale = Number( value );
resizeVolumeCompositor();
} );
engineering.add( uiState, 'volumeRenderTarget' ).name( 'Volume target' ).listen().disable();
engineering.add( fluid, 'iterations', 1, 64, 1 ).name( 'Pressure iterations' ).onChange( value => fluid.setPressureIterations( value ) );
}
function applyFireAmount( amount = uiState.fire ) {
fireDensity.value = 0.55 * amount;
fireHeat.value = 1.35 * amount;
material.smokeUniforms.fireIntensity.value = 0.95 * amount;
}
function resetView() {
camera.position.copy( CAMERA_POSITION );
controls.target.copy( CAMERA_TARGET );
controls.update();
volumeCompositor?.resetHistory();
}
function onResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
resizeVolumeCompositor();
resizeScreenFlames();
}
function setupVolumeCompositor() {
volumeCompositor = new VolumeSmokeRenderCompositor( renderer, {
scale: volumeResolutionScale,
upsampling: 'bilateral',
outputMode: 'unclamped-hdr',
depthSigma: volumeDepthSigma,
depthTexture: scenePass.getTexture( 'depth' ),
} );
}
function setupRenderPipeline() {
const smokeColor = volumeCompositor.getTextureNode();
const linearComposite = Fn( () => {
const resolvedSmoke = vec4( smokeColor ).toVar( 'bodyFireResolvedSmoke' );
const resolvedScene = vec4( sceneColorNode ).toVar( 'bodyFireResolvedScene' );
return vec4( resolvedSmoke.rgb.add( resolvedScene.rgb.mul( resolvedSmoke.a.oneMinus() ) ), 1 );
} )();
// Threshold 1.0: only the blackbody core and the ember rim bloom, never the grey smoke.
bloomPassNode = bloom( linearComposite, 0.5, 0.55, 1.0 );
shaderCache.container( 'smoke/bloom', bloomPassNode );
const bloomed = linearComposite.add( bloomPassNode );
const vignetteDistance = screenUV.sub( 0.5 ).length();
const vignette = float( 1 ).sub( smoothstep( 0.3, 0.74, vignetteDistance ).mul( postVignetteStrength ) );
renderPipeline = new THREE.RenderPipeline( renderer );
renderPipeline.outputColorTransform = false;
renderPipeline.outputNode = renderOutput( vec4( bloomed.rgb.mul( vignette ), 1 ), THREE.ACESFilmicToneMapping );
}
function resizeVolumeCompositor() {
if ( ! volumeCompositor ) return;
volumeCompositor.setScale( volumeResolutionScale );
if ( uiState ) uiState.volumeRenderTarget = `${volumeCompositor.width} × ${volumeCompositor.height}`;
}
function setQualityTier( tier ) {
const normalizedTier = String( tier ).toUpperCase();
if ( ! Object.hasOwn( QUALITY_TIERS, normalizedTier ) ) throw new Error( `Unknown smoke quality tier: ${tier}` );
activeQualityTier = normalizedTier;
activeQuality = QUALITY_TIERS[ activeQualityTier ];
volumeResolutionScale = activeQuality.volumeScale;
material.smokeUniforms.steps.value = activeQuality.steps;
material.smokeUniforms.temporalJitter.value = activeQuality.temporal ? 1 : 0;
material.setShaderVariants( {
useFlowDetail: activeQuality.flowDetail,
useHighFrequencyDetail: activeQuality.highFrequencyDetail,
useGradientLighting: activeQuality.gradientLighting !== false,
} );
resizeVolumeCompositor();
volumeCompositor.resetHistory();
if ( uiState ) {
uiState.qualityTier = activeQualityTier;
uiState.volumeResolutionScale = volumeResolutionScale;
}
return {
tier: activeQualityTier,
...activeQuality,
gridMatchesTier: fluid.simRes === activeQuality.simRes && fluid.dyeRes === activeQuality.dyeRes,
};
}
function updateAdaptiveQuality( frameDelta ) {
if ( requestedQualityTier || ! autoQualityEnabled ) return;
qualityProbeCooldown -= frameDelta;
if ( qualityProbeCooldown > 0 ) return;
qualityProbeElapsed += frameDelta;
qualityProbeFrames ++;
if ( qualityProbeElapsed < 2 ) return;
const averageFrameTime = qualityProbeElapsed / Math.max( qualityProbeFrames, 1 );
const tierIndex = QUALITY_ORDER.indexOf( activeQualityTier );
if ( averageFrameTime > 0.02 && tierIndex > 0 ) setQualityTier( QUALITY_ORDER[ tierIndex - 1 ] );
qualityProbeElapsed = 0;
qualityProbeFrames = 0;
qualityProbeCooldown = 8;
}
function updateVolumeRasterState() {
tmpCameraLocal.copy( camera.position );
mesh.worldToLocal( tmpCameraLocal );
const cameraInside = Math.abs( tmpCameraLocal.x ) < 0.5 && Math.abs( tmpCameraLocal.y ) < 0.5 && Math.abs( tmpCameraLocal.z ) < 0.5;
const nextSide = cameraInside ? THREE.BackSide : THREE.FrontSide;
const nextDepthTest = ! cameraInside;
if ( material.side === nextSide && material.depthTest === nextDepthTest ) return;
material.side = nextSide;
material.depthTest = nextDepthTest;
material.needsUpdate = true;
}
function renderVolumeLayer( activeRenderer ) {
const previousLayerMask = camera.layers.mask;
// The background mesh writes alpha 1; inside the smoke target that would occlude the
// whole opaque pass at composite time, so the volume layer renders over a clear target.
const previousBackgroundNode = scene.backgroundNode;
scene.backgroundNode = null;
camera.layers.set( VOLUME_LAYER );
try {
activeRenderer.render( scene, camera );
} finally {
camera.layers.mask = previousLayerMask;
scene.backgroundNode = previousBackgroundNode;
}
}
function syncVolumeTextures() {
material.syncVolumeTextures( {
densityTexture: fluid.getDensityTexture3D(),
velocityTexture: fluid.getVelocityTexture3D(),
curlTexture: fluid.getCurlTexture3D(),
pressureTexture: fluid.getPressureTexture3D(),
divergenceTexture: fluid.getDivergenceTexture3D(),
occupancyTexture: fluid.getOccupancyTexture3D(),
lightOpticalDepthTexture: fluid.getLightOpticalDepthTexture3D(),
} );
}
function animate() {
const currentFrameTime = performance.now();
const frameDelta = Math.min( ( currentFrameTime - previousFrameTime ) / 1000, 0.05 );
previousFrameTime = currentFrameTime;
controls.update();
updateAdaptiveQuality( frameDelta );
flameDelta = frameDelta;
if ( uiState.autoStep === true && uiState.fireMode !== 'volume' ) {
advanceDance( frameDelta * ( uiState.dance ? uiState.dancePace : 0 ) );
} else if ( uiState.autoStep === true ) {
simulationAccumulator = Math.min( simulationAccumulator + frameDelta, SIMULATION_FIXED_DELTA * MAX_SIMULATION_SUBSTEPS );
const substeps = Math.min( Math.floor( simulationAccumulator / SIMULATION_FIXED_DELTA ), MAX_SIMULATION_SUBSTEPS );
if ( substeps > 0 ) {
// One pose per frame: the field rebuild is shared by every substep.
advanceDance( substeps * SIMULATION_FIXED_DELTA * ( uiState.dance ? uiState.dancePace : 0 ) );
for ( let index = 0; index < substeps; index ++ ) {
simulationStep( { refreshRenderCaches: index === substeps - 1 } );
simulationAccumulator -= SIMULATION_FIXED_DELTA;
}
syncVolumeTextures();
}
}
renderFrame();
}
function renderFrame() {
postFrame.value ++;
material.smokeUniforms.detailTime.value = fluid.turbulenceTime.value;
material.smokeUniforms.temporalFrame.value = postFrame.value;
// The fire breathes: the in-volume point light and the scene light flicker together.
const flicker = 0.86 + 0.14 * ( Math.sin( danceTime * 17.3 ) * 0.5 + Math.sin( danceTime * 29.1 + 1.7 ) * 0.3 + Math.sin( danceTime * 7.7 ) * 0.2 );
fireLight.intensity = FIRE_LIGHT_INTENSITY * flicker * uiState.fire;
material.smokeUniforms.pointLightPosition.value.copy( fireLight.position );
material.smokeUniforms.pointLightIntensity.value = fireLight.intensity * 0.015;
if ( uiState.fireMode !== 'volume' ) {
renderScreenFlames();
return;
}
updateVolumeRasterState();
// The material's scene-depth dependency renders the opaque pass first; the volume then
// stops at that depth and the pipeline composites both targets in linear HDR.
volumeCompositor.render(
( { renderer: scaledRenderer } ) => renderVolumeLayer( scaledRenderer ),
{ depthTexture: scenePass.getTexture( 'depth' ), composite: false }
);
renderPipeline.render();
}
function setFireMode( mode ) {
if ( mode !== 'volume' && mode !== 'flames' ) throw new Error( `Unknown fire mode: ${mode}` );
uiState.fireMode = mode;
volumeCompositor?.resetHistory();
return mode;
}
// ---------------------------------------------------------------------------
// Screen flames — port of onepiece-meramera/app/src/render/fire.ts
// ---------------------------------------------------------------------------
/** Fire-X's blackbody ramp: 720K deep red through orange and gold to a pale white above 2600K. */
const blackbody = Fn( ( [ temperature ] ) => {
const t = clamp( temperature.sub( 720 ).div( 1900 ), 0, 1 );
const red = vec3( 1.0, 0.035, 0.002 );
const orange = vec3( 1.0, 0.24, 0.008 );
const gold = vec3( 1.0, 0.68, 0.12 );
const white = vec3( 1.0, 0.94, 0.72 );
return mix(
mix( red, orange, smoothstep( 0.0, 0.32, t ) ),
mix( gold, white, smoothstep( 0.58, 1.0, t ) ),
smoothstep( 0.26, 0.72, t )
);
} );
const hash2 = Fn( ( [ cell, seed ] ) => fract( sin( dot( cell, vec2( 127.1, 311.7 ) ).add( seed ) ).mul( 43758.5453 ) ) );
/** Divergence-free 2D flow from a scalar noise potential: v = (∂ψ/∂y, -∂ψ/∂x). */
const curlNoise = Fn( ( [ p, z, eps ] ) => {
const dx = vec2( eps, 0.0 );
const dy = vec2( 0.0, eps );
const dpdx = mx_noise_float( vec3( p.add( dx ), z ) ).sub( mx_noise_float( vec3( p.sub( dx ), z ) ) );
const dpdy = mx_noise_float( vec3( p.add( dy ), z ) ).sub( mx_noise_float( vec3( p.sub( dy ), z ) ) );
return vec2( dpdy, dpdx.negate() ).div( eps.mul( 2.0 ) );
} );
function createScreenFlames() {
const uAspect = uniform( 1 );
const uTime = uniform( 0 );
const uDt = uniform( 0 );
const uBurn = uniform( 1 );
const uSparks = uniform( FLAME_LOOK.sparks );
// Engineering view: 0 composite, 1 silhouette, 2 heat field, 3 flame emission.
const uView = uniform( 0 );
const uHeatTexel = uniform( new THREE.Vector2( 1 / 640, 1 / 400 ), 'vec2' );
const makeTarget = ( hdr ) => new THREE.RenderTarget( 8, 8, {
type: hdr ? THREE.HalfFloatType : THREE.UnsignedByteType,
format: THREE.RGBAFormat,
minFilter: THREE.LinearFilter,
magFilter: THREE.LinearFilter,
generateMipmaps: false,
depthBuffer: ! hdr,
stencilBuffer: false,
} );
const maskTarget = makeTarget( false );
const heatTargets = [ makeTarget( true ), makeTarget( true ) ];
const flameTarget = makeTarget( true );
const maskNode = texture( maskTarget.texture );
const heatNode = texture( heatTargets[ 0 ].texture );
const flameNode = texture( flameTarget.texture );
// Screen position in height units (x scaled by aspect, y down) from the quad's uv, which
// is also exactly the coordinate every target here is sampled with.
const heightUnits = () => vec2( uv().x.mul( uAspect ), uv().y ).toVar();
const toUV = ( p ) => vec2( p.x.div( uAspect ), p.y );
// A band along the silhouette boundary: 1 on the edge, 0 inside and outside.
const edgeBand = ( at, e ) => {
const dx = vec2( float( e ).div( uAspect ), 0.0 );
const dy = vec2( 0.0, e );
const around = maskNode.sample( at.add( dx ) ).r
.add( maskNode.sample( at.sub( dx ) ).r )
.add( maskNode.sample( at.add( dy ) ).r )
.add( maskNode.sample( at.sub( dy ) ).r )
.mul( 0.25 );
return around.mul( around.oneMinus() ).mul( 4.0 );
};
const fullscreen = () => {
const material = new THREE.NodeMaterial();
material.depthTest = false;
material.depthWrite = false;
return material;
};
// The dancer's silhouette: the scene drawn white on black through an override material.
const maskMaterial = new THREE.MeshBasicNodeMaterial( { color: 0xffffff } );
// Heat field. Semi-Lagrangian: every texel fetches the parcel that flowed into it —
// carried up by buoyancy (hotter rises faster) and stirred by curl noise — cools, and is
// re-lit by the silhouette: hard along its edge, in moving patches across its interior.
// r = heat, g = haze, b = per-parcel noise, a = age since injection.
const simMaterial = fullscreen();
simMaterial.fragmentNode = Fn( () => {
const p = heightUnits();
const t = uTime;
const dt = uDt;
const here = heatNode.sample( uv() ).toVar();
const swirl = curlNoise( p.mul( FLAME_LOOK.swirlScale ), t.mul( 0.45 ), float( 0.02 ) )
.mul( FLAME_LOOK.swirl )
.add( curlNoise( p.mul( FLAME_LOOK.swirlScale * 2.7 ).add( vec2( 5.1, 2.3 ) ), t.mul( 1.1 ), float( 0.015 ) ).mul( FLAME_LOOK.swirl * 0.45 ) );
const wander = mx_noise_float( vec3( p.mul( 1.4 ), t.mul( 0.25 ) ) ).mul( 0.16 );
const rise = float( FLAME_LOOK.rise ).add( clamp( here.r, 0.0, 1.0 ).mul( FLAME_LOOK.riseHot ) );
const velocity = vec2( swirl.x.add( wander ), swirl.y.sub( rise ) );
// Where this texel's parcel came from (y runs down, so "below" is +y).
const from = p.sub( velocity.mul( dt ) );
const previous = heatNode.sample( toUV( from ) ).toVar();
const cooled = max( previous.r.mul( exp( dt.mul( - FLAME_LOOK.cool ) ) ).sub( dt.mul( FLAME_LOOK.coolFloor ) ), 0.0 );
const haze = previous.g.mul( exp( dt.mul( - FLAME_LOOK.hazeCool ) ) );
const age = previous.a.add( dt ).min( 6.0 );
const sil = maskNode.sample( uv() ).r;
const edge = edgeBand( uv(), FLAME_LOOK.edgeBand ).mul( uBurn );
const patches = mx_fractal_noise_float( vec3( p.x.mul( 11.0 ), p.y.mul( 13.0 ).add( t.mul( 1.1 ) ), t.mul( 0.8 ) ), 2, 2.2, 0.5 );
const interior = sil.mul( uBurn ).mul( float( FLAME_LOOK.interiorFloor ).add( smoothstep( - 0.05, 0.5, patches ).mul( FLAME_LOOK.interiorPeak - FLAME_LOOK.interiorFloor ) ) );
const flicker = float( 0.78 ).add( mx_noise_float( vec3( p.mul( 18.0 ), t.mul( 6.0 ) ) ).mul( 0.22 ) );
const inject = max( interior, edge ).mul( flicker ).toVar();
const heat = max( cooled, inject );
const fresh = smoothstep( 0.15, 0.6, inject );
const grain = mx_noise_float( vec3( p.mul( 11.0 ), t.mul( 1.6 ) ) );
return vec4(
heat,
max( haze, inject.mul( 0.85 ).min( 1.0 ) ),
mix( previous.b, grain, fresh ),
mix( age, float( 0.0 ), fresh )
);
} )();
// Flame: the heat torn into tongues by noise sampled in flow-following coordinates,
// coloured through the blackbody ramp. rgb = HDR emission, a = how much it hides.
const flameMaterial = fullscreen();
flameMaterial.fragmentNode = Fn( () => {
const p = heightUnits();
const t = uTime;
const field = heatNode.sample( uv() ).toVar();
const heat = field.r;
const age = field.a;
const grain = field.b.mul( 0.5 ).add( 0.5 );
// The big noise is sampled where the parcel started, so the pattern rides up with
// the flame instead of scrolling through it.
const flowY = p.y.add( age.mul( FLAME_LOOK.rise + FLAME_LOOK.riseHot * 0.5 ) );
const born = t.sub( age );
const tongues = mx_fractal_noise_float( vec3( p.x.mul( 7.5 ), flowY.mul( 3.6 ), born.mul( 0.55 ).add( 2.7 ) ), 3, 2.0, 0.55 );
const fibre = abs( mx_noise_float( vec3( p.x.mul( 20.0 ), flowY.mul( 13.0 ), born.mul( 0.7 ).add( 9.0 ) ) ) );
const lick = mx_noise_float( vec3( p.x.mul( 30.0 ), p.y.add( t.mul( 1.6 ) ).mul( 22.0 ), t.mul( 1.1 ) ) );
const tear = float( 1.0 ).add( smoothstep( 0.0, 1.2, age ).mul( 0.5 ) );
const shape = heat
.mul( float( 1.0 ).add( tongues.mul( tear ) ).sub( fibre.mul( 0.5 ) ).add( lick.mul( 0.15 ) ) )
.mul( float( 0.82 ).add( grain.mul( 0.36 ) ) )
.toVar();
const fringe = smoothstep( 0.26, 0.4, shape );
const body = smoothstep( 0.42, 0.62, shape );
const core = smoothstep( 0.62, 0.88, shape );
const white = smoothstep( 0.95, 1.3, shape );
const temperature = float( 760.0 ).add( fringe.mul( 490.0 ) ).add( body.mul( 500.0 ) ).add( core.mul( 600.0 ) ).add( white.mul( 550.0 ) );
const emission = blackbody( temperature ).mul( fringe.mul( 0.7 ).add( body.mul( 1.15 ) ).add( core.mul( 1.5 ) ).add( white.mul( 1.3 ) ) );
const cover = fringe.mul( 0.75 ).add( body.mul( 0.2 ) ).add( core.mul( 0.05 ) );
return vec4( emission, cover );
} )();
// Sparks: layers of tall cells, each with one ember born at the cell's foot that streaks
// up swaying and dies at the top — lit only if there was fire where it was born.
const sparks = ( p, t ) => {
const glow = vec3( 0.0 ).toVar();
for ( const [ cellW, cellH, offset, seed ] of [ [ 0.055, 0.2, 0.0, 1.0 ], [ 0.07, 0.26, 0.37, 7.0 ], [ 0.045, 0.16, 0.71, 13.0 ] ] ) {
const size = vec2( cellW, cellH );
const q = p.div( size ).add( offset );
const cell = floor( q );
const f = fract( q );
const h1 = hash2( cell, seed );
const h2 = hash2( cell, seed + 3.7 );
const h3 = hash2( cell, seed + 9.1 );
const life = float( 1.1 ).add( h3.mul( 0.9 ) );
const phase = fract( t.div( life ).add( h1 ) );
const sway = sin( t.mul( 2.4 ).add( h1.mul( 25.0 ) ) ).mul( 0.09 ).mul( phase );
const sx = float( 0.5 ).add( h2.sub( 0.5 ).mul( 0.7 ) ).add( sway );
const sy = phase.oneMinus();
const d = f.sub( vec2( sx, sy ) ).mul( size );
const stretched = vec2( d.x, d.y.mul( 0.45 ) );
const r2 = dot( stretched, stretched );
const dotGlow = exp( r2.mul( - 1.0 / ( 0.0026 * 0.0026 ) ) );
// Each ember only exists inside its own cell, so the halo must die out well within
// half a cell (0.0225 height units) or it is clipped into a visible rectangle.
const halo = exp( r2.mul( - 1.0 / ( 0.006 * 0.006 ) ) ).mul( 0.06 );
const fade = smoothstep( 0.0, 0.12, phase ).mul( smoothstep( 0.55, 1.0, phase ).oneMinus() );
const flicker = float( 0.7 ).add( sin( t.mul( 17.0 ).add( h2.mul( 50.0 ) ) ).mul( 0.3 ) );
const foot = cell.add( vec2( sx, 1.0 ) ).sub( offset ).mul( size );
const fire = heatNode.sample( toUV( foot ) ).r;
const lit = smoothstep( 0.25, 0.7, fire ).mul( step( 0.2, h3 ) );
const emberColor = blackbody( float( 1500.0 ).add( h2.mul( 900.0 ) ) );
glow.addAssign( emberColor.mul( dotGlow.add( halo ) ).mul( fade.mul( flicker ).mul( lit ).mul( 2.6 ) ) );
}
return glow;
};
// Composite: the opaque pass refracted by the heat haze and lit by the fire; the burning
// silhouette warms, crawls with embers and gets a white-hot rim but stays a person; the
// tongues in front (translucent fringe, opaque core), their bloom, and sparks. Linear HDR
// until the ACES output transform, like the volume path.
const sceneNode = scenePass.getTextureNode( 'output' );
const bloomNode = bloom( flameNode, FLAME_LOOK.bloom, 0.5, 0.0 );
shaderCache.container( 'smoke/flame-bloom', bloomNode );
const composite = Fn( () => {
const p = heightUnits();
const t = uTime;
const field = heatNode.sample( uv() ).toVar( 'flameField' );
const warmth = field.r.add( field.g );
const gx = heatNode.sample( uv().add( vec2( uHeatTexel.x, 0.0 ) ) ).r.sub( heatNode.sample( uv().sub( vec2( uHeatTexel.x, 0.0 ) ) ).r );
const gy = heatNode.sample( uv().add( vec2( 0.0, uHeatTexel.y ) ) ).r.sub( heatNode.sample( uv().sub( vec2( 0.0, uHeatTexel.y ) ) ).r );
const shimmer = mx_noise_float( vec3( p.x.mul( 22.0 ), p.y.add( t.mul( 0.9 ) ).mul( 16.0 ), t.mul( 1.7 ) ) );
const haze = vec2( gx, gy )
.mul( FLAME_LOOK.refract )
.add( vec2( shimmer, shimmer.mul( 0.6 ) ).mul( field.g ).mul( FLAME_LOOK.shimmer ) )
.mul( smoothstep( 0.0, 0.2, warmth ) );
const picture = sceneNode.sample( uv().add( haze ) ).rgb;
const sil = maskNode.sample( uv() ).r.mul( uBurn ).toVar( 'flameSilhouette' );
const rim = edgeBand( uv(), 0.007 ).mul( uBurn ).mul( float( 0.45 ).add( sil.mul( 0.55 ) ) );
const flame = flameNode.sample( uv() ).toVar( 'flameSample' );
const glow = vec4( bloomNode ).rgb.toVar( 'flameGlow' );
const lit = picture.mul( float( 1.0 ).add( glow.mul( FLAME_LOOK.fireLight ) ) ).toVar( 'flameLit' );
const ember = mx_fractal_noise_float( vec3( p.x.mul( 24.0 ), p.y.mul( 24.0 ).add( t.mul( 1.1 ) ), t.mul( 2.0 ) ), 2, 2.1, 0.5 ).mul( 0.5 ).add( 0.5 );
const hot = blackbody( float( 1800.0 ).add( ember.mul( 800.0 ) ) );
const skin = lit.mul( vec3( 1.25, 0.72, 0.42 ) ).mul( float( 1.1 ).add( ember.mul( 0.5 ) ) ).add( hot.mul( ember.mul( 0.3 ).add( 0.08 ) ) );
lit.assign( mix( lit, skin, sil.mul( 0.8 ) ) );
const rimFlicker = float( 0.55 ).add( mx_noise_float( vec3( p.mul( 44.0 ), t.mul( 8.0 ) ) ).mul( 0.45 ) );
lit.addAssign( blackbody( float( 2400.0 ) ).mul( rim.mul( rimFlicker ).mul( 0.7 ) ) );
lit.mulAssign( field.g.mul( 0.22 ).mul( sil.oneMinus() ).oneMinus() );
const fire = flame.rgb.add( glow ).add( sparks( p, t ).mul( uSparks ) ).mul( FLAME_LOOK.exposure );
const cover = clamp( flame.a.mul( sil.mul( 0.45 ).oneMinus() ), 0.0, 1.0 );
const colorOut = lit.mul( cover.oneMinus() ).add( fire ).toVar( 'flameComposite' );
const vignetteDistance = screenUV.sub( 0.5 ).length();
const vignette = float( 1 ).sub( smoothstep( 0.3, 0.74, vignetteDistance ).mul( postVignetteStrength ) );
colorOut.mulAssign( vignette );
colorOut.assign( mix( colorOut, vec3( maskNode.sample( uv() ).r ), step( 0.5, uView ).mul( step( uView, 1.5 ) ) ) );
colorOut.assign( mix( colorOut, vec3( field.r, field.g, field.a.mul( 0.2 ) ), step( 1.5, uView ).mul( step( uView, 2.5 ) ) ) );
colorOut.assign( mix( colorOut, flame.rgb, step( 2.5, uView ) ) );
return vec4( colorOut, 1 );
} )();
const pipeline = new THREE.RenderPipeline( renderer );
pipeline.outputColorTransform = false;
pipeline.outputNode = renderOutput( composite, THREE.ACESFilmicToneMapping );
flames = {
maskTarget,
heatTargets,
heatIndex: 0,
flameTarget,
maskMaterial,
heatNode,
simQuad: new THREE.QuadMesh( simMaterial ),
flameQuad: new THREE.QuadMesh( flameMaterial ),
pipeline,
uAspect,
uTime,
uDt,
uBurn,
uSparks,
uView,
uHeatTexel,
dispose() {
for ( const target of [ maskTarget, ...heatTargets, flameTarget ] ) target.dispose();
pipeline.dispose();
simMaterial.dispose();
flameMaterial.dispose();
maskMaterial.dispose();
},
};
resizeScreenFlames();
}
function resizeScreenFlames() {
if ( ! flames ) return;
const size = renderer.getDrawingBufferSize( new THREE.Vector2() );
const simWidth = Math.max( 8, Math.round( size.width * FLAME_SIM_SCALE ) );
const simHeight = Math.max( 8, Math.round( size.height * FLAME_SIM_SCALE ) );
flames.maskTarget.setSize( simWidth, simHeight );
for ( const target of flames.heatTargets ) target.setSize( simWidth, simHeight );
flames.flameTarget.setSize( size.width, size.height );
flames.uAspect.value = size.width / size.height;
flames.uHeatTexel.value.set( 1.5 / simWidth, 1.5 / simHeight );
}
function renderFlameMask() {
const previousTarget = renderer.getRenderTarget();
const previousBackground = scene.backgroundNode;
const previousOverride = scene.overrideMaterial;
const previousLayerMask = camera.layers.mask;
scene.backgroundNode = null;
scene.overrideMaterial = flames.maskMaterial;
camera.layers.set( DANCER_LAYER );
try {
renderer.setRenderTarget( flames.maskTarget );
renderer.render( scene, camera );
} finally {
renderer.setRenderTarget( previousTarget );
scene.backgroundNode = previousBackground;
scene.overrideMaterial = previousOverride;
camera.layers.mask = previousLayerMask;
}
}
function renderScreenFlames() {
flameClock += flameDelta;
flames.uTime.value = flameClock;
flames.uDt.value = Math.min( 0.05, Math.max( 0, flameDelta ) );
flames.uBurn.value = THREE.MathUtils.clamp( uiState.fire, 0, 1 );
flameDelta = 0;
renderFlameMask();
// Heat: read the previous field, write the next one.
const previous = flames.heatTargets[ flames.heatIndex ];
const next = flames.heatTargets[ 1 - flames.heatIndex ];
flames.heatNode.value = previous.texture;
renderer.setRenderTarget( next );
flames.simQuad.render( renderer );
flames.heatIndex = 1 - flames.heatIndex;
flames.heatNode.value = next.texture;
renderer.setRenderTarget( flames.flameTarget );
flames.flameQuad.render( renderer );
renderer.setRenderTarget( null );
// The composite reads the scene pass through its texture node, which renders it first.
flames.pipeline.render();
}
function createControls() {
const getDiagnostics = () => ( {
fixedDelta: SIMULATION_FIXED_DELTA,
danceTime,
fireMode: uiState.fireMode,
camera: {
position: camera.position.toArray(),
quaternion: camera.quaternion.toArray(),
},
controls: {
enabled: controls.enabled,
autoRotate: controls.autoRotate,
},
mesh: {
visible: mesh.visible,
scale: mesh.scale.toArray(),
position: mesh.position.toArray(),
},
sceneChildren: scene.children.length,
shaderVariants: {
useFlowDetail: material.useFlowDetail,
useHighFrequencyDetail: material.useHighFrequencyDetail,
useDiagnosticLighting: material.useDiagnosticLighting,
},
quality: {
tier: activeQualityTier,
resolutionScale: volumeResolutionScale,
activeRenderTarget: [ volumeCompositor.width, volumeCompositor.height ],
depthSigma: volumeDepthSigma,
raymarchSteps: material.smokeUniforms.steps.value,
temporal: volumeCompositor.temporal,
temporalJitter: material.smokeUniforms.temporalJitter.value,
volumeSide: material.side,
volumeDepthTest: material.depthTest,
},
grid: {
simRes: fluid.simRes,
dyeRes: fluid.dyeRes,
sdfRes: bodySDF.resolution,
turbulenceRes: fluid.turbulenceRes,
occupancyRes: fluid.occupancyRes,
lightRes: fluid.lightRes,
},
solver: {
iterations: fluid.iterations,
lastStep: fluid.getLastStepStats(),
},
} );
const step = ( steps = 1, { emit = true, dance = uiState.dance } = {} ) => {
uiState.autoStep = false;
for ( let index = 0; index < steps; index ++ ) {
advanceDance( dance ? SIMULATION_FIXED_DELTA * uiState.dancePace : 0 );
if ( uiState.fireMode !== 'volume' ) {
flameDelta = SIMULATION_FIXED_DELTA;
if ( index < steps - 1 ) renderScreenFlames();
continue;
}
if ( emit ) emitBodyFire();
fluid.step( renderer, SIMULATION_FIXED_DELTA, { refreshRenderCaches: index === steps - 1 } );
}
syncVolumeTextures();
renderFrame();
return getDiagnostics();
};
const resume = () => {
simulationAccumulator = 0;
previousFrameTime = performance.now();
uiState.autoStep = true;
};
return {
renderer,
pause: () => uiState.autoStep = false,
resume,
start: resume,
step,
prewarmPipelineVariants: ( options = {} ) => {
uiState.autoStep = false;
fluid.prewarmBatchedSplatVariants( renderer );
fluid.prewarmRenderCacheVariants( renderer, options );
syncVolumeTextures();
// Both render modes compile their pipelines.
const mode = uiState.fireMode;
for ( const variant of [ 'volume', 'flames' ] ) {
setFireMode( variant );
renderFrame();
}
setFireMode( mode );
renderFrame();
return getDiagnostics();
},
stir: stirPlume,
getDiagnostics,
setOrbitEnabled: ( enabled ) => controls.enabled = enabled === true,
setDance: ( enabled ) => uiState.dance = enabled === true,
setFireMode,
setFlameLook: ( { sparks, burn, view } = {} ) => {
if ( Number.isFinite( sparks ) ) flames.uSparks.value = sparks;
if ( Number.isFinite( burn ) ) uiState.fire = burn;
if ( Number.isFinite( view ) ) flames.uView.value = view;
},
setFire: ( amount ) => {
uiState.fire = Number( amount );
applyFireAmount();
},
setVolumeQuality: ( { resolutionScale, depthSigma, steps } = {} ) => {
if ( Number.isFinite( resolutionScale ) ) {
volumeResolutionScale = THREE.MathUtils.clamp( resolutionScale, 0.25, 1 );
uiState.volumeResolutionScale = volumeResolutionScale;
resizeVolumeCompositor();
}
if ( Number.isFinite( depthSigma ) ) {
volumeDepthSigma = Math.max( 0, depthSigma );
volumeCompositor.setDepthSigma( volumeDepthSigma );
}
if ( Number.isFinite( steps ) ) material.smokeUniforms.steps.value = steps;
return getDiagnostics().quality;
},
setQuality: setQualityTier,
setShaderVariants: ( variants = {} ) => material.setShaderVariants( variants ),
render: renderFrame,
setSimulationUniforms: ( settings = {} ) => {
for ( const [ key, value ] of Object.entries( settings ) ) {
if ( fluid[ key ]?.value !== undefined && typeof value === 'number' ) fluid[ key ].value = value;
}
},
setSmokeUniforms: ( settings = {} ) => {
for ( const [ key, value ] of Object.entries( settings ) ) {
const target = material.smokeUniforms[ key ];
if ( target?.value?.isColor === true ) target.value.set( value );
else if ( target && typeof value === 'number' ) target.value = value;
}
},
setCamera: ( { position = CAMERA_POSITION.toArray(), target = CAMERA_TARGET.toArray(), fov = 40 } = {} ) => {
camera.position.fromArray( position );
camera.fov = fov;
camera.updateProjectionMatrix();
controls.target.fromArray( target );
controls.update();
volumeCompositor.resetHistory();
},
};
}
export function unmount() {
window.removeEventListener( 'resize', onResize );
renderer?.setAnimationLoop( null );
controls?.dispose();
gui?.destroy();
gui = null;
mixer?.stopAllAction();
mixer = null;
action = null;
bodySDF?.dispose();
bodySDF = null;
fireKernels = null;
renderPipeline?.dispose();
volumeCompositor?.dispose();
fluid?.dispose();
fluid = null;
devtools?.dispose();
devtools = null;
renderer?.dispose();
renderer?.domElement?.remove();
flames?.dispose();
flames = null;
dancerRoot = null;
skinnedMesh = null;
hipsBone = null;
scene = null;
renderer = null;
container = null;
}