Fire (HLSL)

glint · Examples · Tutorials · Gallery

Written in HLSL: turbulent flames from stretched fractal noise, a black-body colour ramp and embers rising, the whole blaze roaring with the bass.

Audio-reactive: it moves with music from a microphone, line-in or a file.

Fire (HLSL): an audio-reactive HLSL shader

An example in glint, a free live shader editor in the browser: the GLSL code floats over the running picture and recompiles as you type.

The code

One pass, in HLSL.

vertex shader

// HLSL vertex shader (translated to GLSL in the browser).
float4x4 mvp;

struct VSOut
{
    float4 pos : SV_Position;
    float2 uv : TEXCOORD0;
    float3 normal : NORMAL;
};

VSOut main(float4 pos : POSITION, float3 normal : NORMAL, float2 uv : TEXCOORD0)
{
    VSOut o;
    o.pos = mul(mvp, pos);
    o.uv = uv;
    o.normal = normal;
    return o;
}

fragment shader

// Fire, in HLSL. Globals are uniforms; glint fills in time, resolution and the audio values by name.
float time;
float2 resolution;
float3 spectrum;
float beat;
float heat;

float hash(float2 p)
{
    return frac(sin(dot(p, float2(127.1, 311.7))) * 43758.5453);
}

float noise(float2 p)
{
    float2 i = floor(p);
    float2 f = frac(p);
    float2 u = f * f * (3.0 - 2.0 * f);
    return lerp(lerp(hash(i), hash(i + float2(1, 0)), u.x), lerp(hash(i + float2(0, 1)), hash(i + float2(1, 1)), u.x), u.y);
}

float fbm(float2 p)
{
    float v = 0.0;
    float a = 0.5;
    float2x2 m = float2x2(1.6, 1.2, -1.2, 1.6);
    [unroll]
    for (int i = 0; i < 6; i++)
    {
        v += a * noise(p);
        p = mul(m, p);
        a *= 0.5;
    }
    return v;
}

// Black-body-ish ramp: dark red -> orange -> yellow -> white.
float3 blackbody(float t)
{
    t = saturate(t);
    return float3(saturate(t * 3.0), saturate(t * 3.0 - 1.0), saturate(t * 3.0 - 2.0)) * (0.3 + 0.7 * t) + float3(0.1, 0.0, 0.0) * t;
}

float4 main(float4 pos : SV_Position, float2 uv : TEXCOORD0) : SV_Target
{
    float2 p = (pos.xy - float2(0.5 * resolution.x, 0.0)) / resolution.y;
    float roar = 1.0 + spectrum.x * 1.5 + beat;
    // Rising, turbulent noise: sample it moving downward, stretched vertically, and warp it with itself.
    float2 q = float2(p.x * 3.0, p.y * 1.5 - time * 1.4);
    float warp = fbm(q * 0.8 + time * 0.2);
    float n = fbm(q + warp * 1.5);
    // Flame shape: wide at the base, narrowing and fading with height.
    float shape = 1.0 - saturate(abs(p.x) * (1.6 - p.y) * 0.9);
    float flame = n * shape * heat * roar * 1.3 - p.y * 0.55;
    float3 col = blackbody(flame * 1.6);
    // Embers: sparse bright specks drifting up.
    float2 e = float2(p.x * 20.0, p.y * 20.0 - time * 6.0);
    float ember = step(0.985, hash(floor(e))) * smoothstep(0.3, 0.0, length(frac(e) - 0.5)) * saturate(1.0 - p.y);
    col += float3(1.0, 0.6, 0.2) * ember * roar;
    return float4(col, 1.0);
}

More HLSL & Bonzomatic examples

Bonzomatic starter · HLSL starter · HLSL raymarcher