All examples
Lightmaps
A MeshRenderer's lightmap record samples a baked texture named by a .lightmap.json; in shadowmap mode it multiplies the floor's shading, so the soft shadows of two pillars, a wall and two crates cost one texture fetch and no shadow map. Only a static entity with a PBR material samples a lightmap. ignifx has no lightmap baker yet: a small tool beside the example ray-casts this scene's sun past its boxes and writes the PNG.
Off airLivePaused
Lightmaps
Lighting & GI · 3D

WebGPU: checking…See browser support
Try this
- Turn on Real-time shadow and turn off the lightmap: the shadows land in the same place, and the baked ones are softer.
- Untick Floor is static: the floor draws without its lightmap, because only static entities sample one.
- Set Mode to add: the same mask is added instead of multiplied, which is the mode for a texture of baked light, not of shadow.
Show source code
Source
import { Camera, Environment, LIGHTMAP_MODES, MeshRenderer } from "ignifx";import { bootExample } from "../_kit/boot.ts";import { twoPlaces } from "../_kit/format.ts";import { attachOrbit } from "../_kit/orbit.ts";import { bind, readout, select, slider, toggle } from "../_kit/panel.ts";import { loadEnvironment } from "../_kit/stage.ts";import { createYard, FOCUS, SHOT } from "./scene.ts";import type { LightmapAsset, LightmapMode, MeshRendererLightmap } from "ignifx";/** * A lightmap: light baked into a texture and painted back onto a static surface, so a shadow that * never moves costs one texture fetch instead of a shadow map every frame. * * The floor's `MeshRenderer` has a `lightmap` record (ignifx 0.19.0, beta) pointing at * `lightmap-yard.lightmap.json`, which names the texture. In `"shadowmap"` mode the sample * multiplies the floor's shading, so the soft shadows of the pillars, the wall and the crates are * baked, while the blocks themselves are lit by the sun in real time. Only a renderer on a static * entity (`entity.isStatic`) with a PBR material samples a lightmap; it then draws with its own * copy of the material. * * The texture is not from an engine baker — ignifx has none yet. `tools/bake-shadow.ts` ray-casts * the sun's disc from every floor texel past this scene's boxes, a one-scene baker in about a * hundred lines, and writes the PNG and the `.lightmap.json`. `MeshAsset.ground` has no second UV * set, so the floor samples with its first one (`uv2: false`); a mesh from a lightmapper carries * its own `uvs2`. Per-entity atlas `entries` other than the identity are not drawn yet, so this * floor has a texture of its own. * * Turn the real-time shadow on and the lightmap off to compare: the edges match because the bake * used the same sun, and the baked one is softer because it sampled the sun as a disc. *//** The exposure the yard is graded at. */const EXPOSURE = 1;/** The lightmap's address. */const LIGHTMAP_ADDRESS = "lighting/lightmap-yard.lightmap.json";bootExample({ title: "Lightmaps", settings: { rendering: { clearColor: { r: 0.05, g: 0.06, b: 0.075, a: 1 }, // Only for the comparison: the real-time shadow starts off. features: { shadows: true }, }, }, async setup({ app, panel }) { const eye = app.world.createEntity("Main Camera"); eye.addComponent(Camera, { near: 0.1, far: 100, fov: SHOT.fov }); attachOrbit(app, eye, { yaw: SHOT.yaw, pitch: SHOT.pitch, distance: SHOT.distance, target: FOCUS, minDistance: 4, maxDistance: 24, }); const studio = loadEnvironment(app, "studio"); // The loader loads the texture the file names with it. const baked = app.assets.loadAsync<LightmapAsset>(LIGHTMAP_ADDRESS); await studio.promise; const sky = app.world .createEntity("Environment") .addComponent(Environment, { environment: studio, skybox: { enabled: false, size: 20 } }); sky.imageProcessing.exposure = EXPOSURE; sky.imageProcessing.toneMapping = "agx"; const { floor, sun } = createYard(app); // The shadow-example settings for PCF; off until the panel turns it on. sun.shadows.technique = "pcf"; sun.shadows.mapSize = 2048; sun.shadows.bias = 0.00005; sun.shadows.normalBias = 0.02; sun.shadows.darkness = 0.32; sun.shadows.enabled = false; // One record, edited in place by the panel; `null` switches the lightmap off. const lightmap: MeshRendererLightmap = { asset: await baked, mode: "shadowmap", level: 1, gamma: false, uv2: false, }; const renderer = floor.requireComponent(MeshRenderer); renderer.lightmap = lightmap; panel({ title: "Lightmaps", groups: [ { label: "Floor lightmap", controls: [ toggle("Enabled", { value: true, change: (on: boolean): void => { renderer.lightmap = on ? lightmap : null; }, read: (): boolean => renderer.lightmap !== null, }), select("Mode", LIGHTMAP_MODES, { value: lightmap.mode, change: (mode: string): void => { lightmap.mode = mode as LightmapMode; }, read: (): string => lightmap.mode, }), slider("Level", { min: 0, max: 2, step: 0.05, format: twoPlaces }, bind(lightmap, "level")), toggle("Floor is static", bind(floor, "isStatic")), ], }, { label: "Sun", controls: [ toggle("Real-time shadow", bind(sun.shadows, "enabled")), slider("Intensity", { min: 0, max: 5, step: 0.1, format: twoPlaces }, bind(sun, "intensity")), ], }, { label: "Frame", collapsed: true, controls: [ slider("Exposure", { min: 0.3, max: 3, step: 0.05, format: twoPlaces }, bind(sky.imageProcessing, "exposure")), readout("Draw calls", (): string => String(app.renderer.drawCalls)), ], }, ], }); },});/** * The yard `lightmaps` draws: a square stone floor, two pillars, a low wall and two crates, and a * low sun from the -X side. * * @remarks * Shared by the page and by `tools/bake-shadow.ts`, which ray-casts the sun's shadow of these same * blocks onto the floor and writes it as the floor's lightmap, so the texture and the scene cannot * drift apart. * * The layout is mirror-symmetric across the X axis (every block at `z` has a twin at `-z`, or sits * on `z = 0`) and the sun is in the XY plane, so the shadow mask is the same whichever way up a * texture's V axis runs. */import { Light, MeshAsset } from "ignifx";import { paint, place } from "../_kit/props.ts";import type { Point3 } from "../_kit/stage.ts";import type { App, Entity } from "ignifx";/** The floor's edge, in metres; it is centred on the origin. */export const FLOOR_SIZE = 12;/** The point the camera orbits. */export const FOCUS: Point3 = { x: 0.4, y: 0.6, z: 0 };/** The opening shot: from the lit side, a little above. */export const SHOT = { fov: 44, yaw: -35, pitch: 32, distance: 13 } as const;/** * The sun: a directional light at `at`, aimed at the origin. It shines along -`at`, so its shadows * fall toward +X. */export const SUN = { at: { x: -6, y: 7, z: 0 }, intensity: 2.4, color: { r: 1, g: 0.95, b: 0.86, a: 1 }, /** The sun disc's angular radius the bake samples, in degrees: wider than the real sun's, for a soft edge. */ radiusDegrees: 2.5,} as const;/** * How much light a fully shadowed texel keeps. The lightmap multiplies the floor's whole shading * (`mode: "shadowmap"`), sky light included, so a shadow of 0 would be black. */export const SHADOW_FLOOR = 0.32;/** One axis-aligned block standing on the floor. */export interface Block { /** The entity's name. */ readonly name: string; /** The centre of its footprint, on the floor. */ readonly x: number; readonly z: number; /** Its size along X, Y and Z, in metres. */ readonly size: Point3;}/** The blocks, mirror-symmetric across the X axis. */export const BLOCKS: readonly Block[] = [ { name: "Pillar north", x: -3, z: 2.2, size: { x: 0.6, y: 3, z: 0.6 } }, { name: "Pillar south", x: -3, z: -2.2, size: { x: 0.6, y: 3, z: 0.6 } }, { name: "Wall", x: -0.4, z: 0, size: { x: 0.4, y: 1.5, z: 3 } }, { name: "Crate north", x: 2.6, z: 1.6, size: { x: 0.8, y: 0.8, z: 0.8 } }, { name: "Crate south", x: 2.6, z: -1.6, size: { x: 0.8, y: 0.8, z: 0.8 } },];/** What {@link createYard} hands back. */export interface Yard { /** The floor: a static entity whose `MeshRenderer` the page gives the lightmap. */ readonly floor: Entity; /** The sun. */ readonly sun: Light;}/** * Builds the floor, the blocks and the sun. * * @param app - The app the entities and the assets belong to. * @returns The floor and the sun. */export function createYard(app: App): Yard { // `MeshAsset.ground`'s first UV set runs U along +X and V along +Z across the whole plane, which // is the square the bake fills. It has no second UV set, so the page samples with the first. const floor = place( app, "Floor", MeshAsset.ground(app, { width: FLOOR_SIZE, height: FLOOR_SIZE, subdivisions: 1 }), paint(app, "lightmaps/stone", { r: 0.78, g: 0.75, b: 0.7, a: 1 }, { roughness: 0.92 }), { at: { x: 0, y: 0, z: 0 } }, ); // Only a static entity samples a lightmap; set it before the renderer's first frame. floor.isStatic = true; const box = MeshAsset.box(app, { size: 1 }); const stone = paint(app, "lightmaps/block", { r: 0.62, g: 0.6, b: 0.66, a: 1 }, { roughness: 0.85 }); const wood = paint(app, "lightmaps/crate", { r: 0.62, g: 0.43, b: 0.26, a: 1 }, { roughness: 0.8 }); for (const block of BLOCKS) { place(app, block.name, box, block.name.startsWith("Crate") ? wood : stone, { at: { x: block.x, y: block.size.y / 2, z: block.z }, scale: block.size, }); } // A directional light shines along its entity's +Z, so `lookAt` aims it. const sunEntity = app.world.createEntity("Sun", { position: SUN.at }); sunEntity.transform.lookAt({ x: 0, y: 0, z: 0 }); const sun = sunEntity.addComponent(Light, { type: "directional", intensity: SUN.intensity, color: SUN.color }); return { floor, sun };}// Writes `examples/assets/lighting/lightmap-yard.png` and `lightmap-yard.lightmap.json`, the floor// lightmap `lightmaps` draws. Run it from the repository root://// node examples/lightmaps/tools/bake-shadow.ts//// ignifx has no lightmap baker yet, so this is a small one for this scene only: for every texel of// the floor it casts rays toward points on the sun's disc and counts how many reach the sun past the// blocks in `../scene.ts` (each an axis-aligned box, so a slab test is exact). The texel stores// `SHADOW_FLOOR + (1 - SHADOW_FLOOR) * visible`, linear, in a plain RGB PNG: a baked shadow mask the// page multiplies into the floor's shading (`mode: "shadowmap"`). It is deterministic, so the// committed files are what it writes.//// Texel (i, j) is at U = (i + 0.5) / SIZE, V = (j + 0.5) / SIZE, which on `MeshAsset.ground` is// x = -6 + 12U and z = -6 + 12V. The yard is mirror-symmetric in Z, so whether a texture's first row// is V = 0 or V = 1 does not matter.import { mkdir, writeFile } from "node:fs/promises";import path from "node:path";import sharp from "sharp";import { writeLightmapFile } from "ignifx";import { BLOCKS, FLOOR_SIZE, SHADOW_FLOOR, SUN } from "../scene.ts";/** Texels along each side. */const SIZE = 256;/** Rays per texel, spread over the sun's disc. */const RAYS = 64;/** The golden angle, for a Fibonacci spiral over the disc. */const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5));/** Where the files land, and their asset addresses. */const DIR = path.resolve(import.meta.dirname, "..", "..", "assets", "lighting");const TEXTURE = "lighting/lightmap-yard.png";type Vec = readonly [number, number, number];const normalize = (v: Vec): Vec => { const length = Math.hypot(v[0], v[1], v[2]); return [v[0] / length, v[1] / length, v[2] / length];};const cross = (a: Vec, b: Vec): Vec => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];/** The directions toward points on the sun's disc. */function sunDirections(): Vec[] { const centre = normalize([SUN.at.x, SUN.at.y, SUN.at.z]); const side = normalize(cross(centre, [0, 1, 0])); const up = cross(side, centre); const radius = Math.tan((SUN.radiusDegrees * Math.PI) / 180); const directions: Vec[] = []; for (let k = 0; k < RAYS; k += 1) { const r = radius * Math.sqrt((k + 0.5) / RAYS); const a = k * GOLDEN_ANGLE; const s = r * Math.cos(a); const t = r * Math.sin(a); directions.push( normalize([ centre[0] + side[0] * s + up[0] * t, centre[1] + side[1] * s + up[1] * t, centre[2] + side[2] * s + up[2] * t, ]), ); } return directions;}/** Each block's bounds, `[min, max]`. */const boxes = BLOCKS.map((block): readonly [Vec, Vec] => [ [block.x - block.size.x / 2, 0, block.z - block.size.z / 2], [block.x + block.size.x / 2, block.size.y, block.z + block.size.z / 2],]);/** Whether a ray from `origin` along `direction` hits any block (slab test). */function blocked(origin: Vec, direction: Vec): boolean { for (const [min, max] of boxes) { let near = 0; let far = Infinity; let hit = true; for (let axis = 0; axis < 3 && hit; axis += 1) { const o = origin[axis] ?? 0; const d = direction[axis] ?? 0; const lo = min[axis] ?? 0; const hi = max[axis] ?? 0; if (Math.abs(d) < 1e-12) { hit = o >= lo && o <= hi; } else { const t0 = (lo - o) / d; const t1 = (hi - o) / d; near = Math.max(near, Math.min(t0, t1)); far = Math.min(far, Math.max(t0, t1)); hit = near <= far; } } if (hit) { return true; } } return false;}const directions = sunDirections();const pixels = Buffer.alloc(SIZE * SIZE * 3);for (let j = 0; j < SIZE; j += 1) { for (let i = 0; i < SIZE; i += 1) { const origin: Vec = [-FLOOR_SIZE / 2 + ((i + 0.5) / SIZE) * FLOOR_SIZE, 1e-3, -FLOOR_SIZE / 2 + ((j + 0.5) / SIZE) * FLOOR_SIZE]; let visible = 0; for (const direction of directions) { if (!blocked(origin, direction)) { visible += 1; } } const value = Math.round((SHADOW_FLOOR + (1 - SHADOW_FLOOR) * (visible / RAYS)) * 255); const at = (j * SIZE + i) * 3; pixels[at] = value; pixels[at + 1] = value; pixels[at + 2] = value; }}await mkdir(DIR, { recursive: true });await sharp(pixels, { raw: { width: SIZE, height: SIZE, channels: 3 } }) .png({ compressionLevel: 9 }) .toFile(path.join(DIR, "lightmap-yard.png"));// No `entries`: the floor samples the whole texture (the identity placement).const file = writeLightmapFile({ texture: TEXTURE, entries: {} });await writeFile(path.join(DIR, "lightmap-yard.lightmap.json"), `${JSON.stringify(file, null, 2)}\n`);console.log(`${path.relative(process.cwd(), DIR)}: lightmap-yard.png (${String(SIZE)}², ${String(RAYS)} rays a texel) and lightmap-yard.lightmap.json`);