GameCrew AIEarly access
Sign in
Three.jsvfxRevision 1 · Compile-verified pattern

Volumetric Storm Lightning, Branching Bolts & Internal Cloud Glow in Three.js

Fractal branching 3D lightning bolts rendered as screen-facing MaxEquation strips with per-vertex volumetric cloud veiling, dual internal-scattering line lights, multi-stroke return timelines, distant horizon flashes, and distance-delayed GameAudio thunder.

  • lightning
  • storm
  • vfx
  • volumetric
  • shader
  • bolts
  • line-lights
  • branching
  • thunder
  • weather
  • blending

No demo.

When to Use & Field Best Practices

Flat billboard sprites or additive line strips break immersion in storm scenes: overlapping segments double-blend into glowing beads, bolts float *in front* of clouds instead of inside them, and single-frame flashes miss the organic flicker of real lightning.

Five rules for believable real-time storm lightning in Three.js r183:

  1. THREE.MaxEquation blending for branching channels: Draw screen-facing strips with CustomBlending + MaxEquation (OneFactor, OneFactor). Overlapping segment caps take the maximum of their core/halo profiles instead of double-brightening.
  2. Per-vertex volumetric veiling: Estimate cloud transmittance along the ray from camera to each bolt vertex (from altitude or a baked 3D cloud SDF) so foreground clouds naturally hide or veil the channel.
  3. Three flash archetypes + multi-stroke timelines: Deep in-cloud (~65%, internal glow only), cloud-to-ground (~20%, stepped leader via path-time s <= uProg followed by 1–4 return strokes + flickering continuing current), and in-cloud crawlers (~15%, wandering pulse trains).
  4. Dual volumetric line-segment lights (LIGHTNING_GLSL): Feed uLa0..uLb1 and uLi0..uLi1 into cloud/terrain shaders via closest-point-on-segment (lightningSegPoint) with gentle multiple-scattering falloff exp(-od * d * 0.2 - d * 0.03) / (1 + d^2 * 0.06) and luminance-preserving cool-to-gold color tuning.
  5. Respect prefers-reduced-motion and studio GameAudio: Soften strikes into a single gentle pulse (tau = 0.14) under reduced motion, and schedule recorded thunder via game.audio.play('thunder', { volume, pitch }) after 0.8 + dist * 0.012 seconds (never synthesize raw AudioContext noise).

Mathematical & Algorithmic Core

  • Midpoint-displacement fractal bolt: Recursively bisect p -> q, displacing the midpoint perpendicular to q - p by (r_1 + r_2 - 1) \cdot |q - p| \cdot \text{roughness} (triangular distribution).
  • Analytic strip profile: For pixel offset dpx from the projected segment: $E = C_core\,6\,e^-(d_px/w_c)^2 + C_halo\,1.1\,e^-d_px/w_h(1 - d_px/w_half)$
  • Line-segment light: For world point p and segment (a, b), compute v = a + clamp(((p-a)·(b-a))/(|b-a|^2), 0, 1)(b-a) - p and attenuate by I\,e^-0.2τ|v| - 0.03|v| / (1 + 0.06|v|^2).

Engine Implementation

Strict TypeScript Storm Lightning System (Assets/Game/stormLightning.ts)

Pre-allocates a reusable dynamic BufferGeometry pool (zero GPU allocations inside game.onUpdate), exports LIGHTNING_GLSL + lightUniforms for cloud/terrain shaders, and schedules distance-delayed game.audio.play thunder:

import * as THREE from 'three';
import type { Game } from 'ccgd';

export type FlashKind = 'cg' | 'ic' | 'deep';
export interface StormCell { x: number; z: number; baseY: number; topY: number; radius: number; }
export interface StormLightningOptions {
  storms: StormCell[];
  groundY?: number;
  minGapSeconds?: number;
  meanGapSeconds?: number;
  warmth?: number;
  thunderCue?: string;
  cloudVeilHeight?: number;
  maxSegments?: number;
}
export interface StormLightningController {
  mesh: THREE.Mesh;
  lightUniforms: Record<string, THREE.IUniform>;
  triggerFlash(kind?: FlashKind, stormIndex?: number): boolean;
  setWarmth(warmth: number): void;
  dispose(): void;
}

/** Include in cloud or terrain shaders to light volumes from active lightning channels. */
export const LIGHTNING_GLSL = /* glsl */ `
uniform float uFlash, uLR2, uLi0, uLi1, uGroundI;
uniform vec3 uLa0, uLb0, uLa1, uLb1, uGround, uLCol;
vec3 lightningSegPoint(vec3 p, vec3 a, vec3 b){
  vec3 ab = b - a; return a + ab * clamp(dot(p - a, ab) / max(dot(ab, ab), 1e-4), 0.0, 1.0);
}
float lightningSegLight(vec3 p, vec3 a, vec3 b, float I, float od){
  if (I <= 0.0) return 0.0;
  vec3 v = lightningSegPoint(p, a, b) - p; float d2 = dot(v, v);
  if (d2 > uLR2) return 0.0;
  float d = sqrt(d2); return I * exp(-od * d * 0.2 - d * 0.03) / (1.0 + d2 * 0.06);
}
vec3 lightningAt(vec3 p, float od){
  return uFlash > 0.5 ? uLCol * (lightningSegLight(p, uLa0, uLb0, uLi0, od) + lightningSegLight(p, uLa1, uLb1, uLi1, od)) : vec3(0.0);
}
`;

const BOLT_VERT = /* glsl */ `
precision highp float;
uniform vec3 uCamPos, uCamR, uCamU, uCamF;
uniform float uTanHalf, uAspect, uPx, uVeilHeight;
uniform vec2 uRes;
attribute vec3 aA, aB; attribute vec4 aInfo; attribute vec2 aCorner;
varying vec2 vSA, vSB; varying vec4 vInfo; varying float vTr, vHW;

vec3 proj(vec3 x){
  vec3 v = x - uCamPos; float z = dot(v, uCamF);
  return vec3(dot(v, uCamR) / (z * uTanHalf * uAspect), dot(v, uCamU) / (z * uTanHalf), z);
}
void main(){
  vec3 pa = proj(aA), pb = proj(aB);
  if (pa.z < 0.3 || pb.z < 0.3){ gl_Position = vec4(0.0, 0.0, 2.0, 1.0); return; }
  vec2 sa = (pa.xy * 0.5 + 0.5) * uRes, sb = (pb.xy * 0.5 + 0.5) * uRes;
  vec2 d = sb - sa; float l = length(d); d = l > 1e-3 ? d / l : vec2(1.0, 0.0);
  vec2 n = vec2(-d.y, d.x); float hw = (5.0 + 9.0 * aInfo.z) * uPx;
  vec2 s = mix(sa, sb, aCorner.y) + n * aCorner.x * hw + d * (aCorner.y * 2.0 - 1.0) * hw;
  gl_Position = vec4(s / uRes * 2.0 - 1.0, 0.0, 1.0);
  vSA = sa; vSB = sb; vInfo = aInfo; vHW = hw;
  vec3 p = aCorner.y > 0.5 ? aB : aA;
  vTr = mix(1.0, 0.35, smoothstep(uVeilHeight - 6.0, uVeilHeight + 12.0, p.y)) * exp(-length(p - uCamPos) * 0.0055);
}
`;

const BOLT_FRAG = /* glsl */ `
precision highp float;
uniform float uProg, uMainE, uBranchE, uLeaderE, uPx;
uniform vec3 uCoreC, uHaloC;
varying vec2 vSA, vSB; varying vec4 vInfo; varying float vTr, vHW;
void main(){
  vec2 ab = vSB - vSA, fp = gl_FragCoord.xy - vSA;
  float h = clamp(dot(fp, ab) / max(dot(ab, ab), 1e-4), 0.0, 1.0);
  float dpx = length(fp - ab * h);
  if (dpx > vHW) discard;
  float s = mix(vInfo.x, vInfo.y, h);
  if (s > uProg) discard;
  float w = vInfo.z;
  float e = (vInfo.w > 0.5 ? uBranchE : uMainE) * w + uLeaderE * (0.15 + 1.6 * exp(-(uProg - s) * 25.0)) * mix(0.4, 1.0, w);
  float cw = (0.45 + 0.75 * w) * uPx;
  vec3 col = (uCoreC * exp(-dpx * dpx / (cw * cw)) * 6.0 + uHaloC * exp(-dpx / ((1.2 + 2.6 * w) * uPx)) * (1.0 - dpx / vHW) * 1.1) * e * vTr;
  gl_FragColor = vec4(col, 1.0);
  #include <colorspace_fragment>
}
`;

type V3 = [number, number, number];
interface BoltLine { pts: V3[]; s: number[]; w: number; br: number; len: number; }
interface Stroke { t: number; peak: number; tau: number; cc: number; ccDur: number; a?: V3; b?: V3; }
interface ActiveFlash { kind: FlashKind; lines: BoltLine[]; seg0: [V3, V3]; seg1: [V3, V3]; ground: V3; centre: V3; strokes: Stroke[]; lead: number; dur: number; age: number; power: number; }

const vsub = (a: V3, b: V3): V3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
const vadd = (a: V3, b: V3): V3 => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
const vmul = (a: V3, k: number): V3 => [a[0] * k, a[1] * k, a[2] * k];
const vdot = (a: V3, b: V3): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const vlen = (a: V3): number => Math.sqrt(vdot(a, a));
const vnorm = (a: V3): V3 => vmul(a, 1 / Math.max(vlen(a), 1e-6));
const vmix = (a: V3, b: V3, t: number): V3 => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t];

export function createStormLightning(game: Game, opts: StormLightningOptions): StormLightningController {
  let seed = 4219;
  const rnd = () => {
    seed = (seed + 0x6d2b79f5) | 0;
    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
  const reduceMotion = typeof window !== 'undefined' && Boolean(window.matchMedia?.('(prefers-reduced-motion: reduce)').matches);
  const maxSeg = opts.maxSegments ?? 512, groundY = opts.groundY ?? -40;
  const minGap = opts.minGapSeconds ?? 8, meanGap = opts.meanGapSeconds ?? 18, thunderCue = opts.thunderCue ?? 'thunder';

  const vrand = (): V3 => { let v: V3; do { v = [rnd() * 2 - 1, rnd() * 2 - 1, rnd() * 2 - 1]; } while (vdot(v, v) > 1 || vdot(v, v) < 1e-3); return vnorm(v); };
  const jagged = (a: V3, b: V3, rough: number, minLen: number): V3[] => {
    let pts: V3[] = [a, b];
    for (let lev = 0; lev < 7 && vlen(vsub(pts[1], pts[0])) > minLen; lev++) {
      const out: V3[] = [pts[0]];
      for (let i = 0; i < pts.length - 1; i++) {
        const p = pts[i], q = pts[i + 1], d = vsub(q, p), l = vlen(d);
        let r = vrand(); r = vnorm(vsub(r, vmul(d, vdot(r, d) / Math.max(l * l, 1e-6))));
        out.push(vadd(vmix(p, q, 0.4 + rnd() * 0.2), vmul(r, (rnd() + rnd() - 1) * l * rough)), q);
      }
      pts = out;
    }
    return pts;
  };
  const makeChain = (pts: V3[], s0: number, ref: number, w: number, br: number): BoltLine => {
    const s = [s0];
    for (let i = 1; i < pts.length; i++) s.push(s[i - 1] + vlen(vsub(pts[i], pts[i - 1])) / Math.max(ref, 1e-3));
    return { pts, s, w, br, len: (s[s.length - 1] - s0) * ref };
  };
  const addBranches = (line: BoltLine, count: number, biasY: number, out: BoltLine[]): void => {
    const m = line.pts.length;
    for (let b = 0; b < count; b++) {
      const i = Math.min(m - 2, Math.floor((0.1 + rnd() * 0.72) * (m - 1)));
      const d0 = vnorm(vsub(line.pts[Math.min(m - 1, i + 3)], line.pts[Math.max(0, i - 3)]));
      const dir = vnorm(vadd(vadd(d0, vmul(vrand(), 0.9)), [0, biasY, 0]));
      const len = line.len * (0.08 + rnd() * 0.18);
      out.push(makeChain(jagged(line.pts[i], vadd(line.pts[i], vmul(dir, len)), 0.3, 1.2), line.s[i], Math.max(line.len, 1), line.w * (0.28 + rnd() * 0.3), 1));
    }
  };

  const bufA = new Float32Array(maxSeg * 12), bufB = new Float32Array(maxSeg * 12);
  const bufInfo = new Float32Array(maxSeg * 16), bufCorner = new Float32Array(maxSeg * 8), idxArr = new Uint32Array(maxSeg * 6);
  for (let s = 0; s < maxSeg; s++) {
    const v = s * 4;
    for (let c = 0; c < 4; c++) { bufCorner[(v + c) * 2] = c & 1 ? 1 : -1; bufCorner[(v + c) * 2 + 1] = c >> 1; }
    idxArr.set([v, v + 1, v + 2, v + 2, v + 1, v + 3], s * 6);
  }
  const attrA = new THREE.BufferAttribute(bufA, 3).setUsage(THREE.DynamicDrawUsage);
  const attrB = new THREE.BufferAttribute(bufB, 3).setUsage(THREE.DynamicDrawUsage);
  const attrInfo = new THREE.BufferAttribute(bufInfo, 4).setUsage(THREE.DynamicDrawUsage);
  const geom = new THREE.BufferGeometry();
  geom.setAttribute('position', attrA); geom.setAttribute('aA', attrA); geom.setAttribute('aB', attrB);
  geom.setAttribute('aInfo', attrInfo); geom.setAttribute('aCorner', new THREE.BufferAttribute(bufCorner, 2));
  geom.setIndex(new THREE.BufferAttribute(idxArr, 1)); geom.setDrawRange(0, 0);

  const boltUniforms: Record<string, THREE.IUniform> = {
    uCamPos: { value: new THREE.Vector3() }, uCamR: { value: new THREE.Vector3(1, 0, 0) }, uCamU: { value: new THREE.Vector3(0, 1, 0) }, uCamF: { value: new THREE.Vector3(0, 0, -1) },
    uTanHalf: { value: 0.55 }, uAspect: { value: 16 / 9 }, uRes: { value: new THREE.Vector2(640, 360) }, uPx: { value: 1 }, uVeilHeight: { value: opts.cloudVeilHeight ?? 14 },
    uProg: { value: 0 }, uMainE: { value: 0 }, uBranchE: { value: 0 }, uLeaderE: { value: 0 },
    uCoreC: { value: new THREE.Vector3(1.0, 0.97, 1.0) }, uHaloC: { value: new THREE.Vector3(0.42, 0.5, 1.0) },
  };
  const lightUniforms: Record<string, THREE.IUniform> = {
    uFlash: { value: 0 }, uLR2: { value: 0 }, uLa0: { value: new THREE.Vector3() }, uLb0: { value: new THREE.Vector3() }, uLi0: { value: 0 },
    uLa1: { value: new THREE.Vector3() }, uLb1: { value: new THREE.Vector3() }, uLi1: { value: 0 },
    uGround: { value: new THREE.Vector3() }, uGroundI: { value: 0 }, uLCol: { value: new THREE.Vector3(0.8, 0.84, 1.0) },
  };
  const mat = new THREE.ShaderMaterial({
    vertexShader: BOLT_VERT, fragmentShader: BOLT_FRAG, uniforms: boltUniforms,
    transparent: true, depthTest: false, depthWrite: false, side: THREE.DoubleSide,
    blending: THREE.CustomBlending, blendEquation: THREE.MaxEquation, blendSrc: THREE.OneFactor, blendDst: THREE.OneFactor,
  });
  const mesh = new THREE.Mesh(geom, mat);
  mesh.name = 'VolumetricStormLightning'; mesh.renderOrder = 950; mesh.frustumCulled = false; mesh.visible = false;
  game.scene.add(mesh);

  function setWarmth(wRaw: number): void {
    const w = THREE.MathUtils.clamp(wRaw, 0, 1);
    const lum = (c: V3) => 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
    const mixLum = (a: V3, b: V3): V3 => {
      const c: V3 = [a[0] + (b[0] - a[0]) * w, a[1] + (b[1] - a[1]) * w, a[2] + (b[2] - a[2]) * w];
      const g = lum(a) / Math.max(lum(c), 1e-4); return [c[0] * g, c[1] * g, c[2] * g];
    };
    (lightUniforms.uLCol.value as THREE.Vector3).fromArray(mixLum([0.8, 0.84, 1.0], [1.0, 0.76, 0.36]));
    (boltUniforms.uCoreC.value as THREE.Vector3).fromArray(mixLum([1.0, 0.97, 1.0], [1.0, 0.9, 0.68]));
    (boltUniforms.uHaloC.value as THREE.Vector3).fromArray(mixLum([0.42, 0.5, 1.0], [1.0, 0.64, 0.22]));
  }
  setWarmth(opts.warmth ?? 0);

  function uploadLines(lines: BoltLine[] | null): void {
    if (!lines) { geom.setDrawRange(0, 0); mesh.visible = false; return; }
    let seg = 0;
    for (const line of lines) for (let i = 0; i < line.pts.length - 1 && seg < maxSeg; i++, seg++) {
      const v = seg * 4;
      for (let c = 0; c < 4; c++) {
        bufA.set(line.pts[i], (v + c) * 3); bufB.set(line.pts[i + 1], (v + c) * 3);
        bufInfo.set([line.s[i], line.s[i + 1], line.w, line.br], (v + c) * 4);
      }
    }
    attrA.needsUpdate = attrB.needsUpdate = attrInfo.needsUpdate = true;
    geom.setDrawRange(0, seg * 6); mesh.visible = seg > 0;
  }

  let active: ActiveFlash | null = null, nextAuto = minGap + rnd() * meanGap;
  const thunders: { remaining: number; volume: number; pitch: number }[] = [];

  function triggerFlash(requested?: FlashKind, stormIndex?: number): boolean {
    if (!opts.storms.length) return false;
    const storm = opts.storms[stormIndex ?? Math.floor(rnd() * opts.storms.length)]!;
    const kind: FlashKind = requested ?? (rnd() < 0.6 ? 'deep' : rnd() < 0.5 ? 'cg' : 'ic');
    const span = Math.max(4, storm.topY - storm.baseY), ang = rnd() * Math.PI * 2;
    const origin: V3 = [storm.x + (rnd() - 0.5) * storm.radius, storm.baseY + (0.35 + 0.35 * rnd()) * span, storm.z + (rnd() - 0.5) * storm.radius];
    let lines: BoltLine[], seg0: [V3, V3], seg1: [V3, V3], ground: V3;
    if (kind === 'cg') {
      const exit: V3 = [storm.x + Math.cos(ang) * storm.radius * 0.7, storm.baseY - 2, storm.z + Math.sin(ang) * storm.radius * 0.7];
      ground = [exit[0] + (rnd() - 0.5) * storm.radius, groundY, exit[2] + (rnd() - 0.5) * storm.radius];
      const pts = jagged(origin, exit, 0.28, 1.4).concat(jagged(exit, ground, 0.26, 1.4).slice(1));
      const main = makeChain(pts, 0, Math.max(1, vlen(vsub(origin, ground)) * 1.25), 1, 0);
      lines = [main]; addBranches(main, 5, -0.35, lines); seg0 = [origin, exit]; seg1 = [exit, ground];
    } else {
      const end: V3 = [storm.x + Math.cos(ang) * storm.radius * 0.9, storm.baseY + (0.25 + 0.5 * rnd()) * span, storm.z + Math.sin(ang) * storm.radius * 0.9];
      const main = makeChain(jagged(origin, end, 0.34, 1.4), 0, Math.max(1, vlen(vsub(end, origin)) * 1.3), 0.85, 0);
      lines = [main]; if (kind === 'ic') addBranches(main, 6, 0.05, lines); seg0 = [origin, end]; seg1 = [origin, end]; ground = end;
    }
    const strokes: Stroke[] = [], lead = kind === 'cg' ? (reduceMotion ? 0 : 0.08 + rnd() * 0.1) : 0.16;
    const count = reduceMotion ? 1 : kind === 'cg' ? 1 + Math.floor(rnd() * 3) : 2 + Math.floor(rnd() * 4);
    for (let k = 0, t = lead; k < count; k++) {
      const cc = kind === 'cg' && !reduceMotion && rnd() < 0.35 ? 0.12 + rnd() * 0.12 : 0, ccDur = 0.08 + rnd() * 0.16;
      const m = lines[0].pts.length, u = rnd();
      strokes.push({
        t: kind === 'cg' ? t : (k === 0 ? 0.02 : 0.04 + rnd() * 0.55), peak: reduceMotion ? 0.55 : (k === 0 ? 1 : 0.45 + rnd() * 0.45),
        tau: reduceMotion ? 0.14 : (kind === 'deep' ? 0.08 + rnd() * 0.08 : 0.035 + rnd() * 0.035), cc, ccDur,
        a: lines[0].pts[Math.floor(Math.max(0, u - 0.2) * (m - 1))], b: lines[0].pts[Math.floor(Math.min(1, u + 0.2) * (m - 1))],
      });
      t += 0.06 + rnd() * 0.09 + (cc ? ccDur : 0);
    }
    strokes.sort((a, b) => a.t - b.t);
    const centre = vmix(seg0[0], seg0[1], 0.5);
    active = { kind, lines, seg0, seg1, ground, centre, strokes, lead, dur: strokes[strokes.length - 1].t + 0.45, age: 0, power: kind === 'cg' ? 0.9 : kind === 'ic' ? 0.8 : 0.6 };
    uploadLines(kind === 'deep' ? null : lines);
    const dist = Math.hypot(centre[0] - game.camera.position.x, centre[1] - game.camera.position.y, centre[2] - game.camera.position.z);
    thunders.push({
      remaining: 0.8 + dist * 0.012,
      volume: THREE.MathUtils.clamp((kind === 'cg' ? 0.95 : 0.7) / (1 + dist / 160), 0.1, 1.0),
      pitch: THREE.MathUtils.clamp((kind === 'deep' ? 0.84 : 0.96) - dist * 0.0005, 0.72, 1.06),
    });
    return true;
  }

  const pulseAt = (st: Stroke, age: number, dt: number) => {
    let a = age - st.t; if (a < 0) return 0; if (a < dt) a = 0;
    let v = st.peak * Math.exp(-a / st.tau);
    if (st.cc > 0) v += st.cc * (a < st.ccDur ? 0.8 + 0.4 * rnd() : Math.exp(-(a - st.ccDur) / 0.06));
    return v;
  };
  const sizeScratch = new THREE.Vector2(), camR = new THREE.Vector3(), camU = new THREE.Vector3(), camF = new THREE.Vector3();

  game.onUpdate((dt) => {
    for (let i = thunders.length - 1; i >= 0; i--) {
      if ((thunders[i].remaining -= dt) <= 0) { const th = thunders.splice(i, 1)[0]; game.audio.play(thunderCue, { volume: th.volume, pitch: th.pitch }); }
    }
    if (!active && (nextAuto -= dt) <= 0) { triggerFlash(); nextAuto = minGap + -Math.log(1 - Math.min(0.999, rnd())) * meanGap; }
    if (!active) { lightUniforms.uFlash.value = 0; mesh.visible = false; return; }
    if ((active.age += dt) > active.dur) { active = null; uploadLines(null); lightUniforms.uFlash.value = 0; return; }
    let env = 0, top = 0, topSt: Stroke | undefined;
    for (const st of active.strokes) { const v = pulseAt(st, active.age, dt); env += v; if (v > top) { top = v; topSt = st; } }
    const first = pulseAt(active.strokes[0], active.age, dt), k = 20 * active.power;
    if (active.kind === 'cg') {
      const leading = active.age < active.lead;
      boltUniforms.uProg.value = leading ? active.age / Math.max(active.lead, 1e-3) : 10;
      boltUniforms.uLeaderE.value = leading ? 0.08 : 0; boltUniforms.uMainE.value = env; boltUniforms.uBranchE.value = first * 0.6;
      (lightUniforms.uLa0.value as THREE.Vector3).fromArray(active.seg0[0]); (lightUniforms.uLb0.value as THREE.Vector3).fromArray(active.seg0[1]);
      (lightUniforms.uLa1.value as THREE.Vector3).fromArray(active.seg1[0]); (lightUniforms.uLb1.value as THREE.Vector3).fromArray(active.seg1[1]);
      lightUniforms.uLi0.value = (env + (leading ? 0.02 : 0)) * k * 0.8; lightUniforms.uLi1.value = env * k;
      (lightUniforms.uGround.value as THREE.Vector3).fromArray(active.ground); lightUniforms.uGroundI.value = env * k;
    } else {
      boltUniforms.uProg.value = active.age / Math.max(active.lead, 1e-3); boltUniforms.uLeaderE.value = 0;
      boltUniforms.uMainE.value = env * 0.8; boltUniforms.uBranchE.value = env * 0.5;
      (lightUniforms.uLa0.value as THREE.Vector3).fromArray(active.seg0[0]); (lightUniforms.uLb0.value as THREE.Vector3).fromArray(active.seg0[1]);
      if (topSt?.a && topSt?.b) { (lightUniforms.uLa1.value as THREE.Vector3).fromArray(topSt.a); (lightUniforms.uLb1.value as THREE.Vector3).fromArray(topSt.b); }
      lightUniforms.uLi0.value = env * k * 0.45; lightUniforms.uLi1.value = top * k; lightUniforms.uGroundI.value = 0;
    }
    const iMax = Math.max(lightUniforms.uLi0.value as number, lightUniforms.uLi1.value as number);
    let r = 0; while (r < 360 && (iMax * Math.exp(-0.03 * r)) / (1 + 0.06 * r * r) > 0.003) r += 4;
    lightUniforms.uLR2.value = r * r; lightUniforms.uFlash.value = iMax > 0.003 ? 1 : 0;
    mesh.visible = active.kind !== 'deep' && (boltUniforms.uMainE.value as number) + (boltUniforms.uBranchE.value as number) + (boltUniforms.uLeaderE.value as number) > 0.002;
  });

  game.onAlways(() => {
    game.camera.updateMatrixWorld(); game.camera.matrixWorld.extractBasis(camR, camU, camF); camF.negate();
    game.renderer.getDrawingBufferSize(sizeScratch); const dpr = game.renderer.getPixelRatio();
    const w = Math.max(1, Math.round((game.canvas.clientWidth || sizeScratch.x || 640) * dpr));
    const h = Math.max(1, Math.round((game.canvas.clientHeight || sizeScratch.y || 360) * dpr));
    (boltUniforms.uCamPos.value as THREE.Vector3).copy(game.camera.position);
    (boltUniforms.uCamR.value as THREE.Vector3).copy(camR); (boltUniforms.uCamU.value as THREE.Vector3).copy(camU); (boltUniforms.uCamF.value as THREE.Vector3).copy(camF);
    boltUniforms.uTanHalf.value = Math.tan(THREE.MathUtils.degToRad(game.camera.fov * 0.5));
    boltUniforms.uAspect.value = w / h; (boltUniforms.uRes.value as THREE.Vector2).set(w, h); boltUniforms.uPx.value = dpr;
  });

  return { mesh, lightUniforms, triggerFlash, setWarmth, dispose() { game.scene.remove(mesh); geom.dispose(); mat.dispose(); } };
}

Performance & Platform Traps

  • Zero per-frame allocation: Updating a pre-allocated DynamicDrawUsage BufferGeometry pool avoids GC pauses and passes step-loop static lint cleanly.
  • Distant horizon heat lightning: Add a vec4 uFar (dir.xz, intensity) to your composite shader weighted by c.a + 2.5 * c.a * (1.0 - c.a) so distant cloud tops silhouette dark while thin cloud rims catch the distant flash.
  • Studio audio compliance: Wire thunderCue to a studio audio file (Assets/Game/Resources/Audio/thunder.wav) via game.audio.play; never instantiate AudioContext directly.

Verification Checklist

  1. Call lightning.triggerFlash('cg', 0) in a PlayMode test, step 2–6 frames, and verify lightning.mesh.visible === true and lightUniforms.uFlash.value === 1.
  2. Run compile and capture during a strike to verify crisp cores without hot dots at segment joints.
  3. Verify game.audio.plays('thunder') increments after the distance delay expires.

Official references

  • Weeb Labs — Nightscape (MIT)
  • Theodore Kim & Ming C. Lin (ACM TOG 2004 — Physically Based Simulation of Lightning)
  • Vladimir Rakov & Martin Uman (Lightning: Physics and Effects)

Open-source sources

  • Adapts code from Nightscape by Weeb Labs (MIT License): branching bolts, veiling and strike timelines adapted to Three.js 0.183 TypeScript and the ccgd kit

Games built with this guide carry these credits, and the licence notices they ask for, in their third-party notices.

More Three.js games

Games made with GameCrew on the same engine. No game has been built with this guide yet: these show what Three.js games here look like.

More Three.js techniques

atmosphere

Baked 3D Volumetric Cloud Sea, World-Anchored Marching & TAA in Three.js →

Endless fly-above volumetric cloud sea in Three.js r183 WebGL 2 using a GPU-baked WebGL3DRenderTarget SDF and lighting volume, anti-boiling world-anchored z-plane marching, 3-octave Henyey-Greenstein scattering, and variance-clamped depth-packed TAA.

physics

BVH Mesh & Character Capsule Collision in Three.js →

Fast capsule-vs-triangle pushout and slope resolution using three-mesh-bvh shapecasts, pre-allocated scratch vectors, and CollisionWorld.

ai

Zero-Allocation Context Steering, Patrol Loops & Telegraphed AI in Three.js →

Deterministic 60 Hz enemy and companion AI in Three.js using 8-slot context steering against CollisionWorld, level.json patrol loops, attack-token pacing, and telegraphed strikes.

optimization

Instanced Wind Foliage, Object-Pooled Particles & Spring Feel in Three.js →

Single-draw-call THREE.InstancedMesh wind foliage with player bend, zero-GC pooled burst particles, and dt-invariant second-order springs that keep 60 Hz steps under 2 ms.

Use verified techniques inside a real game

Describe your game idea for free or connect an MCP assistant to search and contribute techniques.

Learn about collaboration