~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/stream

jetstream v2 in zig · mirror of https://tangled.org/zat.dev/stream

0
0
329 lines · 18.8 KB Raw History
(() => {
  // The background is a slow river with an eddy or two, drawn as fine fibers lying along the flow.
  // Everything it does comes from the sequence numbers the page already polls:
  // it moves only as far as they say the firehose moved, and the rate against
  // what is typical sets the regime. Slow is nearly laminar, typical turns the
  // eddies, busy roughens the water. It opens no connection of its own.
  const SETTLE_MS = 5000, REST_MS = 4000, RISE_MS = 600, MAX_DELTA = 5000n, TYPICAL_RATE = 450;
  const RIVER_SHARE = 30; // one river packet stands for this many observed events

  function createCurrent() {
    return { sequence: 0n, from: 0, to: 0, at: 0, fromRegime: 1, toRegime: 1, rate: 0, lift: 0 };
  }
  function progress(current, now) {
    return Math.max(0, Math.min(1, (now - current.at) / SETTLE_MS));
  }
  // seconds of flow at the typical rate: one poll's worth of events is played out over the next poll interval
  function position(current, now) {
    return current.from + (current.to - current.from) * progress(current, now);
  }
  // observed rate over the typical rate, eased between polls. 1 is an ordinary hour.
  function regime(current, now) {
    return current.fromRegime + (current.toRegime - current.fromRegime) * progress(current, now);
  }
  function receive(current, sequence, now, typical = TYPICAL_RATE) {
    if (sequence <= 0n || sequence === current.sequence) return false;
    const fresh = current.sequence === 0n || sequence < current.sequence;
    const gap = sequence - current.sequence, seconds = (now - current.at) / 1000;
    const delta = fresh ? 0 : Number(gap > MAX_DELTA ? MAX_DELTA : gap);
    current.lift = fresh ? 0 : energy(current, now);
    current.fromRegime = fresh ? 1 : regime(current, now);
    current.from = fresh ? 0 : position(current, now);
    // a first sample, or one after a long gap, says nothing reliable about the rate
    current.rate = fresh || seconds < 1 || seconds > 30 ? 0 : Number(gap) / seconds;
    current.toRegime = current.rate > 0 && typical > 0 ? Math.max(.2, Math.min(2.5, current.rate / typical)) : current.fromRegime;
    current.to = current.from + delta / TYPICAL_RATE;
    current.at = now;
    current.sequence = sequence;
    return true;
  }
  // 1 while the last observed advance is still being played out, easing to 0 once it has been.
  // from rest it comes up over RISE_MS instead of jumping.
  function energy(current, now) {
    if (current.to === current.from) return 0;
    const level = Math.max(0, Math.min(1, 1 - (now - current.at - SETTLE_MS) / REST_MS));
    return current.lift + (level - current.lift) * Math.max(0, Math.min(1, (now - current.at) / RISE_MS));
  }
  function moving(current, now) {
    return current.to !== current.from && now < current.at + SETTLE_MS + REST_MS;
  }
  // how many river packets the events observed up to `now` amount to, in all
  function packets(current, now) {
    return Math.floor(position(current, now) * TYPICAL_RATE / RIVER_SHARE);
  }
  function seedFor(index) {
    let seed = Math.imul(index ^ 2166136261, 16777619);
    seed = Math.imul(seed ^ seed >>> 15, 0x735a2d97);
    return (seed ^ seed >>> 13) >>> 0;
  }
  // device pixels per css pixel for a surface of this css size, within a fixed pixel budget
  function surfaceScale(width, height, ratio, budget = 8000000) {
    return Math.max(.6, Math.min(ratio, 2, Math.sqrt(budget / Math.max(1, width * height))));
  }
  // when frames keep arriving late the surface is drawn smaller, so a weak GPU gets a softer picture
  // instead of a slow page. `gap` is the time since the previous painted frame; 33 ms is on pace.
  function pace(state, gap) {
    state.late = gap > 55 ? state.late + 1 : Math.max(0, state.late - 1);
    if (state.late <= 24 || state.quality <= .5) return false;
    state.quality *= .8; state.late = 0;
    return true;
  }
  // the current as a record another page can pick up: times become ages, since each page has its own clock
  function keep(current, now) {
    return { ...current, sequence: String(current.sequence), at: now - current.at };
  }
  // carry on from a record kept `elapsed` ms ago, as if this page had been drawing all along
  function resume(current, kept, now, elapsed) {
    Object.assign(current, kept, { sequence: BigInt(kept.sequence), at: now - kept.at - elapsed });
  }
  if (typeof module !== 'undefined') module.exports = { createCurrent, position, regime, receive, energy, moving, packets, seedFor, surfaceScale, pace, keep, resume };
  if (typeof document === 'undefined') return;

  if (document.body.dataset.page === 'strata' && !document.getElementById('atmosphere')) {
    const layer = document.createElement('div'); layer.id = 'atmosphere'; layer.setAttribute('aria-hidden', 'true');
    const surface = document.createElement('canvas'); surface.id = 'depth'; surface.dataset.current = '';
    layer.append(surface); document.body.prepend(layer);
  }
  const canvas = document.querySelector('canvas[data-current]');
  if (!canvas) return;

  const COMMON = `#version 300 es
precision highp float;
float h21(vec2 p){ p = fract(p * vec2(123.34, 456.21)); p += dot(p, p + 45.32); return fract(p.x * p.y); }
float vn(vec2 p){ vec2 i = floor(p), f = fract(p); f = f * f * (3. - 2. * f);
  return mix(mix(h21(i), h21(i + vec2(1, 0)), f.x), mix(h21(i + vec2(0, 1)), h21(i + vec2(1, 1)), f.x), f.y); }
`;
  // the seeds of the fibers: small soft dots, never thresholded, at four texels per css pixel. red is the
  // near layer and green the far one; blue and alpha carry which near dots are pigmented and their hue.
  // the pattern repeats every 512 css pixels so the texture tiles.
  const SEEDS = COMMON + `out vec4 o;
void layer(vec2 x, float cells, float keep, float sigma, float salt, inout vec3 acc){
  float size = 512. / cells; vec2 base = floor(x / size);
  for (int j = -1; j <= 1; j++) for (int i = -1; i <= 1; i++) {
    vec2 c = base + vec2(i, j), id = mod(c, cells) + salt;
    if (h21(id + 7.7) > keep) continue;
    vec2 centre = (c + vec2(h21(id), h21(id + 3.3))) * size, d = x - centre;
    float g = (.45 + .55 * h21(id + 11.1)) * exp(-dot(d, d) / (2. * sigma * sigma));
    float pig = step(.86, h21(id + 19.9));
    acc += g * vec3(1., pig, pig * h21(id + 23.3));
  }
}
void main(){
  vec2 x = gl_FragCoord.xy * .25; vec3 near = vec3(0.), far = vec3(0.);
  layer(x, 64., .13, .42, 0., near); layer(x, 80., .16, .42, 100., far);
  o = vec4(near.x, far.x, near.y, near.z);
}`;
  const FLOWFN = `uniform vec2 R;  // surface size in device pixels
uniform float D; // device pixels per css pixel
uniform float T; // seconds of observed flow
uniform float Q; // observed rate over the typical rate
uniform vec4 V;  // the viewport inside this surface, in css pixels: origin, then size
float psi(vec2 p){
  float t = T * .03, s = 0., a = 1.; vec2 q = p * .0032;
  for (int i = 0; i < 3; i++) { s += a * vn(q + vec2(t * (1. + float(i)), -t * .7)); q = q * 2.03 + 17.3; a *= .397; }
  return s;
}
vec2 curl(vec2 p){ float a = psi(p); return vec2(psi(p + vec2(0., 2.)) - a, a - psi(p + vec2(2., 0.))) / 2.; }
vec2 vort(vec2 p, vec2 c, float g, float core){ vec2 r = p - c; return g * vec2(-r.y, r.x) / (dot(r, r) + core * core); }
// a river that bends slowly, with one great eddy off to one side and a small one far from it, placed
// by the viewport so every screen gets the same composition. below about a third of the typical rate
// the eddies barely turn and the fibers lie along the bends; around typical they turn fully; above it
// small turbulence roughens the water. T runs at the observed rate, so it all moves as the firehose does.
vec2 flow(vec2 p){
  vec2 m = V.zw, u = p - V.xy; float L = max(m.x, m.y * 1.4), w = T * .02, q = min(Q, 1.6);
  float turn = smoothstep(.3, .9, Q) * (.7 + .3 * q), k = 3.14159265 / (m.x * .62);
  vec2 v = vec2(1., -.34 * cos(k * u.x + 1.1 + w * .5) - .12 * cos(k * 2.3 * u.x - u.y * k * .8));
  v += vort(u, m * vec2(.74, .30) + 14. * vec2(sin(w), cos(w * .8)), .30 * L * turn, .11 * L);
  v += vort(u, m * vec2(.17, .80), -.10 * L * turn, .05 * L);
  return v + curl(p) * (2. + 9. * q * q);
}
`;
  // pass 0, a quarter of the resolution: the flow is smooth, so it is worked out once per sixteen pixels
  const FIELD = COMMON + FLOWFN + `out vec4 o;
void main(){
  vec2 p = vec2(gl_FragCoord.x, R.y - gl_FragCoord.y) / D, v = flow(p); float s = length(v);
  o = vec4(v / max(s, 1e-6) * .5 + .5, clamp(s / 3., 0., 1.), 1.);
}`;
  // pass 1: each seed is drawn out into a short streak along the flow, in 15 steps of about half a css pixel
  const STREAK = `#version 300 es
precision highp float;
uniform vec2 R; uniform float D, T; uniform sampler2D S, F; out vec4 o;
void main(){
  vec2 p = vec2(gl_FragCoord.x, R.y - gl_FragCoord.y) / D, d = normalize(texture(F, gl_FragCoord.xy / R).xy * 2. - 1.);
  // the seeds drift along the flow in two phases that cross-fade, so the offset never exceeds 20 css pixels
  float t = T * .125, a = fract(t), b = fract(t + .5), wa = 1. - abs(2. * a - 1.);
  vec2 pa = p - d * (a - .5) * 40. + floor(t) * 197.3, pb = p - d * (b - .5) * 40. + floor(t + .5) * 311.7 + 83.;
  vec4 acc = vec4(0.);
  for (int i = -7; i <= 7; i++) {
    vec2 s = d * float(i) * .55;
    acc += wa * texture(S, (pa + s) / 512.) + (1. - wa) * texture(S, (pb + s) / 512.);
  }
  o = clamp(acc / 15. * 6., 0., 1.);
}`;
  // pass 2: the streaks are drawn out again, in steps as long as a streak, into long fibers that taper to
  // nothing at both ends. nothing is thresholded and nothing is dithered: a fiber is a soft ridge of light.
  const FIBER = `#version 300 es
precision highp float;
uniform vec2 R; uniform float D, E; uniform sampler2D F, I; out vec4 o;
// decorative contrast is reduced through the text column instead of putting a panel behind the text
float column(float x, float w){
  float hw = min(w * .5, 330.), d = abs(x - w * .5), t = clamp((d - hw * .75) / (hw * .6), 0., 1.);
  return mix(.5, 1., t * t * (3. - 2. * t));
}
void main(){
  vec2 uv = gl_FragCoord.xy / R; vec4 f = texture(F, uv);
  vec2 px = vec2(1., -1.) * D / R * 4.; float speed = f.z * 3.;
  vec4 a = texture(I, uv); vec3 near = a.rba; float far = a.g, wn = 1.;
  for (float side = -1.; side <= 1.; side += 2.) {
    vec2 q = uv, d = normalize(f.xy * 2. - 1.);
    for (int i = 1; i <= 7; i++) {
      q += side * d * px; d = normalize(texture(F, q).xy * 2. - 1.);
      float w = .5 + .5 * cos(3.14159265 * float(i) / 8.);
      a = texture(I, q); near += w * a.rba; far += w * a.g; wn += w;
    }
  }
  near /= wn; far /= wn;
  float inkNear = 1. - exp(-near.x * 16.), inkFar = 1. - exp(-far * 12.);
  float share = clamp(near.y / max(near.x, 1e-4), 0., 1.), hue = near.z / max(near.y, 1e-4);
  vec3 pigment = hue < .35 ? vec3(72., 117., 101.) : hue < .70 ? vec3(76., 112., 142.) : hue < .90 ? vec3(111., 96., 135.) : hue < .97 ? vec3(141., 120., 79.) : vec3(139., 74., 82.);
  // matte: the page colour, fibers a shade above it, about one in seven in a muted pigment, no glow
  vec3 base = vec3(4., 7., 8.) / 255., light = vec3(18., 27., 32.) / 255., tone = mix(light, pigment / 255. * .42, share);
  float k = .5 * (.3 + .7 * E) * column(gl_FragCoord.x / D, R.x / D) * (.55 + .45 * smoothstep(.3, 1.8, speed));
  vec3 col = mix(base, light * .62, min(1., inkFar * k));
  col = mix(col, tone, min(1., inkNear * k));
  o = vec4(col, 1.);
}`;
  const TRIANGLE = '#version 300 es\nvoid main(){ vec2 v = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2)); gl_Position = vec4(v * 2. - 1., 0., 1.); }';

  const programs = {}, textures = {}, targets = {};
  let gl = null, drawing = false;
  function surface(name, width, height, repeat) {
    if (textures[name]) { gl.deleteTexture(textures[name]); gl.deleteFramebuffer(targets[name]); }
    textures[name] = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, textures[name]);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
    for (const side of [gl.TEXTURE_WRAP_S, gl.TEXTURE_WRAP_T]) gl.texParameteri(gl.TEXTURE_2D, side, repeat ? gl.REPEAT : gl.CLAMP_TO_EDGE);
    targets[name] = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, targets[name]);
    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textures[name], 0);
  }
  // on a first visit, compile off the main thread where the browser allows it, and only after the page
  // has painted, so the shaders never delay the content. until they are ready the canvas shows the page
  // colour, which is also their ground. without WebGL2 it stays that way and the river still runs.
  // arriving from another page of the site, `now` is set: the picture is drawn before the first paint,
  // so it is already there when the old page goes away.
  function prepare(now) {
    gl = canvas.getContext('webgl2', { antialias: false, alpha: false, powerPreference: 'low-power' });
    if (!gl) return;
    const parallel = now ? null : gl.getExtension('KHR_parallel_shader_compile');
    for (const [name, fragment] of [['seeds', SEEDS], ['field', FIELD], ['streak', STREAK], ['fiber', FIBER]]) {
      const program = gl.createProgram();
      for (const [type, source] of [[gl.VERTEX_SHADER, TRIANGLE], [gl.FRAGMENT_SHADER, fragment]]) {
        const shader = gl.createShader(type); gl.shaderSource(shader, source); gl.compileShader(shader); gl.attachShader(program, shader);
      }
      gl.linkProgram(program);
      programs[name] = { program, u: {} };
    }
    const all = Object.values(programs);
    const finish = () => {
      if (parallel && !all.every(each => gl.getProgramParameter(each.program, parallel.COMPLETION_STATUS_KHR))) return requestAnimationFrame(finish);
      if (!all.every(each => gl.getProgramParameter(each.program, gl.LINK_STATUS))) return;
      for (const each of all) for (let i = 0; i < gl.getProgramParameter(each.program, gl.ACTIVE_UNIFORMS); i++) {
        const name = gl.getActiveUniform(each.program, i).name; each.u[name] = gl.getUniformLocation(each.program, name);
      }
      gl.bindVertexArray(gl.createVertexArray());
      surface('seeds', 2048, 2048, true);
      gl.viewport(0, 0, 2048, 2048); gl.useProgram(programs.seeds.program); gl.drawArrays(gl.TRIANGLES, 0, 3);
      drawing = true; resize(); wake();
    };
    finish();
  }

  const current = createCurrent();
  const reduced = matchMedia('(prefers-reduced-motion: reduce)');
  let scale = 1, frame = 0, last = 0, sent = 0, painted = 0;
  const load = { quality: 1, late: 0 };

  function bind(unit, name) { gl.activeTexture(gl.TEXTURE0 + unit); gl.bindTexture(gl.TEXTURE_2D, textures[name]); }
  function paint(now) {
    if (!drawing) return;
    const still = reduced.matches, box = canvas.getBoundingClientRect();
    const width = canvas.width, height = canvas.height, fw = Math.ceil(width / 4), fh = Math.ceil(height / 4);
    const clock = still ? current.to : position(current, now);
    let pass = programs.field;
    gl.bindFramebuffer(gl.FRAMEBUFFER, targets.field); gl.viewport(0, 0, fw, fh); gl.useProgram(pass.program);
    gl.uniform2f(pass.u.R, fw, fh); gl.uniform1f(pass.u.D, scale * fw / width); gl.uniform1f(pass.u.T, clock);
    gl.uniform1f(pass.u.Q, still ? current.toRegime : regime(current, now));
    gl.uniform4f(pass.u.V, -box.left, -box.top, innerWidth, innerHeight);
    gl.drawArrays(gl.TRIANGLES, 0, 3);
    pass = programs.streak;
    gl.bindFramebuffer(gl.FRAMEBUFFER, targets.streak); gl.viewport(0, 0, width, height); gl.useProgram(pass.program);
    bind(0, 'seeds'); bind(1, 'field');
    gl.uniform2f(pass.u.R, width, height); gl.uniform1f(pass.u.D, scale); gl.uniform1f(pass.u.T, clock);
    gl.uniform1i(pass.u.S, 0); gl.uniform1i(pass.u.F, 1);
    gl.drawArrays(gl.TRIANGLES, 0, 3);
    pass = programs.fiber;
    gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.viewport(0, 0, width, height); gl.useProgram(pass.program);
    bind(0, 'field'); bind(1, 'streak');
    gl.uniform2f(pass.u.R, width, height); gl.uniform1f(pass.u.D, scale);
    gl.uniform1f(pass.u.E, still ? Math.min(1, current.to) : energy(current, now));
    gl.uniform1i(pass.u.F, 0); gl.uniform1i(pass.u.I, 1);
    gl.drawArrays(gl.TRIANGLES, 0, 3);
  }
  // the river's packets are the same observed events, one for every RIVER_SHARE of them
  function feedRiver(now) {
    const due = packets(current, now);
    if (due < sent || due - sent > 64) sent = due - Math.min(due, 8);
    for (; sent < due; sent++) dispatchEvent(new CustomEvent('stream-arrival', { detail: seedFor(sent) }));
  }
  function animate(now) {
    frame = 0;
    if (document.hidden) return;
    if (now - last >= 33) {
      if (painted && pace(load, now - painted)) resize();
      paint(now); painted = now;
      if (!reduced.matches) feedRiver(now);
      last = now;
    }
    if (!reduced.matches && moving(current, now)) frame = requestAnimationFrame(animate);
  }
  function wake() {
    if (!frame && !document.hidden) { painted = 0; frame = requestAnimationFrame(animate); }
  }
  function resize() {
    const width = canvas.clientWidth, height = canvas.clientHeight;
    scale = Math.max(.6, surfaceScale(width, height, devicePixelRatio || 1) * load.quality);
    canvas.dataset.scale = String(scale);
    canvas.width = Math.round(width * scale); canvas.height = Math.round(height * scale);
    if (drawing) { surface('field', Math.ceil(canvas.width / 4), Math.ceil(canvas.height / 4), false); surface('streak', canvas.width, canvas.height, false); }
    paint(performance.now());
  }
  addEventListener('stream-sequence', event => {
    const typical = typeof window.__typicalRate === 'function' ? window.__typicalRate() : TYPICAL_RATE;
    if (receive(current, BigInt(event.detail), performance.now(), typical)) wake();
  });
  new ResizeObserver(resize).observe(canvas);
  document.addEventListener('visibilitychange', () => { if (!document.hidden) wake(); });
  reduced.addEventListener('change', wake);
  // a page of the site left moments ago hands its current over, so the picture carries on where it was
  let carried = false;
  try {
    const kept = JSON.parse(sessionStorage.getItem('current') || 'null'), elapsed = kept ? Date.now() - kept.t : 0;
    if (kept && elapsed >= 0 && elapsed < 30000) { resume(current, kept.current, performance.now(), elapsed); carried = true; }
  } catch {}
  addEventListener('pagehide', () => {
    try { sessionStorage.setItem('current', JSON.stringify({ t: Date.now(), current: keep(current, performance.now()) })); } catch {}
  });
  if (carried) prepare(true); else requestAnimationFrame(() => setTimeout(prepare, 0));
  if (document.body.dataset.page === 'strata') {
    async function observe() {
      if (document.hidden) return;
      try {
        const response = await fetch('/status', { headers: { Accept: 'text/plain' }, cache: 'no-store' });
        if (!response.ok) return;
        const match = (await response.text()).match(/upstream seq\s+([\d,]+)/);
        if (match) dispatchEvent(new CustomEvent('stream-sequence', { detail: match[1].replace(/,/g, '') }));
      } catch {}
    }
    observe(); setInterval(observe, 5000);
  }
})();