xlerobot-sim / src /render /pixel.js
VectorW's picture
Pixel over a splat: no ink lines, brighter robot and objects; ?style= in the URL
db418f4 verified
Raw History Blame Contribute Delete
15.9 kB
// The Pixel renderer: pixel art of whatever the scene shows, a 3D Gaussian splat included. Each view is
// drawn small (about 240 pixels high), every pixel takes one of a few colours fitted to what that view
// shows (palette.js), in-between colours become an ordered dither of the two nearest ones, and the result
// is scaled up by a whole number of screen pixels. A scene made of meshes gets ink lines around its shapes,
// as in Toon; a splat has no such lines, so the robot and the objects in it get none either.
//
// A view is first drawn with 2x2 samples per pixel, and each pixel then takes one of its four samples, never
// a blend: the colours stay those of the scene, while a line thinner than a pixel is drawn whole or not at
// all (sampled once per pixel it would come out dotted, and crawl when the camera moves).
import * as THREE from "three";
import { CHROMA, MAX_COLOURS, Palette } from "./palette.js";
/** Layers of the meshes a pixel can show, and of those that only hide them (the splat's stand-in). */
export const OUTLINED = 1;
export const OCCLUDER = 2;
const REFIT_MS = 250; // between updates of a view's palette
const VERTEX = /* glsl */ `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = vec4(position.xy, 0.0, 1.0);
}`;
// One pixel from its 2x2 samples. The nearest surface among them takes the pixel, so a thin part of the
// robot is not lost; of that surface's samples, the one closest to their mean colour is kept. The alpha
// channel says whether that surface is an outlined mesh, and the depth is that of its nearest sample.
const RESOLVE = /* glsl */ `
uniform sampler2D tScene;
uniform sampler2D tMask;
uniform sampler2D tDepth;
uniform vec2 texel;
uniform float near;
uniform float far;
uniform bool edges;
varying vec2 vUv;
void main() {
vec2 o = 0.5 * texel;
vec2 at[4] = vec2[4](vUv - o, vUv + vec2(o.x, -o.y), vUv + vec2(-o.x, o.y), vUv + o);
float depth[4];
int nearest = 0;
for (int i = 0; i < 4; i++) {
depth[i] = edges ? texture2D(tDepth, at[i]).x : 1.0;
if (depth[i] < depth[nearest]) nearest = i;
}
// One over the distance is linear in the depth value; the same surface: within 3% of the nearest.
float scale = 1.0 / near - 1.0 / far;
float limit = (1.0 / near - depth[nearest] * scale) * 0.97;
vec3 colour[4];
vec3 mean = vec3(0.0);
float n = 0.0;
for (int i = 0; i < 4; i++) {
colour[i] = sqrt(texture2D(tScene, at[i]).rgb);
if (1.0 / near - depth[i] * scale < limit) continue;
mean += colour[i];
n += 1.0;
}
mean /= n;
int pick = nearest;
float best = 1e9;
for (int i = 0; i < 4; i++) {
if (1.0 / near - depth[i] * scale < limit) continue;
vec3 d = colour[i] - mean;
float dd = dot(d, d);
if (dd < best) {
best = dd;
pick = i;
}
}
gl_FragColor = vec4(colour[pick] * colour[pick], edges ? texture2D(tMask, at[nearest]).r : 0.0);
gl_FragDepth = depth[nearest];
}`;
const QUANTISE = /* glsl */ `
#include <packing>
uniform sampler2D tPicked;
uniform sampler2D tDepth;
uniform vec2 texel;
uniform float near;
uniform float far;
uniform vec3 matched[MAX_COLOURS];
uniform vec3 colours[MAX_COLOURS];
uniform int count;
uniform float sharpness;
uniform bool lines;
uniform vec3 ink;
varying vec2 vUv;
const float BAYER[16] = float[16](0.0, 8.0, 2.0, 10.0, 12.0, 4.0, 14.0, 6.0, 3.0, 11.0, 1.0, 9.0, 15.0, 7.0, 13.0, 5.0);
vec3 oklab(vec3 c) {
vec3 lms = mat3(0.4122214708, 0.2119034982, 0.0883024619, 0.5363325363, 0.6806995451, 0.2817188376, 0.0514459929, 0.1073969566, 0.6299787005) * c;
lms = pow(max(lms, 0.0), vec3(1.0 / 3.0));
vec3 lab = mat3(0.2104542553, 1.9779984951, 0.0259040371, 0.7936177850, -2.4285922050, 0.7827717662, -0.0040720468, 0.4505937099, -0.8086757660) * lms;
return vec3(lab.x, lab.yz * CHROMA);
}
// One over the distance: it changes evenly across a flat surface, however steeply the surface is seen.
float nearness(vec2 uv) { return -1.0 / perspectiveDepthToViewZ(texture2D(tDepth, uv).x, near, far); }
// Whether an outlined surface next to this pixel, toward d, stands in front of it. Both surfaces are
// carried on, each with its own slope, to the point half way between the two pixels: a step leaves a gap
// there, while two faces meeting in a crease (a worktop against a wall) leave at most half the difference
// of their slopes. The line is drawn on the far side, around the shape.
float inFront(vec2 d, float here) {
float front = nearness(vUv + d);
float slopeFront = nearness(vUv + 2.0 * d) - front;
float slopeHere = here - nearness(vUv - d);
float gap = (front - 0.5 * slopeFront) - (here + 0.5 * slopeHere);
return texture2D(tPicked, vUv + d).a * step(0.6 * (abs(slopeFront) + abs(slopeHere)) + 0.02 * front, gap);
}
void main() {
vec3 colour = texture2D(tPicked, vUv).rgb;
float line = 0.0;
if (lines) {
float here = nearness(vUv);
vec2 dx = vec2(texel.x, 0.0);
vec2 dy = vec2(0.0, texel.y);
line = min(1.0, inFront(dx, here) + inFront(-dx, here) + inFront(dy, here) + inFront(-dy, here));
}
if (count > 1) {
// The two nearest palette colours, and how far the colour lies from the first toward the second
// (never past half way). Past a point the pixel takes the second colour on part of a 4x4 pattern.
vec3 lab = oklab(colour);
float d1 = 1e9;
float d2 = 1e9;
int i1 = 0;
int i2 = 0;
for (int i = 0; i < MAX_COLOURS; i++) {
if (i >= count) break;
vec3 d = lab - matched[i];
float dd = dot(d, d);
if (dd < d1) {
d2 = d1;
i2 = i1;
d1 = dd;
i1 = i;
} else if (dd < d2) {
d2 = dd;
i2 = i;
}
}
vec3 span = matched[i2] - matched[i1];
float t = dot(lab - matched[i1], span) / max(dot(span, span), 1e-6);
ivec2 cell = ivec2(gl_FragCoord.xy) & 3;
float threshold = (BAYER[cell.x + 4 * cell.y] + 0.5) / 16.0;
colour = (t - 0.5) * sharpness + 0.5 > threshold ? colours[i2] : colours[i1];
}
gl_FragColor = vec4(mix(colour, ink, line), 1.0);
#include <colorspace_fragment>
}`;
const COPY = /* glsl */ `
uniform sampler2D tPixels;
varying vec2 vUv;
void main() {
gl_FragColor = texture2D(tPixels, vUv);
#include <colorspace_fragment>
}`;
export class PixelPass {
/**
* `rows`: about how many pixels high the main view is drawn; `colours`: the palette's size (48 at most);
* `sharpness`: 1 dithers all the way between two colours, more keeps the dither to where they meet.
*/
constructor({ rows = 240, colours = 32, sharpness = 2, ink = 0x16141f } = {}) {
this.rows = rows;
this.size = colours;
this.views = new Map(); // per view: its render targets and its palette
this.solid = new THREE.MeshBasicMaterial({ color: 0xffffff });
this.hidden = new THREE.MeshBasicMaterial({ colorWrite: false });
const options = { vertexShader: VERTEX, depthTest: false, depthWrite: false };
this.resolve = new THREE.ShaderMaterial({
vertexShader: VERTEX,
depthFunc: THREE.AlwaysDepth, // the pass writes each pixel's depth
uniforms: {
tScene: { value: null },
tMask: { value: null },
tDepth: { value: null },
texel: { value: new THREE.Vector2() },
near: { value: 0.1 },
far: { value: 100 },
edges: { value: false },
},
fragmentShader: RESOLVE,
});
this.quantise = new THREE.ShaderMaterial({
...options,
defines: { MAX_COLOURS, CHROMA: CHROMA.toFixed(3) },
uniforms: {
tPicked: { value: null },
tDepth: { value: null },
texel: { value: new THREE.Vector2() },
near: { value: 0.1 },
far: { value: 100 },
matched: { value: null },
colours: { value: null },
count: { value: 0 },
sharpness: { value: sharpness },
lines: { value: false },
ink: { value: new THREE.Color(ink) },
},
fragmentShader: QUANTISE,
});
this.copy = new THREE.ShaderMaterial({ ...options, uniforms: { tPixels: { value: null } }, fragmentShader: COPY });
this.quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), this.quantise);
this.quad.frustumCulled = false;
this.screen = new THREE.Scene();
this.screen.add(this.quad);
this.screenCamera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
this.clear = new THREE.Color();
}
/** The size of each view's palette. */
get colours() {
return this.size;
}
set colours(n) {
this.size = Math.max(2, Math.min(MAX_COLOURS, Math.round(n)));
for (const view of this.views.values()) {
view.palette.size = this.size;
view.palette.reset();
}
}
get sharpness() {
return this.quantise.uniforms.sharpness.value;
}
set sharpness(v) {
this.quantise.uniforms.sharpness.value = v;
}
/** Pick the colours afresh on the next frame (a new scene or look). */
reset() {
for (const view of this.views.values()) view.palette.reset();
}
/** Screen pixels to one drawn pixel, for a view filling the canvas. */
scale(renderer) {
return Math.max(2, Math.round(renderer.domElement.height / this.rows));
}
#viewFor(key, w, h) {
let view = this.views.get(key);
if (!view) {
const nearest = { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, generateMipmaps: false };
const srgb = { ...nearest, colorSpace: THREE.SRGBColorSpace };
view = {
// The scene with 2x2 samples per pixel, and which of them show an outlined mesh, with their depth.
scene: new THREE.WebGLRenderTarget(2 * w, 2 * h, srgb),
mask: new THREE.WebGLRenderTarget(2 * w, 2 * h, { ...nearest, depthTexture: new THREE.DepthTexture(2 * w, 2 * h) }),
// One sample per pixel, then the pixels in the palette's colours.
picked: new THREE.WebGLRenderTarget(w, h, { ...srgb, depthTexture: new THREE.DepthTexture(w, h) }),
pixels: new THREE.WebGLRenderTarget(w, h, { ...srgb, depthBuffer: false }),
palette: new Palette(this.size),
fitted: performance.now() + 90 * this.views.size, // the views take turns at refitting
reading: false,
last: 0,
};
this.views.set(key, view);
}
if (view.picked.width !== w || view.picked.height !== h) {
view.scene.setSize(2 * w, 2 * h);
view.mask.setSize(2 * w, 2 * h);
view.picked.setSize(w, h);
view.pixels.setSize(w, h);
}
return view;
}
/**
* Draw `scene` from `camera` as pixel art into the canvas rectangle `rect` (CSS pixels from the top left;
* null for the whole canvas), `scale` screen pixels to a pixel. `key` names the view, which keeps its
* own render targets and palette. `draw` draws the scene in place of renderer.render (a view with its
* own Spark state); `edges` tells the meshes apart, so that each pixel shows its nearest one: {occluders}
* says whether OCCLUDER meshes exist, {ink} asks for a line around the OUTLINED ones.
*/
render(renderer, scene, camera, key, rect = null, { scale = this.scale(renderer), draw = null, edges = null } = {}) {
const pr = renderer.getPixelRatio();
const canvas = renderer.domElement;
const x = rect ? Math.round(rect.x * pr) : 0;
const y = rect ? Math.round(rect.y * pr) : 0;
const w = rect ? Math.round(rect.w * pr) : canvas.width;
const h = rect ? Math.round(rect.h * pr) : canvas.height;
const cols = Math.ceil(w / scale);
const rows = Math.ceil(h / scale);
const t = this.#viewFor(key, cols, rows);
// Whole pixels cover the view, so the last column and row may hang over its right and bottom edges:
// the frustum widens by as much, and the picture stays where the other renderers draw it.
camera.setViewOffset(w, h, 0, 0, cols * scale, rows * scale);
renderer.setRenderTarget(t.scene);
if (draw) draw();
else renderer.render(scene, camera);
if (edges) this.#drawMask(renderer, scene, camera, t.mask, edges.occluders);
camera.clearViewOffset();
const r = this.resolve.uniforms;
r.tScene.value = t.scene.texture;
r.tMask.value = t.mask.texture;
r.tDepth.value = t.mask.depthTexture;
r.texel.value.set(0.5 / cols, 0.5 / rows);
r.near.value = camera.near;
r.far.value = camera.far;
r.edges.value = Boolean(edges);
this.quad.material = this.resolve;
renderer.setRenderTarget(t.picked);
renderer.render(this.screen, this.screenCamera);
this.#follow(renderer, t);
const u = this.quantise.uniforms;
u.tPicked.value = t.picked.texture;
u.tDepth.value = t.picked.depthTexture;
u.texel.value.set(1 / cols, 1 / rows);
u.near.value = camera.near;
u.far.value = camera.far;
u.matched.value = t.palette.matched;
u.colours.value = t.palette.colours;
u.count.value = t.palette.count;
u.lines.value = Boolean(edges?.ink);
this.quad.material = this.quantise;
renderer.setRenderTarget(t.pixels);
renderer.render(this.screen, this.screenCamera);
this.copy.uniforms.tPixels.value = t.pixels.texture;
this.quad.material = this.copy;
renderer.setRenderTarget(null);
renderer.setViewport(x / pr, (canvas.height - y - rows * scale) / pr, (cols * scale) / pr, (rows * scale) / pr);
renderer.setScissor(x / pr, (canvas.height - y - h) / pr, w / pr, h / pr);
renderer.setScissorTest(true);
renderer.render(this.screen, this.screenCamera);
renderer.setScissorTest(false);
}
/** Which samples show an OUTLINED mesh, and the depth of those and of what hides them. */
#drawMask(renderer, scene, camera, target, occluders) {
const background = scene.background;
const layers = camera.layers.mask;
const autoClear = renderer.autoClear;
const clearAlpha = renderer.getClearAlpha();
renderer.getClearColor(this.clear);
scene.background = null;
renderer.setClearColor(0x000000, 0);
renderer.setRenderTarget(target);
renderer.clear();
renderer.autoClear = false;
if (occluders) {
camera.layers.set(OCCLUDER);
scene.overrideMaterial = this.hidden;
renderer.render(scene, camera);
}
camera.layers.set(OUTLINED);
scene.overrideMaterial = this.solid;
renderer.render(scene, camera);
scene.overrideMaterial = null;
scene.background = background;
camera.layers.mask = layers;
renderer.autoClear = autoClear;
renderer.setClearColor(this.clear, clearAlpha);
}
/** Keep a view's palette on what it shows: at once for a first frame, a few times a second after. */
#follow(renderer, view) {
const { palette, picked: target } = view;
const now = performance.now();
const { width, height } = target;
if (palette.count === 0) {
const pixels = new Uint8Array(4 * width * height);
renderer.readRenderTargetPixels(target, 0, 0, width, height, pixels);
palette.fit(pixels);
} else {
palette.ease(Math.min(0.1, (now - view.last) / 1000));
if (!view.reading && now - view.fitted >= REFIT_MS) {
// Read without stalling the frame; a palette reset meanwhile makes the answer stale.
view.reading = true;
view.fitted = now;
const generation = palette.generation;
const pixels = new Uint8Array(4 * width * height);
renderer
.readRenderTargetPixelsAsync(target, 0, 0, width, height, pixels)
.then(() => {
if (generation === palette.generation) palette.fit(pixels);
})
.catch(() => {})
.finally(() => {
view.reading = false;
});
}
}
view.last = now;
}
dispose() {
for (const view of this.views.values()) {
view.scene.dispose();
view.mask.depthTexture.dispose();
view.mask.dispose();
view.picked.depthTexture.dispose();
view.picked.dispose();
view.pixels.dispose();
}
this.views.clear();
}
}