xlerobot-sim / src /render /home.js
VectorW's picture
Kitchen: Toon and Pixel draw the photographic room, no flicker from flush faces, the microwave without a handle, the fridge's crispers behind its door bins; the page opens on the kitchen in Lit
675b16f verified
Raw History Blame Contribute Delete
18.4 kB
// Lit's photographic room (tools/home): a scene built and lit in Blender on the environment's MuJoCo layout, its
// light baked in Cycles. The page draws it instead of the MuJoCo geoms of the scenery and the fixtures (they stay for
// the physics, for picking, and for Toon and Pixel):
// - surfaces tagged `lm` take the baked light map (TEXCOORD_1; Cycles bakes irradiance / pi, hence the factor pi) and
// no realtime light, except that what moves darkens them where it shades the key light (its shadow map);
// - everything else (small things, the fixtures' moving parts, the robot and the objects) is lit by a light-probe
// grid captured in the page from the lit room, a key light standing in for the lamps nearest to where you look, and
// reflections of the room (a cube capture);
// - nodes tagged `body` follow that MuJoCo body; nodes tagged `cut` (a wall, the ceiling and what is on them) are not
// drawn while the camera is outside them, so the room opens toward you like a doll's house;
// - the sky the room was lit by shows behind its windows while the camera is inside the room.
// Toon and Pixel draw the same room in flat colours (each material's mean colour, from the export) with their ink
// lines and the key light's shadows of the furniture (setLook).
import * as THREE from "three";
import { DRACOLoader } from "three/addons/loaders/DRACOLoader.js";
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
import { LightProbeGridWebGL } from "three/addons/lighting/LightProbeGridWebGL.js";
import { download } from "../core/assets.js";
import { makeMaterial } from "./materials.js";
import { OUTLINED } from "./pixel.js";
// Share of the lamps' direct light that what moves gets from the shadow-casting key light; the probes see the rest.
const KEY = 0.7;
// How much a moving thing's shadow (of the key light) darkens the baked room where it falls.
const BAKED_SHADOW = 0.6;
// Probe spacing (m) and the most probes baked per frame (the page stays responsive while they are captured).
const PROBE_SPACING = [0.4, 0.4, 0.45];
const PROBES_PER_FRAME = 96;
const swap = (src, a, b) => {
if (!src.includes(a)) throw new Error(`three.js shader chunk changed: ${a.slice(0, 60)}`);
return src.replace(a, b);
};
// With a probe grid in the scene the probes give the diffuse ambient light, the environment map only reflections
// (three.js would add both). Programs without a grid compile as before.
const IBL_DIFFUSE = "iblIrradiance += getIBLIrradiance( geometryNormal );";
if (!THREE.ShaderChunk.lights_fragment_maps.includes("NUM_LIGHT_PROBE_GRIDS == 0")) {
THREE.ShaderChunk.lights_fragment_maps = swap(THREE.ShaderChunk.lights_fragment_maps, IBL_DIFFUSE, `#if NUM_LIGHT_PROBE_GRIDS == 0\n${IBL_DIFFUSE}\n#endif`);
}
// Baked surfaces: no realtime direct light, no hemisphere or probe light; the light map, darkened by the key light's
// shadow of what moves; the environment map for reflections only.
const BAKED = (() => {
let begin = THREE.ShaderChunk.lights_fragment_begin;
for (const a of [
"#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )",
"#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )",
"#if ( NUM_SUN_LIGHTS > 0 ) && defined( RE_Direct )",
"#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )",
"#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )",
"#if ( NUM_HEMI_LIGHTS > 0 )",
"#if NUM_LIGHT_PROBE_GRIDS > 0",
])
begin = swap(begin, a, "#if 0");
let maps = swap(THREE.ShaderChunk.lights_fragment_maps, `#if NUM_LIGHT_PROBE_GRIDS == 0\n${IBL_DIFFUSE}\n#endif`, "");
maps = swap(
maps,
"irradiance += lightMapIrradiance;",
`#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
DirectionalLightShadow bakedShadow = directionalLightShadows[ 0 ];
float bakedVis = receiveShadow ? getShadow( directionalShadowMap[ 0 ], bakedShadow.shadowMapSize, bakedShadow.shadowIntensity,
bakedShadow.shadowBias, bakedShadow.shadowRadius, vDirectionalShadowCoord[ 0 ] ) : 1.0;
lightMapIrradiance *= mix( 1.0, bakedVis, bakedShadowStrength * saturate( 4.0 * dot( geometryNormal, directionalLights[ 0 ].direction ) ) );
#endif
irradiance += lightMapIrradiance;`,
);
return { begin, maps, strength: { value: BAKED_SHADOW } };
})();
function makeBaked(material) {
material.onBeforeCompile = (shader) => {
shader.uniforms.bakedShadowStrength = BAKED.strength;
shader.fragmentShader = `uniform float bakedShadowStrength;\n${shader.fragmentShader}`
.replace("#include <lights_fragment_begin>", BAKED.begin)
.replace("#include <lights_fragment_maps>", BAKED.maps);
};
material.customProgramCacheKey = () => "home-baked";
}
/** Linear RGB of a black body at `k` kelvin, brightest channel 1 (as tools/home/hb.py's kelvin). */
function kelvin(k) {
const t = k / 100;
const r = t <= 66 ? 255 : 329.698727446 * (t - 60) ** -0.1332047592;
const g = t <= 66 ? 99.4708025861 * Math.log(t) - 161.1195681661 : 288.1221695283 * (t - 60) ** -0.0755148492;
const b = t >= 66 ? 255 : t <= 19 ? 0 : 138.5177312231 * Math.log(t - 10) - 305.0447927307;
const c = new THREE.Color().setRGB(...[r, g, b].map((v) => Math.min(255, Math.max(0, v)) / 255), THREE.SRGBColorSpace);
const m = Math.max(c.r, c.g, c.b);
return c.multiplyScalar(1 / m);
}
export class HomeScene {
/** Load the room described by `url` (home.json, from tools/home/bake_home.py) for `sim`. */
static async load(url, sim) {
const base = url.slice(0, url.lastIndexOf("/") + 1);
const meta = await (await fetch(url)).json();
const textures = new THREE.TextureLoader();
const [glb, lightmap, sky] = await Promise.all([
download(`${base}${meta.glb}`),
textures.loadAsync(`${base}${meta.lightmap.file}`),
meta.sky ? textures.loadAsync(`${base}${meta.sky.file}`) : null,
]);
const draco = new DRACOLoader().setDecoderPath(`${import.meta.env.BASE_URL}draco/`);
const gltf = await new GLTFLoader().setDRACOLoader(draco).parseAsync(glb.buffer.slice(glb.byteOffset, glb.byteOffset + glb.byteLength), base);
draco.dispose();
return new HomeScene(meta, gltf.scene, lightmap, sky, sim);
}
constructor(meta, scene, lightmap, sky, sim) {
this.meta = meta;
this.root = new THREE.Group();
this.root.name = "home";
this.owned = new Set();
lightmap.flipY = false;
lightmap.colorSpace = THREE.SRGBColorSpace;
lightmap.channel = 1;
this.lightmap = lightmap;
if (sky) {
sky.mapping = THREE.EquirectangularReflectionMapping;
sky.colorSpace = THREE.SRGBColorSpace;
}
this.sky = sky;
this.bodies = []; // {node, body}
this.meshes = []; // every mesh of the room
this.cuts = { N: [], S: [], E: [], W: [], C: [] };
this.moving = [];
const materials = new Map();
const tops = [...scene.children];
for (const top of tops) {
scene.remove(top);
this.root.add(top);
}
this.root.updateMatrixWorld(true);
// a node's tags (glTF extras) hold for what is under it: a mesh of several materials loads as a group of meshes
const tagged = (o) => {
const u = {};
for (let n = o; n && n !== this.root; n = n.parent) for (const [k, v] of Object.entries(n.userData ?? {})) if (!(k in u)) u[k] = v;
return u;
};
this.root.traverse((o) => {
const u = o.isMesh ? tagged(o) : (o.userData ?? {});
const own = o.userData ?? {};
if (own.body !== undefined) {
const body = sim.id("body", own.body);
if (body >= 0) {
o.matrixAutoUpdate = false;
this.bodies.push({ node: o, body });
o.traverse((c) => c.isMesh && this.moving.push(c));
}
}
if (own.cut && this.cuts[own.cut]) this.cuts[own.cut].push(o);
if (!o.isMesh) return;
const toon = this.#toon(o.material, materials);
o.material = this.#material(o.material, Boolean(u.lm), materials);
o.castShadow = false; // the room's own shadows are baked; the moving parts' are set below
o.receiveShadow = Boolean(u.lm); // what moves shades the baked room (and the robot); the rest stays plain: cheaper
o.layers.enable(OUTLINED); // Pixel's ink lines go round it
// Lit's and Toon's looks; in Toon everything but the walls and the ceiling (and glass) casts the key light's shadow
o.userData.looks = { lit: o.material, toon, litCasts: false, toonCasts: !u.cut && !toon.transparent, litReceives: Boolean(u.lm) };
this.meshes.push(o);
this.owned.add(o.geometry);
});
for (const m of this.moving) m.castShadow = m.userData.looks.litCasts = !m.material.transparent; // not in the bake: they cast the key light's
for (const m of materials.values()) this.owned.add(m);
this.owned.add(lightmap);
if (sky) this.owned.add(sky);
// the room's bounds and lamps
const r = meta.room;
this.box = { x0: r.x[0], x1: r.x[1], y0: r.y[0], y1: r.y[1], z1: r.z[1] };
this.lamps = meta.lamps.map((L) => ({
kind: L.kind,
p: new THREE.Vector3(...L.pos),
d: new THREE.Vector3(...L.dir).normalize(),
power: L.power,
cos: L.kind === "spot" ? Math.cos(THREE.MathUtils.degToRad(L.spot_deg / 2)) : -1,
color: L.color ? new THREE.Color(L.color[0], L.color[1], L.color[2]) : kelvin(L.kelvin),
}));
this.reflection = null;
this.reflectionWithParts = false;
this.grid = null;
this.gridNext = 0;
this.gridDone = false;
}
/** Toon's flat-coloured stand-in for a GLB material: its mean colour (extras "toon"), its glow ("toon_glow"). */
#toon(src, cache) {
const key = `${src.uuid}|toon`;
if (cache.has(key)) return cache.get(key);
const u = src.userData ?? {};
const glass = src.transmission > 0.5;
const color = glass ? new THREE.Color(0xc9dde4) : u.toon ? new THREE.Color().setRGB(u.toon[0], u.toon[1], u.toon[2]) : src.color.clone();
const m = makeMaterial("toon", null, { color, vertexColors: Boolean(src.vertexColors) && src.name.startsWith("Painted"), opacity: glass ? 0.3 : 1 });
if (u.toon_glow) {
m.emissive = new THREE.Color().setRGB(u.toon_glow[0], u.toon_glow[1], u.toon_glow[2]);
m.emissiveIntensity = 0.7;
}
cache.set(key, m);
return m;
}
/** Draw the room as Lit ("lit") or as Toon and Pixel do ("toon"); the probe grid only lights Lit. */
setLook(look, scene) {
const toon = look === "toon";
if (this.look === look) return;
this.look = look;
for (const m of this.meshes) {
const l = m.userData.looks;
m.material = toon ? l.toon : l.lit;
m.castShadow = toon ? l.toonCasts : l.litCasts;
m.receiveShadow = toon ? true : l.litReceives;
}
if (this.grid && this.gridDone) {
if (toon) scene.remove(this.grid);
else scene.add(this.grid);
}
}
/** The GLB's material made for the page: light-mapped, glass, or as it is. */
#material(src, baked, cache) {
const key = `${src.uuid}|${baked}`;
if (cache.has(key)) return cache.get(key);
for (const k of ["map", "normalMap", "roughnessMap", "metalnessMap", "emissiveMap"]) if (src[k]) src[k].anisotropy = 4;
let m = src;
if (src.vertexColors && !src.name.startsWith("Painted")) {
// merged meshes carry the painted things' vertex colours everywhere: only "Painted" takes them
m = src.clone();
m.vertexColors = false;
src = m;
}
if (src.transmission > 0.5) {
// transmission draws the whole scene again each frame: plain see-through glass, with its reflections
m = src.clone();
m.transmission = 0;
m.transparent = true;
m.opacity = Math.min(m.opacity, 0.14);
m.roughness = Math.min(m.roughness, 0.05);
m.depthWrite = false;
} else if (baked) {
m = src.clone();
m.lightMap = this.lightmap;
m.lightMapIntensity = Math.PI * this.meta.lightmap.scale;
makeBaked(m);
}
for (const t of Object.values(src)) if (t?.isTexture) this.owned.add(t);
this.owned.add(src);
cache.set(key, m);
return m;
}
/** The moving parts where their bodies are now. */
update(data) {
const { xpos: p, xmat: R } = data;
for (const { node, body: b } of this.bodies) {
node.matrix.set(R[9 * b], R[9 * b + 1], R[9 * b + 2], p[3 * b], R[9 * b + 3], R[9 * b + 4], R[9 * b + 5], p[3 * b + 1], R[9 * b + 6], R[9 * b + 7], R[9 * b + 8], p[3 * b + 2], 0, 0, 0, 1);
node.matrixWorldNeedsUpdate = true;
}
}
/** Light the model of geom `name` up (a device's power light) or let it go dark again. */
glow(name, on, color) {
const node = this.root.getObjectByName(name);
const mesh = node?.isMesh ? node : node?.children.find((c) => c.isMesh);
if (!mesh) return;
const u = mesh.userData;
if (!u.ownGlow) {
mesh.material = mesh.material.clone();
this.owned.add(mesh.material);
u.base = mesh.material.color.clone();
u.ownGlow = true;
}
mesh.material.color.set(on ? color : u.base);
mesh.material.emissive.set(on ? color : 0x000000);
mesh.material.emissiveIntensity = on ? 0.4 : 1; // the room is seen at +1.6 EV: brighter turns white
}
inside(p) {
const b = this.box;
return p.x > b.x0 && p.x < b.x1 && p.y > b.y0 && p.y < b.y1 && p.z < b.z1;
}
/** Hide the walls (and the ceiling) the camera is outside of, until uncut(). */
cut(camera) {
const c = camera.position;
const b = this.box;
const hidden = (this.hidden ??= []);
const hide = (nodes) => {
for (const n of nodes) {
if (!n.visible) continue;
n.visible = false;
hidden.push(n);
}
};
if (c.y > b.y1) hide(this.cuts.N);
if (c.y < b.y0) hide(this.cuts.S);
if (c.x > b.x1) hide(this.cuts.E);
if (c.x < b.x0) hide(this.cuts.W);
if (c.z > b.z1) hide(this.cuts.C);
}
uncut() {
const hidden = this.hidden ?? [];
for (const n of hidden) n.visible = true;
hidden.length = 0;
}
/** The key light at `target`: the lamps' direct irradiance there (Cycles watts: W/sr = P / 4 pi), KEY of it. */
placeKey(key, target) {
const v = (this.v ??= new THREE.Vector3());
const dir = (this.dir ??= new THREE.Vector3()).set(0, 0, 0);
const col = (this.col ??= new THREE.Color()).setRGB(0, 0, 0);
let sum = 0;
for (const L of this.lamps) {
v.subVectors(L.p, target);
const r2 = v.lengthSq();
if (r2 > 25 || r2 < 1e-4) continue;
const r = Math.sqrt(r2);
let I = L.power / (4 * Math.PI);
if (L.kind === "spot") {
if (-v.dot(L.d) / r < L.cos) continue;
} else if (L.kind === "area") {
I = (L.power / Math.PI) * Math.max(0, -v.dot(L.d) / r);
}
const E = I / r2;
dir.addScaledVector(v, E / r);
col.r += E * L.color.r;
col.g += E * L.color.g;
col.b += E * L.color.b;
sum += E;
}
if (sum <= 0) {
key.intensity = 0;
return;
}
dir.normalize();
key.color.setRGB(col.r / sum, col.g / sum, col.b / sum);
key.intensity = KEY * sum;
key.target.position.copy(target);
key.position.copy(target).addScaledVector(dir, 5);
}
/**
* Before a frame in Lit: the room's reflections (once, then again with the moving parts lit by the probes), and
* the next probes of the grid. `hide` lists what must not be seen by the captures (the robot, the objects).
*/
prepare(renderer, scene, hide) {
if (!this.reflection || (this.gridDone && !this.reflectionWithParts)) this.#capture(renderer, scene, hide, this.gridDone);
if (!this.gridDone) this.#bakeProbes(renderer, scene, hide);
}
/** Whether the captures are all done (prepare has nothing left to do). */
get ready() {
return this.gridDone && this.reflectionWithParts;
}
#isolate(scene, hide, parts) {
const hidden = [];
const off = (o) => {
if (o.visible) {
o.visible = false;
hidden.push(o);
}
};
for (const o of hide) off(o);
if (!parts) for (const m of this.moving) off(m);
const saved = { background: scene.background, backgroundIntensity: scene.backgroundIntensity, environment: scene.environment };
scene.background = this.sky ?? new THREE.Color(0xdddddd);
scene.backgroundIntensity = this.meta.sky?.scale ?? 1;
scene.environment = null;
return () => {
for (const o of hidden) o.visible = true;
Object.assign(scene, saved);
};
}
#capture(renderer, scene, hide, parts) {
const restore = this.#isolate(scene, hide, parts);
const pmrem = new THREE.PMREMGenerator(renderer);
const r = this.box;
const target = pmrem.fromScene(scene, 0, 0.05, 30, { size: 256, position: new THREE.Vector3((r.x0 + r.x1) / 2, (r.y0 + r.y1) / 2, 1.3) });
pmrem.dispose();
restore();
this.reflection?.dispose();
this.reflection = target;
this.reflectionWithParts = parts;
}
#bakeProbes(renderer, scene, hide) {
if (!this.grid) {
const b = this.box;
const size = new THREE.Vector3(b.x1 - b.x0, b.y1 - b.y0, b.z1);
const res = [0, 1, 2].map((k) => Math.max(2, Math.round(size.getComponent(k) / PROBE_SPACING[k])));
this.grid = new LightProbeGridWebGL(size.x, size.y, size.z, res[0], res[1], res[2]);
this.grid.position.set((b.x0 + b.x1) / 2, (b.y0 + b.y1) / 2, b.z1 / 2);
this.grid.updateMatrixWorld(true);
this.gridTotal = res[0] * res[1] * res[2];
this.gridStarted = performance.now();
}
const restore = this.#isolate(scene, hide, false);
const count = Math.min(PROBES_PER_FRAME, this.gridTotal - this.gridNext);
renderer.shadowMap.needsUpdate = true;
this.grid.bake(renderer, scene, { cubemapSize: 16, near: 0.05, far: 30, start: this.gridNext, count });
restore();
this.gridNext += count;
if (this.gridNext >= this.gridTotal) {
this.gridDone = true;
this.gridMs = Math.round(performance.now() - this.gridStarted);
if (this.look !== "toon") scene.add(this.grid);
}
}
/** The background now: the sky while the camera is in the room, otherwise none (the caller's). */
backgroundFor(camera) {
return this.sky && this.inside(camera.position) ? this.sky : null;
}
dispose(scene) {
if (this.grid) {
scene?.remove(this.grid);
this.grid.dispose?.();
}
this.reflection?.dispose();
for (const x of this.owned) x.dispose?.();
}
}