xlerobot-sim / src /render /toon.js
VectorW's picture
Household tasks in the style of the BEHAVIOR Challenge; walls cut away in the view; fixes
d72771b verified
Raw History Blame Contribute Delete
5.43 kB
// Ink outlines for the Toon renderer. Each view is drawn twice into render targets, once in colour and
// once as view-space normals with depth, and a full-screen pass darkens the pixels where the depth jumps
// (silhouettes) or the surface bends sharply (creases). Textures do not draw lines, only shapes do.
import * as THREE from "three";
const VERTEX = /* glsl */ `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = vec4(position.xy, 0.0, 1.0);
}`;
const FRAGMENT = /* glsl */ `
#include <packing>
uniform sampler2D tColour;
uniform sampler2D tNormal;
uniform sampler2D tDepth;
uniform vec2 texel;
uniform float near;
uniform float far;
uniform vec3 ink;
uniform float strength;
varying vec2 vUv;
float distanceAt(vec2 uv) { return -perspectiveDepthToViewZ(texture2D(tDepth, uv).x, near, far); }
vec3 normalAt(vec2 uv) { return texture2D(tNormal, uv).xyz * 2.0 - 1.0; }
void main() {
vec4 colour = texture2D(tColour, vUv);
vec2 dx = vec2(texel.x, 0.0);
vec2 dy = vec2(0.0, texel.y);
// Depth: the second difference is ~0 across a plane and large at a step, relative to the distance.
float z = distanceAt(vUv);
float zx = abs(distanceAt(vUv - dx) + distanceAt(vUv + dx) - 2.0 * z);
float zy = abs(distanceAt(vUv - dy) + distanceAt(vUv + dy) - 2.0 * z);
float silhouette = smoothstep(0.025, 0.07, max(zx, zy) / z);
// Normals: how far the neighbours turn away.
vec3 n = normalAt(vUv);
float bend = max(
max(1.0 - dot(n, normalAt(vUv - dx)), 1.0 - dot(n, normalAt(vUv + dx))),
max(1.0 - dot(n, normalAt(vUv - dy)), 1.0 - dot(n, normalAt(vUv + dy))));
float crease = smoothstep(0.22, 0.5, bend);
float edge = max(silhouette, crease) * strength;
gl_FragColor = vec4(mix(colour.rgb, ink, edge), 1.0);
#include <colorspace_fragment>
}`;
export class OutlinePass {
constructor({ ink = 0x2e2a27, strength = 0.85 } = {}) {
this.targets = new Map();
this.normals = new THREE.MeshNormalMaterial();
this.material = new THREE.ShaderMaterial({
uniforms: {
tColour: { value: null },
tNormal: { value: null },
tDepth: { value: null },
texel: { value: new THREE.Vector2() },
near: { value: 0.1 },
far: { value: 100 },
ink: { value: new THREE.Color(ink) },
strength: { value: strength },
},
vertexShader: VERTEX,
fragmentShader: FRAGMENT,
depthTest: false,
depthWrite: false,
});
const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), this.material);
quad.frustumCulled = false;
this.screen = new THREE.Scene();
this.screen.add(quad);
this.screenCamera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
this.clear = new THREE.Color();
}
#targetsFor(key, w, h, samples) {
let t = this.targets.get(key);
if (t && t.colour.samples !== samples) {
this.#dispose(t);
t = null;
}
if (!t) {
// 8-bit sRGB colour: half the memory traffic of half floats, and enough for flat toon shading.
t = {
colour: new THREE.WebGLRenderTarget(w, h, { colorSpace: THREE.SRGBColorSpace, samples }),
normal: new THREE.WebGLRenderTarget(w, h, { depthTexture: new THREE.DepthTexture(w, h) }),
};
this.targets.set(key, t);
}
if (t.colour.width !== w || t.colour.height !== h) {
t.colour.setSize(w, h);
t.normal.setSize(w, h);
}
return t;
}
/**
* Draw `scene` from `camera` with outlines into the canvas rectangle `rect` (CSS pixels from the top left;
* null for the whole canvas). `key` names the view, which keeps its own render targets.
*/
render(renderer, scene, camera, key, rect = null) {
const size = renderer.getSize(new THREE.Vector2());
const r = rect ?? { x: 0, y: 0, w: size.x, h: size.y };
const pr = renderer.getPixelRatio();
const w = Math.max(1, Math.round(r.w * pr));
const h = Math.max(1, Math.round(r.h * pr));
// Multisampling matters less on a dense screen, where it costs more.
const t = this.#targetsFor(key, w, h, pr >= 1.75 ? 2 : 4);
renderer.setRenderTarget(t.colour);
renderer.render(scene, camera);
const background = scene.background;
const clearAlpha = renderer.getClearAlpha();
renderer.getClearColor(this.clear);
scene.background = null;
scene.overrideMaterial = this.normals;
renderer.setClearColor(0x8080ff, 1); // a normal facing the camera
renderer.setRenderTarget(t.normal);
renderer.render(scene, camera);
scene.overrideMaterial = null;
scene.background = background;
renderer.setClearColor(this.clear, clearAlpha);
const u = this.material.uniforms;
u.tColour.value = t.colour.texture;
u.tNormal.value = t.normal.texture;
u.tDepth.value = t.normal.depthTexture;
u.texel.value.set(Math.max(1, pr) / w, Math.max(1, pr) / h); // lines about one CSS pixel wide
u.near.value = camera.near;
u.far.value = camera.far;
renderer.setRenderTarget(null);
const y = size.y - r.y - r.h;
renderer.setViewport(r.x, y, r.w, r.h);
renderer.setScissor(r.x, y, r.w, r.h);
renderer.setScissorTest(true);
renderer.render(this.screen, this.screenCamera);
renderer.setScissorTest(false);
}
#dispose(t) {
t.colour.dispose();
t.normal.depthTexture.dispose();
t.normal.dispose();
}
dispose() {
for (const t of this.targets.values()) this.#dispose(t);
this.targets.clear();
}
}