// Bake an environment's light for the Lit renderer: a light map of its scenery and a grid of light probes // for everything that moves. // // usage: node tools/bake_light.mjs [env=kitchen] [--samples 256] [--bounces 3] [--threads N] // // The scenery (src/render/statics.js, the same triangles and light map layout as the page) is lit by a // sky over the open room (overcast-like, brightest overhead, a little cool), by a warm sun, and by its // emissive surfaces (windows, lamps), with light bouncing between the surfaces: each pass gathers, for // every texel of the light map, the light arriving over its hemisphere, where a ray that hits a surface // brings that surface's light from the pass before. The sun's own light is drawn at run time (a // directional light with a shadow map, src/render/view.js), so the maps leave it out but keep its bounce; // as there, the walls do not stand in its way (the room is a cutaway, and their shade would fill it). // The robot, the objects and the moving parts (doors, drawers) are not in it: they move. They are lit at // run time from the probes, a grid of irradiance from six directions (an ambient cube). // // Writes, next to the environment's XML: light/lightmap.png (irradiance over pi, sRGB-encoded over // `scale`), light/probes.bin.gz (the probes, the same way, RGBA per direction) and light/light.json (the // layout's fingerprint, sizes, the probe grid, the sun). The page uses them only if the fingerprint // matches its own layout: after changing the scenery, bake again. import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { availableParallelism } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads"; import { deflateSync, gzipSync } from "node:zlib"; import { buildBVH, makeCaster } from "./light/bvh.mjs"; const SKY = [1.0, 0.98, 0.95]; // the sky's radiance overhead (linear RGB); toward the horizon a third of it const GROUND = 0.25; // radiance below the horizon, outside // A sun, or null for the sky alone: where it is (azimuth from +x toward +y, elevation, degrees), its // irradiance square to it, its colour, and its disc's angular radius (degrees: the shade's soft edge). Its // hard shadows looked less real than the sky alone (2026-11-17); one that was tried: // { azimuth: -60, elevation: 50, irradiance: 4.5, color: [1.0, 0.93, 0.83], radius: 1.2, samples: 16 } const SUN = null; const SCALE = 1.6; // the stored range: irradiance / pi up to this const PROBE_STEP = 0.15; // metres between probes // --------------------------------------------------------------------------------------------------- async function main() { const args = process.argv.slice(2); const opt = (name, fallback) => { const k = args.indexOf(`--${name}`); return k >= 0 ? Number(args[k + 1]) : fallback; }; const envId = args.find((a) => !a.startsWith("--") && !/^\d/.test(a)) ?? "kitchen"; const samples = opt("samples", 256); const bounces = opt("bounces", 3); const threads = opt("threads", Math.max(1, availableParallelism() - 2)); const started = Date.now(); const log = (...m) => console.log(`[${((Date.now() - started) / 1000).toFixed(1)} s]`, ...m); const { loadScene, ASSETS } = await import("./node_env.mjs"); const { collectScenery, dressingMatrix, dressingTurn, layoutLightmap, lightmapSurfaces } = await import("../src/render/statics.js"); const { albedoOf, lookFor, surfaceColour } = await import("../src/render/materials.js"); const { glbTriangles, readGlb } = await import("./light/glb.mjs"); const THREE = await import("three"); const { sim, robot, env } = await loadScene(envId); sim.forward(); const robotRoots = robot.roots ?? (robot.root >= 0 ? [robot.root] : []); // furniture models (dressing.json's items) stand in for some scenery, in the light too const envDir = join(ASSETS, "environments", dirname(env.xml)); const dressing = env.dressing ? JSON.parse(readFileSync(join(envDir, env.dressing), "utf8")) : null; const scenery = collectScenery(sim, robotRoots, null, dressing); const layout = layoutLightmap(scenery); const { width: W, height: H } = layout; log(`${envId}: light map ${W} x ${H}, ${layout.charts.length} charts, fingerprint ${layout.hash}`); // --- what light hits: the scenery as the Lit renderer shows it --- const decor = scenery.groups.some((g) => g.role === "decor"); const occluders = []; // { geometry, albedo, emit, receiver, owner } const colourOf = (g) => { const c = g.attributes.color; return { r: c.getX(0), g: c.getY(0), b: c.getZ(0) }; }; for (const group of scenery.groups) { if ((group.role === "proxy" && decor) || group.opacity < 0.5 || (group.dressed !== null && group.dressed !== undefined)) continue; for (const part of group.parts) occluders.push({ geometry: part, albedo: albedoOf(group.look, colourOf(part)), emit: group.look?.emissive ?? 0 }); } for (const wall of scenery.walls) { if (wall.role === "proxy" && decor) continue; occluders.push({ geometry: wall.full, albedo: albedoOf(wall.look, wall.colour), emit: 0, wall: true }); } for (const plane of scenery.planes) { if (!plane.room || decor) continue; const look = lookFor(plane.matName); occluders.push({ geometry: plane.room, albedo: albedoOf(look, surfaceColour(look, plane.rgba)), emit: 0 }); } // the furniture models, placed as the page places them const glbs = {}; for (const { item, box } of scenery.dressing ?? []) { if (box.isEmpty()) continue; const model = dressing.models[item.model]; glbs[item.model] ??= glbTriangles(readGlb(readFileSync(join(envDir, dirname(env.dressing), model.file)))); const turn = dressingTurn(item); const turned = new THREE.Box3(); const v = new THREE.Vector3(); for (const { positions } of glbs[item.model]) for (let k = 0; k < positions.length; k += 3) turned.expandByPoint(v.fromArray(positions, k).applyMatrix4(turn)); const fit = dressingMatrix(item, turned, box); for (const { positions, material } of glbs[item.model]) { const g = new THREE.BufferGeometry().setAttribute("position", new THREE.BufferAttribute(positions.slice(), 3)).applyMatrix4(fit); occluders.push({ geometry: g, albedo: model.albedo[material] ?? [0.5, 0.5, 0.5], emit: 0 }); } } let nTri = 0; for (const o of occluders) nTri += o.geometry.attributes.position.count / 3; const input = new Float32Array(9 * nTri); const attrs = { albedo: new Float32Array(3 * nTri), emit: new Float32Array(nTri), uv1: new Float32Array(6 * nTri), owner: new Int32Array(nTri) }; let t = 0; for (const o of occluders) { const p = o.geometry.attributes.position; const uv1 = o.geometry.attributes.uv1; for (let v = 0; v < p.count; v += 3, t++) { for (let k = 0; k < 3; k++) { input.set([p.getX(v + k), p.getY(v + k), p.getZ(v + k)], 9 * t + 3 * k); attrs.uv1.set(uv1 ? [uv1.getX(v + k), uv1.getY(v + k)] : [NaN, NaN], 6 * t + 2 * k); } attrs.albedo.set(o.albedo, 3 * t); attrs.emit[t] = o.emit; attrs.owner[t] = o.geometry.userData.geom ?? -1; } } const bvh = buildBVH(input, nTri, true); // what stands in the sun's way: everything but the walls let nSunTri = 0; for (const o of occluders) if (!o.wall) nSunTri += o.geometry.attributes.position.count / 3; const sunInput = new Float32Array(9 * nSunTri); { let at = 0; let from = 0; for (const o of occluders) { const n = 9 * (o.geometry.attributes.position.count / 3); if (!o.wall) { sunInput.set(input.subarray(from, from + n), at); at += n; } from += n; } } const sunBvh = buildBVH(sunInput, nSunTri, true); const el = ((SUN?.elevation ?? 90) * Math.PI) / 180; const az = ((SUN?.azimuth ?? 0) * Math.PI) / 180; const sunDir = [Math.cos(el) * Math.cos(az), Math.cos(el) * Math.sin(az), Math.sin(el)]; const sun = SUN ? { ...SUN, direction: sunDir } : null; // per-triangle attributes in the BVH's order const shared = (Type, n) => new Type(new SharedArrayBuffer(n * Type.BYTES_PER_ELEMENT)); const triAlbedo = shared(Float32Array, 3 * nTri); const triEmit = shared(Float32Array, nTri); const triUV1 = shared(Float32Array, 6 * nTri); const triOwner = shared(Int32Array, nTri); for (let k = 0; k < nTri; k++) { const s = bvh.order[k]; triAlbedo.set(attrs.albedo.subarray(3 * s, 3 * s + 3), 3 * k); triEmit[k] = attrs.emit[s]; triUV1.set(attrs.uv1.subarray(6 * s, 6 * s + 6), 6 * k); triOwner[k] = attrs.owner[s]; } log(`${nTri} triangles, ${bvh.nodeCount} BVH nodes`); // --- the texels: where on the scenery each light map texel lies --- const chartOf = new Int32Array(W * H).fill(-1); // which chart each texel (with its padding) belongs to const texels = []; // [pixel, x, y, z, nx, ny, nz, ignore] const covered = new Uint8Array(W * H); layout.charts.forEach((c, id) => { for (let y = c.y - layout.pad; y < c.y + c.h + layout.pad; y++) for (let x = c.x - layout.pad; x < c.x + c.w + layout.pad; x++) chartOf[y * W + x] = id; const g = c.geometry; const p = g.attributes.position; const n = g.attributes.normal; const uv1 = g.attributes.uv1; const ignore = g.userData.stub ? g.userData.geom : -1; // a stub is lit as if its wall were cut down for (let v = c.start; v + 2 < c.start + c.count; v += 3) { const P = [0, 1, 2].map((k) => [uv1.getX(v + k) * W, uv1.getY(v + k) * H]); const x0 = Math.max(c.x, Math.floor(Math.min(P[0][0], P[1][0], P[2][0]) - 0.5)); const x1 = Math.min(c.x + c.w - 1, Math.ceil(Math.max(P[0][0], P[1][0], P[2][0]) - 0.5)); const y0 = Math.max(c.y, Math.floor(Math.min(P[0][1], P[1][1], P[2][1]) - 0.5)); const y1 = Math.min(c.y + c.h - 1, Math.ceil(Math.max(P[0][1], P[1][1], P[2][1]) - 0.5)); const det = (P[1][0] - P[0][0]) * (P[2][1] - P[0][1]) - (P[2][0] - P[0][0]) * (P[1][1] - P[0][1]); if (Math.abs(det) < 1e-12) continue; for (let y = y0; y <= y1; y++) { for (let x = x0; x <= x1; x++) { const px = x + 0.5, py = y + 0.5; const b1 = ((px - P[0][0]) * (P[2][1] - P[0][1]) - (P[2][0] - P[0][0]) * (py - P[0][1])) / det; const b2 = ((P[1][0] - P[0][0]) * (py - P[0][1]) - (px - P[0][0]) * (P[1][1] - P[0][1])) / det; const b0 = 1 - b1 - b2; if (b0 < -1e-4 || b1 < -1e-4 || b2 < -1e-4) continue; const pixel = y * W + x; if (covered[pixel]) continue; covered[pixel] = 1; const at = (attr, k) => b0 * attr.getComponent(v, k) + b1 * attr.getComponent(v + 1, k) + b2 * attr.getComponent(v + 2, k); let nx = at(n, 0), ny = at(n, 1), nz = at(n, 2); const l = Math.hypot(nx, ny, nz) || 1; nx /= l; ny /= l; nz /= l; texels.push([pixel, at(p, 0), at(p, 1), at(p, 2), nx, ny, nz, ignore]); } } } }); const nTex = texels.length; const texPixel = shared(Int32Array, nTex); const texData = shared(Float32Array, 6 * nTex); const texIgnore = shared(Int32Array, nTex); texels.forEach(([pixel, x, y, z, nx, ny, nz, ignore], k) => { texPixel[k] = pixel; texData.set([x, y, z, nx, ny, nz], 6 * k); texIgnore[k] = ignore; }); log(`${nTex} texels to light (${((100 * nTex) / (W * H)).toFixed(0)}% of the atlas)`); // --- the passes, on worker threads --- const counter = shared(Int32Array, 1); const prev = shared(Float32Array, 3 * W * H); const out = shared(Float32Array, 3 * W * H); const back = shared(Float32Array, W * H); // the share of rays that met a surface from behind const sunMap = shared(Float32Array, 3 * W * H); // the sun's own light on each texel (irradiance / pi) const common = { bvh: { nodes: bvh.nodes, info: bvh.info, tris: bvh.tris }, sunBvh: { nodes: sunBvh.nodes, info: sunBvh.info, tris: sunBvh.tris }, triAlbedo, triEmit, triUV1, triOwner, texPixel, texData, texIgnore, counter, prev, out, back, sunMap, W, H, SKY, GROUND, sun, }; const workers = Array.from({ length: threads }, () => new Worker(fileURLToPath(import.meta.url), { workerData: common })); const run = (job) => Promise.all( workers.map( (w) => new Promise((resolve, reject) => { w.once("message", resolve); w.once("error", reject); w.postMessage(job); }), ), ); const normals = new Float32Array(3 * W * H); // each texel's normal, for the denoiser for (let k = 0; k < nTex; k++) normals.set(texData.subarray(6 * k + 3, 6 * k + 6), 3 * texPixel[k]); for (let pass = 0; pass < bounces; pass++) { counter[0] = 0; out.fill(0); await run({ kind: "texels", pass, samples, bounce: pass > 0 }); // inside other geometry (most rays leave through back faces): taken from the neighbours, as uncovered texels are for (let k = 0; k < nTex; k++) if (back[texPixel[k]] > 0.3) covered[texPixel[k]] = 0; denoise(out, covered, chartOf, normals, W, H); dilate(out, covered, chartOf, W, H); if (pass === 0 && sun) { // the sun on every texel (the texels inside geometry known now), for what it bounces counter[0] = 0; await run({ kind: "sun" }); dilate(sunMap, covered, chartOf, W, H); log("sun done"); } // what the next pass's rays find on the surfaces they hit: their light, the sun's with it for (let k = 0; k < out.length; k++) prev[k] = out[k] + sunMap[k]; log(`pass ${pass + 1}/${bounces} done`); } const lightmap = encode(out, W * H, 3); writePng(lightmapPath(), lightmap, W, H); // --- the probes --- const box = scenery.room ?? boundsOf(lightmapSurfaces(scenery)); const z1 = Math.min(2.6, box.z1 ?? 2.6); const dims = [Math.round((box.x1 - box.x0) / PROBE_STEP) + 1, Math.round((box.y1 - box.y0) / PROBE_STEP) + 1, Math.round(z1 / PROBE_STEP) + 1]; const origin = [box.x0, box.y0, 0]; const step = [(box.x1 - box.x0) / (dims[0] - 1), (box.y1 - box.y0) / (dims[1] - 1), z1 / (dims[2] - 1)]; const nProbe = dims[0] * dims[1] * dims[2]; const probeOut = shared(Float32Array, 18 * nProbe); const probeBack = shared(Float32Array, nProbe); counter[0] = 0; await run({ kind: "probes", samples: Math.max(256, 2 * samples), origin, step, dims, probeOut, probeBack }); fillProbes(probeOut, probeBack, dims); await Promise.all(workers.map((w) => w.terminate())); // RGBA per direction (+x, -x, +y, -y, +z, -z), each a block of x fastest, then y, then z const probeBytes = new Uint8Array(4 * 6 * nProbe); for (let d = 0; d < 6; d++) { for (let k = 0; k < nProbe; k++) { for (let c = 0; c < 3; c++) probeBytes[4 * (d * nProbe + k) + c] = toByte(probeOut[18 * k + 3 * d + c] / SCALE, k * 7 + d * 3 + c); probeBytes[4 * (d * nProbe + k) + 3] = 255; } } const dir = join(ASSETS, "environments", dirname(env.xml), "light"); mkdirSync(dir, { recursive: true }); writeFileSync(join(dir, "probes.bin.gz"), gzipSync(probeBytes, { level: 9 })); const meta = { about: "Baked by tools/bake_light.mjs; used by src/render/view.js when the fingerprint matches the page's layout.", fingerprint: layout.hash, lightmap: { file: "lightmap.png", width: W, height: H, density: layout.density }, probes: { file: "probes.bin.gz", dims, origin, step }, scale: SCALE, sky: SKY, // drawn at run time: a directional light from `direction` (toward the sun), `irradiance` square to it sun: SUN ? { direction: sunDir.map((v) => +v.toFixed(5)), irradiance: SUN.irradiance, color: SUN.color, radius: SUN.radius } : undefined, samples, bounces, }; writeFileSync(join(dir, "light.json"), `${JSON.stringify(meta, null, 2)}\n`); log(`wrote ${dir}: ${nProbe} probes (${dims.join(" x ")})`); function lightmapPath() { const d = join(ASSETS, "environments", dirname(env.xml), "light"); mkdirSync(d, { recursive: true }); return join(d, "lightmap.png"); } } /** The bounds of some geometries (for a scene without walls). */ function boundsOf(geometries) { const b = { x0: Infinity, y0: Infinity, z1: 0, x1: -Infinity, y1: -Infinity }; for (const g of geometries) { g.computeBoundingBox(); b.x0 = Math.min(b.x0, g.boundingBox.min.x); b.y0 = Math.min(b.y0, g.boundingBox.min.y); b.x1 = Math.max(b.x1, g.boundingBox.max.x); b.y1 = Math.max(b.y1, g.boundingBox.max.y); b.z1 = Math.max(b.z1, g.boundingBox.max.z); } return b; } /** * Smooth the sampling noise, keeping edges: each texel becomes a weighted mean of the texels around it in * the same chart, weighted by distance, by how alike their normals are (a cylinder's chart bends) and by * how alike their light is (a contact shadow's edge stays). */ function denoise(map, covered, chartOf, normals, W, H, radius = 2) { const src = Float32Array.from(map); const luma = (p) => 0.2126 * src[3 * p] + 0.7152 * src[3 * p + 1] + 0.0722 * src[3 * p + 2]; for (let y = 0; y < H; y++) { for (let x = 0; x < W; x++) { const p = y * W + x; if (!covered[p]) continue; const lp = luma(p); const range = 0.25 * (lp + 0.02); let sw = 0, r = 0, g = 0, b = 0; for (let dy = -radius; dy <= radius; dy++) { const qy = y + dy; if (qy < 0 || qy >= H) continue; for (let dx = -radius; dx <= radius; dx++) { const qx = x + dx; if (qx < 0 || qx >= W) continue; const q = qy * W + qx; if (!covered[q] || chartOf[q] !== chartOf[p]) continue; const dn = normals[3 * p] * normals[3 * q] + normals[3 * p + 1] * normals[3 * q + 1] + normals[3 * p + 2] * normals[3 * q + 2]; if (dn < 0.8) continue; const dl = (luma(q) - lp) / range; const w = Math.exp(-(dx * dx + dy * dy) / (radius * radius) - 0.5 * dl * dl) * dn * dn; sw += w; r += w * src[3 * q]; g += w * src[3 * q + 1]; b += w * src[3 * q + 2]; } } if (sw > 0) map.set([r / sw, g / sw, b / sw], 3 * p); } } } /** * Fill the texels no ray found (padding round the charts, texels inside other geometry) from their * neighbours in the same chart, ring by ring. */ function dilate(map, covered, chartOf, W, H) { const known = Uint8Array.from(covered); for (let ring = 0; ring < 24; ring++) { const next = []; for (let y = 0; y < H; y++) { for (let x = 0; x < W; x++) { const p = y * W + x; if (known[p] || chartOf[p] < 0) continue; let n = 0, r = 0, g = 0, b = 0; for (let dy = -1; dy <= 1; dy++) { for (let dx = -1; dx <= 1; dx++) { const qx = x + dx, qy = y + dy; if (qx < 0 || qy < 0 || qx >= W || qy >= H) continue; const q = qy * W + qx; if (!known[q] || chartOf[q] !== chartOf[p]) continue; r += map[3 * q]; g += map[3 * q + 1]; b += map[3 * q + 2]; n++; } } if (n) next.push([p, r / n, g / n, b / n]); } } if (!next.length) break; for (const [p, r, g, b] of next) { map.set([r, g, b], 3 * p); known[p] = 1; } } } /** Probes inside geometry (rays mostly meeting back faces) take the mean of their valid neighbours. */ function fillProbes(values, back, [nx, ny, nz]) { const valid = Uint8Array.from(back, (b) => (b < 0.25 ? 1 : 0)); for (let ring = 0; ring < 12; ring++) { const next = []; for (let z = 0; z < nz; z++) for (let y = 0; y < ny; y++) for (let x = 0; x < nx; x++) { const k = x + nx * (y + ny * z); if (valid[k]) continue; const sum = new Float64Array(18); let n = 0; for (const [dx, dy, dz] of [[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]]) { const X = x + dx, Y = y + dy, Z = z + dz; if (X < 0 || Y < 0 || Z < 0 || X >= nx || Y >= ny || Z >= nz) continue; const q = X + nx * (Y + ny * Z); if (!valid[q]) continue; for (let c = 0; c < 18; c++) sum[c] += values[18 * q + c]; n++; } if (n) next.push([k, sum.map((v) => v / n)]); } if (!next.length) break; for (const [k, v] of next) { values.set(v, 18 * k); valid[k] = 1; } } } /** A linear value in [0, 1] as an sRGB byte, dithered by `seed`'s noise. */ function toByte(v, seed) { const c = Math.min(1, Math.max(0, v)); const s = c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055; return Math.min(255, Math.max(0, Math.floor(s * 255 + hash01(seed)))); } function encode(map, n, channels) { const bytes = new Uint8Array(channels * n); for (let k = 0; k < n * channels; k++) bytes[k] = toByte(map[k] / SCALE, k); return bytes; } function hash01(k) { let h = (k * 0x9e3779b1) >>> 0; h ^= h >>> 16; h = Math.imul(h, 0x85ebca6b) >>> 0; h ^= h >>> 13; h = Math.imul(h, 0xc2b2ae35) >>> 0; h ^= h >>> 16; return h / 4294967296; } /** A PNG file of 8-bit RGB rows, each filtered the way that compresses it best (sum of absolute values). */ function writePng(path, rgb, W, H) { const stride = 3 * W; const raw = new Uint8Array((stride + 1) * H); const cand = Array.from({ length: 5 }, () => new Uint8Array(stride)); for (let y = 0; y < H; y++) { const row = rgb.subarray(y * stride, (y + 1) * stride); const up = y ? rgb.subarray((y - 1) * stride, y * stride) : new Uint8Array(stride); let best = 0; let bestScore = Infinity; for (let f = 0; f < 5; f++) { const o = cand[f]; let score = 0; for (let i = 0; i < stride; i++) { const a = i >= 3 ? row[i - 3] : 0, b = up[i], c = i >= 3 ? up[i - 3] : 0; let pred = 0; if (f === 1) pred = a; else if (f === 2) pred = b; else if (f === 3) pred = (a + b) >> 1; else if (f === 4) { const p = a + b - c, pa = Math.abs(p - a), pb = Math.abs(p - b), pc = Math.abs(p - c); pred = pa <= pb && pa <= pc ? a : pb <= pc ? b : c; } const v = (row[i] - pred) & 255; o[i] = v; score += v < 128 ? v : 256 - v; } if (score < bestScore) { bestScore = score; best = f; } } raw[y * (stride + 1)] = best; raw.set(cand[best], y * (stride + 1) + 1); } const chunk = (type, data) => { const out = Buffer.alloc(12 + data.length); out.writeUInt32BE(data.length, 0); out.write(type, 4, "ascii"); Buffer.from(data).copy(out, 8); out.writeUInt32BE(crc32(out.subarray(4, 8 + data.length)), 8 + data.length); return out; }; const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(W, 0); ihdr.writeUInt32BE(H, 4); ihdr.set([8, 2, 0, 0, 0], 8); // 8 bits, RGB writeFileSync(path, Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", ihdr), chunk("IDAT", deflateSync(raw, { level: 9 })), chunk("IEND", new Uint8Array(0))])); } let crcTable = null; function crc32(bytes) { crcTable ??= Int32Array.from({ length: 256 }, (_, n) => { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c; }); let c = -1; for (const b of bytes) c = crcTable[(c ^ b) & 255] ^ (c >>> 8); return (c ^ -1) >>> 0; } // --------------------------------------------------------------------------------------------------- // A worker: texels or probes, a chunk at a time, until none are left. function work() { const d = workerData; const { cast, hit } = makeCaster(d.bvh); const sunCaster = makeCaster(d.sunBvh); // everything but the walls const { W, H, SKY: sky, GROUND: ground } = d; /** Radiance arriving along -dir at the origin from what the ray (o, dir) meets; counts back faces. */ const state = { back: 0 }; function radiance(ox, oy, oz, dx, dy, dz, ignore, bounce, out) { for (let tries = 0; tries < 4; tries++) { if (!cast(ox, oy, oz, dx, dy, dz, 1e9)) { if (dz > 0) { const k = (1 + 2 * dz) / 3; out[0] = sky[0] * k; out[1] = sky[1] * k; out[2] = sky[2] * k; } else { out[0] = out[1] = out[2] = ground; } return; } const tri = hit.tri; if (d.triOwner[tri] === ignore) { // the wall this stub stands for: go on past it ox += dx * (hit.t + 1e-4); oy += dy * (hit.t + 1e-4); oz += dz * (hit.t + 1e-4); continue; } const o = 9 * tri; const t = d.bvh.tris; // the triangle's front: (e1 x e2) const nx = t[o + 4] * t[o + 8] - t[o + 5] * t[o + 7]; const ny = t[o + 5] * t[o + 6] - t[o + 3] * t[o + 8]; const nz = t[o + 3] * t[o + 7] - t[o + 4] * t[o + 6]; if (nx * dx + ny * dy + nz * dz > 0) { state.back++; out[0] = out[1] = out[2] = 0; return; } const e = d.triEmit[tri]; out[0] = e; out[1] = e; out[2] = e; if (bounce) { const uv = d.triUV1; const w0 = 1 - hit.u - hit.v; const u = w0 * uv[6 * tri] + hit.u * uv[6 * tri + 2] + hit.v * uv[6 * tri + 4]; const v = w0 * uv[6 * tri + 1] + hit.u * uv[6 * tri + 3] + hit.v * uv[6 * tri + 5]; const a = d.triAlbedo; if (Number.isNaN(u)) { // not in the light map: lit like open ground const g = 0.78 * sky[1]; out[0] += a[3 * tri] * g; out[1] += a[3 * tri + 1] * g; out[2] += a[3 * tri + 2] * g; } else { sample(d.prev, u, v, rgb); // a diffuse surface's radiance: albedo / pi * irradiance, and the map holds irradiance / pi out[0] += a[3 * tri] * rgb[0]; out[1] += a[3 * tri + 1] * rgb[1]; out[2] += a[3 * tri + 2] * rgb[2]; } } return; } out[0] = out[1] = out[2] = 0; } const rgb = new Float32Array(3); /** Bilinear lookup in a map of W x H RGB texels. */ function sample(map, u, v, res) { const x = Math.min(W - 1, Math.max(0, u * W - 0.5)); const y = Math.min(H - 1, Math.max(0, v * H - 0.5)); const x0 = Math.floor(x), y0 = Math.floor(y); const x1 = Math.min(W - 1, x0 + 1), y1 = Math.min(H - 1, y0 + 1); const fx = x - x0, fy = y - y0; for (let c = 0; c < 3; c++) { const a = map[3 * (y0 * W + x0) + c], b = map[3 * (y0 * W + x1) + c]; const e = map[3 * (y1 * W + x0) + c], f = map[3 * (y1 * W + x1) + c]; res[c] = (a * (1 - fx) + b * fx) * (1 - fy) + (e * (1 - fx) + f * fx) * fy; } } const radical = (i) => { let b = i; b = ((b << 16) | (b >>> 16)) >>> 0; b = (((b & 0x55555555) << 1) | ((b & 0xaaaaaaaa) >>> 1)) >>> 0; b = (((b & 0x33333333) << 2) | ((b & 0xcccccccc) >>> 2)) >>> 0; b = (((b & 0x0f0f0f0f) << 4) | ((b & 0xf0f0f0f0) >>> 4)) >>> 0; b = (((b & 0x00ff00ff) << 8) | ((b & 0xff00ff00) >>> 8)) >>> 0; return b / 4294967296; }; const L = new Float32Array(3); parentPort.on("message", (job) => { if (job.kind === "texels") { const n = d.texPixel.length; const N = job.samples; for (;;) { const start = Atomics.add(d.counter, 0, 256); if (start >= n) break; for (let k = start; k < Math.min(n, start + 256); k++) { const b = 6 * k; const px = d.texData[b], py = d.texData[b + 1], pz = d.texData[b + 2]; const nx = d.texData[b + 3], ny = d.texData[b + 4], nz = d.texData[b + 5]; // a frame round the normal (Duff et al. 2017) const s = nz >= 0 ? 1 : -1; const a = -1 / (s + nz); const bb = nx * ny * a; const tx = 1 + s * nx * nx * a, ty = s * bb, tz = -s * nx; const ux = bb, uy = s + ny * ny * a, uz = -ny; const ox = px + nx * 1e-3, oy = py + ny * 1e-3, oz = pz + nz * 1e-3; // Hammersley points, shifted per texel and pass (Cranley-Patterson) const r1 = hash01(k * 2 + 1 + job.pass * 7919), r2 = hash01(k * 2 + 2 + job.pass * 104729); let er = 0, eg = 0, eb = 0; state.back = 0; for (let i = 0; i < N; i++) { let u1 = i / N + r1; if (u1 >= 1) u1 -= 1; let u2 = radical(i) + r2; if (u2 >= 1) u2 -= 1; // cosine-weighted const r = Math.sqrt(u1); const phi = 2 * Math.PI * u2; const lx = r * Math.cos(phi), ly = r * Math.sin(phi), lz = Math.sqrt(Math.max(0, 1 - u1)); const dx = lx * tx + ly * ux + lz * nx; const dy = lx * ty + ly * uy + lz * ny; const dz = lx * tz + ly * uz + lz * nz; radiance(ox, oy, oz, dx, dy, dz, d.texIgnore[k], job.bounce, L); er += L[0]; eg += L[1]; eb += L[2]; } // irradiance / pi = the mean radiance over cosine-weighted directions const pixel = d.texPixel[k]; d.out[3 * pixel] = er / N; d.out[3 * pixel + 1] = eg / N; d.out[3 * pixel + 2] = eb / N; d.back[pixel] = state.back / N; } } } else if (job.kind === "sun") { // the share of the sun's disc each texel sees (rays over the disc, past nothing but walls), times its // irradiance there: irradiance / pi, as the light map holds const { direction: s, irradiance, color, radius, samples: N } = d.sun; const sgn = s[2] >= 0 ? 1 : -1; const a = -1 / (sgn + s[2]); const b = s[0] * s[1] * a; const t1 = [1 + sgn * s[0] * s[0] * a, sgn * b, -sgn * s[0]]; const t2 = [b, sgn + s[1] * s[1] * a, -s[1]]; const spread = Math.tan((radius * Math.PI) / 180); const n = d.texPixel.length; for (;;) { const start = Atomics.add(d.counter, 0, 512); if (start >= n) break; for (let k = start; k < Math.min(n, start + 512); k++) { const q = 6 * k; const nx = d.texData[q + 3], ny = d.texData[q + 4], nz = d.texData[q + 5]; const cos = nx * s[0] + ny * s[1] + nz * s[2]; const pixel = d.texPixel[k]; if (cos <= 0) continue; const ox = d.texData[q] + nx * 1e-3, oy = d.texData[q + 1] + ny * 1e-3, oz = d.texData[q + 2] + nz * 1e-3; let seen = 0; for (let i = 0; i < N; i++) { // a point on the disc (Vogel's spiral) const r = spread * Math.sqrt((i + 0.5) / N); const phi = i * 2.399963 + hash01(k) * 6.283185; const u = r * Math.cos(phi), v = r * Math.sin(phi); let dx = s[0] + u * t1[0] + v * t2[0], dy = s[1] + u * t1[1] + v * t2[1], dz = s[2] + u * t1[2] + v * t2[2]; const l = Math.hypot(dx, dy, dz); dx /= l; dy /= l; dz /= l; if (!sunCaster.cast(ox, oy, oz, dx, dy, dz, 1e9)) seen++; } const e = (irradiance * cos * seen) / N / Math.PI; d.sunMap[3 * pixel] = e * color[0]; d.sunMap[3 * pixel + 1] = e * color[1]; d.sunMap[3 * pixel + 2] = e * color[2]; } } } else if (job.kind === "probes") { const [nx, ny, nz] = job.dims; const total = nx * ny * nz; const N = job.samples; const axes = [[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]]; for (;;) { const start = Atomics.add(d.counter, 0, 16); if (start >= total) break; for (let k = start; k < Math.min(total, start + 16); k++) { const x = k % nx, y = Math.floor(k / nx) % ny, z = Math.floor(k / (nx * ny)); const px = job.origin[0] + x * job.step[0], py = job.origin[1] + y * job.step[1], pz = job.origin[2] + Math.max(0.02, z * job.step[2]); const acc = new Float64Array(18); state.back = 0; const r1 = hash01(k * 3 + 11), r2 = hash01(k * 3 + 12); for (let i = 0; i < N; i++) { // uniform over the sphere let u1 = (i + 0.5) / N + r1; if (u1 >= 1) u1 -= 1; let u2 = radical(i) + r2; if (u2 >= 1) u2 -= 1; const cz = 1 - 2 * u1; const sr = Math.sqrt(Math.max(0, 1 - cz * cz)); const phi = 2 * Math.PI * u2; const dx = sr * Math.cos(phi), dy = sr * Math.sin(phi), dz = cz; radiance(px, py, pz, dx, dy, dz, -1, true, L); for (let a = 0; a < 6; a++) { const c = Math.max(0, dx * axes[a][0] + dy * axes[a][1] + dz * axes[a][2]); if (!c) continue; acc[3 * a] += L[0] * c; acc[3 * a + 1] += L[1] * c; acc[3 * a + 2] += L[2] * c; } } // irradiance / pi from each axis: (4 pi / N) sum L cos, over pi for (let c = 0; c < 18; c++) job.probeOut[18 * k + c] = (4 * acc[c]) / N; job.probeBack[k] = state.back / N; } } } parentPort.postMessage("done"); }); } if (isMainThread) await main(); else work();