Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

8.3 KB
Raw Blame
// The landing page's background: a low-poly sheet of glass over a flowing light, drawn by one fragment shader on a
// fixed canvas behind the page. Each triangle is a facet with its own tilt: it shows the light behind it shifted
// (refraction), shades across its own thickness, catches a moving glint, and its edges catch the light. The light is
// the page's own: a warm key top left, a cool rim top right, a warm bounce below, with a flow running through them;
// it scrolls away slower than the page. Without WebGL2 the page keeps its CSS light (html:not(.glass-on)); reduced
// motion draws one still frame. 30 fps at most, below the screen's resolution, and nothing while the tab is hidden.

const VERT = `#version 300 es
in vec2 p;
void main() { gl_Position = vec4(p, 0., 1.); }`;

const FRAG = `#version 300 es
precision highp float;
uniform vec2 uRes;     // canvas pixels
uniform float uScale;  // canvas pixels per CSS pixel
uniform float uTime;   // seconds
uniform float uScroll; // page scrolled, in viewport heights
uniform vec2 uMouse;   // pointer, CSS pixels in the viewport (far away when there is none)
out vec4 o;

const float CELL = 96.;  // a triangle's size, CSS pixels
const vec3 INK = vec3(.024, .027, .035);
const vec3 EMBER = vec3(1., .416, .075);
const vec3 TUNGSTEN = vec3(1., .706, .329);
const vec3 FILAMENT = vec3(1., .922, .769);
const vec3 COOL = vec3(.478, .635, .969);

vec2 h22(vec2 p) { p = vec2(dot(p, vec2(127.1, 311.7)), dot(p, vec2(269.5, 183.3))); return fract(sin(p) * 43758.5453); }
float h21(vec2 p) { return fract(sin(dot(p, vec2(12.9898, 78.233))) * 43758.5453); }
float noise(vec2 p) {
  vec2 i = floor(p), f = fract(p), u = f * f * (3. - 2. * f);
  return mix(mix(h21(i), h21(i + vec2(1, 0)), u.x), mix(h21(i + vec2(0, 1)), h21(i + vec2(1, 1)), u.x), u.y);
}
float fbm(vec2 p) {
  float a = .5, s = 0.;
  for (int i = 0; i < 4; i++) { s += a * noise(p); p = p * 2.02 + vec2(1.7, 9.2); a *= .5; }
  return s;
}

// A lattice point, moved a little: the sheet's vertices.
vec2 vtx(vec2 c) { return c + (h22(c) - .5) * .44; }

// The light behind the glass at q (viewport heights, y down), with its flow.
vec3 light(vec2 q, float t, float aspect) {
  vec2 w = vec2(fbm(q * 1.3 + vec2(0., t * .06)), fbm(q * 1.3 + vec2(5.2, -t * .05)));
  float flow = fbm(q * 1.7 + w * 2. + vec2(t * .04, -t * .03));
  float streak = smoothstep(.38, .86, flow);
  vec2 k1 = vec2((.2 + .05 * sin(t * .13)) * aspect, .1 + .05 * cos(t * .11));
  vec2 k2 = vec2((.92 + .04 * cos(t * .09)) * aspect, .24 + .06 * sin(t * .1));
  vec2 k3 = vec2((.5 + .28 * sin(t * .06)) * aspect, 1.02 + .04 * sin(t * .15));
  float g1 = exp(-dot(q - k1, q - k1) * 3.);
  float g2 = exp(-dot(q - k2, q - k2) * 4.5);
  float g3 = exp(-dot(q - k3, q - k3) * 2.6);
  vec3 warm = mix(EMBER, TUNGSTEN, clamp(flow * 1.4 - .25, 0., 1.));
  return warm * g1 * (.09 + .17 * streak) + COOL * g2 * (.045 + .09 * streak) + TUNGSTEN * g3 * (.025 + .055 * streak)
       + warm * streak * .01;
}

void main() {
  vec2 vp = uRes / uScale;
  vec2 px = vec2(gl_FragCoord.x, uRes.y - gl_FragCoord.y) / uScale;
  float aspect = vp.x / vp.y, t = uTime;

  // Which facet: the triangle of the jittered lattice around this point that holds it best.
  vec2 p = (px + vec2(0., uScroll * vp.y * .35)) / CELL;
  vec2 base = floor(p);
  float best = -1e9;
  vec3 bw = vec3(0.);
  vec2 A = vec2(0.), B = vec2(0.), C = vec2(0.), id = vec2(0.);
  for (int j = -1; j <= 1; j++) for (int i = -1; i <= 1; i++) {
    vec2 c = base + vec2(i, j);
    vec2 v00 = vtx(c), v10 = vtx(c + vec2(1, 0)), v01 = vtx(c + vec2(0, 1)), v11 = vtx(c + vec2(1, 1));
    bool diag = h21(c + 7.3) > .5;
    for (int k = 0; k < 2; k++) {
      vec2 a, b, e;
      if (diag) { if (k == 0) { a = v00; b = v10; e = v11; } else { a = v00; b = v11; e = v01; } }
      else { if (k == 0) { a = v00; b = v10; e = v01; } else { a = v10; b = v11; e = v01; } }
      vec2 v0 = b - a, v1 = e - a, v2 = p - a;
      float d00 = dot(v0, v0), d01 = dot(v0, v1), d11 = dot(v1, v1), d20 = dot(v2, v0), d21 = dot(v2, v1);
      float den = d00 * d11 - d01 * d01;
      float wb = (d11 * d20 - d01 * d21) / den, we = (d00 * d21 - d01 * d20) / den;
      vec3 w = vec3(1. - wb - we, wb, we);
      float m = min(w.x, min(w.y, w.z));
      if (m > best) { best = m; bw = w; A = a; B = b; C = e; id = c * 2. + vec2(float(k), 0.); }
    }
  }

  // Distance to the facet's nearest edge, in CSS pixels: a hairline.
  float area2 = abs((B.x - A.x) * (C.y - A.y) - (C.x - A.x) * (B.y - A.y));
  vec3 h = area2 / vec3(length(C - B), length(C - A), length(B - A));
  float dEdge = min(min(bw.x * h.x, bw.y * h.y), bw.z * h.z) * CELL;
  float edge = 1. - smoothstep(0., .9 + .8 / uScale, dEdge);

  // The facet: its tilt shifts the light it shows; its thickness shades across it.
  vec3 n = normalize(vec3((h22(id + 3.7) - .5) * .9, 1.));
  vec2 q = px / vp.y + vec2(0., uScroll * .6);
  vec3 L = light(q + n.xy * .05, t, aspect);
  vec2 qm = uMouse / vp.y;
  vec2 dm = px / vp.y + n.xy * .05 - qm;
  L += FILAMENT * exp(-dot(dm, dm) * 34.) * .05 + TUNGSTEN * exp(-dot(dm, dm) * 9.) * .025;
  float tint = .8 + .4 * h21(id + 1.3);
  float thick = dot(bw, vec3(h21(id + 2.1), h21(id + 4.7), h21(id + 6.2)));

  vec3 col = INK + L * tint * (.55 + .6 * thick);
  // A moving light catches whole facets.
  vec3 ld = normalize(vec3(.55 * sin(t * .23), .55 * cos(t * .19), 1.));
  float glint = pow(max(dot(n, normalize(ld + vec3(0., 0., 1.))), 0.), 180.);
  col += glint * (L * 1.6 + TUNGSTEN * .008);
  // The edges catch the light.
  col += edge * (L * 2.4 + vec3(.007, .008, .01));
  // Grain, so the gradients do not band.
  col += (h21(gl_FragCoord.xy + fract(t * 7.) * 91.) - .5) * .012;
  o = vec4(col, 1.);
}`;

export function glass(canvas) {
  const gl = canvas.getContext("webgl2", { alpha: false, antialias: false, depth: false, stencil: false, powerPreference: "low-power" });
  if (!gl) return false;
  const shader = (type, src) => {
    const s = gl.createShader(type);
    gl.shaderSource(s, src);
    gl.compileShader(s);
    if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s) ?? "shader");
    return s;
  };
  const prog = gl.createProgram();
  gl.attachShader(prog, shader(gl.VERTEX_SHADER, VERT));
  gl.attachShader(prog, shader(gl.FRAGMENT_SHADER, FRAG));
  gl.bindAttribLocation(prog, 0, "p");
  gl.linkProgram(prog);
  if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(prog) ?? "link");
  gl.useProgram(prog);
  gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);
  gl.enableVertexAttribArray(0);
  gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
  const u = Object.fromEntries(["uRes", "uScale", "uTime", "uScroll", "uMouse"].map((k) => [k, gl.getUniformLocation(prog, k)]));

  let scale = 1;
  const resize = () => {
    scale = Math.min(Math.max(devicePixelRatio * 0.6, 0.6), 1.25);
    canvas.width = Math.round(innerWidth * scale);
    canvas.height = Math.round(innerHeight * scale);
    gl.viewport(0, 0, canvas.width, canvas.height);
  };
  const still = matchMedia("(prefers-reduced-motion: reduce)").matches;
  const far = -1e4;
  const mouse = { x: far, y: far, tx: far, ty: far };
  if (!still) {
    addEventListener("pointermove", (e) => {
      if (e.pointerType !== "mouse") return;
      mouse.tx = e.clientX;
      mouse.ty = e.clientY;
      if (mouse.x === far) { mouse.x = mouse.tx; mouse.y = mouse.ty; }
    }, { passive: true });
  }
  const t0 = performance.now();
  const draw = (now) => {
    mouse.x += (mouse.tx - mouse.x) * 0.08;
    mouse.y += (mouse.ty - mouse.y) * 0.08;
    gl.uniform2f(u.uRes, canvas.width, canvas.height);
    gl.uniform1f(u.uScale, scale);
    gl.uniform1f(u.uTime, 14 + (still ? 0 : (now - t0) / 1000));
    gl.uniform1f(u.uScroll, scrollY / innerHeight);
    gl.uniform2f(u.uMouse, mouse.x, mouse.y);
    gl.drawArrays(gl.TRIANGLES, 0, 3);
  };

  resize();
  draw(performance.now());
  addEventListener("resize", () => { resize(); draw(performance.now()); });
  if (still) {
    addEventListener("scroll", () => requestAnimationFrame(draw), { passive: true });
  } else {
    let last = 0;
    const loop = (now) => {
      if (!document.hidden && now - last >= 33) { last = now; draw(now); }
      requestAnimationFrame(loop);
    };
    requestAnimationFrame(loop);
  }
  document.documentElement.classList.add("glass-on");
  return true;
}