Cinematic Night Color Grading, Split-Toning & 24 fps Film Grain in Three.js
Zero-LUT Three.js r183 EffectComposer ShaderPass applying linear exposure and white balance, ACES filmic tone mapping, luminance-normalized split toning, lifted night-air blacks, warm-source cast protection, 24 fps clumped film grain, and 8-bit dither.
- color-grading
- postprocessing
- aces
- split-toning
- film-grain
- dither
- night
- tone-mapping
- readability
- shaderpass
No demo.
When to Use & Field Best Practices
Night games frequently suffer from two opposite readability traps: dark shadows that crush straight to flat #000000 (failing visual captures and hiding silhouettes), or heavy blue/teal color washes that turn warm torches, golden moons, and sodium street lamps an ugly sickly green.
This single-pass ShaderPass solves all of those in under 0.25 ms with zero LUT textures:
- Linear exposure & white balance before ACES: Apply
uExposure * uBalancein linear HDR light (insideEffectComposer'sHalfFloatTypebuffer) before rational ACES compression so bright highlights roll off smoothly into natural desaturation. - Luminance-normalized split toning: Divide shadow and highlight tint colors by their Rec.709 luminance (
sT = uShadowTint / dot(uShadowTint, LW)) before multiplying. That guarantees tinting shadows or highlights never shifts exposure. - Lifted night-air black floor ("Night Glow"): Adding
uShadowTint * uLift * 0.012 * (1.0 - lum)lifts dead blacks toward deep atmospheric night air, keeping shadowed silhouettes readable even in dim moonlight. - Warm-source cast protection: When cool teal/blue grades meet a warm orange or red focal light (a rising moon, campfire, or beacon), attenuating the grade cast where warmth (
r - b) is high preserves warm gold/red hues instead of shifting them green. - 24 fps clumped luminance-weighted film grain + 8-bit dither: Refresh grain at 24 Hz (
floor(uTime * 24.0)), scale grain clump size to viewport height (~1.5 pxat 1080p), weight it strongest in shadows/midtones, and always finish with a+/- 0.5 / 255dither so dark sky gradients never show 8-bit banding even when grain is0.
Mathematical & Algorithmic Core
- ACES Filmic Fit (Narkowicz): $
ACES(x) = clamp\!((x(2.51x + 0.03))/(x(2.43x + 0.59) + 0.14),\; 0,\; 1)$ - Luminance-Normalized Split Toning with
w_L = (0.2126, 0.7152, 0.0722): $t_norm = fractmax(t·w_L, 10^-3), c' = c · mix\!(1, t_norm, w(L)· a· (1 - p))$ where $p \in [0, 1]$ is warm-highlight cast protection.
Engine Implementation
Strict TypeScript Night Grading Pipeline (Assets/Game/nightGrade.ts)
Uses Three.js r183 EffectComposer, RenderPass, UnrealBloomPass, and ShaderPass. Automatically bypasses post-processing while game.xr.active is true (preserving headset stereo rendering) and restores game.render cleanly on dispose():
import * as THREE from 'three';
import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
import { ShaderPass } from 'three/addons/postprocessing/ShaderPass.js';
import type { Game } from 'ccgd';
export interface NightGradeSettings {
exposure: number;
temperature: number;
tint: number;
saturation: number;
contrast: number;
shadowColor: string;
shadowAmount: number;
highlightColor: string;
highlightAmount: number;
nightLift: number;
vignette: number;
grain: number;
warmProtect: number;
}
export type NightGradePresetName =
| 'tealNight'
| 'moonlitBlue'
| 'goldenMoon'
| 'deepSea'
| 'silver'
| 'ember'
| 'sodium'
| 'blood';
export const NIGHT_GRADE_PRESETS: Record<NightGradePresetName, NightGradeSettings> = {
tealNight: {
exposure: 1.15, temperature: -0.35, tint: 0.35, saturation: 1.1, contrast: 1.05,
shadowColor: '#0f8f86', shadowAmount: 0.5, highlightColor: '#c4ece2', highlightAmount: 0.25,
nightLift: 0.7, vignette: 0.38, grain: 0.007, warmProtect: 0.55,
},
moonlitBlue: {
exposure: 1.12, temperature: -0.18, tint: 0.05, saturation: 1.0, contrast: 1.04,
shadowColor: '#1e4fa3', shadowAmount: 0.32, highlightColor: '#f3e9d2', highlightAmount: 0.14,
nightLift: 0.45, vignette: 0.36, grain: 0.006, warmProtect: 0.45,
},
goldenMoon: {
exposure: 1.18, temperature: 0.22, tint: 0.06, saturation: 1.12, contrast: 1.06,
shadowColor: '#174878', shadowAmount: 0.42, highlightColor: '#ffd796', highlightAmount: 0.32,
nightLift: 0.55, vignette: 0.38, grain: 0.007, warmProtect: 0.65,
},
deepSea: {
exposure: 1.1, temperature: -0.45, tint: 0.4, saturation: 1.22, contrast: 1.1,
shadowColor: '#0a7a85', shadowAmount: 0.6, highlightColor: '#a6e4df', highlightAmount: 0.28,
nightLift: 0.65, vignette: 0.44, grain: 0.008, warmProtect: 0.5,
},
silver: {
exposure: 1.15, temperature: -0.05, tint: 0.0, saturation: 0.18, contrast: 1.1,
shadowColor: '#54667a', shadowAmount: 0.2, highlightColor: '#e8eef5', highlightAmount: 0.15,
nightLift: 0.4, vignette: 0.4, grain: 0.009, warmProtect: 0.2,
},
ember: {
exposure: 1.18, temperature: 0.18, tint: -0.12, saturation: 1.1, contrast: 1.06,
shadowColor: '#1e4270', shadowAmount: 0.45, highlightColor: '#ffb074', highlightAmount: 0.35,
nightLift: 0.55, vignette: 0.4, grain: 0.007, warmProtect: 0.75,
},
sodium: {
exposure: 1.14, temperature: -0.12, tint: 0.0, saturation: 1.08, contrast: 1.05,
shadowColor: '#1c3b64', shadowAmount: 0.4, highlightColor: '#ffba73', highlightAmount: 0.26,
nightLift: 0.6, vignette: 0.38, grain: 0.007, warmProtect: 0.85,
},
blood: {
exposure: 1.12, temperature: 0.1, tint: -0.25, saturation: 1.18, contrast: 1.12,
shadowColor: '#8f1820', shadowAmount: 0.52, highlightColor: '#ff7d6b', highlightAmount: 0.34,
nightLift: 0.8, vignette: 0.46, grain: 0.008, warmProtect: 0.3,
},
};
export interface NightGradeOptions {
preset?: NightGradePresetName;
bloom?: boolean | { strength?: number; radius?: number; threshold?: number };
}
export interface NightGradeController {
pass: ShaderPass;
applyPreset(name: NightGradePresetName): void;
applySettings(settings: Partial<NightGradeSettings>): void;
dispose(): void;
}
const NIGHT_GRADE_SHADER = {
uniforms: {
tDiffuse: { value: null as THREE.Texture | null },
uRes: { value: new THREE.Vector2(640, 360) },
uTime: { value: 0 },
uExposure: { value: 1.15 },
uBalance: { value: new THREE.Vector3(1, 1, 1) },
uShadowTint: { value: new THREE.Vector3(0.05, 0.3, 0.28) },
uHighTint: { value: new THREE.Vector3(0.7, 0.9, 0.85) },
uShadowAmt: { value: 0.5 },
uHighAmt: { value: 0.25 },
uLift: { value: 0.7 },
uSat: { value: 1.1 },
uContrast: { value: 1.05 },
uVignette: { value: 0.38 },
uGrain: { value: 0.007 },
uWarmProtect: { value: 0.55 },
},
vertexShader: /* glsl */ `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: /* glsl */ `
precision highp float;
uniform sampler2D tDiffuse;
uniform vec2 uRes;
uniform float uTime, uExposure, uShadowAmt, uHighAmt, uLift;
uniform float uSat, uContrast, uVignette, uGrain, uWarmProtect;
uniform vec3 uBalance, uShadowTint, uHighTint;
varying vec2 vUv;
float hash12(vec2 p) {
vec3 p3 = fract(vec3(p.xyx) * 0.1031);
p3 += dot(p3, p3.yzx + 33.33);
return fract((p3.x + p3.y) * p3.z);
}
float grainN(vec2 p, float s) {
vec2 i = floor(p);
vec2 f = fract(p);
f = f * f * (3.0 - 2.0 * f);
vec2 o = vec2(s * 37.0, s * 91.0);
return mix(
mix(hash12(i + o), hash12(i + o + vec2(1.0, 0.0)), f.x),
mix(hash12(i + o + vec2(0.0, 1.0)), hash12(i + o + vec2(1.0, 1.0)), f.x),
f.y
) - 0.5;
}
vec3 aces(vec3 x) {
return clamp((x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14), 0.0, 1.0);
}
void main() {
const vec3 LW = vec3(0.2126, 0.7152, 0.0722);
vec4 tex = texture2D(tDiffuse, vUv);
vec3 col = max(tex.rgb, vec3(0.0));
// Warm-light cast protection prevents cool teal grades from turning orange/gold light sources green.
float warmth = clamp((col.r - col.b) / max(col.r + col.g + col.b, 1e-4) * 2.2, 0.0, 1.0);
float prot = warmth * smoothstep(0.08, 0.45, dot(col, LW)) * uWarmProtect;
col *= uExposure * mix(uBalance, vec3(1.0), prot);
col = aces(col);
float lum = dot(col, LW);
vec3 sT = uShadowTint / max(dot(uShadowTint, LW), 1e-3);
vec3 hT = uHighTint / max(dot(uHighTint, LW), 1e-3);
col *= mix(vec3(1.0), sT, (1.0 - smoothstep(0.0, 0.5, lum)) * uShadowAmt * (1.0 - prot));
col *= mix(vec3(1.0), hT, smoothstep(0.3, 1.0, lum) * uHighAmt * (1.0 - prot));
col += uShadowTint * uLift * 0.012 * (1.0 - lum) * (1.0 - prot);
float l2 = dot(col, LW);
col = max(mix(vec3(l2), col, uSat), 0.0);
col = pow(col, vec3(uContrast));
float aspect = uRes.x / max(uRes.y, 1.0);
vec2 vq = (vUv - 0.5) * vec2(aspect, 1.0);
col *= mix(1.0 - uVignette, 1.0, smoothstep(1.15, 0.30, length(vq)));
// Linear -> sRGB display transfer
col = pow(max(col, 0.0), vec3(1.0 / 2.2));
// 24 fps clumped luminance-weighted film grain + anti-banding dither
float fr = fract(floor(uTime * 24.0) * 0.6180339) * 97.0;
vec2 gp = gl_FragCoord.xy / (1.5 * max(uRes.y / 1080.0, 0.6));
float gm = grainN(gp, fr) + 0.45 * (hash12(gl_FragCoord.xy + fr * 13.0) - 0.5);
vec3 g = vec3(gm) + 0.30 * vec3(grainN(gp + 17.3, fr + 1.0), 0.0, grainN(gp + 41.7, fr + 2.0));
float gl = dot(col, LW);
float gw = (0.4 + 0.6 * smoothstep(0.0, 0.2, gl)) * (1.0 - 0.6 * smoothstep(0.45, 1.0, gl));
col += g * uGrain * 7.0 * gw;
col += (hash12(gl_FragCoord.xy + fract(uTime * 7.31) * 513.0) - 0.5) / 255.0;
gl_FragColor = vec4(clamp(col, 0.0, 1.0), 1.0);
}
`,
};
function hexToLinearVec(hex: string, out: THREE.Vector3): void {
const c = new THREE.Color(hex);
out.set(c.r, c.g, c.b);
}
export function createNightGradePipeline(game: Game, opts: NightGradeOptions = {}): NightGradeController {
const w0 = game.canvas.clientWidth || game.canvas.width || 640;
const h0 = game.canvas.clientHeight || game.canvas.height || 360;
const composer = new EffectComposer(game.renderer);
composer.addPass(new RenderPass(game.scene, game.camera));
if (opts.bloom) {
const b = opts.bloom === true ? {} : opts.bloom;
composer.addPass(new UnrealBloomPass(new THREE.Vector2(w0, h0), b.strength ?? 0.35, b.radius ?? 0.3, b.threshold ?? 0.88));
}
const pass = new ShaderPass(NIGHT_GRADE_SHADER);
composer.addPass(pass);
let current: NightGradeSettings = { ...NIGHT_GRADE_PRESETS[opts.preset ?? 'tealNight'] };
function syncUniforms(): void {
const u = pass.uniforms;
const t = current.temperature;
const g = current.tint;
(u.uBalance.value as THREE.Vector3).set(
Math.exp(t * 0.22 - g * 0.08),
Math.exp(g * 0.16),
Math.exp(-t * 0.28 - g * 0.08)
);
hexToLinearVec(current.shadowColor, u.uShadowTint.value as THREE.Vector3);
hexToLinearVec(current.highlightColor, u.uHighTint.value as THREE.Vector3);
u.uExposure.value = current.exposure;
u.uShadowAmt.value = current.shadowAmount;
u.uHighAmt.value = current.highlightAmount;
u.uLift.value = current.nightLift;
u.uSat.value = current.saturation;
u.uContrast.value = current.contrast;
u.uVignette.value = current.vignette;
u.uGrain.value = current.grain;
u.uWarmProtect.value = current.warmProtect;
}
syncUniforms();
const baseRender = game.render.bind(game);
const sizeScratch = new THREE.Vector2();
const drawScratch = new THREE.Vector2();
game.render = () => {
if (game.xr.active) {
baseRender();
return;
}
const w = game.canvas.clientWidth || game.canvas.width || 640;
const h = game.canvas.clientHeight || game.canvas.height || 360;
game.renderer.getSize(sizeScratch);
if (sizeScratch.x !== w || sizeScratch.y !== h) {
game.renderer.setSize(w, h, false);
composer.setSize(w, h);
}
if (game.camera.aspect !== w / h) {
game.camera.aspect = w / h;
game.camera.updateProjectionMatrix();
}
game.renderer.getDrawingBufferSize(drawScratch);
(pass.uniforms.uRes.value as THREE.Vector2).set(Math.max(1, drawScratch.x), Math.max(1, drawScratch.y));
pass.uniforms.uTime.value = game.time;
composer.render();
};
return {
pass,
applyPreset(name: NightGradePresetName) {
current = { ...NIGHT_GRADE_PRESETS[name] };
syncUniforms();
},
applySettings(partial: Partial<NightGradeSettings>) {
current = { ...current, ...partial };
syncUniforms();
},
dispose() {
game.render = baseRender;
composer.dispose();
},
};
}
Performance & Integration Traps
- Avoid double tone-mapping: Do not add
OutputPassafterNightGradePass—NightGradePassalready applies ACES and sRGB transfer directly onEffectComposer's linearHalfFloatTypebuffer. - Keep
warmProtectbalanced: For scenes with cool night ambience and warm campfires/torches/moons,0.5–0.8keeps warm emitters vivid while grading the rest of the world cleanly. - Headset stereo safety: Because
game.renderchecksif (game.xr.active)and falls back tobaseRender(), VR sessions continue rendering cleanly without flat post-process interference.
Verification Checklist
- Run
compile(threeCompile) and verify zero TypeScript, lint, or WebGL shader errors. - Run
captureon a night scene with both shadowed terrain and a warm emitter (moon/lantern), and verify mean view luminance stays readable (>= 0.06, no crushed flat black) while warm emitters stay amber/gold rather than turning green. - Verify switching presets via
grade.applyPreset('ember')orgrade.applyPreset('blood')updates immediately with zero frame hitches.
Official references
- Weeb Labs — Nightscape (MIT)
- Krzysztof Narkowicz (2016 — ACES Filmic Tone Mapping Curve)
- Naty Hoffman & Academy Color Encoding System (SIGGRAPH — Physically Based Shading & Tone Reproduction)
Open-source sources
- Adapts code from Nightscape by Weeb Labs (MIT License): night grading and film-grain pass 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
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.
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.
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.
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.
