FIRE FOUNTAIN
PARTICLE SYSTEM

By Shane Brumback · · Free Three.js tutorial

Build a realistic fire fountain particle system with Three.js — sphere particles, velocity physics, gravity simulation, and interactive sliders for real-time control — then take the same rig further into a glowing lava fountain.

Fire fountain Particle system Additive blending
See it live

LIVE DEMO

The fire fountain is running in the background right now. Launch the full-screen demo to orbit the scene and use the sliders to adjust the simulation in real-time.

Orbit: drag · Zoom: scroll · Esc to exit

Introduction

Three.js is a powerful JavaScript library for creating stunning 3D visualizations. One exciting application is fire fountain particle systems — realistic, dynamic fire effects that simulate flames erupting upward in a fountain-like manner.

This tutorial creates hundreds of sphere particles with random velocities, simulates gravity pulling them back down, and resets them at the origin to create a continuous flowing fountain. Interactive sliders let you adjust height, velocity, particle count, and radius in real-time — then the Lava & VFX section shows how the same rig becomes a glowing molten lava fountain.

WANT TO BLOW SOMETHING UP?

Switch gears from fountains to a full 3D rockfire explosion in Three.js — flying debris, fire, smoke, a shockwave, and a scorch crater that grows with the blast. The whole effect in one copy-paste file, with a live demo you can orbit.

3D Rockfire Explosion effect built in Three.js See the Rockfire Explosion Tutorial

Frequently Asked Questions

How do I create a fire particle system in Three.js?

Create a BufferGeometry with many vertices, assign random positions and velocities, use a PointsMaterial with an additive blending fire texture, then animate particles upward with gravity and fade-out in the render loop. Reset particles when they die to create a continuous fountain effect.

What is the best blending mode for fire particles in Three.js?

Use THREE.AdditiveBlending on your PointsMaterial. This makes overlapping particles appear brighter (light adds together), creating a realistic glowing fire effect. Combine with depthWrite: false and transparent: true for proper layering.

How do I make particles fade out as they rise?

Track each particle's age or lifetime in an attribute array. In your animation loop, reduce opacity based on age. Use a custom ShaderMaterial for per-particle opacity, or use size attenuation so particles shrink as they age, giving the appearance of fading.

How many particles can Three.js handle for a fire effect?

Modern GPUs handle 10,000-100,000 point particles easily at 60fps. For a fire fountain, 1,000-5,000 particles gives a good look. Use BufferGeometry (not regular Geometry) and update positions via the position attribute buffer for best performance.

How do I make a lava fountain effect in Three.js?

Start from the same fire fountain — velocity-driven particles with gravity and a reset loop — then map each blob's age to a colour ramp (white-hot, then yellow, orange, deep red, and finally dark crust). Render the blobs as one THREE.Points with a custom ShaderMaterial instead of 1,000 meshes, add a second additive Points pass for glow instead of lights or bloom, and spawn ember sparks, drifting smoke, and cooling crust splashes where blobs land.

How do I add glow to particles without bloom in Three.js?

Draw the same particles a second time with THREE.AdditiveBlending, a larger point size, and a soft radial falloff in the fragment shader. Overlapping glow halos add together and read like bloom, but it costs just one extra draw call and runs well on mobile with no post-processing pass.

How It Works

  • Particle Creation: 1,000 sphere meshes with random radii and yellow-to-orange gradient colors
  • Velocity Physics: Each particle gets random X, Y, Z velocity — Y is upward thrust, X/Z create spread
  • Gravity Simulation: Each frame subtracts a random friction value from Y velocity, pulling particles down
  • Reset Loop: When particles fall below reset height, they teleport back to origin with fresh velocity
  • OrbitControls: Auto-rotating camera with drag/zoom for exploring the effect from any angle
  • Interactive Sliders: Real-time adjustment of fountain height, velocity ranges, particle count, and size — drag them live to feel how each parameter shapes the plume

Those six moving parts are the whole engine. Master them here on the fire fountain and you can re-skin the exact same rig into a lava fountain, a water jet, confetti, or sparks — only the colours and spawn rules change, the physics loop stays identical.

From Fire Fountain to Lava Fountain

The fire fountain above already does the hard part: it throws particles upward, lets gravity drag them back, and recycles them forever. To make the same effect read as molten lava instead of fire, you change how the particles look over their lifetime rather than how they move.

  • Age → colour ramp: track how long each blob has been alive and map that to white-hot → yellow → orange → deep red → dark crust. Fresh blobs are blinding; old ones cool to a glowing-cracked rock.
  • Thicker, slower blobs: lava is heavier than flame, so widen the particle radius range and lower the upward velocity a touch — the plume should lob rather than flicker.
  • A churning vent: a small animated noise shader on a ground plane sells the idea that the blobs are erupting from a molten pool, not from nothing.
  • Embers, smoke & splashes: spawn a few bright ember sparks and soft smoke puffs near the vent, and leave cooling crust where blobs land. These extras cost almost nothing but add enormous realism.

Every one of those is a presentation tweak layered on the identical velocity-and-reset loop you already have. That is the real lesson of this tutorial: a solid particle rig is a canvas, and fire vs. lava is just paint.

Performance: 1,000 Meshes vs. One Draw Call

This beginner-friendly version uses 1,000 individual THREE.Mesh spheres because it is the easiest mental model: one object, one position, one colour. It runs fine for a demo, but each mesh is its own draw call, and that cost climbs fast as you crank the particle slider.

The production move — and the one a real lava fountain uses — is to render all the blobs as a single THREE.Points cloud driven by a custom ShaderMaterial. One geometry, one material, roughly one draw call for the whole fountain regardless of count. The colour ramp, the fake-sphere shading, and the glow all live in the shader, so the GPU does the heavy lifting.

  • Glow without bloom: draw the points a second time with additive blending and a soft falloff — one extra draw call that looks like a post-processing bloom pass but costs a fraction of it.
  • Mobile budget: cap the device pixel ratio (around 1.5), skip MSAA, and start with fewer particles so phones stay at 60fps.
  • Pause when hidden: stop the render loop when the tab is in the background so you never waste battery animating an invisible fountain.

The takeaway: learn the effect with 1,000 meshes here, then graduate to Points + a shader when you want thousands of molten blobs without the frame-rate tax.

DEMO VIDEO

Code Breakdown

Here is the whole fountain in plain English. Beginners: read the bold summaries to follow the flow. Developers: the gray notes after each snippet explain the why — the physics, the reset trick, and the performance choices.

1. Scene, camera, renderer & orbit controls

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, innerWidth/innerHeight, 0.1, 1000);
camera.position.set(20, 30, 35);

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);

const controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.autoRotate = true;
controls.target.set(0, 5, 0);

In plain English: the standard Three.js starting point — a scene to hold objects, a camera to view them, a renderer that draws to the canvas, and OrbitControls so you can drag to spin and scroll to zoom. Developer note: the camera is pulled back and up (20, 30, 35) and the orbit target is lifted to y=5 so the framing sits on the fountain’s plume rather than the ground, and autoRotate gives a gentle idle spin.

2. A pool of gradient-colored particles

const colorStart = new THREE.Color(0xffff00);   // yellow core
const colorEnd   = new THREE.Color(0xffa500);   // orange tips

for (let i = 0; i < 1000; i++) {
  const r = Math.random() * 0.5 + 0.1;
  const geo = new THREE.SphereGeometry(r);
  const mat = new THREE.MeshBasicMaterial({
    color: colorStart.clone().lerp(colorEnd, Math.random())
  });
  const p = new THREE.Mesh(geo, mat);
  // ...give it a velocity (next step)...
  particles.push(p);
  scene.add(p);
}

In plain English: we build 1,000 little spheres of random size and give each a color blended somewhere between yellow and orange, so the fountain reads as fire instead of one flat color. Developer note: colorStart.clone().lerp(colorEnd, Math.random()) picks a random point along the yellow→orange gradient per particle. MeshBasicMaterial is unlit, so the spheres glow at full brightness with no lighting cost — ideal for a fire look.

3. Launch velocity: up hard, out gently

p.velocity = new THREE.Vector3(
  (Math.random() - 0.5) * 0.5,   // X: small sideways spread
  Math.random() * 1.9 + 0.1,     // Y: strong upward thrust
  (Math.random() - 0.5) * 0.5    // Z: small sideways spread
);

In plain English: every particle is shot mostly straight up with just a little sideways drift, which is what makes it fountain upward in a tight column instead of spraying everywhere. Developer note: the (Math.random() - 0.5) trick centers the X/Z spread around zero (equal chance left or right), while Y is always positive and much larger — the ratio of up-thrust to sideways-spread is what tunes the plume’s shape.

4. Gravity + the reset loop (the heart of it)

function animate() {
  requestAnimationFrame(animate);
  for (const p of particles) {
    p.velocity.y -= 0.01 + Math.random() * 0.1;   // gravity pulls Y down
    p.position.add(p.velocity);                    // move by velocity
    if (p.position.y < 0) {                        // fell to the floor?
      p.position.set(0, 0, 0);                     // teleport back to the source
      p.velocity.set((Math.random()-0.5)*0.5, Math.random()*2, (Math.random()-0.5)*0.5);
    }
  }
  controls.update();
  renderer.render(scene, camera);
}
animate();

In plain English: each frame we pull every particle’s upward speed down a bit (gravity), move it, and — the key trick — when one falls back below the ground we snap it to the origin with a fresh velocity so it shoots up again. That recycling is what makes the fountain flow forever. Developer note: reusing the same 1,000 meshes instead of creating/destroying particles keeps memory flat and avoids garbage-collection hitches. The small random term on gravity (0.01 + Math.random()*0.1) makes particles fall at slightly different rates so the plume shimmers instead of moving as one rigid blob.

5. Stay responsive on resize

window.addEventListener('resize', () => {
  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(innerWidth, innerHeight);
});

In plain English: when the window changes size, we match the camera and canvas to it so the fountain never looks stretched. Developer note: you must call camera.updateProjectionMatrix() after changing aspect — without it the new aspect ratio is ignored and the scene distorts.

Lava & VFX: How the Molten Fountain Is Built

The beginner version above threw 1,000 individual THREE.Mesh spheres — one draw call each. The lava fountain running in the live background keeps the exact same velocity-and-reset loop but swaps the look: every molten blob is drawn from a single THREE.Points cloud with a custom ShaderMaterial, so the whole fountain is about eight draw calls no matter the particle count. On top of that it layers a colour ramp, fake-sphere crust, additive glow (fake bloom, no post-processing), a churning vent, embers, smoke, and cooling crust — the upgrade promised in the “1,000 Meshes vs. One Draw Call” card above. Here is how each piece works, straight from js/lava-fountain.js.

1. One Points cloud instead of 1,000 meshes

function makePoints(n, mat) {
  var g = new THREE.BufferGeometry();
  var pos  = new Float32Array(n * 3);
  var size = new Float32Array(n);
  var heat = new Float32Array(n);
  var seed = new Float32Array(n);
  for (var i = 0; i < n; i++) seed[i] = Math.random();
  g.setAttribute('position', new THREE.BufferAttribute(pos, 3).setUsage(THREE.DynamicDrawUsage));
  g.setAttribute('aSize', new THREE.BufferAttribute(size, 1).setUsage(THREE.DynamicDrawUsage));
  g.setAttribute('aHeat', new THREE.BufferAttribute(heat, 1).setUsage(THREE.DynamicDrawUsage));
  g.setAttribute('aSeed', new THREE.BufferAttribute(seed, 1));
  var pts = new THREE.Points(g, mat); pts.frustumCulled = false;
  return { pts: pts, g: g, pos: pos, size: size, heat: heat };
}

In plain English: one geometry holds every blob, with a per-particle position, aSize, aHeat (how hot/young it is) and aSeed (per-blob randomness), drawn as a single THREE.Points — one draw call for the whole fountain. Developer note: DynamicDrawUsage tells the GPU these buffers change every frame, and aHeat is what the shaders read to colour each blob by its age.

2. The lava colour ramp (one GLSL function)

vec3 lavaRamp(float t){            // t: 1 = fresh/white-hot, 0 = cold crust
  vec3 crust  = vec3(0.06,0.03,0.025);
  vec3 red    = vec3(0.55,0.04,0.0);
  vec3 orange = vec3(1.0,0.35,0.02);
  vec3 yellow = vec3(1.0,0.85,0.35);
  vec3 white  = vec3(1.0,0.98,0.85);
  vec3 c = mix(crust, red,    smoothstep(0.0,0.3,t));
  c = mix(c, orange, smoothstep(0.3,0.6,t));
  c = mix(c, yellow, smoothstep(0.6,0.85,t));
  c = mix(c, white,  smoothstep(0.85,1.0,t));
  return c;
}

In plain English: a single function maps a blob’s heat t (1 = just erupted, 0 = cooled crust) through white-hot → yellow → orange → deep red → dark crust. Developer note: fresh blobs are blinding; as aHeat falls each frame the same blob slides down the ramp and cools — this is the entire “fire turns to lava” look, done on the GPU.

3. Fake-sphere shading & glowing crust cracks

void main(){
  vec2 p = gl_PointCoord*2.0-1.0; float d = dot(p,p); if(d>1.0) discard;
  float nz = sqrt(1.0-d);                                  // fake sphere normal
  float n  = fbm(p*2.5 + vSeed*17.0 + uTime*0.6);          // animated noise
  float crust = smoothstep(0.55,0.15,vHeat);               // how much crust covers it
  float crack = smoothstep(0.42,0.5,n)*smoothstep(0.62,0.5,n); // thin glowing cracks
  float heat  = clamp(vHeat + 0.25*(n-0.5), 0.0, 1.0);
  vec3 hot  = lavaRamp(heat)*(0.7+0.6*nz);
  vec3 cold = lavaRamp(0.0)*(0.5+0.8*nz) + lavaRamp(0.35)*crack*1.6;
  vec3 col  = mix(hot, cold, crust*smoothstep(0.3,0.7,n+0.3));
  col += lavaRamp(1.0)*pow(nz,6.0)*vHeat*0.5;              // white-hot centre
  gl_FragColor = vec4(col, smoothstep(1.0,0.8,d));
}

In plain English: each point is a flat square, but nz = sqrt(1.0 - d) fakes a sphere normal from gl_PointCoord so flat points read as round molten blobs. Developer note: fbm noise drives thin cracks that keep glowing (lavaRamp(0.35)*crack), and crust grows as vHeat drops so a cooling blob turns to cracked rock — no lights, no textures.

4. Glow without bloom (a second additive pass)

// GLOW_FRAG
void main(){
  vec2 p = gl_PointCoord*2.0-1.0; float d = dot(p,p); if(d>1.0) discard;
  float a = exp(-d*4.0)*smoothstep(0.08,0.6,vHeat)*uGlow;
  gl_FragColor = vec4(lavaRamp(min(vHeat+0.1,1.0))*a, 1.0);
}

// additive colour (ONE,ONE) but leave destination alpha untouched, so glow never
// punches opaque black holes in the transparent hero canvas
blending: THREE.CustomBlending,
blendSrc: THREE.OneFactor,  blendDst: THREE.OneFactor,  blendEquation: THREE.AddEquation,
blendSrcAlpha: THREE.ZeroFactor, blendDstAlpha: THREE.OneFactor, blendEquationAlpha: THREE.AddEquation

In plain English: the same blob geometry is drawn a second time with a soft radial falloff (exp(-d*4.0)) and additive blending — overlapping halos add up and read like a bloom post-process, but it is just one extra draw call. Developer note: the custom (ONE, ONE) colour blend with ZERO/ONE on the ALPHA channel adds light without destroying the canvas’s destination alpha, so the glow never punches black holes in the transparent hero background.

5. The churning lava vent

void main(){
  vec2 p = vUv*2.0-1.0; float r = length(p); if(r>1.0) discard;
  float n  = fbm(p*3.0 + vec2(uTime*0.3,-uTime*0.2));
  float n2 = fbm(p*6.0 - vec2(uTime*0.5, uTime*0.4));
  float h  = clamp(1.15 - r*0.9 + 0.45*(n-0.5) + 0.25*(n2-0.5), 0.0, 1.0);
  float crust = smoothstep(0.55,0.62,n2)*smoothstep(0.3,1.0,r);  // floating crust plates
  vec3 c = mix(lavaRamp(h), lavaRamp(0.05), crust*0.85);
  gl_FragColor = vec4(c*(1.0+0.3*sin(uTime*3.0+n*6.0)*(1.0-r)), smoothstep(1.0,0.92,r));
}

In plain English: a flat PlaneGeometry on the ground runs two layers of animated fbm noise to sell a molten pool the blobs erupt from. Developer note: dark crust plates float on the hotter centre, and a sin(uTime*...) term makes the pool pulse/flicker, with a separate additive ventGlow sprite (driven by uGlow in the animate loop) over it for the heat bloom.

6. Embers, splashes & cooling crust

function spark(x, y, z, vx, vy, vz, l, s) {
  var j = sIdx; sIdx = (sIdx + 1) % MAX_SPARKS;   // ring buffer, never allocates
  sparks.pos[j*3] = x; sparks.pos[j*3+1] = y; sparks.pos[j*3+2] = z;
  sVel[j*3] = vx; sVel[j*3+1] = vy; sVel[j*3+2] = vz;
  sLife[j] = sMax[j] = l; sparks.size[j] = s;
}
function splash(x, z, r) {
  var n = isMobile ? 3 : 6;
  for (var k = 0; k < n; k++) {
    var a = Math.random()*6.283, sp = rnd(0.08,0.35);
    spark(x, 0.1, z, Math.cos(a)*sp, rnd(0.15,0.5), Math.sin(a)*sp, rnd(18,35), rnd(0.25,0.5));
  }
  if (Math.random() < 0.5) {              // leave a cooling crust decal where it landed
    var d = decalIdx; decalIdx = (decalIdx + 1) % MAX_DECALS;
    dOff[d*3] = x; dOff[d*3+1] = 0.04 + d*0.0001; dOff[d*3+2] = z;
    dSize[d] = r * rnd(2.5,4.5); dHeat[d] = 1;
  }
  if (Math.random() < 0.08) puff(x, 0.5, z, rnd(5,9));  // occasional smoke puff
}

In plain English: sparks live in a fixed-size ring buffer (sIdx = (sIdx+1) % MAX_SPARKS) so emitting embers never allocates memory or triggers garbage collection. Developer note: when the step loop sees a blob cross y < 0 while falling it calls splash(), which sprays a ring of droplet sparks, drops an instanced crust decal (dHeat = 1, cooling toward 0 each frame), and sometimes a smoke puff — the landing feedback that sells real lava.

7. Mobile performance budget

var isMobile = /Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent)
               || Math.min(innerWidth, innerHeight) < 600;

var renderer = new THREE.WebGLRenderer({ antialias: !isMobile, alpha: true, powerPreference: 'high-performance' });
var PR = Math.min(window.devicePixelRatio || 1, isMobile ? 1.5 : 2);
renderer.setPixelRatio(PR);

// fewer embers + less smoke on phones
var em = isMobile ? 2 : 4;
if (frame % (isMobile ? 6 : 3) === 0) puff(/* ... */);

// start count is clamped to 1000 on mobile
particleCount: isMobile ? Math.min(opts.particleCount || 1000, 1000) : (opts.particleCount || 1000),

// stop rendering when the tab is hidden
document.addEventListener('visibilitychange', function () { paused = document.hidden; });

In plain English: on mobile the script caps the device pixel ratio at 1.5, turns MSAA off (antialias: !isMobile), emits fewer embers and smoke, starts at 1,000 blobs, and pauses the whole render loop when the tab is backgrounded. Developer note: it is the same fire-fountain velocity-and-reset loop under the hood — only the look (Points + shaders + glow + vent) and these perf guards changed, which is why phones stay near 60fps and never burn battery on an invisible fountain.

The Full Code

Copy this into a file named index.html and open it in any modern browser — or hit Launch. Three.js and the lava VFX engine (lava-fountain.js) load from a CDN, so it runs as-is. The full shader/particle source lives in lava-fountain.js — walked through step by step in the Lava & VFX section above.

<!DOCTYPE html>
<html><head>
<meta charset="utf-8">
<style>
  body{margin:0;overflow:hidden;background:#000;font-family:Arial,sans-serif}
  #ui{position:fixed;left:14px;top:14px;z-index:2;color:#cfe;min-width:220px}
  #ui label{display:block;font-size:12px;margin:10px 0 2px;color:#9adfe2}
  #ui input[type=range]{width:100%}
</style>
<!-- Pinned so the shaders stay compatible -->
<script src="https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.147.0/examples/js/controls/OrbitControls.js"></script>
</head><body>
<div id="ui">
  <label>Fountain Height</label><input id="h" type="range" min="1" max="10" step="0.25" value="5">
  <label>X Velocity Range</label><input id="x" type="range" min="0.1" max="1" step="0.1" value="0.5">
  <label>Z Velocity Range</label><input id="z" type="range" min="0.1" max="1" step="0.1" value="0.5">
  <label>Particle Count</label><input id="c" type="range" min="1000" max="20000" step="1000" value="1000">
  <label>Y Velocity (max)</label><input id="y" type="range" min="0.1" max="5" step="0.1" value="2">
  <label>Particle Radius (max)</label><input id="r" type="range" min="0.1" max="1" step="0.1" value="0.6">
</div>

<!-- ===== The entire lava VFX engine (window.LavaFountain) ===== -->
<script>
/*! lava-fountain.js v1.0 (2026-10-25) — drop-in Lava Fountain VFX for
 *  /tutorials/how-to-program-a-fire-fountain-particle-system.html
 *  Classic script, uses global THREE (three.min.js r150-r160) + THREE.OrbitControls.
 *  No PointLights, no post-processing. Draw calls: ~8 regardless of particle count.
 *    blobs core (Points) + blob glow (Points, additive) + sparks/splash (Points, additive)
 *    + smoke (Points) + crust decals (instanced quads) + vent pool + vent rim + vent glow + grid
 */
(function () {
  'use strict';
  var T = window.THREE;
  var MAX_BLOBS = 20000, MAX_SPARKS = 1500, MAX_SMOKE = 160, MAX_DECALS = 220;
  var isMobile = /Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent) || Math.min(innerWidth, innerHeight) < 600;

  // ---------- shared GLSL ----------
  var RAMP = [
    'vec3 lavaRamp(float t){',            // t: 1 = fresh/white-hot, 0 = cold crust
    '  vec3 crust=vec3(0.06,0.03,0.025);',
    '  vec3 red=vec3(0.55,0.04,0.0);',
    '  vec3 orange=vec3(1.0,0.35,0.02);',
    '  vec3 yellow=vec3(1.0,0.85,0.35);',
    '  vec3 white=vec3(1.0,0.98,0.85);',
    '  vec3 c=mix(crust,red,smoothstep(0.0,0.3,t));',
    '  c=mix(c,orange,smoothstep(0.3,0.6,t));',
    '  c=mix(c,yellow,smoothstep(0.6,0.85,t));',
    '  c=mix(c,white,smoothstep(0.85,1.0,t));',
    '  return c;}',
    'float hash(vec2 p){return fract(sin(dot(p,vec2(127.1,311.7)))*43758.5453);}',
    'float noise(vec2 p){vec2 i=floor(p),f=fract(p);f=f*f*(3.0-2.0*f);',
    ' return mix(mix(hash(i),hash(i+vec2(1,0)),f.x),mix(hash(i+vec2(0,1)),hash(i+vec2(1,1)),f.x),f.y);}',
    'float fbm(vec2 p){float v=0.0,a=0.5;for(int i=0;i<4;i++){v+=a*noise(p);p*=2.03;a*=0.5;}return v;}'
  ].join('\n');

  var PT_VERT = [
    'attribute float aSize; attribute float aHeat; attribute float aSeed;',
    'uniform float uScale; uniform float uSizeMul; uniform float uMaxPx;',
    'varying float vHeat; varying float vSeed;',
    'void main(){ vHeat=aHeat; vSeed=aSeed;',
    ' vec4 mv=modelViewMatrix*vec4(position,1.0);',
    ' gl_PointSize=min(aSize*uSizeMul*uScale/max(-mv.z,0.1),uMaxPx);',
    ' if(aSize<=0.0) gl_PointSize=0.0;',
    ' gl_Position=projectionMatrix*mv; }'
  ].join('\n');

  function ptMat(frag, additive, extraU) {
    var u = { uScale: { value: 1 }, uSizeMul: { value: 1 }, uMaxPx: { value: 256 }, uTime: { value: 0 } };
    for (var k in (extraU || {})) u[k] = extraU[k];
    return new T.ShaderMaterial({
      uniforms: u, vertexShader: PT_VERT, fragmentShader: RAMP + '\n' + frag,
      transparent: true, depthWrite: false, depthTest: true,
      blending: additive ? T.CustomBlending : T.NormalBlending,
      // additive colour (ONE,ONE) but leave destination alpha untouched, so glow never
      // punches opaque black holes in the transparent hero canvas
      blendSrc: T.OneFactor, blendDst: T.OneFactor, blendEquation: T.AddEquation,
      blendSrcAlpha: T.ZeroFactor, blendDstAlpha: T.OneFactor, blendEquationAlpha: T.AddEquation
    });
  }

  // molten blob core: fake-sphere shading + crust cracks that keep glowing
  var BLOB_FRAG = [
    'uniform float uTime; varying float vHeat; varying float vSeed;',
    'void main(){ vec2 p=gl_PointCoord*2.0-1.0; float d=dot(p,p); if(d>1.0) discard;',
    ' float nz=sqrt(1.0-d);',
    ' float n=fbm(p*2.5+vSeed*17.0+uTime*0.6);',
    ' float crust=smoothstep(0.55,0.15,vHeat);',                 // how much crust covers it
    ' float crack=smoothstep(0.42,0.5,n)*smoothstep(0.62,0.5,n);',// thin glowing cracks
    ' float heat=clamp(vHeat+0.25*(n-0.5),0.0,1.0);',
    ' vec3 hot=lavaRamp(heat)*(0.7+0.6*nz);',
    ' vec3 cold=lavaRamp(0.0)*(0.5+0.8*nz)+lavaRamp(0.35)*crack*1.6;',
    ' vec3 col=mix(hot,cold,crust*smoothstep(0.3,0.7,n+0.3));',
    ' col+=lavaRamp(1.0)*pow(nz,6.0)*vHeat*0.5;',                // white-hot centre
    ' gl_FragColor=vec4(col,smoothstep(1.0,0.8,d)); }'
  ].join('\n');

  // additive halo = fake bloom
  var GLOW_FRAG = [
    'uniform float uGlow; varying float vHeat; varying float vSeed;',
    'void main(){ vec2 p=gl_PointCoord*2.0-1.0; float d=dot(p,p); if(d>1.0) discard;',
    ' float a=exp(-d*4.0)*smoothstep(0.08,0.6,vHeat)*uGlow;',
    ' gl_FragColor=vec4(lavaRamp(min(vHeat+0.1,1.0))*a,1.0); }'
  ].join('\n');

  var SPARK_FRAG = [
    'varying float vHeat; varying float vSeed;',
    'void main(){ vec2 p=gl_PointCoord*2.0-1.0; float d=dot(p,p); if(d>1.0) discard;',
    ' float a=exp(-d*6.0)+0.6*exp(-d*40.0);',
    ' gl_FragColor=vec4(lavaRamp(0.35+0.65*vHeat)*a*vHeat*1.6,1.0); }'
  ].join('\n');

  var SMOKE_FRAG = [
    'uniform float uTime; varying float vHeat; varying float vSeed;',   // vHeat = 1 young -> 0 dead
    'void main(){ vec2 p=gl_PointCoord*2.0-1.0;',
    ' p+=0.12*vec2(sin(uTime*1.7+vSeed*9.0+p.y*4.0),cos(uTime*1.3+vSeed*5.0+p.x*4.0));', // heat-haze wobble
    ' float d=dot(p,p); if(d>1.0) discard;',
    ' float n=fbm(p*1.8+vec2(vSeed*10.0,-uTime*0.25));',
    ' float a=smoothstep(1.0,0.1,d)*n*0.4*smoothstep(0.0,0.35,vHeat)*smoothstep(1.0,0.8,vHeat);',
    ' vec3 c=mix(vec3(0.09,0.08,0.08),vec3(0.55,0.18,0.05),pow(vHeat,3.0));', // lit orange from below when young
    ' gl_FragColor=vec4(c,a); }'
  ].join('\n');

  // ground crust decals (instanced quads lying on y=0)
  var DECAL_VERT = [
    'attribute vec3 iOffset; attribute float iSize; attribute float iHeat; attribute float iSeed;',
    'varying vec2 vUv; varying float vHeat; varying float vSeed;',
    'void main(){ vUv=uv*2.0-1.0; vHeat=iHeat; vSeed=iSeed;',
    ' vec3 p=vec3(position.x*iSize,0.0,position.y*iSize)+iOffset;',
    ' gl_Position=projectionMatrix*modelViewMatrix*vec4(p,1.0); }'
  ].join('\n');
  var DECAL_FRAG = [
    'varying vec2 vUv; varying float vHeat; varying float vSeed;',
    'void main(){ float n=fbm(vUv*3.0+vSeed*31.0);',
    ' float r=length(vUv)+0.35*(n-0.5); if(r>0.9||vHeat<=0.0) discard;',
    ' float crack=smoothstep(0.47,0.5,n)*smoothstep(0.53,0.5,n);',
    ' float h=clamp(vHeat*(1.1-r)+crack*0.35*vHeat,0.0,1.0);',
    ' vec3 c=mix(lavaRamp(0.0),lavaRamp(h),smoothstep(0.05,0.4,h));',
    ' c+=lavaRamp(0.4)*crack*(0.25+vHeat);',
    ' float a=smoothstep(0.9,0.7,r)*min(1.0,vHeat*4.0+0.25);',
    ' gl_FragColor=vec4(c,a); }'
  ].join('\n');

  var VENT_FRAG = [
    'uniform float uTime; varying vec2 vUv;',
    'void main(){ vec2 p=vUv*2.0-1.0; float r=length(p); if(r>1.0) discard;',
    ' float n=fbm(p*3.0+vec2(uTime*0.3,-uTime*0.2));',
    ' float n2=fbm(p*6.0-vec2(uTime*0.5,uTime*0.4));',
    ' float h=clamp(1.15-r*0.9+0.45*(n-0.5)+0.25*(n2-0.5),0.0,1.0);',
    ' float crust=smoothstep(0.55,0.62,n2)*smoothstep(0.3,1.0,r);',  // floating crust plates
    ' vec3 c=mix(lavaRamp(h),lavaRamp(0.05),crust*0.85);',
    ' gl_FragColor=vec4(c*(1.0+0.3*sin(uTime*3.0+n*6.0)*(1.0-r)),smoothstep(1.0,0.92,r)); }'
  ].join('\n');

  function makePoints(n, mat) {
    var g = new T.BufferGeometry();
    var pos = new Float32Array(n * 3), size = new Float32Array(n), heat = new Float32Array(n), seed = new Float32Array(n);
    for (var i = 0; i < n; i++) seed[i] = Math.random();
    g.setAttribute('position', new T.BufferAttribute(pos, 3).setUsage(T.DynamicDrawUsage));
    g.setAttribute('aSize', new T.BufferAttribute(size, 1).setUsage(T.DynamicDrawUsage));
    g.setAttribute('aHeat', new T.BufferAttribute(heat, 1).setUsage(T.DynamicDrawUsage));
    g.setAttribute('aSeed', new T.BufferAttribute(seed, 1));
    g.boundingSphere = new T.Sphere(new T.Vector3(0, 20, 0), 400);
    var pts = new T.Points(g, mat); pts.frustumCulled = false;
    return { pts: pts, g: g, pos: pos, size: size, heat: heat };
  }

  function create(opts) {
    opts = opts || {};
    var S = {
      fountainHeight: 50, resetHeight: 0, xVelocityRange: 0.5, zVelocityRange: 0.5,
      particleCount: isMobile ? Math.min(opts.particleCount || 1000, 1000) : (opts.particleCount || 1000),
      yVelocityRange: { min: 0.1, max: 2 }, particleRadiusRange: { min: 0.1, max: 0.6 }
    };

    var scene = new T.Scene();
    var camera = new T.PerspectiveCamera(75, innerWidth / innerHeight, 0.1, 1000);
    camera.position.set(20, 30, 35);
    camera.lookAt(new T.Vector3(0, 30, 0));
    var renderer = new T.WebGLRenderer({ antialias: !isMobile, alpha: true, powerPreference: 'high-performance' });
    var PR = Math.min(window.devicePixelRatio || 1, isMobile ? 1.5 : 2);
    renderer.setPixelRatio(PR);
    renderer.setSize(innerWidth, innerHeight);
    renderer.toneMapping = T.ReinhardToneMapping;
    renderer.toneMappingExposure = 1.6;
    renderer.setClearColor(0x000000, 0);
    renderer.domElement.id = 'renderer';
    var st = renderer.domElement.style; st.position = 'fixed'; st.zIndex = '-3'; st.left = '0'; st.top = '0';
    document.body.appendChild(renderer.domElement);

    var grid = new T.GridHelper(100, 50, 0x3a1a0a, 0x2a1208);
    scene.add(grid);

    var controls = new T.OrbitControls(camera, renderer.domElement);
    controls.autoRotate = true; controls.autoRotateSpeed = 2;
    controls.target.set(0, 5, 0); controls.enableDamping = true; controls.dampingFactor = 0.05;
    controls.update();

    // --- vent / lava pool ---
    var ventMat = new T.ShaderMaterial({
      uniforms: { uTime: { value: 0 } }, transparent: true, depthWrite: false,
      vertexShader: 'varying vec2 vUv; void main(){vUv=uv; gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.0);}',
      fragmentShader: RAMP + '\n' + VENT_FRAG
    });
    var vent = new T.Mesh(new T.PlaneGeometry(9, 9), ventMat);
    vent.rotation.x = -Math.PI / 2; vent.position.y = 0.03; vent.renderOrder = 1; scene.add(vent);
    var rim = new T.Mesh(new T.RingGeometry(4.1, 6.2, 40, 1), new T.MeshBasicMaterial({ color: 0x140806 }));
    rim.rotation.x = -Math.PI / 2; rim.position.y = 0.02; scene.add(rim);
    var ventGlowMat = ptMat(GLOW_FRAG, true, { uGlow: { value: 0.55 } });
    var ventGlow = makePoints(3, ventGlowMat);
    ventGlow.pos.set([0, 0.8, 0, 0, 3, 0, 0, 8, 0]); ventGlow.size.set([16, 13, 9]); ventGlow.heat.set([0.85, 0.7, 0.5]);
    ventGlow.pts.renderOrder = 5; scene.add(ventGlow.pts);

    // --- decals ---
    var dGeo = new T.InstancedBufferGeometry(); dGeo.copy(new T.PlaneGeometry(2, 2));
    var dOff = new Float32Array(MAX_DECALS * 3), dSize = new Float32Array(MAX_DECALS), dHeat = new Float32Array(MAX_DECALS), dSeed = new Float32Array(MAX_DECALS);
    for (var i = 0; i < MAX_DECALS; i++) dSeed[i] = Math.random();
    dGeo.setAttribute('iOffset', new T.InstancedBufferAttribute(dOff, 3).setUsage(T.DynamicDrawUsage));
    dGeo.setAttribute('iSize', new T.InstancedBufferAttribute(dSize, 1).setUsage(T.DynamicDrawUsage));
    dGeo.setAttribute('iHeat', new T.InstancedBufferAttribute(dHeat, 1).setUsage(T.DynamicDrawUsage));
    dGeo.setAttribute('iSeed', new T.InstancedBufferAttribute(dSeed, 1));
    dGeo.instanceCount = MAX_DECALS;
    var decals = new T.Mesh(dGeo, new T.ShaderMaterial({
      vertexShader: DECAL_VERT, fragmentShader: RAMP + '\n' + DECAL_FRAG, transparent: true, depthWrite: false,
      polygonOffset: true, polygonOffsetFactor: -1
    }));
    decals.frustumCulled = false; decals.renderOrder = 0; scene.add(decals);
    var decalIdx = 0;

    // --- blobs (core + glow share one geometry) ---
    var blobMat = ptMat(BLOB_FRAG, false);
    var blobs = makePoints(MAX_BLOBS, blobMat);
    var glowMat = ptMat(GLOW_FRAG, true, { uGlow: { value: 0.22 } });
    glowMat.uniforms.uSizeMul.value = 3.2; glowMat.uniforms.uMaxPx.value = isMobile ? 64 : 110;
    var blobGlow = new T.Points(blobs.g, glowMat); blobGlow.frustumCulled = false;
    blobs.pts.renderOrder = 3; blobGlow.renderOrder = 4;
    scene.add(blobs.pts); scene.add(blobGlow);
    var vel = new Float32Array(MAX_BLOBS * 3), age = new Float32Array(MAX_BLOBS), life = new Float32Array(MAX_BLOBS), rad = new Float32Array(MAX_BLOBS), landed = new Uint8Array(MAX_BLOBS);

    // --- sparks + splash droplets ---
    var sparkMat = ptMat(SPARK_FRAG, true); sparkMat.uniforms.uMaxPx.value = 24;
    var sparks = makePoints(MAX_SPARKS, sparkMat); sparks.pts.renderOrder = 6; scene.add(sparks.pts);
    var sVel = new Float32Array(MAX_SPARKS * 3), sLife = new Float32Array(MAX_SPARKS), sMax = new Float32Array(MAX_SPARKS), sIdx = 0;

    // --- smoke ---
    var smokeMat = ptMat(SMOKE_FRAG, false); smokeMat.uniforms.uMaxPx.value = isMobile ? 160 : 300;
    var smoke = makePoints(MAX_SMOKE, smokeMat); smoke.pts.renderOrder = 2; scene.add(smoke.pts);
    var mVel = new Float32Array(MAX_SMOKE * 3), mLife = new Float32Array(MAX_SMOKE), mMax = new Float32Array(MAX_SMOKE), mIdx = 0;

    function rnd(a, b) { return a + Math.random() * (b - a); }
    function num(v) { return typeof v === 'number' ? v : parseFloat(v); }

    function spawnBlob(i, randomVy) {
      blobs.pos[i * 3] = rnd(-0.6, 0.6); blobs.pos[i * 3 + 1] = 0; blobs.pos[i * 3 + 2] = rnd(-0.6, 0.6);
      var xr = num(S.xVelocityRange), zr = num(S.zVelocityRange), y = S.yVelocityRange;
      vel[i * 3] = Math.random() * xr - xr / 2;
      vel[i * 3 + 1] = Math.random() * (y.max - y.min) + y.min;
      vel[i * 3 + 2] = Math.random() * zr - zr / 2;
      age[i] = 0; landed[i] = 0;
      life[i] = Math.max(8, vel[i * 3 + 1] * 2 / 0.06); // expected flight frames for heat ramp
      rad[i] = Math.random() * (S.particleRadiusRange.max - S.particleRadiusRange.min) + S.particleRadiusRange.min;
      blobs.size[i] = rad[i] * 2.2;
      blobs.heat[i] = 1;
    }
    function spark(x, y, z, vx, vy, vz, l, s) {
      var j = sIdx; sIdx = (sIdx + 1) % MAX_SPARKS;
      sparks.pos[j * 3] = x; sparks.pos[j * 3 + 1] = y; sparks.pos[j * 3 + 2] = z;
      sVel[j * 3] = vx; sVel[j * 3 + 1] = vy; sVel[j * 3 + 2] = vz;
      sLife[j] = sMax[j] = l; sparks.size[j] = s;
    }
    function puff(x, y, z, s) {
      var j = mIdx; mIdx = (mIdx + 1) % MAX_SMOKE;
      smoke.pos[j * 3] = x; smoke.pos[j * 3 + 1] = y; smoke.pos[j * 3 + 2] = z;
      mVel[j * 3] = rnd(-0.03, 0.03); mVel[j * 3 + 1] = rnd(0.06, 0.12); mVel[j * 3 + 2] = rnd(-0.03, 0.03);
      mLife[j] = mMax[j] = rnd(140, 220); smoke.size[j] = s;
    }
    function splash(x, z, r) {
      var n = isMobile ? 3 : 6;
      for (var k = 0; k < n; k++) {
        var a = Math.random() * 6.283, sp = rnd(0.08, 0.35);
        spark(x, 0.1, z, Math.cos(a) * sp, rnd(0.15, 0.5), Math.sin(a) * sp, rnd(18, 35), rnd(0.25, 0.5));
      }
      if (Math.random() < 0.5) {
        var d = decalIdx; decalIdx = (decalIdx + 1) % MAX_DECALS;
        dOff[d * 3] = x; dOff[d * 3 + 1] = 0.04 + d * 0.0001; dOff[d * 3 + 2] = z;
        dSize[d] = r * rnd(2.5, 4.5); dHeat[d] = 1;
      }
      if (Math.random() < 0.08) puff(x, 0.5, z, rnd(5, 9));
    }

    function setCount(n) { n = Math.max(0, Math.min(MAX_BLOBS, Math.round(num(n)))); for (var i = S.particleCount; i < n; i++) spawnBlob(i); for (var k = n; k < S.particleCount; k++) blobs.size[k] = 0; S.particleCount = n; blobs.g.setDrawRange(0, n); }
    for (var i0 = 0; i0 < S.particleCount; i0++) { spawnBlob(i0); age[i0] = Math.random() * life[i0]; }
    blobs.g.setDrawRange(0, S.particleCount);

    function resize() {
      camera.aspect = innerWidth / innerHeight; camera.updateProjectionMatrix();
      renderer.setSize(innerWidth, innerHeight);
      var sc = innerHeight * PR / (2 * Math.tan(camera.fov * Math.PI / 360));
      [blobMat, glowMat, sparkMat, smokeMat, ventGlowMat].forEach(function (m) { m.uniforms.uScale.value = sc; });
    }
    window.addEventListener('resize', resize); resize();

    var t0 = performance.now(), frame = 0, paused = false;
    function step() {
      var n = S.particleCount, P = blobs.pos;
      for (var i = 0; i < n; i++) {
        var i3 = i * 3;
        vel[i3 + 1] -= 0.01 + Math.random() * 0.1;          // original physics, unchanged
        P[i3] += vel[i3]; P[i3 + 1] += vel[i3 + 1]; P[i3 + 2] += vel[i3 + 2];
        age[i]++;
        var h = 1 - age[i] / life[i];
        if (landed[i]) h = Math.min(h, 0.15);
        blobs.heat[i] = h < 0 ? 0 : h;
        if (!landed[i] && P[i3 + 1] < 0 && vel[i3 + 1] < 0) { landed[i] = 1; splash(P[i3], P[i3 + 2], rad[i]); }
        if (P[i3 + 1] < S.resetHeight) spawnBlob(i);
        else if (h > 0.5 && Math.random() < 0.0015) spark(P[i3], P[i3 + 1], P[i3 + 2], vel[i3] * 0.5 + rnd(-0.1, 0.1), vel[i3 + 1] * 0.5 + rnd(0, 0.2), vel[i3 + 2] * 0.5 + rnd(-0.1, 0.1), rnd(30, 60), rnd(0.15, 0.3));
      }
      // vent embers
      var em = isMobile ? 2 : 4;
      for (var e = 0; e < em; e++) { var a = Math.random() * 6.283, rr = Math.random() * 3; spark(Math.cos(a) * rr, 0.3, Math.sin(a) * rr, rnd(-0.08, 0.08), rnd(0.25, 0.7), rnd(-0.08, 0.08), rnd(40, 90), rnd(0.15, 0.35)); }
      if (frame % (isMobile ? 6 : 3) === 0) puff(rnd(-2, 2), rnd(1, 4), rnd(-2, 2), rnd(7, 13));
      // sparks
      for (var j = 0; j < MAX_SPARKS; j++) {
        if (sLife[j] <= 0) { sparks.size[j] = 0; continue; }
        var j3 = j * 3; sLife[j]--;
        sVel[j3 + 1] -= 0.012; sVel[j3] += rnd(-0.01, 0.01); sVel[j3 + 2] += rnd(-0.01, 0.01);
        sparks.pos[j3] += sVel[j3]; sparks.pos[j3 + 1] += sVel[j3 + 1]; sparks.pos[j3 + 2] += sVel[j3 + 2];
        if (sparks.pos[j3 + 1] < 0) { sparks.pos[j3 + 1] = 0; sVel[j3 + 1] *= -0.3; }
        sparks.heat[j] = sLife[j] / sMax[j] * (0.7 + 0.3 * Math.random());
      }
      // smoke
      for (var m = 0; m < MAX_SMOKE; m++) {
        if (mLife[m] <= 0) { smoke.size[m] = 0; continue; }
        var m3 = m * 3; mLife[m]--;
        smoke.pos[m3] += mVel[m3] + 0.02; smoke.pos[m3 + 1] += mVel[m3 + 1]; smoke.pos[m3 + 2] += mVel[m3 + 2];
        smoke.size[m] += 0.06; smoke.heat[m] = mLife[m] / mMax[m];
      }
      // decals cool slowly into crust
      for (var d = 0; d < MAX_DECALS; d++) if (dHeat[d] > 0) dHeat[d] = Math.max(0.001, dHeat[d] - 0.0025);
      ['position', 'aSize', 'aHeat'].forEach(function (k) { blobs.g.attributes[k].needsUpdate = true; sparks.g.attributes[k].needsUpdate = true; smoke.g.attributes[k].needsUpdate = true; });
      dGeo.attributes.iOffset.needsUpdate = dGeo.attributes.iSize.needsUpdate = dGeo.attributes.iHeat.needsUpdate = true;
    }

    function animate() {
      requestAnimationFrame(animate);
      if (paused) return;
      var t = (performance.now() - t0) / 1000; frame++;
      ventMat.uniforms.uTime.value = blobMat.uniforms.uTime.value = smokeMat.uniforms.uTime.value = t;
      var flick = 0.5 + 0.08 * Math.sin(t * 7.0) + 0.05 * Math.sin(t * 13.0);
      ventGlowMat.uniforms.uGlow.value = flick;
      step();
      controls.update();
      renderer.render(scene, camera);
    }
    document.addEventListener('visibilitychange', function () { paused = document.hidden; });
    animate();

    var api = {
      scene: scene, camera: camera, renderer: renderer, controls: controls, state: S,
      adjustFountainHeight: function (v) { S.fountainHeight = num(v); S.resetHeight = -S.fountainHeight; },
      adjustXVelocityRange: function (v) { S.xVelocityRange = num(v); },
      adjustZVelocityRange: function (v) { S.zVelocityRange = num(v); },
      adjustParticleCount: function (v) { setCount(v); },
      adjustYVelocityRange: function (mn, mx) { S.yVelocityRange.min = num(mn); S.yVelocityRange.max = num(mx); for (var i = 0; i < S.particleCount; i++) { vel[i * 3 + 1] = Math.random() * (mx - mn) + mn; } },
      adjustParticleRadiusRange: function (mn, mx) { S.particleRadiusRange.min = num(mn); S.particleRadiusRange.max = num(mx); for (var i = 0; i < S.particleCount; i++) { rad[i] = Math.random() * (mx - mn) + mn; blobs.size[i] = rad[i] * 2.2; } },
      drawCalls: function () { return renderer.info.render.calls; }
    };
    console.log('[lava-fountain] v1.0 ready — THREE r' + T.REVISION + ', blobs=' + S.particleCount + (isMobile ? ' (mobile)' : ''));
    return api;
  }
  window.LavaFountain = { create: create, version: '1.0' };
})();
</script>

<!-- ===== Build the fountain and wire the sliders ===== -->
<script>
  var LF = LavaFountain.create({ particleCount: 1000 });
  h.oninput = function(e){ LF.adjustFountainHeight(e.target.value); };
  x.oninput = function(e){ LF.adjustXVelocityRange(e.target.value); };
  z.oninput = function(e){ LF.adjustZVelocityRange(e.target.value); };
  c.oninput = function(e){ LF.adjustParticleCount(e.target.value); };
  y.oninput = function(e){ LF.adjustYVelocityRange(0.1, parseFloat(e.target.value)); };
  r.oninput = function(e){ LF.adjustParticleRadiusRange(0.1, parseFloat(e.target.value)); };
</script>
</body></html>

SEE 3D AND 2D BROWSER GAMES IN ACTION

My free browser games are full Three.js 3D experiences — no download, they run right in your browser.

Drag to orbit · Scroll to zoom · Press Esc to exitDrag to orbit · pinch to zoom
FIRE FOUNTAIN CONTROLS