From 30e09bb9c551dc37a7439e4b82b9dc1cd79f003b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 16:59:33 +0000 Subject: [PATCH 01/13] Essay engine stage 1: beat model, reading-time holds, fixed-step clock, seeded RNG (engine/src/essay/beats.js) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Ad4FSZyShDwuPQbAcgGJY3 --- engine/src/essay/beats.js | 209 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 209 insertions(+) create mode 100644 engine/src/essay/beats.js diff --git a/engine/src/essay/beats.js b/engine/src/essay/beats.js new file mode 100644 index 0000000..f643872 --- /dev/null +++ b/engine/src/essay/beats.js @@ -0,0 +1,209 @@ +/* BEATS: the time model of an essay. A scene is a list of beats; each beat has + delay seconds of quiet before it starts arriving + dur seconds it takes to arrive (its progress runs 0 -> 1, eased) + hold seconds it stays before the next beat (default: reading time from its words) + Scenes are joined by transitions that take their own time (the outgoing scene stays at its last beat, the incoming + one at its first beat's progress 0). Everything is a pure function of the playhead t (seconds from the start): + seek, stills and an MP4 export replay exactly. No Math.random: use DHS.beats.rng(seed). + + const TL = DHS.beats.compile(essay, { transDur: (type) => 1.2 }); + const s = TL.at(t); // { t, scene, beat, beatT, raw[], p[], trans, k(beat, t0, t1, ease) } + const C = DHS.beats.clock(); C.advance(realDt); C.t // fixed 1/60 s steps; C.set(t) to seek + + Reading time (Q-Day's rule): hold = 2.6 s + 0.31 s a word, kept between 5.2 and 16 s, for a beat with words. + The words themselves are never changed; only the timing comes from them. + + Standalone: needs only the DHS namespace. */ +(function (G) { + 'use strict'; + const DHS = (G.DHS = G.DHS || {}); + + const clamp = (x, a, b) => (x < a ? a : x > b ? b : x); + const clamp01 = (x) => clamp(x, 0, 1); + + // Ease curves, all f(0) = 0 and f(1) = 1 + const EASE = { + linear: (x) => x, + in: (x) => x * x * x, + out: (x) => 1 - (1 - x) ** 3, + inOut: (x) => (x < 0.5 ? 4 * x * x * x : 1 - (-2 * x + 2) ** 3 / 2), + sine: (x) => 0.5 - 0.5 * Math.cos(Math.PI * x), + slow: (x) => 1 - (1 - x) ** 5, // long, gentle settle: the default for a solemn essay + }; + const ease = (e) => (typeof e === 'function' ? e : EASE[e] || EASE.slow); + + // ---- reading time + const READING = { base: 2.6, perWord: 0.31, min: 5.2, max: 16 }; + const countWords = (s) => (String(s || '').match(/\S+/g) || []).length; + const beatWords = (b) => (b.text || []).reduce((n, x) => n + countWords(typeof x === 'string' ? x : x.text), 0); + const readingHold = (n, r = READING) => (n > 0 ? clamp(r.base + r.perWord * n, r.min, r.max) : 0); + + // ---- seeded random (mulberry32) and a string hash (FNV-1a) to make seeds from names + const hash = (...parts) => { + let h = 2166136261; + const s = parts.join('\u0001'); + for (let i = 0; i < s.length; i++) { + h ^= s.charCodeAt(i); + h = Math.imul(h, 16777619); + } + return h >>> 0; + }; + const rng = (seed) => { + let a = (typeof seed === 'number' ? seed : hash(seed)) >>> 0; + const r = () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; + r.range = (lo, hi) => lo + (hi - lo) * r(); + r.int = (lo, hi) => Math.floor(lo + (hi - lo + 1) * r()); + r.pick = (arr) => arr[Math.floor(r() * arr.length)]; + return r; + }; + + // ---- the timeline + // essay: { scenes: [{ id, chapter, transition: 'crossfade' | { type, dur }, beats: [{ dur, delay, hold, text }] }] } + // opts.transDur(type): a transition's default length (the essay player passes the transition library's) + function compile(essay, opts = {}) { + const transDur = opts.transDur || (() => 1); + const reading = Object.assign({}, READING, opts.reading || {}); + const scenes = []; + let t = 0; + essay.scenes.forEach((sc, i) => { + const tr = typeof sc.transition === 'string' ? { type: sc.transition } : Object.assign({}, sc.transition || {}); + tr.type = tr.type || (i ? 'crossfade' : 'dip'); + tr.dur = tr.type === 'cut' ? 0 : tr.dur != null ? tr.dur : transDur(tr.type); + const S = { index: i, id: sc.id || 's' + (i + 1), chapter: sc.chapter || '', start: t, trans: tr, beats: [] }; + t += tr.dur; + S.body = t; + (sc.beats && sc.beats.length ? sc.beats : [{}]).forEach((b, j) => { + const words = beatWords(b); + const B = { + index: j, + delay: b.delay != null ? b.delay : 0, + dur: b.dur != null ? b.dur : 1.6, + hold: b.hold != null ? b.hold : Math.max(readingHold(words, reading), j === 0 && !words ? 1.5 : 0), + ease: ease(b.ease), + words, + start: t, + }; + B.arrive = B.start + B.delay; + B.shown = B.arrive + B.dur; + B.end = B.shown + B.hold; + t = B.end; + S.beats.push(B); + }); + S.end = t; + scenes.push(S); + }); + const total = t; + + // the chapters, in order, with their time spans (for the progress bar) + const chapters = []; + scenes.forEach((S) => { + const last = chapters[chapters.length - 1]; + if (last && last.name === S.chapter) last.end = S.end; + else chapters.push({ name: S.chapter, start: S.start, end: S.end, scene: S.index }); + }); + + const sceneAt = (t) => { + let lo = 0, + hi = scenes.length - 1; + while (lo < hi) { + const m = (lo + hi + 1) >> 1; + if (scenes[m].start <= t) lo = m; + else hi = m - 1; + } + return lo; + }; + + // reduced motion: arrivals take at most `quick` seconds (same timeline length, so links and seeks still match) + function at(t, o = {}) { + t = clamp(t, 0, total); + const i = sceneAt(t), + S = scenes[i]; + const quick = o.reduced ? 0.35 : Infinity; + let beat = -1; + const raw = S.beats.map((B, j) => { + if (t >= B.arrive) beat = j; + return clamp01((t - B.arrive) / Math.max(1e-6, Math.min(B.dur, quick))); + }); + if (t < S.body) beat = -1; + else if (beat < 0) beat = 0; + const p = raw.map((r, j) => S.beats[j].ease(r)); + const trans = + t < S.body && S.trans.dur > 0 + ? { type: S.trans.type, from: i - 1, to: i, p: clamp01((t - S.start) / S.trans.dur), dur: S.trans.dur } + : null; + const B = beat >= 0 ? S.beats[beat] : null; + return { + t, + total, + scene: i, + id: S.id, + chapter: S.chapter, + beat, + beatT: B ? t - B.start : 0, + sceneT: t - S.body, + raw, + p, + trans, + // progress of a move inside a beat: k(beat, 0.2, 0.8, 'out') runs 0 -> 1 while the beat goes 20% -> 80% + k: (j, t0 = 0, t1 = 1, e = 'inOut') => ease(e)(clamp01(((raw[j] || 0) - t0) / Math.max(1e-6, t1 - t0))), + }; + } + + // time of a beat's moments: 'start', 'arrive', 'shown' (fully in, hold begins), 'end' + const timeOf = (i, j = 0, where = 'shown') => { + const S = scenes[clamp(i, 0, scenes.length - 1)]; + if (j < 0) return S.start; + return S.beats[clamp(j, 0, S.beats.length - 1)][where]; + }; + // flat list of beats in order: [{ scene, beat }], for next/back + const flat = []; + scenes.forEach((S) => S.beats.forEach((B) => flat.push({ scene: S.index, beat: B.index, B }))); + const flatIndex = (t) => { + let k = 0; + for (let n = 0; n < flat.length; n++) if (flat[n].B.start <= t + 1e-9) k = n; + return k; + }; + const sceneIndex = (idOrIndex) => + typeof idOrIndex === 'number' + ? clamp(idOrIndex, 0, scenes.length - 1) + : scenes.findIndex((S) => S.id === idOrIndex); + + return { scenes, chapters, total, at, timeOf, flat, flatIndex, sceneIndex, sceneAt }; + } + + // Fixed-step clock: real time goes in, whole 1/fps steps come out, so frame rate never changes what is shown + // at a given t, and an export stepping at 1/60 s sees exactly the frames a viewer saw. + function clock(fps = 60) { + let n = 0, + acc = 0; + return { + fps, + get t() { + return n / fps; + }, + set(t) { + n = Math.round(t * fps); + acc = 0; + }, + // dt in seconds of real time (capped, so a sleeping tab doesn't jump); rate: 1 forward, -2.4 rewinding + advance(dt, rate = 1) { + acc += Math.min(Math.max(dt, 0), 0.25) * rate; + const k = acc >= 0 ? Math.floor(acc * fps + 1e-9) : Math.ceil(acc * fps - 1e-9); + n += k; + acc -= k / fps; + return k; + }, + step(k = 1) { + n += k; + }, + }; + } + + DHS.beats = { EASE, READING, countWords, beatWords, readingHold, hash, rng, compile, clock, clamp, clamp01 }; +})(globalThis); From 238ea5f4f64c52f814d63c2529d237298d833ec7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 17:02:12 +0000 Subject: [PATCH 02/13] Essay engine stage 2: player shell (start screen, auto-play or click-follow, keys/swipe/right-click, chapter progress bar, #scene-beat links, help card, no-WebGL2 note) + demo essay content (placeholders) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Ad4FSZyShDwuPQbAcgGJY3 --- engine/essay-demo/dev.html | 24 ++ engine/essay-demo/essay.js | 63 +++++ engine/src/essay/player.js | 555 +++++++++++++++++++++++++++++++++++++ 3 files changed, 642 insertions(+) create mode 100644 engine/essay-demo/dev.html create mode 100644 engine/essay-demo/essay.js create mode 100644 engine/src/essay/player.js diff --git a/engine/essay-demo/dev.html b/engine/essay-demo/dev.html new file mode 100644 index 0000000..b47f1c1 --- /dev/null +++ b/engine/essay-demo/dev.html @@ -0,0 +1,24 @@ + + + + + + + Placeholder Motion Essay (dev) + + + + + + + + + + + + + + diff --git a/engine/essay-demo/essay.js b/engine/essay-demo/essay.js new file mode 100644 index 0000000..349b98b --- /dev/null +++ b/engine/essay-demo/essay.js @@ -0,0 +1,63 @@ +/* DEMO ESSAY: placeholder content only. It shows what the kit's essay player can do; ProofEr owns real essays, their + copy, figures and design. Every number here is MADE UP and labelled so on screen. No real figures belong here: + those live in ProofEr's checked figures table. */ +// prettier-ignore +const ESSAY = { + title: 'Placeholder Motion Essay', + subtitle: 'A demo of the EOMD kit. The words and numbers are placeholders, not facts.', + lang: 'en', + lens: { bloom: 0.12, threshold: 0.85, streak: 0, fringe: 0.3, vignette: 0.28, grain: 0.015, tone: 'none' }, + scenes: [ + { + id: 'opening', chapter: 'Opening', scene: 'field', data: { tint: [0.9, 0.86, 0.8] }, + transition: { type: 'dip', dur: 2 }, + beats: [ + { dur: 2.4, text: [{ pos: 'chapter', kind: 'chapter', text: 'Placeholder chapter title' }] }, + { dur: 1.6, text: [{ pos: 'center', kind: 'body', text: 'This sentence stands in for the opening line of an essay. A real essay brings its own words, word for word.' }] }, + ], + }, + { + id: 'bars', chapter: 'Part one', scene: 'bars', + data: { values: [12, 30, 21, 45, 8], labels: ['A', 'B', 'C', 'D', 'E'], max: 50, unit: '', note: 'Made-up placeholder numbers' }, + transition: { type: 'crossfade', dur: 2.2 }, + beats: [ + { dur: 1.2, text: [{ pos: 'top-left', kind: 'headline', text: 'Five made-up values' }] }, + { dur: 3.2, text: [{ pos: 'top-left', kind: 'body', text: 'Each bar starts at zero and its height is exactly proportional to its value.' }] }, + { dur: 1.6, focus: 3, text: [{ pos: 'top-left', kind: 'body', text: 'One bar can be brought forward while the others step back.' }] }, + ], + }, + { + id: 'tally', chapter: 'Part one', scene: 'tally', + data: { count: 640, per: 1, cols: 40, note: 'Made-up placeholder count: one dot is one unit' }, + transition: { type: 'wipe', dur: 1.8 }, + beats: [ + { dur: 1.2, text: [{ pos: 'bottom-left', kind: 'number', text: '640' }, { pos: 'bottom-left-sub', kind: 'body', text: 'A made-up count, one dot for each unit.' }] }, + { dur: 6, text: [{ pos: 'top-right', kind: 'body', text: 'The dots arrive slowly, at a steady pace, so the number has time to register.' }] }, + ], + }, + { + id: 'areas', chapter: 'Part two', scene: 'areas', + data: { values: [100, 400, 25], labels: ['Placeholder X', 'Placeholder Y', 'Placeholder Z'], note: 'Made-up placeholder numbers' }, + transition: { type: 'dissolve', dur: 2.4 }, + beats: [ + { dur: 2.6, text: [{ pos: 'top-left', kind: 'headline', text: 'Areas, not widths' }] }, + { dur: 1.4, text: [{ pos: 'lower-third', kind: 'body', text: 'A circle with four times the value has four times the area, so it is twice as wide, not four times.' }] }, + ], + }, + { + id: 'quote', chapter: 'Part two', scene: 'field', data: { tint: [0.75, 0.8, 0.9], drift: 0.4 }, + transition: { type: 'push', dur: 2 }, + beats: [ + { dur: 2, text: [{ pos: 'quote', kind: 'quote', text: '“A placeholder quotation sits here, set apart from the running text, with room around it.”' }, { pos: 'quote-source', kind: 'source', text: 'Placeholder source, placeholder date' }] }, + ], + }, + { + id: 'close', chapter: 'Close', scene: 'field', data: { tint: [0.9, 0.86, 0.8], drift: 0.2 }, + transition: 'cut', + beats: [ + { dur: 1.2, text: [{ pos: 'center', kind: 'body', text: 'A hard cut ends the essay on a still frame.' }] }, + { dur: 1, text: [{ pos: 'bottom-left', kind: 'source', text: 'Sources: placeholder. A real essay lists every source here.' }] }, + ], + }, + ], +}; diff --git a/engine/src/essay/player.js b/engine/src/essay/player.js new file mode 100644 index 0000000..f9705b2 --- /dev/null +++ b/engine/src/essay/player.js @@ -0,0 +1,555 @@ +/* ESSAY PLAYER: the shell around a motion essay (a sourced essay that plays like a film). It owns time, controls and + links; the picture (DHS.gl.host) and the words (DHS.essayText) draw what it tells them. Needs DHS.beats; uses + DHS.gl.host and DHS.essayText when they are inlined, and still plays the words without them (or without WebGL2). + + const E = DHS.essay.mount(essay, { root: document.body, sound: null }); + essay: { title, subtitle, lang, lens: knobs | null, scenes: [{ id, chapter, scene: 'bars', data: {...}, + transition: 'crossfade' | { type, dur }, beats: [{ dur, delay, hold, text: [{ pos, kind, text }] }] }] } + + Viewer controls: + click, Space, Right arrow, Page Down, swipe left next beat (finishes the current one first) + right-click, Left arrow, Page Up, Backspace, swipe back (runs back 2.4x faster than it came) + A play by itself / wait for clicks K pause . black screen F full screen ? help card + Home / End first / last beat; #scene-beat links (e.g. #bars-2) open at that beat; the back button works. + Controls are hidden until the mouse moves or the screen is tapped, and fade after 3 s. + + Sound (optional): opts.sound = { start(audioContext), update(t, playing) }. With it, the start screen offers + "Begin with sound" and "Begin silently"; without it, just "Begin". + + Test hooks (stills, fresh-eyes review, MP4): E.seek(scene, beat, t), E.trans(scene, p), E.perf(scene), E.state(), + E.textBoxes(), E.hideGlyphs(on). Also on window.EOMD_ESSAY. Add ?manual to the URL to start paused with no start + screen (what the stills and MP4 tools use). */ +(function (G) { + 'use strict'; + const DHS = (G.DHS = G.DHS || {}); + const doc = G.document; + + const CSS = ` +.eo-root{position:fixed;inset:0;background:var(--eo-bg,#050506);color:var(--eo-ink,#f3f0e8);overflow:hidden; + font-family:var(--eo-font,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif);-webkit-tap-highlight-color:transparent; + user-select:none;-webkit-user-select:none;touch-action:none} +.eo-root.eo-nogl{background:var(--eo-fallback-bg,radial-gradient(120% 90% at 50% 40%,#1b1c22 0%,#08080a 70%))} +.eo-gl{position:absolute;inset:0;width:100%;height:100%;display:block} +.eo-black{position:absolute;inset:0;background:#000;opacity:0;pointer-events:none;transition:opacity .6s} +.eo-black.on{opacity:1} +.eo-ui{position:absolute;left:0;right:0;bottom:0;padding:0 max(16px,env(safe-area-inset-right)) max(14px,env(safe-area-inset-bottom)) max(16px,env(safe-area-inset-left)); + opacity:1;transition:opacity .5s;background:linear-gradient(transparent,rgba(0,0,0,.55));padding-top:40px} +.eo-root:not(.eo-on) .eo-ui{display:none} +.eo-idle .eo-ui{opacity:0;pointer-events:none}.eo-idle{cursor:none} +.eo-bar{display:flex;gap:6px;height:18px;align-items:center;cursor:pointer} +.eo-seg{position:relative;height:4px;background:rgba(255,255,255,.22);border-radius:2px;overflow:hidden} +.eo-seg i{position:absolute;inset:0;right:auto;background:var(--eo-accent,#e9e4d8);width:0} +.eo-row{display:flex;align-items:center;gap:10px;margin-top:6px;font-size:14px} +.eo-row button,.eo-start button,.eo-help button{font:inherit;color:inherit;background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.28); + border-radius:6px;padding:7px 12px;cursor:pointer;min-height:36px} +.eo-row button:hover,.eo-start button:hover{background:rgba(255,255,255,.18)} +.eo-row button:focus-visible,.eo-start button:focus-visible,.eo-help button:focus-visible{outline:2px solid var(--eo-accent,#e9e4d8);outline-offset:2px} +.eo-where{flex:1;opacity:.85;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} +.eo-start,.eo-help{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;flex-direction:column; + text-align:center;padding:max(24px,env(safe-area-inset-top)) 24px max(24px,env(safe-area-inset-bottom));background:rgba(5,5,6,.82)} +.eo-start h1{font-family:var(--eo-display,inherit);font-weight:500;font-size:clamp(28px,5vw,64px);margin:0 0 .3em;max-width:20ch;line-height:1.1} +.eo-start p{margin:0 0 1.6em;opacity:.8;max-width:46ch;font-size:clamp(15px,1.6vw,20px);line-height:1.45} +.eo-start .eo-go{display:flex;gap:12px;flex-wrap:wrap;justify-content:center} +.eo-start button{font-size:18px;padding:12px 22px} +.eo-start small{margin-top:1.6em;opacity:.6;font-size:13px} +.eo-help[hidden],.eo-start[hidden],.eo-note[hidden]{display:none} +.eo-help .eo-card{background:#111114;border:1px solid rgba(255,255,255,.2);border-radius:10px;padding:22px 26px;text-align:left;max-width:520px;font-size:15px;line-height:1.5} +.eo-help h2{margin:0 0 .6em;font-size:18px;font-weight:600} +.eo-help dl{display:grid;grid-template-columns:auto 1fr;gap:4px 16px;margin:0 0 1em} +.eo-help dt{font-weight:600;white-space:nowrap}.eo-help dd{margin:0;opacity:.85} +.eo-note{position:absolute;top:max(14px,env(safe-area-inset-top));left:50%;transform:translateX(-50%);max-width:min(560px,90vw); + background:rgba(0,0,0,.7);border:1px solid rgba(255,255,255,.25);border-radius:8px;padding:10px 14px;font-size:14px;line-height:1.4;text-align:center} +.eo-sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap} +@media (prefers-reduced-motion: reduce){.eo-ui,.eo-black{transition:none}} +`; + + const el = (tag, cls, parent, html) => { + const e = doc.createElement(tag); + if (cls) e.className = cls; + if (html != null) e.innerHTML = html; + if (parent) parent.appendChild(e); + return e; + }; + const esc = (s) => + String(s == null ? '' : s).replace( + /[&<>"]/g, + (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c] + ); + + // A plain words layer for when DHS.essayText isn't inlined: each beat's text, no positions or fades. + function plainText(root, TL, essay) { + const box = el('div', '', root); + box.style.cssText = + 'position:absolute;left:8vw;right:8vw;bottom:18vh;font-size:clamp(18px,2.2vw,30px);line-height:1.4'; + let last = ''; + return { + render(s) { + const sc = essay.scenes[s.scene], + b = sc.beats && sc.beats[Math.max(0, s.beat)]; + const html = + b && !s.trans + ? (b.text || []).map((x) => '

' + esc(typeof x === 'string' ? x : x.text) + '

').join('') + : ''; + if (html !== last) box.innerHTML = last = html; + }, + boxes: () => [], + hideGlyphs() {}, + }; + } + + function mount(essay, opts = {}) { + const B = DHS.beats; + const root = el('div', 'eo-root', opts.root || doc.body); + if (essay.lang) root.lang = essay.lang; + if (!doc.getElementById('eo-css')) el('style', '', doc.head, CSS).id = 'eo-css'; + const params = new URLSearchParams(G.location ? G.location.search : ''); + const manual = params.has('manual'); + const reducedMQ = G.matchMedia ? G.matchMedia('(prefers-reduced-motion: reduce)') : { matches: false }; + const reduced = () => reducedMQ.matches || params.get('reduced') === '1'; + + // ---- picture + const canvas = el('canvas', 'eo-gl', root); + canvas.setAttribute('aria-hidden', 'true'); + const lensKnobs = DHS.lens ? DHS.lens.fromQuery(G.location ? G.location.search : '', essay.lens || null) : null; + const host = + DHS.gl && DHS.gl.host && params.get('gl') !== '0' + ? DHS.gl.host(canvas, { essay, lens: lensKnobs, reduced }) + : null; + const transDur = (type) => + DHS.gl && DHS.gl.transitions && DHS.gl.transitions[type] ? DHS.gl.transitions[type].dur : 1; + const TL = B.compile(essay, { transDur }); + + // ---- words + const textRoot = el('div', 'eo-textroot', root); + textRoot.style.cssText = 'position:absolute;inset:0;pointer-events:none'; + const text = DHS.essayText + ? DHS.essayText.create(textRoot, TL, essay, { reduced, host }) + : plainText(textRoot, TL, essay); + const live = el('div', 'eo-sr', root); // screen readers hear each beat's words once + live.setAttribute('aria-live', 'polite'); + + const black = el('div', 'eo-black', root); + const note = el( + 'div', + 'eo-note', + root, + "This screen can't draw the moving pictures. The words and numbers still play." + ); + note.setAttribute('role', 'status'); + const nogl = () => { + root.classList.add('eo-nogl'); + canvas.style.display = 'none'; + note.hidden = false; + }; + note.hidden = true; + if (!host || !host.ok) nogl(); + if (host) host.onfail = nogl; + + // ---- controls + const ui = el('div', 'eo-ui', root); + const bar = el('div', 'eo-bar', ui); + bar.setAttribute('role', 'slider'); + bar.setAttribute('aria-label', 'Progress'); + bar.tabIndex = -1; + const segs = TL.chapters.map((c) => { + const s = el('div', 'eo-seg', bar); + s.style.flex = String(Math.max(0.001, c.end - c.start)); + s.title = c.name; + return { c, fill: el('i', '', s) }; + }); + const row = el('div', 'eo-row', ui); + const bBack = el('button', '', row, '←'); + bBack.setAttribute('aria-label', 'Back'); + const bPlay = el('button', '', row, 'Pause'); + const bNext = el('button', '', row, '→'); + bNext.setAttribute('aria-label', 'Next'); + const where = el('div', 'eo-where', row); + const bAuto = el('button', '', row); + const bHelp = el('button', '', row, '?'); + bHelp.setAttribute('aria-label', 'Keys and help'); + const bFull = el('button', '', row, 'Full screen'); + + const help = el('div', 'eo-help', root); + help.hidden = true; + help.innerHTML = ``; + + const start = el('div', 'eo-start', root); + start.innerHTML = + `

${esc(essay.title || '')}

` + + (essay.subtitle ? `

${esc(essay.subtitle)}

` : '') + + `
${opts.sound ? '' : ''}
` + + `Press ? for keys`; + if (manual) { + start.hidden = true; + root.classList.add('eo-on'); + } + + // ---- state + const clock = B.clock(60); + const st = { + started: manual, + playing: !manual, + auto: essay.autoplay !== false, + rate: 1, + stopAt: null, + target: null, + lastKey: '', + dirty: true, + audio: null, + }; + const setAuto = (a) => { + st.auto = a; + bAuto.textContent = a ? 'Plays by itself' : 'Waits for clicks'; + bAuto.setAttribute('aria-pressed', String(a)); + }; + setAuto(st.auto); + const setPlaying = (p) => { + st.playing = p; + bPlay.textContent = p ? 'Pause' : 'Play'; + }; + + const S = () => TL.at(clock.t, { reduced: reduced() }); + const fi = () => TL.flatIndex(clock.t); + const keyOf = (s) => TL.scenes[s.scene].id + '-' + (Math.max(0, s.beat) + 1); + + // jump straight to a time (seeks, links, long backs) + const jump = (t) => { + clock.set(t); + st.target = null; + st.rate = 1; + st.dirty = true; + }; + // where "next" plays to: finish the current beat; else play the next one in (its scene's transition first) + const next = (user = true) => { + const s = S(), + F = TL.flat, + k = fi(), + cur = F[k].B; + st.target = null; + st.rate = 1; + if (clock.t < cur.shown - 1e-3) jump(cur.shown); + else if (k + 1 < F.length) { + const n = F[k + 1]; + jump(n.beat === 0 ? TL.scenes[n.scene].start : n.B.start); + st.stopAt = st.auto ? null : n.B.shown; + } else jump(TL.total); + st.nav = user; + setPlaying(true); + void s; + }; + // back: run back at 2.4x to the previous beat, fully shown (jump if that would take more than 3 s) + const back = () => { + const F = TL.flat, + k = Math.max(0, fi() - 1); + const to = F[k].B.shown; + if (to >= clock.t) return jump(to); + st.nav = true; + if ((clock.t - to) / 2.4 > 3 || reduced()) jump(to); + else { + st.target = to; + st.rate = -2.4; + } + st.stopAt = st.auto ? null : to; + setPlaying(true); + }; + const goBeat = (i, j, where = 'shown') => { + jump(TL.timeOf(i, j, where)); + st.stopAt = null; + }; + const fromHash = () => { + const m = /^#(.+)-(\d+)$/.exec((G.location && G.location.hash) || ''); + if (!m) return false; + const i = TL.sceneIndex(decodeURIComponent(m[1])); + if (i < 0) return false; + goBeat(i, +m[2] - 1); + return true; + }; + + // ---- the frame + let lastKey = '', + lastLive = ''; + const draw = () => { + const s = S(); + if (host && host.ok) host.render(s); + text.render(s); + // progress, place, link + segs.forEach( + ({ c, fill }) => + (fill.style.width = (100 * B.clamp01((s.t - c.start) / Math.max(1e-6, c.end - c.start))).toFixed(2) + '%') + ); + bar.setAttribute('aria-valuenow', String(Math.round((100 * s.t) / TL.total))); + const key = keyOf(s); + if (key !== lastKey && st.started) { + lastKey = key; + const sc = TL.scenes[s.scene]; + where.textContent = + (sc.chapter ? sc.chapter + ' · ' : '') + 'part ' + (s.scene + 1) + ' of ' + TL.scenes.length; + if (G.history && G.location && !manual) { + const url = '#' + encodeURIComponent(sc.id) + '-' + (Math.max(0, s.beat) + 1); + if (G.location.hash !== url) G.history[st.nav ? 'pushState' : 'replaceState'](null, '', url); + } + st.nav = false; + const b = essay.scenes[s.scene].beats && essay.scenes[s.scene].beats[Math.max(0, s.beat)]; + const said = b ? (b.text || []).map((x) => (typeof x === 'string' ? x : x.text)).join(' ') : ''; + if (said && said !== lastLive) live.textContent = lastLive = said; + } + if (opts.sound && st.audio) opts.sound.update(s.t, st.playing); + }; + + let prev = 0; + const frame = (now) => { + G.requestAnimationFrame(frame); + const dt = prev ? (now - prev) / 1000 : 0; + prev = now; + if (st.started && st.playing) { + const before = clock.t; + clock.advance(dt, st.rate); + if (st.target != null && clock.t <= st.target) { + clock.set(st.target); + st.target = null; + st.rate = 1; + if (!st.auto) setPlaying(false); + } + if (st.stopAt != null && clock.t >= st.stopAt && st.rate > 0) { + clock.set(st.stopAt); + st.stopAt = null; + setPlaying(false); + } + // waiting for clicks: stop when the current beat is fully shown + if (!st.auto && st.rate > 0 && st.stopAt == null) { + const cur = TL.flat[fi()].B; + if (before < cur.shown && clock.t >= cur.shown) { + clock.set(cur.shown); + setPlaying(false); + } + } + if (clock.t >= TL.total) { + clock.set(TL.total); + setPlaying(false); + bPlay.textContent = 'Play again'; + } + if (clock.t !== before) st.dirty = true; + } + if (st.dirty) { + st.dirty = false; + draw(); + } + }; + + // ---- resize (pixel density capped at 2, picture capped at 2560 x 1600) + const resize = () => { + const r = root.getBoundingClientRect(); + let d = Math.min(2, G.devicePixelRatio || 1); + d = Math.min(d, 2560 / Math.max(1, r.width), 1600 / Math.max(1, r.height), d); + if (host && host.ok) + host.resize(Math.max(2, Math.round(r.width * d)), Math.max(2, Math.round(r.height * d)), r.width, r.height); + if (text.resize) text.resize(r.width, r.height); + st.dirty = true; + }; + G.addEventListener('resize', resize); + + // ---- input + let idleT = 0; + const wake = () => { + root.classList.remove('eo-idle'); + G.clearTimeout(idleT); + idleT = G.setTimeout(() => { + if (help.hidden && st.started) root.classList.add('eo-idle'); + }, 3000); + }; + root.addEventListener('mousemove', wake); + const inUI = (e) => e.target.closest && e.target.closest('.eo-ui,.eo-help,.eo-start'); + root.addEventListener('click', (e) => { + if (!st.started || inUI(e) || e.pointerType === 'touch') return; + next(); + }); + root.addEventListener('contextmenu', (e) => { + if (!st.started || inUI(e)) return; + e.preventDefault(); + back(); + }); + let tx = null, + ty = 0; + root.addEventListener('touchstart', (e) => { + tx = e.touches[0].clientX; + ty = e.touches[0].clientY; + }); + root.addEventListener('touchend', (e) => { + if (tx == null || !st.started) return; + const t = e.changedTouches[0], + dx = t.clientX - tx, + dy = t.clientY - ty; + tx = null; + if (inUI(e)) return; + if (Math.abs(dx) > 50 && Math.abs(dx) > Math.abs(dy)) dx < 0 ? next() : back(); + else wake(); // a tap shows the controls + }); + const toggleHelp = (on = help.hidden) => { + help.hidden = !on; + if (on) help.querySelector('button').focus(); + wake(); + }; + const fullscreen = () => { + if (doc.fullscreenElement) doc.exitFullscreen(); + else if (root.requestFullscreen) root.requestFullscreen().catch(() => {}); + }; + G.addEventListener('keydown', (e) => { + if (e.ctrlKey || e.metaKey || e.altKey) return; + if (!st.started) return; + const k = e.key; + if (!help.hidden && (k === 'Escape' || k === '?')) return toggleHelp(false); + if (e.target.tagName === 'BUTTON' && (k === ' ' || k === 'Enter')) return; + const act = { + ' ': next, + ArrowRight: next, + PageDown: next, + Enter: next, + ArrowLeft: back, + PageUp: back, + Backspace: back, + a: () => setAuto(!st.auto), + A: () => setAuto(!st.auto), + k: () => setPlaying(!st.playing), + K: () => setPlaying(!st.playing), + '.': () => black.classList.toggle('on'), + f: fullscreen, + F: fullscreen, + '?': () => toggleHelp(), + h: () => toggleHelp(), + Home: () => goBeat(0, 0), + End: () => goBeat(TL.scenes.length - 1, 1e9), + }[k]; + if (act) { + e.preventDefault(); + act(); + wake(); + } + }); + bBack.onclick = () => back(); + bNext.onclick = () => next(); + bPlay.onclick = () => { + if (clock.t >= TL.total) jump(0); + setPlaying(!st.playing); + }; + bAuto.onclick = () => setAuto(!st.auto); + bHelp.onclick = () => toggleHelp(); + bFull.onclick = fullscreen; + help.querySelector('button').onclick = () => toggleHelp(false); + bar.addEventListener('click', (e) => { + const r = bar.getBoundingClientRect(), + x = (e.clientX - r.left) / r.width; + // the segments have gaps, so find the chapter under the pointer and the fraction inside it + let t = x * TL.total; + for (const { c } of segs) { + const sr = segs.find((q) => q.c === c).fill.parentNode.getBoundingClientRect(); + if (e.clientX >= sr.left - 3 && e.clientX <= sr.right + 3) + t = c.start + B.clamp01((e.clientX - sr.left) / sr.width) * (c.end - c.start); + } + const k = TL.flatIndex(t); + st.nav = true; + goBeat(TL.flat[k].scene, TL.flat[k].beat, 'shown'); + }); + G.addEventListener('popstate', () => fromHash()); + G.addEventListener('hashchange', () => fromHash()); + + const begin = (withSound) => { + start.hidden = true; + st.started = true; + root.classList.add('eo-on'); + if (withSound && opts.sound) { + try { + const AC = G.AudioContext || G.webkitAudioContext; + st.audio = new AC({ sampleRate: 48000 }); + opts.sound.start(st.audio); + } catch (err) { + console.warn('essay: no sound', err); + } + } + if (!fromHash()) jump(0); + setPlaying(true); + fullscreen(); + wake(); + }; + start.querySelectorAll('button').forEach((b) => (b.onclick = () => begin(b.dataset.s === '1'))); + + // ---- test hooks: repeatable stills of any beat or any point in a transition + const E = { + TL, + host, + // scene: index or id; beat: index (-1 = the start of its transition); t: seconds after the beat starts, + // or 'shown' (fully in) / 'end' (the last frame of its hold) + seek(scene, beat = 0, t = 'shown') { + const i = TL.sceneIndex(scene), + Sc = TL.scenes[i]; + if (beat < 0) jump(Sc.start); + else { + const b = Sc.beats[Math.min(beat, Sc.beats.length - 1)]; + jump(t === 'shown' ? b.shown : t === 'end' ? b.end - 1e-3 : b.start + t); + } + setPlaying(false); + draw(); + return E.state(); + }, + // the transition into scene `scene` at progress p (0..1) + trans(scene, p) { + const Sc = TL.scenes[TL.sceneIndex(scene)]; + jump(Sc.start + B.clamp01(p) * Sc.trans.dur * 0.99999); + setPlaying(false); + draw(); + return E.state(); + }, + at(t) { + jump(t); + setPlaying(false); + draw(); + return E.state(); + }, + // ms per frame for a scene (GPU finished each frame), drawn n times at its last beat + perf(scene, n = 60) { + if (!host || !host.ok) return null; + E.seek(scene, 1e9, 'shown'); + const s = S(); + const t0 = G.performance.now(); + for (let f = 0; f < n; f++) host.render(Object.assign({}, s, { t: s.t + f / 60 }), true); + host.finish(); + return (G.performance.now() - t0) / n; + }, + state() { + const s = S(); + return { + t: s.t, + total: TL.total, + scene: s.scene, + id: s.id, + beat: s.beat, + trans: s.trans, + gl: !!(host && host.ok), + reduced: reduced(), + }; + }, + textBoxes: () => text.boxes(), + hideGlyphs: (on) => { + text.hideGlyphs(on); + }, + next, + back, + begin, + setAuto, + }; + G.EOMD_ESSAY = E; + + resize(); + if (manual) { + setPlaying(false); + draw(); + } + G.requestAnimationFrame(frame); + return E; + } + + DHS.essay = { mount }; +})(globalThis); From e0ad75cd3876405bc7b19fb5a778fdcdd726bf7f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 17:02:54 +0000 Subject: [PATCH 03/13] Essay engine stage 3: test hooks (seek/trans/at/perf/state) and engine/tools/essay-qa.js (stills of every beat and transition, flash, contrast and speed report) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Ad4FSZyShDwuPQbAcgGJY3 --- engine/tools/essay-qa.js | 155 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 155 insertions(+) create mode 100644 engine/tools/essay-qa.js diff --git a/engine/tools/essay-qa.js b/engine/tools/essay-qa.js new file mode 100644 index 0000000..bf87a13 --- /dev/null +++ b/engine/tools/essay-qa.js @@ -0,0 +1,155 @@ +// ESSAY QA: stills and checks for an essay player (the kit's DHS.essay), for fresh-eyes review (brief/CRAFT.md §11) +// and before an MP4. Uses the player's test hooks (?manual, window.EOMD_ESSAY: seek, trans, perf, flashCheck, contrast). +// node tools/essay-qa.js [W H] +// Writes to outDir: +// s--b-shown.png / -end.png every beat, fully arrived and at the end of its hold +// s--trans-25.png / 50 / 75 every transition at 0.25, 0.5, 0.75 +// report.md + report.json flash check per transition (3-per-second rule), WCAG contrast of +// every text block against the brightest and darkest picture under it +// (sampled through the beat), ms per frame per scene, page errors +// Exit code 1 if anything fails (a page error, a flash, contrast under AA). +const { chromium } = require('playwright'); +const path = require('path'); +const fs = require('fs'); + +(async () => { + const [, , file, outDir, W = '1280', H = '720'] = process.argv; + if (!file || !outDir) { + console.log('usage: node tools/essay-qa.js [W H]'); + process.exit(2); + } + fs.mkdirSync(outDir, { recursive: true }); + const b = await chromium.launch({ + args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'], + }); + const errors = []; + const open = async (query, opts = {}) => { + const p = await b.newPage({ + viewport: { width: +W, height: +H }, + reducedMotion: opts.reduced ? 'reduce' : 'no-preference', + }); + p.on('pageerror', (e) => errors.push(e.message)); + p.on('console', (m) => m.type() === 'error' && errors.push(m.text())); + await p.goto('file://' + path.resolve(file) + query); + await p.waitForFunction('window.EOMD_ESSAY', null, { timeout: 30000 }); + return p; + }; + const p = await open('?manual'); + const info = await p.evaluate(() => { + const E = window.EOMD_ESSAY; + return { + gl: !!(E.host && E.host.ok), + scenes: E.TL.scenes.map((S) => ({ + id: S.id, + trans: S.trans, + beats: S.beats.map((B) => ({ start: B.start, shown: B.shown, end: B.end, hold: B.hold })), + })), + total: E.TL.total, + }; + }); + const report = { + file, + size: [+W, +H], + gl: info.gl, + total: info.total, + stills: [], + flashes: [], + contrast: [], + perf: [], + errors, + }; + const name = (i, rest) => `s${String(i + 1).padStart(2, '0')}-${info.scenes[i].id}-${rest}.png`; + + for (let i = 0; i < info.scenes.length; i++) { + const S = info.scenes[i]; + if (S.trans.dur > 0) + for (const q of [0.25, 0.5, 0.75]) { + await p.evaluate(([i, q]) => window.EOMD_ESSAY.trans(i, q), [i, q]); + const f = name(i, 'trans-' + Math.round(q * 100)); + await p.screenshot({ path: path.join(outDir, f) }); + report.stills.push(f); + } + for (let j = 0; j < S.beats.length; j++) { + for (const w of ['shown', 'end']) { + await p.evaluate(([i, j, w]) => window.EOMD_ESSAY.seek(i, j, w), [i, j, w]); + const f = name(i, `b${j + 1}-${w}`); + await p.screenshot({ path: path.join(outDir, f) }); + report.stills.push(f); + } + // contrast: sample through the beat (arrival done .. end of hold), keep the worst + const c = await p.evaluate( + ([i, j, B]) => { + const E = window.EOMD_ESSAY; + if (!E.contrast) return null; + const worst = {}; + for (let k = 0; k <= 4; k++) { + E.at(B.shown + ((B.end - 1e-3 - B.shown) * k) / 4); + for (const r of E.contrast()) { + if (!worst[r.key] || r.ratio < worst[r.key].ratio) worst[r.key] = r; + } + } + return Object.values(worst); + }, + [i, j, S.beats[j]] + ); + if (c) c.forEach((r) => report.contrast.push(Object.assign({ scene: S.id, beat: j + 1 }, r))); + } + if (info.gl) + report.perf.push({ scene: S.id, msPerFrame: await p.evaluate((i) => window.EOMD_ESSAY.perf(i, 30), i) }); + } + // flash check: each transition stepped at 60 fps (the picture only; the text layer is checked by its own rules) + if (info.gl) { + const small = await open('?manual'); + await small.setViewportSize({ width: 320, height: 180 }); + for (let i = 0; i < info.scenes.length; i++) { + if (!info.scenes[i].trans.dur) continue; + const r = await small.evaluate((i) => window.EOMD_ESSAY.flashCheck && window.EOMD_ESSAY.flashCheck(i), i); + if (r) report.flashes.push(Object.assign({ scene: info.scenes[i].id, type: info.scenes[i].trans.type }, r)); + } + // reduced motion: the transitions the viewer actually gets + const red = await open('?manual', { reduced: true }); + report.reducedMotion = await red.evaluate(() => + window.EOMD_ESSAY.TL.scenes.map((S) => + window.EOMD_ESSAY.host.transitionFor ? window.EOMD_ESSAY.host.transitionFor(S.trans.type) : S.trans.type + ) + ); + } + await b.close(); + + const bad = []; + if (errors.length) bad.push(errors.length + ' page error(s)'); + report.flashes.filter((f) => !f.pass).forEach((f) => bad.push(`flash: ${f.scene} (${f.type}) ${f.maxPerSecond}/s`)); + report.contrast + .filter((c) => !c.pass) + .forEach((c) => + bad.push(`contrast: ${c.scene} beat ${c.beat} "${c.text}" ${c.ratio.toFixed(2)}:1 (needs ${c.need}:1)`) + ); + report.pass = !bad.length; + fs.writeFileSync(path.join(outDir, 'report.json'), JSON.stringify(report, null, 2)); + const md = [ + `# Essay QA: ${path.basename(file)}`, + ``, + `${report.pass ? 'PASS' : 'FAIL'} · ${W}x${H} · WebGL2 ${info.gl ? 'yes' : 'no (fallback)'} · ${info.total.toFixed(1)} s · ${report.stills.length} stills`, + ...bad.map((x) => '- ' + x), + ``, + `## Flashes (at most 3 a second; WCAG 2.3.1, picture luminance in a 16x9 grid)`, + ...report.flashes.map( + (f) => + `- ${f.scene} (${f.type}): ${f.maxPerSecond} per second, biggest step ${f.maxStep.toFixed(3)} ${f.pass ? 'ok' : 'FAIL'}` + ), + ``, + `## Contrast (worst frame of each beat; AA: 4.5:1, large text 3:1)`, + ...report.contrast.map( + (c) => + `- ${c.scene} b${c.beat} ${c.kind} "${c.text.slice(0, 40)}": ${c.ratio.toFixed(2)}:1 against the ${c.against} pixel ${c.pass ? 'ok' : 'FAIL'}` + ), + ``, + `## Speed (ms a frame on this machine's GPU; SwiftShader in CI is far slower than a real one)`, + ...report.perf.map((x) => `- ${x.scene}: ${x.msPerFrame == null ? '-' : x.msPerFrame.toFixed(1)}`), + ``, + `Reduced motion transitions: ${(report.reducedMotion || []).join(', ')}`, + ].join('\n'); + fs.writeFileSync(path.join(outDir, 'report.md'), md + '\n'); + console.log(md); + process.exit(report.pass ? 0 : 1); +})(); From 184ef885fe80adca709bfd8f9aacfb721fb0f75a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 17:07:19 +0000 Subject: [PATCH 04/13] Essay engine stage 4: plain-WebGL2 toolkit + GLSL preamble (engine/src/gl/gl.js), scene host + render-to-texture compositor (host.js), example scenes field/bars/tally/areas (scenes.js); lens.drawTexture takes a linear-light GPU texture in a shared context Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Ad4FSZyShDwuPQbAcgGJY3 --- engine/essay-demo/essay.js | 6 +- engine/src/essay/beats.js | 18 ++- engine/src/fx/lens.js | 78 ++++++++----- engine/src/gl/gl.js | 142 +++++++++++++++++++++++ engine/src/gl/host.js | 225 +++++++++++++++++++++++++++++++++++++ engine/src/gl/scenes.js | 222 ++++++++++++++++++++++++++++++++++++ 6 files changed, 659 insertions(+), 32 deletions(-) create mode 100644 engine/src/gl/gl.js create mode 100644 engine/src/gl/host.js create mode 100644 engine/src/gl/scenes.js diff --git a/engine/essay-demo/essay.js b/engine/essay-demo/essay.js index 349b98b..b96215d 100644 --- a/engine/essay-demo/essay.js +++ b/engine/essay-demo/essay.js @@ -18,7 +18,7 @@ const ESSAY = { }, { id: 'bars', chapter: 'Part one', scene: 'bars', - data: { values: [12, 30, 21, 45, 8], labels: ['A', 'B', 'C', 'D', 'E'], max: 50, unit: '', note: 'Made-up placeholder numbers' }, + data: { values: [12, 30, 21, 45, 8], labels: ['A', 'B', 'C', 'D', 'E'], max: 50, grow: 1, note: 'Made-up placeholder numbers' }, transition: { type: 'crossfade', dur: 2.2 }, beats: [ { dur: 1.2, text: [{ pos: 'top-left', kind: 'headline', text: 'Five made-up values' }] }, @@ -28,11 +28,11 @@ const ESSAY = { }, { id: 'tally', chapter: 'Part one', scene: 'tally', - data: { count: 640, per: 1, cols: 40, note: 'Made-up placeholder count: one dot is one unit' }, + data: { count: 640, cols: 40, grow: 1, note: 'Made-up placeholder count: one dot is one unit' }, transition: { type: 'wipe', dur: 1.8 }, beats: [ { dur: 1.2, text: [{ pos: 'bottom-left', kind: 'number', text: '640' }, { pos: 'bottom-left-sub', kind: 'body', text: 'A made-up count, one dot for each unit.' }] }, - { dur: 6, text: [{ pos: 'top-right', kind: 'body', text: 'The dots arrive slowly, at a steady pace, so the number has time to register.' }] }, + { dur: 6, ease: 'linear', text: [{ pos: 'top-right', kind: 'body', text: 'The dots arrive slowly, at a steady pace, so the number has time to register.' }] }, ], }, { diff --git a/engine/src/essay/beats.js b/engine/src/essay/beats.js index f643872..2596e9b 100644 --- a/engine/src/essay/beats.js +++ b/engine/src/essay/beats.js @@ -135,7 +135,14 @@ const p = raw.map((r, j) => S.beats[j].ease(r)); const trans = t < S.body && S.trans.dur > 0 - ? { type: S.trans.type, from: i - 1, to: i, p: clamp01((t - S.start) / S.trans.dur), dur: S.trans.dur } + ? { + type: S.trans.type, + from: i - 1, + to: i, + p: clamp01((t - S.start) / S.trans.dur), + dur: S.trans.dur, + fromT: i ? t - scenes[i - 1].body : 0, + } : null; const B = beat >= 0 ? S.beats[beat] : null; return { @@ -180,15 +187,18 @@ // Fixed-step clock: real time goes in, whole 1/fps steps come out, so frame rate never changes what is shown // at a given t, and an export stepping at 1/60 s sees exactly the frames a viewer saw. function clock(fps = 60) { - let n = 0, + let base = 0, + n = 0, acc = 0; return { fps, get t() { - return n / fps; + return base + n / fps; }, + // a seek lands exactly on t; steps continue from there in whole 1/fps steps set(t) { - n = Math.round(t * fps); + base = t; + n = 0; acc = 0; }, // dt in seconds of real time (capped, so a sleeping tab doesn't jump); rate: 1 forward, -2.4 rewinding diff --git a/engine/src/fx/lens.js b/engine/src/fx/lens.js index 402798b..9926b97 100644 --- a/engine/src/fx/lens.js +++ b/engine/src/fx/lens.js @@ -18,6 +18,11 @@ L.draw(canvas, t); // every frame, after the 2D canvas is drawn L.set({ bloom: 0.5 }); L.onfail = () => {...}; L.dispose(); + On a GPU texture (kit 0.2.0): share the scene's WebGL2 context and pass its texture, so nothing is uploaded and + linear-light highlights above 1 reach the glow and tone curve at full strength: + const L = DHS.lens.create(knobs, { gl }); // draws into gl's default framebuffer + L.drawTexture(texture, w, h, t); // texture: linear light (e.g. a half-float render target) + Standalone: needs only the DHS namespace, so any build (CD-ROM, living posters, gen) can inline it. */ (function (G) { 'use strict'; @@ -58,9 +63,10 @@ float h13(vec3 p){p=fract(p*.1031);p+=dot(p,p.zyx+31.32);return fract((p.x+p.y)* // 13-tap downsample (sRGB source on the first level, with the soft threshold); linear light after that const DOWN = HEAD + - `uniform sampler2D S;uniform vec2 uPx;uniform float uFirst,uTh,uKnee; + `uniform sampler2D S;uniform vec2 uPx;uniform float uFirst,uTh,uKnee,uLin; vec3 s(vec2 d){vec3 c=texture(S,v+d*uPx).rgb; - if(uFirst>.5){float m=max(c.r,max(c.g,c.b));c=toLin(c)*smoothstep(uTh-uKnee,uTh+uKnee,m);c/=1.+luma(c)*.12;} + if(uFirst>.5){vec3 g=uLin>.5?toSrgb(min(c,1.)):c;float m=max(g.r,max(g.g,g.b)); + c=(uLin>.5?max(c,0.):toLin(c))*smoothstep(uTh-uKnee,uTh+uKnee,m);c/=1.+luma(c)*.12;} return c;} void main(){vec3 c=s(vec2(0))*.125; c+=(s(vec2(-1,-1))+s(vec2(1,-1))+s(vec2(-1,1))+s(vec2(1,1)))*.125; @@ -77,7 +83,7 @@ void main(){vec3 c=vec3(0); const POST = HEAD + `uniform sampler2D S,B,SB;uniform vec2 R;uniform vec3 uTint,uLift,uGain; -uniform float uExp,uBloom,uHal,uStreak,uFringe,uTone,uCon,uSat,uVig,uGrain,uDither,uSeed; +uniform float uExp,uBloom,uHal,uStreak,uFringe,uTone,uCon,uSat,uVig,uGrain,uDither,uSeed,uLin; vec3 aces(vec3 x){return clamp((x*(2.51*x+.03))/(x*(2.43*x+.59)+.14),0.,1.);} vec3 agx(vec3 v){const mat3 M=mat3(.842479062253094,.0423282422610123,.0423756549057051,.0784335999999992,.878468636469772,.0784336,.0792237451477643,.0791661274605434,.879142973793104); v=M*v;v=clamp(log2(max(v,1e-10)),-12.47393,4.026069);v=(v+12.47393)/(4.026069+12.47393); @@ -87,9 +93,9 @@ vec3 agx(vec3 v){const mat3 M=mat3(.842479062253094,.0423282422610123,.042375654 void main(){vec2 q=v-.5; vec3 src=texture(S,v).rgb,c=src; if(uFringe>0.){vec2 off=q*1.41421*(dot(q,q)*2.)*uFringe/R;c.r=texture(S,v+off).r;c.b=texture(S,v-off).b;} - bool touched=uExp!=1.||uBloom>0.||uStreak>0.||uTone>.5; + bool touched=uLin>.5||uExp!=1.||uBloom>0.||uStreak>0.||uTone>.5; if(touched){ - c=toLin(c)*uExp; + c=(uLin>.5?max(c,0.):toLin(c))*uExp; if(uBloom>0.)c+=texture(B,v).rgb*uBloom*vec3(1.+uHal*.35,1.-uHal*.05,1.-uHal*.35); if(uStreak>0.){vec3 st=vec3(0);float ws=0.; for(int i=1;i<17;i++){float fi=float(i),w=exp(-fi*.21);ws+=2.*w; @@ -111,22 +117,25 @@ void main(){vec2 q=v-.5; const reduced = () => !!(G.matchMedia && G.matchMedia('(prefers-reduced-motion: reduce)').matches); const TONE = { none: 0, aces: 1, film: 1, agx: 2 }; - function create(knobs = {}) { + function create(knobs = {}, shared = null) { const k = Object.assign({}, DEFAULTS, knobs); - const canvas = G.document ? G.document.createElement('canvas') : null; + const canvas = shared && shared.gl ? shared.gl.canvas : G.document ? G.document.createElement('canvas') : null; const api = { canvas, ok: false, knobs: k, onfail: null }; api.set = (o) => Object.assign(k, o); api.draw = () => false; api.dispose = () => {}; if (!canvas) return api; // preserveDrawingBuffer: stills and MP4 frames (page screenshots, toDataURL) always see the last frame - const gl = canvas.getContext('webgl2', { - alpha: false, - antialias: false, - depth: false, - stencil: false, - preserveDrawingBuffer: true, - }); + const gl = + shared && shared.gl + ? shared.gl + : canvas.getContext('webgl2', { + alpha: false, + antialias: false, + depth: false, + stencil: false, + preserveDrawingBuffer: true, + }); if (!gl) return api; const mk = (fs) => { @@ -188,6 +197,7 @@ void main(){vec2 q=v-.5; const BLOOM_K = 0.5; // calibration: bloom 0.25 matches the first lens next to a bright edge, with a wider, softer tail let P = null, src = null, + vao = null, down = [], up = [], W = 0, @@ -204,7 +214,7 @@ void main(){vec2 q=v-.5; if (!P.down || !P.up || !P.post) return false; half = !!gl.getExtension('EXT_color_buffer_float') || !!gl.getExtension('EXT_color_buffer_half_float'); gl.getExtension('OES_texture_float_linear'); - const vao = gl.createVertexArray(); + vao = gl.createVertexArray(); gl.bindVertexArray(vao); gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer()); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW); // one triangle over the screen @@ -248,17 +258,14 @@ void main(){vec2 q=v-.5; }; const tri = () => gl.drawArrays(gl.TRIANGLES, 0, 3); - // source: any canvas, image or video. t: seconds (seeds grain and dither). - api.draw = (source, t = 0) => { - if (!api.ok || lost) return false; - const w = source.width, - h = source.height; - if (!w || !h) return false; + const size = (w, h) => { if (w !== W || h !== H) { W = w; H = h; - canvas.width = w; - canvas.height = h; + if (!shared) { + canvas.width = w; + canvas.height = h; + } freeAll(); for (let l = 0; l < MAXL; l++) { const s = 2 << l, @@ -268,11 +275,29 @@ void main(){vec2 q=v-.5; up.push(target(lw, lh)); } } + }; + // source: any canvas, image or video. t: seconds (seeds grain and dither). + api.draw = (source, t = 0) => { + if (!api.ok || lost) return false; + const w = source.width, + h = source.height; + if (!w || !h) return false; + size(w, h); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, src); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); + return run(src, t, 0); + }; + // texture: a GPU texture in this context holding linear light, w x h (the output size) + api.drawTexture = (texture, w, h, t = 0) => { + if (!api.ok || lost || !w || !h) return false; + size(w, h); + return run(texture, t, 1); + }; + const run = (srcTex, t, lin) => { + gl.bindVertexArray(vao); const glow = k.bloom > 0 || k.streak > 0, L = Math.max(1, Math.min(MAXL, Math.round(k.levels))); @@ -280,13 +305,14 @@ void main(){vec2 q=v-.5; streakTex = down[0].t, streakN = 1; if (glow) { - let prev = src, + let prev = srcTex, pw = W, ph = H; for (let l = 0; l < L; l++) { pass(P.down, down[l], [['S', prev]]); setf(P.down.u, 'uPx', 1 / pw, 1 / ph); setf(P.down.u, 'uFirst', l ? 0 : 1); + setf(P.down.u, 'uLin', lin); setf(P.down.u, 'uTh', k.threshold); setf(P.down.u, 'uKnee', Math.max(1e-3, k.knee)); tri(); @@ -313,12 +339,13 @@ void main(){vec2 q=v-.5; const u = P.post.u, seedN = reduced() ? 0 : Math.floor(Math.max(0, t) * k.grainFps); pass(P.post, null, [ - ['S', src], + ['S', srcTex], ['B', glowTex], ['SB', streakTex], ]); setf(u, 'R', W, H); setf(u, 'uExp', k.exposure); + setf(u, 'uLin', lin); setf(u, 'uBloom', glow ? (k.bloom * BLOOM_K) / L : 0); setf(u, 'uHal', k.halation); setf(u, 'uStreak', glow ? k.streak / streakN : 0); @@ -338,6 +365,7 @@ void main(){vec2 q=v-.5; }; api.dispose = () => { freeAll(); + if (shared) return void (api.ok = false); const x = gl.getExtension('WEBGL_lose_context'); if (x) x.loseContext(); api.ok = false; diff --git a/engine/src/gl/gl.js b/engine/src/gl/gl.js new file mode 100644 index 0000000..f49e7d3 --- /dev/null +++ b/engine/src/gl/gl.js @@ -0,0 +1,142 @@ +/* GL: the small plain-WebGL2 toolkit under the essay picture (no three.js, no libraries). + DHS.gl.context(canvas) a WebGL2 context for stills and export (preserveDrawingBuffer), or null + DHS.gl.program(gl, fs[, vs]) { p, u } with every uniform location, or null (the log goes to the console) + DHS.gl.target(gl, w, h) a render target { t, f, w, h }: half-float when the GPU can, so scenes keep + their full range (highlights above 1 reach the lens's glow and tone curve) + DHS.gl.tri(gl) binds a vertex array with one triangle over the screen; draw with + gl.drawArrays(gl.TRIANGLES, 0, 3) + DHS.gl.LIB the shared GLSL preamble for scenes and transitions (below) + Scenes write linear light; the lens (or the plain presenter in the host) turns it into screen colour. + + GLSL preamble (DHS.gl.LIB): + toLin, toSrgb, luma colour space helpers + h11, h21, h22, noise(vec2), fbm(vec2, octaves) hash and value noise, all deterministic + sdCircle, sdBox, sdRoundBox, sdCapsule, sdTorus, smin distance-field shapes (2D, torus in 3D) + aa(d, px) antialiased coverage of a distance field + studio(n, base) a fake studio light on a surface normal: softbox key from upper left, a soft + fill, a rim from behind, and a floor bounce. The "real object under studio + light" look without image files. + Standalone: needs only the DHS namespace. */ +(function (G) { + 'use strict'; + const DHS = (G.DHS = G.DHS || {}); + const GL = (DHS.gl = DHS.gl || {}); + + GL.VS = `#version 300 es +in vec2 a;out vec2 v;void main(){v=a*.5+.5;gl_Position=vec4(a,0.,1.);}`; + + GL.LIB = ` +vec3 toLin(vec3 c){return mix(c/12.92,pow((c+.055)/1.055,vec3(2.4)),step(.04045,c));} +vec3 toSrgb(vec3 c){c=max(c,0.);return mix(c*12.92,1.055*pow(c,vec3(1./2.4))-.055,step(.0031308,c));} +float luma(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} +float h11(float p){p=fract(p*.1031);p*=p+33.33;p*=p+p;return fract(p);} +float h21(vec2 p){vec3 q=fract(vec3(p.xyx)*.1031);q+=dot(q,q.yzx+33.33);return fract((q.x+q.y)*q.z);} +vec2 h22(vec2 p){vec3 q=fract(vec3(p.xyx)*vec3(.1031,.103,.0973));q+=dot(q,q.yzx+33.33);return fract((q.xx+q.yz)*q.zy);} +float noise(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);} +float fbm(vec2 p,int oct){float s=0.,a=.5;for(int i=0;i<8;i++){if(i>=oct)break;s+=a*noise(p);p=p*2.03+vec2(17.1,9.7);a*=.5;}return s;} +float sdCircle(vec2 p,float r){return length(p)-r;} +float sdBox(vec2 p,vec2 b){vec2 d=abs(p)-b;return length(max(d,0.))+min(max(d.x,d.y),0.);} +float sdRoundBox(vec2 p,vec2 b,float r){return sdBox(p,b-r)-r;} +float sdCapsule(vec2 p,vec2 a,vec2 b,float r){vec2 pa=p-a,ba=b-a;float h=clamp(dot(pa,ba)/dot(ba,ba),0.,1.);return length(pa-ba*h)-r;} +float sdTorus(vec3 p,vec2 t){vec2 q=vec2(length(p.xz)-t.x,p.y);return length(q)-t.y;} +float smin(float a,float b,float k){float h=clamp(.5+.5*(b-a)/k,0.,1.);return mix(b,a,h)-k*h*(1.-h);} +float aa(float d,float px){return clamp(.5-d/px,0.,1.);} +vec3 studio(vec3 n,vec3 base){ + vec3 key=normalize(vec3(-.55,.65,.6)),fill=normalize(vec3(.7,.1,.7)); + float k=max(dot(n,key),0.),f=max(dot(n,fill),0.),rim=pow(1.-max(n.z,0.),3.),bounce=max(-n.y,0.)*.5+.5; + vec3 r=reflect(vec3(0,0,-1),n); + float box=smoothstep(.55,.95,dot(r,key)); /* the softbox seen in the surface */ + return base*(.06+.85*k+.18*f)*mix(.8,1.,bounce)+vec3(1.,.97,.92)*(box*.9+rim*.12);} +`; + + GL.context = (canvas) => { + const gl = canvas.getContext('webgl2', { + alpha: false, + antialias: false, + depth: false, + stencil: false, + preserveDrawingBuffer: true, + }); + if (!gl) return null; + gl.half = !!gl.getExtension('EXT_color_buffer_float') || !!gl.getExtension('EXT_color_buffer_half_float'); + gl.getExtension('OES_texture_float_linear'); + return gl; + }; + + GL.program = (gl, fs, vs = GL.VS, label = 'gl') => { + const p = gl.createProgram(); + for (const [ty, src] of [ + [gl.VERTEX_SHADER, vs], + [gl.FRAGMENT_SHADER, fs], + ]) { + const sh = gl.createShader(ty); + gl.shaderSource(sh, src); + gl.compileShader(sh); + if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS) && !gl.isContextLost()) { + console.error(label + ':', gl.getShaderInfoLog(sh)); + return null; + } + gl.attachShader(p, sh); + } + gl.bindAttribLocation(p, 0, 'a'); + gl.linkProgram(p); + if (!gl.getProgramParameter(p, gl.LINK_STATUS)) { + if (!gl.isContextLost()) console.error(label + ':', gl.getProgramInfoLog(p)); + return null; + } + const u = {}, + n = gl.getProgramParameter(p, gl.ACTIVE_UNIFORMS); + for (let i = 0; i < n; i++) { + const inf = gl.getActiveUniform(p, i); + u[inf.name.replace(/\[0\]$/, '')] = gl.getUniformLocation(p, inf.name); + } + return { p, u }; + }; + + GL.target = (gl, w, h) => { + const t = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, t); + for (const [k, v] of [ + [gl.TEXTURE_MIN_FILTER, gl.LINEAR], + [gl.TEXTURE_MAG_FILTER, gl.LINEAR], + [gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE], + [gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE], + ]) + gl.texParameteri(gl.TEXTURE_2D, k, v); + if (gl.half) gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA16F, w, h, 0, gl.RGBA, gl.HALF_FLOAT, null); + else gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + const f = gl.createFramebuffer(); + gl.bindFramebuffer(gl.FRAMEBUFFER, f); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, t, 0); + return { t, f, w, h, free: () => (gl.deleteTexture(t), gl.deleteFramebuffer(f)) }; + }; + + GL.tri = (gl) => { + if (!gl._tri) { + gl._tri = gl.createVertexArray(); + gl.bindVertexArray(gl._tri); + 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); + } + gl.bindVertexArray(gl._tri); + }; + + // set a uniform from a JS value: number, [x,y], [x,y,z], [x,y,z,w], or a flat Float32Array for vec4 arrays + GL.set = (gl, u, name, v) => { + const l = u[name]; + if (l == null) return; + if (typeof v === 'number') gl.uniform1f(l, v); + else if (v instanceof Float32Array) gl.uniform4fv(l, v); + else gl['uniform' + v.length + 'f'](l, ...v); + }; + + // WCAG relative luminance and contrast ratio, for checks (sRGB 0..255 or 0..1) + GL.relLum = (r, g, b, max = 255) => { + const f = (c) => ((c /= max) <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4); + return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b); + }; + GL.contrast = (l1, l2) => (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05); +})(globalThis); diff --git a/engine/src/gl/host.js b/engine/src/gl/host.js new file mode 100644 index 0000000..be0119f --- /dev/null +++ b/engine/src/gl/host.js @@ -0,0 +1,225 @@ +/* HOST: the essay picture. Draws the current scene (or, during a transition, the outgoing and incoming scenes into + two buffers and a transition shader between them) into a half-float buffer, then finishes it with the lens on the + GPU texture (DHS.lens with a shared context: no 2D upload, full range kept) or a plain presenter. + + const H = DHS.gl.host(canvas, { essay, lens: knobs | null, reduced: () => bool }); + H.ok false without WebGL2 (the player then shows the words on a plain background) + H.render(state) state from DHS.beats timeline .at(t) + H.resize(w, h) drawing-buffer pixels + H.lumaGrid(cols, rows) mean relative luminance per screen cell of the last frame (flash checks) + H.pixels() { w, h, data } of the last frame, RGBA bottom row first (contrast checks) + H.transitionFor(type) the transition actually used (prefers-reduced-motion swaps some for a crossfade) + H.finish(), H.onfail + Scene shaders are built on first use; one that won't build falls back to the plain scene (logged once). + Needs DHS.gl (gl.js, scenes.js, transitions.js); DHS.lens is optional. */ +(function (G) { + 'use strict'; + const DHS = (G.DHS = G.DHS || {}); + const GL = (DHS.gl = DHS.gl || {}); + + const SCENE_HEAD = `#version 300 es +precision highp float;in vec2 v;out vec4 o; +uniform vec2 R;uniform float T,uMotion,uSeed,uG,uN;uniform float uP[8];uniform vec2 uF;uniform vec4 uD[16]; +`; + const SCENE_MAIN = ` +void main(){vec2 p=(v-.5)*vec2(R.x/R.y,1.);o=vec4(max(scene(p),0.),1.);}`; + const TRANS_HEAD = `#version 300 es +precision highp float;in vec2 v;out vec4 o;uniform sampler2D SA,SB;uniform vec2 R;uniform float uP,uSeed; +vec3 A(vec2 uv){return texture(SA,uv).rgb;}vec3 B(vec2 uv){return texture(SB,uv).rgb;} +`; + const TRANS_MAIN = ` +void main(){o=vec4(trans(v,uP),1.);}`; + // no lens: linear light to the screen, with a one-shade dither so dark gradients don't band + const PRESENT = `#version 300 es +precision highp float;in vec2 v;out vec4 o;uniform sampler2D S;uniform float uSeed; +`; + + GL.host = (canvas, opts = {}) => { + const essay = opts.essay, + reduced = opts.reduced || (() => false); + const H = { ok: false, onfail: null }; + H.render = H.resize = H.finish = () => {}; + H.lumaGrid = () => null; + H.pixels = () => null; + H.transitionFor = (type) => (reduced() ? GL.reducedTransition(type) : type); + const gl = GL.context(canvas); + if (!gl) return H; + H.gl = gl; + + const progs = {}, + failed = {}; + const scenesUsed = new Set(essay.scenes.map((s) => s.scene || 'plain')); + const sceneProg = (name) => { + if (progs['s:' + name]) return progs['s:' + name]; + const def = GL.scenes[name]; + let pr = def ? GL.program(gl, SCENE_HEAD + GL.LIB + def.frag + SCENE_MAIN, GL.VS, 'scene ' + name) : null; + if (!pr) { + if (!failed[name]) console.warn('essay: scene "' + name + '" did not build; showing the plain scene'); + failed[name] = true; + if (name !== 'plain') pr = sceneProg('plain'); + } + return (progs['s:' + name] = pr); + }; + const transProg = (type) => { + const k = 't:' + type; + if (progs[k] !== undefined) return progs[k]; + const def = GL.transitions[type] || GL.transitions.crossfade; + return (progs[k] = + GL.program(gl, TRANS_HEAD + GL.LIB + def.frag + TRANS_MAIN, GL.VS, 'transition ' + type) || + (type !== 'crossfade' ? transProg('crossfade') : null)); + }; + const present = GL.program( + gl, + PRESENT + + GL.LIB + + `void main(){vec3 c=toSrgb(texture(S,v).rgb);c+=(h21(gl_FragCoord.xy+uSeed)+h21(gl_FragCoord.xy+uSeed+17.)-1.)/255.;o=vec4(clamp(c,0.,1.),1.);}`, + GL.VS, + 'present' + ); + if (!present || !sceneProg('plain')) return H; + // build every scene and transition the essay uses now, so the first cut doesn't stutter + scenesUsed.forEach(sceneProg); + essay.scenes.forEach((s) => + transProg( + H.transitionFor( + typeof s.transition === 'string' ? s.transition : (s.transition && s.transition.type) || 'crossfade' + ) + ) + ); + + const lens = opts.lens && DHS.lens ? DHS.lens.create(opts.lens, { gl }) : null; + + let W = 0, + Hh = 0, + bufs = []; + const layouts = new Map(); + H.resize = (w, h) => { + if (w === W && h === Hh) return; + W = canvas.width = w; + Hh = canvas.height = h; + bufs.forEach((b) => b.free()); + bufs = [GL.target(gl, w, h), GL.target(gl, w, h), GL.target(gl, w, h)]; + layouts.clear(); + }; + const layoutOf = (i) => { + const k = i + ':' + (W / Hh).toFixed(4); + if (!layouts.has(k)) { + const spec = essay.scenes[i], + def = GL.scenes[spec.scene] || GL.scenes.plain; + layouts.set(k, def.layout(spec.data || {}, W / Hh)); + } + return layouts.get(k); + }; + + // draw scene i with beat progress p (array) at scene time T into target out + const drawScene = (i, p, T, out) => { + const spec = essay.scenes[i], + pr = sceneProg(spec.scene || 'plain'), + L = layoutOf(i), + vars = GL.sceneVars(spec, p); + gl.bindFramebuffer(gl.FRAMEBUFFER, out.f); + gl.viewport(0, 0, W, Hh); + gl.useProgram(pr.p); + const u = pr.u, + P8 = new Float32Array(8); + p.slice(0, 8).forEach((x, j) => (P8[j] = x)); + GL.set(gl, u, 'R', [W, Hh]); + GL.set(gl, u, 'T', T); + GL.set(gl, u, 'uMotion', reduced() ? 0.15 : 1); + GL.set(gl, u, 'uSeed', (DHS.beats ? DHS.beats.hash(spec.id || i) : i) % 1000); + GL.set(gl, u, 'uG', vars.g); + GL.set(gl, u, 'uF', vars.f); + GL.set(gl, u, 'uN', L.n || 0); + if (u.uP != null) gl.uniform1fv(u.uP, P8); + GL.set(gl, u, 'uD', L.d); + gl.drawArrays(gl.TRIANGLES, 0, 3); + }; + const ones = (i) => essay.scenes[i].beats.map(() => 1); + const zeros = (i) => essay.scenes[i].beats.map(() => 0); + const black = (out) => { + gl.bindFramebuffer(gl.FRAMEBUFFER, out.f); + gl.viewport(0, 0, W, Hh); + gl.clearColor(0, 0, 0, 1); + gl.clear(gl.COLOR_BUFFER_BIT); + }; + + H.render = (s) => { + if (!H.ok || !W) return; + GL.tri(gl); + gl.disable(gl.BLEND); + const [A, B, C] = bufs; + let out = C; + const tr = s.trans; + if (tr) { + const type = H.transitionFor(tr.type), + from = tr.from, + to = tr.to; + // the outgoing scene keeps moving (its own clock), shown at its last beat; the incoming one waits at beat 0 + if (from >= 0) drawScene(from, ones(from), tr.fromT, A); + else black(A); + drawScene(to, zeros(to), s.sceneT, B); + const pr = transProg(type); + gl.bindFramebuffer(gl.FRAMEBUFFER, C.f); + gl.viewport(0, 0, W, Hh); + gl.useProgram(pr.p); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, A.t); + gl.uniform1i(pr.u.SA, 0); + gl.activeTexture(gl.TEXTURE1); + gl.bindTexture(gl.TEXTURE_2D, B.t); + gl.uniform1i(pr.u.SB, 1); + GL.set(gl, pr.u, 'R', [W, Hh]); + GL.set(gl, pr.u, 'uP', tr.p); + GL.set(gl, pr.u, 'uSeed', to * 7.31); + gl.drawArrays(gl.TRIANGLES, 0, 3); + } else drawScene(s.scene, s.p, s.sceneT, C); + + if (lens && lens.ok) lens.drawTexture(out.t, W, Hh, s.t); + else { + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + gl.viewport(0, 0, W, Hh); + gl.useProgram(present.p); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, out.t); + gl.uniform1i(present.u.S, 0); + GL.set(gl, present.u, 'uSeed', reduced() ? 0 : (Math.floor(s.t * 24) % 61) * 1.37); + GL.tri(gl); + gl.drawArrays(gl.TRIANGLES, 0, 3); + } + }; + H.finish = () => gl.finish(); + H.pixels = () => { + if (!W) return null; + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + const data = new Uint8Array(W * Hh * 4); + gl.readPixels(0, 0, W, Hh, gl.RGBA, gl.UNSIGNED_BYTE, data); + return { w: W, h: Hh, data }; + }; + H.lumaGrid = (cols = 16, rows = 9) => { + const px = H.pixels(); + if (!px) return null; + const sum = new Float64Array(cols * rows), + cnt = new Float64Array(cols * rows), + lut = new Float64Array(256); + for (let i = 0; i < 256; i++) lut[i] = GL.relLum(i, 0, 0) / 0.2126; + for (let y = 0; y < px.h; y++) + for (let x = 0; x < px.w; x++) { + const k = (y * px.w + x) * 4, + c = + Math.min(cols - 1, Math.floor((x / px.w) * cols)) + + cols * Math.min(rows - 1, Math.floor(((px.h - 1 - y) / px.h) * rows)); + sum[c] += 0.2126 * lut[px.data[k]] + 0.7152 * lut[px.data[k + 1]] + 0.0722 * lut[px.data[k + 2]]; + cnt[c]++; + } + return Array.from(sum, (s, i) => s / Math.max(1, cnt[i])); + }; + H.labels = (s, aspect) => (GL.sceneLabels ? GL.sceneLabels(essay.scenes[s.scene], s.p, aspect) : []); + canvas.addEventListener('webglcontextlost', (e) => { + e.preventDefault(); + H.ok = false; + if (H.onfail) H.onfail(); + }); + H.ok = true; + return H; + }; +})(globalThis); diff --git a/engine/src/gl/scenes.js b/engine/src/gl/scenes.js new file mode 100644 index 0000000..0bb840c --- /dev/null +++ b/engine/src/gl/scenes.js @@ -0,0 +1,222 @@ +/* SCENES: shader scene cartridges for the essay picture. Each scene is one fragment shader over the whole screen + that writes linear light, plus plain-JS layout so the words layer can put labels exactly where the shapes are + (and still show them, with every number, when there is no WebGL2). + + A cartridge: + frag GLSL defining vec3 scene(vec2 p) with p in screen units: y from -0.5 (bottom) to 0.5 (top), x from + -aspect/2 to aspect/2. It can use DHS.gl.LIB and these uniforms: + R (pixels), T (seconds into the scene), uMotion (1, or 0.15 under prefers-reduced-motion), + uP[8] (each beat's eased progress), uG (progress of the beat that grows the data: data.grow, + default 0), uF (x: the index brought forward, y: how far), uD[16] (vec4 data from layout), uN + layout(data, aspect) -> { d: Float32Array(64), n } pure: the same data always gives the same shapes + labels(data, L, v, aspect) -> [{ x, y, text, kind, align, alpha }] in the same units as p + + Honest charts: bars start at zero and their height is linear in the value; areas are proportional to the value + (radius goes with the square root). Each data scene shows data.note (e.g. "Made-up placeholder numbers") in its + corner when the essay gives one. + + Scenes here: field (quiet backdrop for titles and quotes), bars, tally (one dot per unit), areas (circles). + Standalone: needs only the DHS namespace (DHS.gl.LIB at draw time). */ +(function (G) { + 'use strict'; + const DHS = (G.DHS = G.DHS || {}); + const GL = (DHS.gl = DHS.gl || {}); + const S = (GL.scenes = GL.scenes || {}); + const fmt = (data, v) => (data.format ? data.format(v) : String(v)); + const note = (data, aspect) => + data.note ? [{ x: aspect / 2 - 0.04, y: -0.44, text: data.note, kind: 'note', align: 'right', alpha: 1 }] : []; + const ease = (x) => 1 - (1 - Math.min(1, Math.max(0, x))) ** 3; + // stagger: item i of n starts at i/(n-1) * spread of the grow beat; GLSL twin is stag() below + const stag = (g, i, n, spread = 0.35) => ease((g - (n > 1 ? (i / (n - 1)) * spread : 0)) / (1 - spread)); + const STAG = `float stag(float g,float i,float n){float sp=.35;float s=n>1.?i/(n-1.)*sp:0.;float x=clamp((g-s)/(1.-sp),0.,1.);return 1.-pow(1.-x,3.);} +float bevel(float d,float w){return clamp(-d/w,0.,1.);} +vec3 bevelN(float d,float w){vec2 g=vec2(dFdx(d),dFdy(d));float l=length(g);g=l>0.?g/l:vec2(0);float t=bevel(d,w);return normalize(vec3(g*(1.-t)*1.4,.35+t));} +vec3 backdrop(vec2 p,vec3 tint){vec2 q=p-vec2(-.15,.22);float pool=exp(-dot(q,q)*2.6); + return vec3(.006,.006,.007)+tint*(.022*pool+.006*(.5-p.y));} +`; + + // quiet backdrop: slow haze and a few motes drifting up; data: { tint: [r,g,b], drift } + S.field = { + frag: + STAG + + `vec3 scene(vec2 p){vec3 tint=uD[0].xyz;float drift=uD[0].w; + float t=T*uMotion*drift; + vec3 c=backdrop(p,tint); + float h=fbm(p*1.4+vec2(t*.03,-t*.012),5); + c+=tint*.03*smoothstep(.35,.9,h)*(1.-smoothstep(-.1,.6,abs(p.y+.05))); + for(int L=0;L<2;L++){float sc=6.+float(L)*5.;vec2 g=p*sc+vec2(0.,-t*(.25+.15*float(L)));vec2 id=floor(g);vec2 r=h22(id+float(L)*31.); + if(r.x>.84){vec2 c2=id+.2+.6*h22(id+7.);float d=length(g-c2)/sc;c+=tint*.22*(.4+.6*r.y)*exp(-d*d*2.6e4/(1.+float(L)));}} + return c;}`, + layout: (data) => { + const d = new Float32Array(64), + t = data.tint || [0.9, 0.87, 0.82]; + d.set([t[0], t[1], t[2], data.drift != null ? data.drift : 1], 0); + return { d, n: 0 }; + }, + labels: () => [], + }; + + // bars from zero; data: { values, labels, max (top of the scale; default the largest value), grow, note, format } + S.bars = { + frag: + STAG + + `vec4 bar(vec2 p,int i,out vec3 n){vec4 b=uD[1+i];float base=uD[0].x,H=uD[0].y,hw=uD[0].z; + float g=stag(uG,float(i),uN),h=H*b.y*g;n=vec3(0,0,1);if(h<=0.)return vec4(0); + vec2 cc=vec2(b.x,base+h*.5);float r=min(.006,h*.5);float d=sdRoundBox(p-cc,vec2(hw,h*.5),r); + n=bevelN(d,.012);return vec4(d,g,h,0);} +vec3 scene(vec2 p){vec3 c=backdrop(p,vec3(1.,.95,.88));float base=uD[0].x,px=1.4/R.y; + float w=uD[0].w;c+=vec3(.16)*aa(abs(p.y-base)-.5/R.y,px)*step(abs(p.x),w)*clamp(uP[0]*3.+uG*3.,0.,1.); + for(int i=0;i<8;i++){if(float(i)>=uN)break; + bool foc=int(uF.x+.5)==i;float dim=uF.x<0.?1.:foc?1.+.25*uF.y:1.-.6*uF.y; + vec3 base3=mix(vec3(.30,.29,.27),vec3(.55,.42,.28),foc?uF.y:0.)*dim; + vec3 n;vec4 b=bar(p,i,n); + if(b.z>0.){float cov=aa(b.x,px);c=mix(c,studio(n,base3)*mix(.8,1.,dim),cov);} + vec3 n2;vec4 m=bar(vec2(p.x,2.*base-p.y),i,n2); + if(m.z>0.&&p.y { + const g = stag(v.g, i, L.n), + h = (L.H * Math.max(0, data.values[i])) / L.max; + const dim = v.f[0] < 0 ? 1 : v.f[0] === i ? 1 : 1 - 0.45 * v.f[1]; + out.push({ + x, + y: L.base + h * g + 0.035, + text: fmt(data, data.values[i]), + kind: 'value', + align: 'center', + alpha: Math.min(1, Math.max(0, (g - 0.85) / 0.15)) * dim, + }); + if (data.labels && data.labels[i] != null) + out.push({ + x, + y: L.base - 0.045, + text: data.labels[i], + kind: 'category', + align: 'center', + alpha: Math.min(1, v.g * 4) * dim, + }); + }); + return out.concat(note(data, aspect)); + }, + }; + + // one dot per unit, filling row by row at a steady pace; data: { count, cols, grow, note } + S.tally = { + frag: + STAG + + `vec3 scene(vec2 p){vec3 c=backdrop(p,vec3(.95,.92,.86));float N=uD[0].x,cols=uD[0].y,s=uD[0].z,rows=uD[1].z; + vec2 q=(p-uD[1].xy)/s;q.y=-q.y;vec2 id=floor(q); + if(id.x>=0.&&id.x=0.&&id.y note(data, aspect), + }; + + // circles with area proportional to value, side by side on one line; data: { values, labels, grow, note, format } + S.areas = { + frag: + STAG + + `vec3 scene(vec2 p){vec3 c=backdrop(p,vec3(.9,.92,1.));float px=1.4/R.y,base=uD[0].x; + for(int i=0;i<6;i++){if(float(i)>=uN)break;vec4 b=uD[1+i]; + float g=stag(uG,float(i),uN),r=b.z*sqrt(g);if(r<=0.)continue; + float d=sdCircle(p-vec2(b.x,base+b.z),r); + vec3 n=bevelN(d,.01);c=mix(c,studio(n,vec3(.26,.28,.31)),aa(d,px));} + return c;}`, + layout(data, aspect) { + const v = (data.values || []).slice(0, 6), + n = v.length, + vmax = Math.max(...v, 1e-9), + gap = 0.07; + let R = 0.22; + let rs = v.map((x) => R * Math.sqrt(Math.max(0, x) / vmax)); + const total = rs.reduce((a, r) => a + 2 * r, 0) + gap * (n - 1), + fit = aspect * 0.82; + if (total > fit) rs = rs.map((r) => (r * (fit - gap * (n - 1))) / (total - gap * (n - 1))); + const width = rs.reduce((a, r) => a + 2 * r, 0) + gap * (n - 1); + const base = -0.24, + d = new Float32Array(64), + xs = []; + d.set([base, 0, 0, 0], 0); + let x = -width / 2; + rs.forEach((r, i) => { + xs.push(x + r); + d.set([x + r, 0, r, 0], 4 * (1 + i)); + x += 2 * r + gap; + }); + return { d, n, xs, rs, base }; + }, + labels(data, L, v, aspect) { + const out = []; + L.xs.forEach((x, i) => { + const g = stag(v.g, i, L.n); + const name = data.labels && data.labels[i] != null ? data.labels[i] + ': ' : ''; + out.push({ + x, + y: L.base - 0.05, + text: name + fmt(data, data.values[i]), + kind: 'category', + align: 'center', + alpha: Math.min(1, Math.max(0, (g - 0.6) / 0.4)), + }); + }); + return out.concat(note(data, aspect)); + }, + }; + + // shown when a scene's shader won't build (or its name is unknown): a dark backdrop, labels still drawn + S.plain = { + frag: STAG + 'vec3 scene(vec2 p){return backdrop(p,vec3(1.));}', + layout: () => ({ d: new Float32Array(64), n: 0 }), + labels: (data, L, v, a) => note(data, a), + }; + + // the values every scene reads from the beat state: g = the grow beat's progress, f = [index forward, progress] + GL.sceneVars = (spec, p) => { + const data = spec.data || {}; + let f = [-1, 0]; + (spec.beats || []).forEach((b, j) => { + if (b.focus != null && (p[j] || 0) > 0) f = [b.focus, p[j]]; + }); + return { g: p[data.grow || 0] || 0, f }; + }; + // labels for a scene spec at this beat state (no GL needed) + GL.sceneLabels = (spec, p, aspect) => { + const def = S[spec.scene] || S.plain, + data = spec.data || {}; + return def.labels(data, def.layout(data, aspect), GL.sceneVars(spec, p), aspect); + }; +})(globalThis); From 399886ff9049cbfd075a258d1be27073eae86071 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 17:08:43 +0000 Subject: [PATCH 05/13] Essay engine stage 5: transition set (cut, crossfade, dip, wipe, dissolve, push; reduced motion -> crossfade) and a 3-flashes-a-second check (E.flashCheck, DHS.essay.flashCount); worst case white<->black: 0 flashes/s Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Ad4FSZyShDwuPQbAcgGJY3 --- engine/src/essay/player.js | 51 ++++++++++++++++++++++++++++++++++- engine/src/gl/transitions.js | 52 ++++++++++++++++++++++++++++++++++++ 2 files changed, 102 insertions(+), 1 deletion(-) create mode 100644 engine/src/gl/transitions.js diff --git a/engine/src/essay/player.js b/engine/src/essay/player.js index f9705b2..d8e5f08 100644 --- a/engine/src/essay/player.js +++ b/engine/src/essay/player.js @@ -97,6 +97,37 @@ }; } + // series: one array of cell luminances (0..1) per frame at `fps`. A change is a swing of at least 0.1 from the last + // turning point with the darker side under 0.8; a flash is a pair of opposing changes (WCAG 2.3.1). + // Returns the most flashes in any one second in any cell, and the biggest frame-to-frame step. + function flashCount(series, fps = 60) { + let maxPerSecond = 0, + maxStep = 0; + const cells = series.length ? series[0].length : 0; + for (let c = 0; c < cells; c++) { + const changes = []; + let ext = series[0][c], + dir = 0; + for (let f = 1; f < series.length; f++) { + const v = series[f][c]; + maxStep = Math.max(maxStep, Math.abs(v - series[f - 1][c])); + if ((dir > 0 && v > ext) || (dir < 0 && v < ext)) + ext = v; // still moving the same way + else if (Math.abs(v - ext) >= 0.1 && Math.min(v, ext) < 0.8) { + changes.push(f); + dir = v > ext ? 1 : -1; + ext = v; + } + } + for (let a = 0; a < changes.length; a++) { + let b = a; + while (b + 1 < changes.length && changes[b + 1] - changes[a] < fps) b++; + maxPerSecond = Math.max(maxPerSecond, Math.floor((b - a + 1) / 2)); + } + } + return { maxPerSecond, maxStep }; + } + function mount(essay, opts = {}) { const B = DHS.beats; const root = el('div', 'eo-root', opts.root || doc.body); @@ -518,6 +549,24 @@ host.finish(); return (G.performance.now() - t0) / n; }, + // the 3-flashes-a-second rule (WCAG 2.3.1) for the transition into `scene`: the picture is stepped at 60 fps + // from 0.5 s before to 0.5 s after; in each cell of a 16 x 9 grid, a change is a swing in relative luminance + // of at least 0.1 with the darker side under 0.8, and a flash is two opposing changes + flashCheck(scene, cols = 16, rows = 9) { + if (!host || !host.ok) return null; + const Sc = TL.scenes[TL.sceneIndex(scene)], + t0 = Math.max(0, Sc.start - 0.5), + t1 = Math.min(TL.total, Sc.body + 0.5), + n = Math.round((t1 - t0) * 60); + const series = []; + for (let f = 0; f <= n; f++) { + host.render(TL.at(t0 + f / 60, { reduced: reduced() })); + series.push(host.lumaGrid(cols, rows)); + } + const { maxPerSecond, maxStep } = flashCount(series); + draw(); + return { maxPerSecond, maxStep, frames: series.length, pass: maxPerSecond <= 3 }; + }, state() { const s = S(); return { @@ -551,5 +600,5 @@ return E; } - DHS.essay = { mount }; + DHS.essay = { mount, flashCount }; })(globalThis); diff --git a/engine/src/gl/transitions.js b/engine/src/gl/transitions.js new file mode 100644 index 0000000..c3448bb --- /dev/null +++ b/engine/src/gl/transitions.js @@ -0,0 +1,52 @@ +/* TRANSITIONS: how one essay scene gives way to the next. Each is a shader + vec3 trans(vec2 uv, float p) uv 0..1 on screen, p 0..1 through the transition + reading the outgoing picture with A(uv) and the incoming one with B(uv) (both linear light), plus R (pixels). + Every one changes each part of the screen in one direction only, or (dip) down once and up once over 2 s, so none + comes near the 3-flashes-a-second limit; the essay QA tool measures it anyway (engine/tools/essay-qa.js). + Quiet ones first: a solemn essay mostly wants cut, crossfade and dip. + + cut instant (no shader) + crossfade slow mix in linear light (no muddy dip in the middle) + dip fade to black, a breath of black, fade up + wipe a soft edge crossing the screen at a slight angle + dissolve cells change one by one, each once, in a seeded order + push the new scene slides in and moves the old one out, the old one dimming + + Under prefers-reduced-motion, wipe, dissolve and push become a crossfade (DHS.gl.reducedTransition). + Standalone: needs only the DHS namespace. */ +(function (G) { + 'use strict'; + const DHS = (G.DHS = G.DHS || {}); + const GL = (DHS.gl = DHS.gl || {}); + const SM = 'float sm(float a,float b,float x){return smoothstep(a,b,x);}float ease(float x){return x*x*(3.-2.*x);}\n'; + GL.transitions = { + cut: { dur: 0, frag: 'vec3 trans(vec2 uv,float p){return p<1.?A(uv):B(uv);}' }, + crossfade: { dur: 2, frag: SM + 'vec3 trans(vec2 uv,float p){return mix(A(uv),B(uv),ease(p));}' }, + dip: { + dur: 2, + frag: SM + 'vec3 trans(vec2 uv,float p){return A(uv)*(1.-ease(sm(0.,.45,p)))+B(uv)*ease(sm(.55,1.,p));}', + }, + wipe: { + dur: 1.8, + frag: + SM + + `vec3 trans(vec2 uv,float p){float a=R.x/R.y,x=uv.x*a+(uv.y-.5)*.18;float e=mix(-.25,a+.25,ease(p)); + float m=sm(e-.12,e+.12,x);return mix(B(uv),A(uv),m);}`, + }, + dissolve: { + dur: 2.2, + frag: + SM + + `vec3 trans(vec2 uv,float p){vec2 c=floor(uv*R/max(8.,R.y/36.));float r=h21(c+uSeed)*.8; + return mix(A(uv),B(uv),ease(sm(r,r+.2,p)));}`, + }, + push: { + dur: 1.6, + frag: + SM + + `vec3 trans(vec2 uv,float p){float e=ease(ease(p));float x=uv.x+e; + if(x<1.)return A(vec2(x,uv.y))*(1.-.6*e);return B(vec2(x-1.,uv.y));}`, + }, + }; + GL.reducedTransition = (type) => (type === 'cut' || type === 'dip' ? type : 'crossfade'); +})(globalThis); From 1524dbe4cf8ef4b63b6208606958904c30a4467d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 17:16:16 +0000 Subject: [PATCH 06/13] Essay engine stage 6: HTML text over the picture (engine/src/essay/text.js): named positions, soft dark patch, word-by-word fade, data labels, reduced motion; WCAG check per paragraph with opacity and patch composited (E.contrast); fixes: last scene's words, perf timing, stills hide the controls Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Ad4FSZyShDwuPQbAcgGJY3 --- engine/essay-demo/essay.js | 8 +- engine/src/essay/player.js | 11 +- engine/src/essay/text.js | 347 +++++++++++++++++++++++++++++++++++++ engine/src/gl/host.js | 5 +- engine/src/gl/scenes.js | 14 +- 5 files changed, 373 insertions(+), 12 deletions(-) create mode 100644 engine/src/essay/text.js diff --git a/engine/essay-demo/essay.js b/engine/essay-demo/essay.js index b96215d..9f65305 100644 --- a/engine/essay-demo/essay.js +++ b/engine/essay-demo/essay.js @@ -28,10 +28,10 @@ const ESSAY = { }, { id: 'tally', chapter: 'Part one', scene: 'tally', - data: { count: 640, cols: 40, grow: 1, note: 'Made-up placeholder count: one dot is one unit' }, + data: { count: 640, cols: 40, grow: 1, box: [0.4, 0.3, 0.94, 0.76], note: 'Made-up placeholder count: one dot is one unit' }, transition: { type: 'wipe', dur: 1.8 }, beats: [ - { dur: 1.2, text: [{ pos: 'bottom-left', kind: 'number', text: '640' }, { pos: 'bottom-left-sub', kind: 'body', text: 'A made-up count, one dot for each unit.' }] }, + { dur: 1.2, text: [{ pos: 'bottom-left', kind: 'number', text: '640' }, { pos: 'bottom-left', kind: 'body', text: 'A made-up count, one dot for each unit.' }] }, { dur: 6, ease: 'linear', text: [{ pos: 'top-right', kind: 'body', text: 'The dots arrive slowly, at a steady pace, so the number has time to register.' }] }, ], }, @@ -41,14 +41,14 @@ const ESSAY = { transition: { type: 'dissolve', dur: 2.4 }, beats: [ { dur: 2.6, text: [{ pos: 'top-left', kind: 'headline', text: 'Areas, not widths' }] }, - { dur: 1.4, text: [{ pos: 'lower-third', kind: 'body', text: 'A circle with four times the value has four times the area, so it is twice as wide, not four times.' }] }, + { dur: 1.4, text: [{ pos: 'top-left', kind: 'body', text: 'A circle with four times the value has four times the area, so it is twice as wide, not four times.' }] }, ], }, { id: 'quote', chapter: 'Part two', scene: 'field', data: { tint: [0.75, 0.8, 0.9], drift: 0.4 }, transition: { type: 'push', dur: 2 }, beats: [ - { dur: 2, text: [{ pos: 'quote', kind: 'quote', text: '“A placeholder quotation sits here, set apart from the running text, with room around it.”' }, { pos: 'quote-source', kind: 'source', text: 'Placeholder source, placeholder date' }] }, + { dur: 2, text: [{ pos: 'quote', kind: 'quote', text: '“A placeholder quotation sits here, set apart from the running text, with room around it.”' }, { pos: 'quote', kind: 'source', text: 'Placeholder source, placeholder date' }] }, ], }, { diff --git a/engine/src/essay/player.js b/engine/src/essay/player.js index d8e5f08..41a1f2c 100644 --- a/engine/src/essay/player.js +++ b/engine/src/essay/player.js @@ -153,6 +153,7 @@ // ---- words const textRoot = el('div', 'eo-textroot', root); textRoot.style.cssText = 'position:absolute;inset:0;pointer-events:none'; + textRoot.setAttribute('aria-hidden', 'true'); const text = DHS.essayText ? DHS.essayText.create(textRoot, TL, essay, { reduced, host }) : plainText(textRoot, TL, essay); @@ -216,7 +217,7 @@ `Press ? for keys`; if (manual) { start.hidden = true; - root.classList.add('eo-on'); + root.classList.add('eo-on', 'eo-idle'); // stills: no controls until the mouse moves } // ---- state @@ -502,6 +503,7 @@ } if (!fromHash()) jump(0); setPlaying(true); + if (!note.hidden) G.setTimeout(() => (note.hidden = true), 8000); // said once; then out of the words' way fullscreen(); wake(); }; @@ -545,8 +547,10 @@ E.seek(scene, 1e9, 'shown'); const s = S(); const t0 = G.performance.now(); - for (let f = 0; f < n; f++) host.render(Object.assign({}, s, { t: s.t + f / 60 }), true); - host.finish(); + for (let f = 0; f < n; f++) { + host.render(Object.assign({}, s, { sceneT: s.sceneT + f / 60, t: s.t + f / 60 })); + host.finish(); // wait for the GPU each frame (reads one pixel: finish alone may not wait) + } return (G.performance.now() - t0) / n; }, // the 3-flashes-a-second rule (WCAG 2.3.1) for the transition into `scene`: the picture is stepped at 60 fps @@ -581,6 +585,7 @@ }; }, textBoxes: () => text.boxes(), + contrast: () => (text.contrast ? text.contrast() : []), hideGlyphs: (on) => { text.hideGlyphs(on); }, diff --git a/engine/src/essay/text.js b/engine/src/essay/text.js new file mode 100644 index 0000000..94b9042 --- /dev/null +++ b/engine/src/essay/text.js @@ -0,0 +1,347 @@ +/* ESSAY TEXT: the words over the picture, in HTML (sharp at any size, selectable by screen readers through the + player's live region, and still there without WebGL2). A beat's text is a list of blocks: + { pos, kind, text } + pos center, chapter, quote (these three share the middle), lower-third, top-left, top-right, bottom-left, + bottom-right. Several blocks of one beat at one position stack (a big number and its caption). + kind body, headline, chapter, quote, source, number, note + The text is shown exactly as written; only its timing comes from it. + + Timing (a pure function of t, so seeks and stills match playback): + - a beat's blocks at one position arrive word by word when the beat arrives (each word fades in over 0.6 s, + about 0.09 s apart; a number arrives whole); + - they stay until a later beat puts text at the same position (then they fade out over 0.5 s while the new + text fades in), or until the scene ends (they fade out in the first 40% of the next transition); + - prefers-reduced-motion: each group fades in whole over 0.3 s, nothing moves. + Behind each group is a soft dark patch (a dark rounded box with soft edges, no glow) so the words hold on any picture. + Data labels from the scene (DHS.gl.sceneLabels: values, categories, the placeholder note) are drawn here too. + + const X = DHS.essayText.create(root, timeline, essay, { reduced, host }); + X.render(state); X.resize(w, h); X.boxes(); X.hideGlyphs(on); + X.contrast() -> [{ key, text, kind, ratio, need, against, pass }] WCAG contrast of each visible group against + the brightest and darkest picture pixels under it, with the patch composited in + Restyle with CSS variables on the player root: --eo-ink, --eo-font, --eo-display, --eo-serif, --eo-patch. */ +(function (G) { + 'use strict'; + const DHS = (G.DHS = G.DHS || {}); + const doc = G.document; + + const SLOT = { center: 'middle', chapter: 'middle', quote: 'middle' }; + const PATCH = { + body: 0.55, + headline: 0.5, + chapter: 0.42, + quote: 0.5, + source: 0.55, + number: 0.45, + note: 0.55, + label: 0.5, + }; + const CSS = ` +.eo-text{position:absolute;inset:0;pointer-events:none;color:var(--eo-ink,#f3f0e8);--m:max(5vw,env(safe-area-inset-left));--mt:max(8vh,env(safe-area-inset-top));--mb:calc(max(8vh,env(safe-area-inset-bottom)) + 44px)} +.eo-pos{position:absolute;display:grid} +.eo-pos>.eo-g{grid-area:1/1;position:relative;padding:.9em 1.3em} +.eo-g>.eo-patch{position:absolute;inset:0;z-index:-1;border-radius:1.4em;background:rgba(0,0,0,var(--a));box-shadow:0 0 2.6em 1.2em rgba(0,0,0,var(--a))} +.eo-pos{z-index:0;isolation:isolate} +.eo-p-middle{left:50%;top:50%;transform:translate(-50%,-50%);width:min(30em,84vw);text-align:center} +.eo-g.eo-gp-quote{text-align:left} +.eo-p-lower-third{left:var(--m);right:var(--m);bottom:var(--mb);max-width:40em} +.eo-p-top-left{left:var(--m);top:var(--mt);width:min(28em,52vw)} +.eo-p-top-right{right:var(--m);top:var(--mt);width:min(28em,52vw)} +.eo-p-bottom-left{left:var(--m);bottom:var(--mb);width:min(28em,52vw)} +.eo-p-bottom-right{right:var(--m);bottom:var(--mb);width:min(28em,52vw);text-align:right} +.eo-b{margin:0}.eo-b+.eo-b{margin-top:.5em} +.eo-k-body{font-size:var(--eo-body,clamp(18px,1.1vw + 1.1vmin,34px));line-height:1.42;font-weight:400} +.eo-k-headline{font-family:var(--eo-display,inherit);font-size:clamp(26px,2vw + 2vmin,60px);line-height:1.12;font-weight:600;letter-spacing:-.01em} +.eo-k-chapter{font-family:var(--eo-display,inherit);font-size:clamp(30px,2.6vw + 2.4vmin,76px);line-height:1.1;font-weight:500;letter-spacing:.01em} +.eo-k-quote{font-family:var(--eo-serif,Georgia,"Times New Roman",serif);font-style:italic;font-size:clamp(22px,1.5vw + 1.5vmin,44px);line-height:1.35} +.eo-k-source{font-size:clamp(14px,.6vw + .8vmin,20px);line-height:1.4;opacity:.92} +.eo-k-number{font-family:var(--eo-display,inherit);font-size:clamp(44px,5vw + 4vmin,150px);line-height:1;font-weight:600;font-variant-numeric:tabular-nums;letter-spacing:-.02em} +.eo-w{display:inline-block;will-change:opacity} +.eo-hide .eo-w,.eo-hide .eo-lb{color:transparent!important} +.eo-lb{position:absolute;left:0;top:0;white-space:nowrap;font-size:clamp(13px,.5vw + .9vmin,22px);font-variant-numeric:tabular-nums;padding:.25em .6em; + border-radius:.8em; + background:rgba(0,0,0,${PATCH.label});box-shadow:0 0 .9em .4em rgba(0,0,0,${PATCH.label})} +.eo-lb.eo-k-value{font-weight:600;font-size:clamp(15px,.7vw + 1vmin,26px)} +.eo-lb.eo-k-note{font-size:clamp(12px,.4vw + .8vmin,17px);opacity:.95} +@media (max-width:700px){.eo-p-top-left,.eo-p-top-right,.eo-p-bottom-left,.eo-p-bottom-right{width:auto;left:var(--m);right:var(--m)}} +`; + + const el = (tag, cls, parent) => { + const e = doc.createElement(tag); + if (cls) e.className = cls; + if (parent) parent.appendChild(e); + return e; + }; + const clamp01 = (x) => (x < 0 ? 0 : x > 1 ? 1 : x); + const smooth = (x) => ((x = clamp01(x)), x * x * (3 - 2 * x)); + + function create(root, TL, essay, opts = {}) { + const reduced = opts.reduced || (() => false), + host = opts.host; + if (!doc.getElementById('eo-text-css')) { + const st = el('style', '', doc.head); + st.id = 'eo-text-css'; + st.textContent = CSS; + } + const layer = el('div', 'eo-text', root); + layer.setAttribute('aria-hidden', 'true'); // the player's live region reads the words once + let W = 1, + H = 1; + + // build every scene's groups once + const scenes = essay.scenes.map((spec, i) => { + const S = TL.scenes[i], + box = el('div', '', layer); + box.style.display = 'none'; + const posEls = {}, + groups = []; + (spec.beats || []).forEach((b, j) => { + const byPos = {}; + (b.text || []).forEach((x) => { + const blk = typeof x === 'string' ? { text: x } : x; + const pos = blk.pos || 'lower-third'; + (byPos[pos] = byPos[pos] || []).push(blk); + }); + Object.keys(byPos).forEach((pos) => { + // center, chapter and quote share the middle of the screen: a later one there replaces an earlier one + const slot = SLOT[pos] || pos; + if (!posEls[slot]) posEls[slot] = el('div', 'eo-pos eo-p-' + slot, box); + const g = el('div', 'eo-g eo-gp-' + pos, posEls[slot]), + patch = el('div', 'eo-patch', g); + const kind0 = byPos[pos][0].kind || 'body'; + const alpha = Math.max(...byPos[pos].map((x) => PATCH[x.kind || 'body'] || 0.5)); + patch.style.setProperty('--a', String(alpha)); + const words = [], + blocks = []; + byPos[pos].forEach((blk) => { + const kind = blk.kind || 'body', + p = el('p', 'eo-b eo-k-' + kind, g), + bw = []; + blocks.push({ kind, text: String(blk.text), words: bw }); + // exact text: words become spans, the whitespace between them is kept as it was + String(blk.text) + .split(/(\s+)/) + .forEach((part) => { + if (!part) return; + if (/^\s+$/.test(part)) return p.appendChild(doc.createTextNode(part)); + const w = el('span', 'eo-w', p); + w.textContent = part; + words.push({ el: w, whole: kind === 'number', last: '' }); + bw.push(w); + }); + }); + groups.push({ + pos: slot, + beat: j, + g, + patch, + words, + blocks, + alpha, + kind: kind0, + text: byPos[pos].map((x) => x.text).join(' '), + start: S.beats[j].arrive, + out: null, + last: '', + }); + }); + }); + // when each group leaves: the next group at the same position, or the next scene's transition + const nextS = TL.scenes[i + 1]; + groups.forEach((gr, k) => { + const later = groups.slice(k + 1).find((x) => x.pos === gr.pos && x.beat > gr.beat); + if (later) gr.out = [later.start, later.start + 0.5]; + else if (nextS) + gr.out = + nextS.trans.dur > 0 + ? [nextS.start, nextS.start + 0.4 * nextS.trans.dur] + : [nextS.start - 1e-6, nextS.start]; + else gr.out = null; // the last scene's words stay to the end + }); + return { box, groups, labels: [], lbBox: el('div', '', box) }; + }); + + const setOp = (o, e, v) => { + const s = v.toFixed(3); + if (o.last !== s) { + e.style.opacity = s; + o.last = s; + } + }; + const groupOp = (gr, t) => { + const red = reduced(); + if (t < gr.start) return 0; + const inn = red ? clamp01((t - gr.start) / 0.3) : 1; + return gr.out ? inn * (1 - smooth((t - gr.out[0]) / Math.max(1e-6, gr.out[1] - gr.out[0]))) : inn; + }; + const drawScene = (i, t, s, labelFade, p) => { + const sc = scenes[i], + red = reduced(); + sc.box.style.display = ''; + sc.groups.forEach((gr) => { + const op = groupOp(gr, t); + setOp(gr, gr.g, op); + gr.g.style.visibility = op > 0 ? 'visible' : 'hidden'; + const n = gr.words.length, + stag = red ? 0 : Math.min(0.09, 2.2 / Math.max(1, n)); + gr.words.forEach((w, k) => setOp(w, w.el, red ? 1 : clamp01((t - gr.start - (w.whole ? 0 : k * stag)) / 0.6))); + }); + // data labels + const spec = essay.scenes[i]; + const L = DHS.gl && DHS.gl.sceneLabels ? DHS.gl.sceneLabels(spec, p, W / H) : []; + while (sc.labels.length < L.length) + sc.labels.push({ el: el('div', 'eo-lb', sc.lbBox), last: '', txt: null, pos: '' }); + sc.labels.forEach((lb, k) => { + const d = L[k]; + if (!d) return (lb.el.style.display = 'none'); + lb.el.style.display = ''; + if (lb.txt !== d.text) lb.el.textContent = lb.txt = d.text; + lb.el.className = 'eo-lb eo-k-' + d.kind; + const x = (d.x / (W / H) + 0.5) * W, + y = (0.5 - d.y) * H, + ax = d.align === 'right' ? '-100%' : d.align === 'left' ? '0' : '-50%'; + const pos = `translate(${x.toFixed(1)}px,${y.toFixed(1)}px) translate(${ax},-50%)`; + if (lb.pos !== pos) lb.el.style.transform = lb.pos = pos; + lb.data = d; + setOp(lb, lb.el, d.alpha * labelFade); + }); + }; + let shown = new Set(); + const X = { + render(s) { + const now = new Set([s.scene]); + if (s.trans && s.trans.from >= 0) now.add(s.trans.from); + shown.forEach((i) => !now.has(i) && (scenes[i].box.style.display = 'none')); + shown = now; + if (s.trans && s.trans.from >= 0) { + const f = s.trans.from; + drawScene( + f, + s.t, + s, + 1 - smooth(s.trans.p / 0.4), + TL.scenes[f].beats.map(() => 1) + ); + } + drawScene(s.scene, s.t, s, s.trans ? smooth((s.trans.p - 0.6) / 0.4) : 1, s.p); + }, + resize(w, h) { + W = Math.max(1, w); + H = Math.max(1, h); + }, + hideGlyphs(on) { + layer.classList.toggle('eo-hide', !!on); + }, + // visible groups and labels with their screen rectangles (CSS pixels) + boxes() { + const out = []; + shown.forEach((i) => { + scenes[i].groups.forEach((gr) => { + if (+gr.last > 0.5) { + const pr = gr.patch.getBoundingClientRect(); + // one entry per paragraph: a big number and its small caption need different ratios + gr.blocks.forEach((b, n) => { + if (!b.words.length) return; + const wr = b.words.map((w) => w.getBoundingClientRect()); + out.push({ + key: i + ':' + gr.beat + ':' + gr.pos + ':' + n, + text: b.text, + kind: b.kind, + rect: b.words[0].parentNode.getBoundingClientRect(), + patch: pr, + alpha: gr.alpha * +gr.last, + words: wr, + el: b.words[0], + }); + }); + } + }); + scenes[i].labels.forEach((lb, k) => { + if (lb.el.style.display !== 'none' && +lb.last > 0.5) { + const r = lb.el.getBoundingClientRect(); + out.push({ + key: i + ':label:' + k, + text: lb.txt, + kind: lb.data.kind, + rect: r, + patch: r, + alpha: PATCH.label * +lb.last, + words: [r], + el: lb.el, + }); + } + }); + }); + return out; + }, + contrast() { + const px = host && host.ok ? host.pixels() : null; + const rootR = layer.getBoundingClientRect(); + const sx = px ? px.w / rootR.width : 1, + sy = px ? px.h / rootR.height : 1; + const lum = DHS.gl.relLum, + con = DHS.gl.contrast; + // with no picture (no WebGL2), the fallback background's lightest colour + const fallback = [0x1b, 0x1c, 0x22]; + return X.boxes().map((b) => { + const cs = G.getComputedStyle(b.el), + ink = cs.color.match(/[\d.]+/g).map(Number); + // the text's own opacity (fades, dimmed labels, a lighter source line), up to the layer + let op = 1; + for (let e = b.el; e && e !== layer; e = e.parentElement) op *= +G.getComputedStyle(e).opacity; + const size = parseFloat(cs.fontSize), + bold = +cs.fontWeight >= 600; + const need = size >= 24 || (bold && size >= 18.66) ? 3 : 4.5; + let worst = Infinity, + against = '', + lo = Infinity, + hi = -Infinity; + const samples = []; + b.words.forEach((r) => { + const step = Math.max(1, Math.floor(Math.min(r.width, r.height) / 6)); + for (let y = r.top; y <= r.bottom; y += step) + for (let x = r.left; x <= r.right; x += step) { + // inside the patch box the patch is solid (its soft edge lies outside, past the words) + const inside = x >= b.patch.left && x <= b.patch.right && y >= b.patch.top && y <= b.patch.bottom; + const a = inside ? b.alpha : 0; + let c = fallback; + if (px) { + const X0 = Math.min(px.w - 1, Math.max(0, Math.round((x - rootR.left) * sx))), + Y0 = Math.min(px.h - 1, Math.max(0, Math.round((y - rootR.top) * sy))); + const k = ((px.h - 1 - Y0) * px.w + X0) * 4; + c = [px.data[k], px.data[k + 1], px.data[k + 2]]; + } + const bg = c.map((v) => v * (1 - a)); + const l = lum(bg[0], bg[1], bg[2]); + lo = Math.min(lo, l); + hi = Math.max(hi, l); + samples.push([bg, l]); + } + }); + samples.forEach(([bg, l]) => { + // text drawn at opacity op over this pixel (CSS blends in sRGB) + const t = ink.slice(0, 3).map((v, i) => v * op + bg[i] * (1 - op)); + const r = con(lum(t[0], t[1], t[2]), l); + if (r < worst) { + worst = r; + against = l >= (lo + hi) / 2 ? 'brightest' : 'darkest'; + } + }); + return { + key: b.key, + text: b.text, + kind: b.kind, + ratio: worst, + need, + against, + opacity: +op.toFixed(3), + pass: worst >= need, + }; + }); + }, + }; + return X; + } + + DHS.essayText = { create, PATCH }; +})(globalThis); diff --git a/engine/src/gl/host.js b/engine/src/gl/host.js index be0119f..3ed90ee 100644 --- a/engine/src/gl/host.js +++ b/engine/src/gl/host.js @@ -187,7 +187,10 @@ precision highp float;in vec2 v;out vec4 o;uniform sampler2D S;uniform float uSe gl.drawArrays(gl.TRIANGLES, 0, 3); } }; - H.finish = () => gl.finish(); + H.finish = () => { + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(4)); + }; H.pixels = () => { if (!W) return null; gl.bindFramebuffer(gl.FRAMEBUFFER, null); diff --git a/engine/src/gl/scenes.js b/engine/src/gl/scenes.js index 0bb840c..907143e 100644 --- a/engine/src/gl/scenes.js +++ b/engine/src/gl/scenes.js @@ -24,7 +24,7 @@ const S = (GL.scenes = GL.scenes || {}); const fmt = (data, v) => (data.format ? data.format(v) : String(v)); const note = (data, aspect) => - data.note ? [{ x: aspect / 2 - 0.04, y: -0.44, text: data.note, kind: 'note', align: 'right', alpha: 1 }] : []; + data.note ? [{ x: aspect / 2 - 0.04, y: -0.4, text: data.note, kind: 'note', align: 'right', alpha: 1 }] : []; const ease = (x) => 1 - (1 - Math.min(1, Math.max(0, x))) ** 3; // stagger: item i of n starts at i/(n-1) * spread of the grow beat; GLSL twin is stag() below const stag = (g, i, n, spread = 0.35) => ease((g - (n > 1 ? (i / (n - 1)) * spread : 0)) / (1 - spread)); @@ -120,7 +120,8 @@ vec3 scene(vec2 p){vec3 c=backdrop(p,vec3(1.,.95,.88));float base=uD[0].x,px=1.4 }, }; - // one dot per unit, filling row by row at a steady pace; data: { count, cols, grow, note } + // one dot per unit, filling row by row at a steady pace; data: { count, cols, grow, note, box } + // box: [left, top, right, bottom] as fractions of the screen, to leave room for words (default: the middle) S.tally = { frag: STAG + @@ -137,10 +138,15 @@ vec3 scene(vec2 p){vec3 c=backdrop(p,vec3(1.,.95,.88));float base=uD[0].x,px=1.4 const N = Math.max(0, Math.floor(data.count || 0)), cols = Math.max(1, data.cols || Math.ceil(Math.sqrt(N * aspect))), rows = Math.max(1, Math.ceil(N / cols)); - const s = Math.min((aspect * 0.7) / cols, 0.5 / rows); + const bx = data.box || [0.15, 0.22, 0.85, 0.74]; + const L0 = (bx[0] - 0.5) * aspect, + R0 = (bx[2] - 0.5) * aspect, + T0 = 0.5 - bx[1], + B0 = 0.5 - bx[3]; + const s = Math.min((R0 - L0) / cols, (T0 - B0) / rows); const d = new Float32Array(64); d.set([N, cols, s, 0], 0); - d.set([(-cols * s) / 2, (rows * s) / 2 - 0.04, rows, 0], 4); + d.set([(L0 + R0 - cols * s) / 2, (T0 + B0 + rows * s) / 2, rows, 0], 4); return { d, n: N }; }, labels: (data, L, v, aspect) => note(data, aspect), From e8ba52437b58ceadf24b3c8e8e81cc89cfbeb675 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 17:20:10 +0000 Subject: [PATCH 07/13] Kit v0.2.0: the motion-essay engine (essay/, gl/, tools/essay-qa.js, lens.drawTexture) + demo essay (tools/build_essay_demo.py -> players/essay-demo.html, placeholder content); docs, TODO next list, STATUS Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Ad4FSZyShDwuPQbAcgGJY3 --- README.md | 4 +- STATUS.md | 4 +- TODO.md | 49 +- engine/CLAUDE.md | 11 +- index.html | 7 + kit/CHANGELOG.md | 36 + kit/KIT.json | 16 +- kit/README.md | 51 +- kit/essay/beats.js | 221 ++++ kit/essay/player.js | 611 ++++++++++ kit/essay/text.js | 349 ++++++ kit/fx/lens.js | 78 +- kit/gl/gl.js | 144 +++ kit/gl/host.js | 230 ++++ kit/gl/scenes.js | 230 ++++ kit/gl/transitions.js | 54 + kit/tools/essay-qa.js | 157 +++ players/essay-demo.html | 2350 +++++++++++++++++++++++++++++++++++++ tools/CLAUDE.md | 3 +- tools/build_essay_demo.py | 70 ++ tools/build_kit.py | 8 + 21 files changed, 4630 insertions(+), 53 deletions(-) create mode 100644 kit/essay/beats.js create mode 100644 kit/essay/player.js create mode 100644 kit/essay/text.js create mode 100644 kit/gl/gl.js create mode 100644 kit/gl/host.js create mode 100644 kit/gl/scenes.js create mode 100644 kit/gl/transitions.js create mode 100644 kit/tools/essay-qa.js create mode 100644 players/essay-demo.html create mode 100644 tools/build_essay_demo.py diff --git a/README.md b/README.md index 582017d..172c46f 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,7 @@ Start sound for the music. Move the mouse to see the controls. | `players/danbury-academies-clock.html` | The Academies film below with a wall clock and a session timer, for a classroom screen | | `players/sanctioned-corporate-calm.html` | Sanctioned Corporate Calm: a 20-minute seamless study loop built from the Academies film's tunes, with a wall clock and a session timer | | `players/gen-player.html` | The generative library below as one self-contained file (USB-stick ready) | +| `players/essay-demo.html` | The motion-essay engine in the kit (for ProofEr): shader scenes (bars from zero, a dot tally, proportional areas), quiet transitions, words over the picture. Placeholder words and made-up numbers, labelled so. Built by `tools/build_essay_demo.py` | - **Generative motion library:** double-click **`gen/player.html`**. Press **G** for the gallery of ready-made cartridges (Truchet tiles, 3D dot meshes, dot swarms that fly into words, flow fields, Julia sets, tunnels, @@ -89,6 +90,7 @@ so they run from Thonny or any editor's Run button, or from a terminal (`python3 | The **Academies film and the Sanctioned Corporate Calm study loop, with a wall clock + timer** | `tools/build_academies_clock.py` (re-run after any change to either master in `academies-film/`) | `dist/danbury-academies-clock.html`, `dist/sanctioned-corporate-calm.html` | | A **self-contained gen player** to put on a USB stick | `python3 gen/build.py` | `gen/dist/gen-player.html` | | **One gen cartridge as its own HTML and/or an MP4 with its music** | run `tools/gen_export.py` (pick cartridge + folder) | the folder you picked | +| The **motion essay demo** (the kit's essay engine) | `tools/build_kit.py`, then `tools/build_essay_demo.py` | `dist/essay-demo.html` | The first build downloads the open-source fonts (SIL OFL, from Google Fonts' GitHub) and caches them; after that, everything is offline. `tools/build.py` needs `pip install fonttools brotli`. @@ -165,7 +167,7 @@ the project: the reusable parts are already here, so a new piece is mostly a sho | `proj//` | One piece's brief, copy and sources (`cdrom`, `pltw`, `cs`, `ex`, `ssr`, `academies`) | | `living/`, `jukebox/` | The living-poster engine and the jukebox page | | `engine/` | The starter timeline engine the Academies film grew from; `engine/src/audio/dsp.js` is the DSP everything uses | -| `kit/` | Engine parts packaged for other projects (the lens, the DSP), versioned, with sha256s in `kit/KIT.json`; built by `tools/build_kit.py`, never edited by hand | +| `kit/` | Engine parts packaged for other projects (the lens, the DSP, the motion-essay engine), versioned, with sha256s in `kit/KIT.json`; built by `tools/build_kit.py`, never edited by hand | | `academies-film/` | The finished Academies hallway film | | `fonts/` | Downloaded open-source fonts and their licenses | diff --git a/STATUS.md b/STATUS.md index b1e2a4f..961158b 100644 --- a/STATUS.md +++ b/STATUS.md @@ -3,7 +3,7 @@ > **Visitors:** this is the project's working log, kept for the people and AI assistants working on it. For what > EOMD is and how to use it, start with [README.md](README.md). -_Last updated: Nov 28, 2026 (kit v0.1.0: `kit/` + `tools/build_kit.py` for ProofEr; both repos are AGPLv3, so no licence obstacle; video-essay plan in `TODO.md`; lens upgraded: 6-level glow, halation, AgX/ACES, grade, dither; engine audio fallback renders in slices and works when the worker is blocked. Nov 27: optional WebGL2 lens finish, ideas taken from the Q-Day player; before that Nov 21: CD-ROM link options `?start=`, `?go`, `?airship`; before that Nov 4: fresh-eyes review added to the design stages; Academies film: clock + timer version). Each piece's history, limits and open questions live in its +_Last updated: Dec 1, 2026 (kit v0.2.0: the motion-essay engine for ProofEr: beat model + fixed-step clock, essay player shell, test hooks + `engine/tools/essay-qa.js`, plain-WebGL2 scene host + compositor with the lens on a GPU texture, 4 scenes, 6 transitions, HTML text with a WCAG check; demo at `players/essay-demo.html`. Nov 28: kit v0.1.0: `kit/` + `tools/build_kit.py` for ProofEr; both repos are AGPLv3, so no licence obstacle; video-essay plan in `TODO.md`; lens upgraded: 6-level glow, halation, AgX/ACES, grade, dither; engine audio fallback renders in slices and works when the worker is blocked. Nov 27: optional WebGL2 lens finish, ideas taken from the Q-Day player; before that Nov 21: CD-ROM link options `?start=`, `?go`, `?airship`; before that Nov 4: fresh-eyes review added to the design stages; Academies film: clock + timer version). Each piece's history, limits and open questions live in its folder's `STATUS.md`; repo-wide history in `notes/history.md`._ ## Pieces @@ -15,7 +15,7 @@ folder's `STATUS.md`; repo-wide history in `notes/history.md`._ | CSE hallway loop (new, full creative) | Done; published Oct 25 (`players/cse-loop.html`) | ES/PT check; real-TV check | `proj/cse-loop/STATUS.md` | | PLTW CSE promo | r2 published ("cheesy as hell, but exactly what I asked for") | The PLTW test below | `proj/pltw/STATUS.md` | | Engine lens finish (`engine/src/fx/lens.js`) | Built Nov 27, upgraded Nov 28; in the engine's dev, kiosk, stills and MP4 paths; off by default | Not yet seen on a real TV; not yet inlined in CD-ROM, living or gen | -| Video essays (Q-Day / Last Boring Slide level) | Planned: `TODO.md`. Decided Nov 28: EOMD builds the engine as a versioned kit; ProofEr hosts motion essays (TODO §0) | Kit v0.1.0 built (`kit/`, `tools/build_kit.py`); next: ProofEr's sync script against it, then the GPU scene layer | +| Video essays (Q-Day / Last Boring Slide level) | Kit v0.2.0 (Dec 1): the essay engine (`engine/src/essay/`, `engine/src/gl/`), demo `players/essay-demo.html` (placeholder words, made-up numbers), QA PASS at 1280×720 (0–1 flashes/s, every text block AA, worst 5.2:1). EOMD builds the engine; ProofEr hosts motion essays (TODO §0) | ProofEr syncs 0.2.0 and builds its first essay; next here (`TODO.md` top): GPU letter type, sound hits/beds, essay MP4, presenter tools. Not yet seen on a real GPU or TV (tested in SwiftShader) | | gen library (incl. Dust Type) | Working; `tools/gen_export.py` | Check Dust Type knobs | `gen/STATUS.md` | | Jukebox | 15 cartridges | Redesign its look | `jukebox/STATUS.md` | diff --git a/TODO.md b/TODO.md index 58034f2..050a69d 100644 --- a/TODO.md +++ b/TODO.md @@ -12,6 +12,19 @@ background beds, presenter tools). Take their mechanisms, never their look or mu - Engine audio renders in slices on the main thread (`P.steps`, `P.runAsync`, `DHS.audio.renderAsync`). A blocked worker now falls back to it instead of going silent. +**Kit v0.2.0 (Dec 1, 2026): the essay engine.** Beat model + fixed-step clock (§2), essay player shell (§5), test +hooks + `engine/tools/essay-qa.js` (§6), WebGL2 toolkit, scene host, render-to-texture compositor and lens on a GPU +texture (§1), six transitions (§1), HTML text over the picture (§3), and a demo essay with placeholder content +(`players/essay-demo.html`, built by `tools/build_essay_demo.py`). Sources: `engine/src/essay/`, `engine/src/gl/`. + +**Next, in order** (not started): +1. **GPU letter-by-letter type** (§3). +2. **Sound hits and beds that know the cut** (§4), with the live-mix loudness plan; then the start screen's "Begin with + sound" gets a real sound (the shell already takes `opts.sound`). +3. **MP4 export of an essay** (§6): `tools/html_to_mp4.py` stepping the fixed clock via `EOMD_ESSAY.at(t)`. +4. **Presenter tools** (§5): notes (N), a second window (P), the scene grid (O), a talk timer. +5. Adaptive quality and warm-up (§5); linked/portal transitions and scene snapshots (§1); scrambled headlines (§3). + Ordered by what unblocks the most. Each item says where it would live. "Essay player" means the player shell EOMD builds for the kit (§0), which ProofEr uses for motion essays. @@ -28,9 +41,9 @@ videos blur the line between interactive scrollytelling and video." Not yet: see **v0.1.0 built Nov 28** (lens, DSP with `P.steps`/`P.runAsync`; `tools/build_kit.py`, CI check): add each part below as it lands: - the lens; - - the GPU toolkit, scene host and shader scene cartridges (§1); + - the GPU toolkit, scene host and shader scene cartridges (§1): **v0.2.0**; - the DSP and sliced synthesis (`P.steps`, `P.runAsync`); - - the beat model and essay player shell (§2, §5); + - the beat model and essay player shell (§2, §5): **v0.2.0**; - GPU type (§3) and sound hits and beds (§4). Every file needs only the `DHS` namespace. - [ ] **`kit/KIT.json`: the kit's manifest, agreed with ProofEr (Nov 28).** ProofEr's sync script is being written @@ -76,8 +89,8 @@ videos blur the line between interactive scrollytelling and video." Not yet: see the kit. - **ProofEr:** anything sourced: infographics, scrolling data essays, and motion essays. - **Test:** if a piece's claims need sources, it's ProofEr, however much it moves. -- [ ] **No three.js.** The Last Boring Slide bundles it. Rebuild everything below in plain WebGL2, as the lens is. - Confirm this rule and add it to `engine/CLAUDE.md`. +- [x] **No three.js.** The Last Boring Slide bundles it. Everything is plain WebGL2, as the lens is; the rule is in + `engine/CLAUDE.md` (Dec 1). **Merge triggers.** Re-merge into one repo with two front doors ("motion piece", "sourced piece") sharing one method folder and one engine when any of these happens: @@ -89,18 +102,22 @@ Merging means keeping each front door's first-question context small (EOMD's is tokens today). ## 1. The picture: GPU scenes and how they join -- [ ] **Shader scenes.** Each scene is one fragment shader over the whole screen: +- [x] **Shader scenes** (v0.2.0: `engine/src/gl/gl.js` preamble, `scenes.js` with field, bars, tally, areas and a + plain fallback). Each scene is one fragment shader over the whole screen: - it gets time, a smoothed beat value, the mouse, and one or two data values; - a shared GLSL preamble gives hash, value noise, fbm, distance-field shapes (box, capsule, torus, smooth min) and a fake studio light for reflections; - this is the "real object under studio light" look with no image files. Both files do this. Lives in: `engine/src/gl/` (new), with a fallback scene when a shader won't build. -- [ ] **Render-to-texture compositor.** Draw the outgoing and incoming scenes into two buffers, run a transition +- [x] **Render-to-texture compositor** (v0.2.0: `engine/src/gl/host.js`; `DHS.lens.create(knobs, { gl })` + + `drawTexture`). Draw the outgoing and incoming scenes into two buffers, run a transition shader between them, then the lens. - The lens gets an entry point that takes a GPU texture, so GPU scenes skip the 2D upload and keep their full floating-point range (AgX and halation work properly on real highlights). - Canvas 2D scenes keep working through the upload path. -- [ ] **Transition library**, with timing as a function of transition progress: +- [ ] **Transition library**, with timing as a function of transition progress. **v0.2.0 has six** (cut, crossfade, + dip, wipe, dissolve, push; `engine/src/gl/transitions.js`), each measured at 0 or 1 flashes a second. Still to + take, as mechanisms only: - from Q-Day: collapse (cell dissolve), ripple, tile flip, zoom-blur warp, slices. Q-Day also lists lens, glass, liquid, cube and burn, but never wrote them; - from The Last Boring Slide: fold, wash, flaps, slam (paper fibres), daybreak, line, tear, portal-in and @@ -117,14 +134,14 @@ tokens today). shaders. ## 2. Time, beats and pacing -- [ ] **Beat model.** A scene is a list of beats, each with `dur`, `delay` and `hold`. +- [x] **Beat model** (v0.2.0: `engine/src/essay/beats.js`; back runs 2.4× faster in the player). A scene is a list of beats, each with `dur`, `delay` and `hold`. - Each beat has its own 0→1 progress that eases forward and runs back 2.4× faster when you go back. - `s.k(beat, t0, t1, ease)` times a move inside a beat. - It plays by itself (dur + hold, then next) or follows clicks. Lives in: the essay player. -- [ ] **Reading-time pacing.** A beat's hold comes from its word count (Q-Day: 2.6 s + 0.31 s a word, kept between +- [x] **Reading-time pacing** (v0.2.0). A beat's hold comes from its word count (Q-Day: 2.6 s + 0.31 s a word, kept between 5.2 and 16 s). Client copy stays word for word; only the timing comes from the words. -- [ ] **A pure function of time where possible.** Both files build up progress from frame to frame. For an MP4 and a +- [x] **A pure function of time where possible** (v0.2.0: `DHS.beats.clock`, `DHS.beats.rng`). Both files build up progress from frame to frame. For an MP4 and a seamless loop, the essay player needs a fixed-step clock (1/60 s) that seek and export can replay exactly, and a seeded random generator in place of `Math.random`. @@ -136,7 +153,8 @@ tokens today). - arrival styles: rise, blur, type, fade, scatter, track, drop, by letter, word or line, with stagger; - it can also sit inside a 3D scene. Lives in: `engine/src/gl/type.js`; later the gen `type` layer. -- [ ] **HTML text over the picture** (Q-Day's way, for long copy and sources): +- [x] **HTML text over the picture** (Q-Day's way, for long copy and sources). v0.2.0: `engine/src/essay/text.js`, all + but the scrambled headlines: - named positions (corners, centre, quote, chapter card, giant number); - a soft dark patch behind the text instead of glows; - words fading in one by one, and headlines that arrive scrambled and resolve; @@ -165,7 +183,7 @@ tokens today). Yield inside long instrument notes if it shows on a slow machine. ## 5. Player, presenter and performance -- [ ] **Essay player shell:** +- [x] **Essay player shell** (v0.2.0: `engine/src/essay/player.js`; right-click goes back; no sound yet): - start screen with Begin with sound / Begin silently; - controls hidden until the mouse moves, fading after 3 s (both files use less); - progress bar with gaps between chapters; @@ -183,15 +201,16 @@ tokens today). - [ ] **Warm-up:** a loading bar that runs every scene and transition once, off-screen, before the show (no stutter at the first cut). Scenes far from the current one shrink their buffers to 2×2 pixels; the next two scenes warm up ahead. -- [ ] **No WebGL2:** the text and sound still play, with a plain note on screen (both files do this). +- [x] **No WebGL2:** the text and sound still play, with a plain note on screen (both files do this). ## 6. Export and QA -- [ ] **Test hooks for stepped and essay players:** `seek(scene, beat, t)`, `trans(scene, p)` and `perf(scene)`, +- [x] **Test hooks for essay players** (v0.2.0: `window.EOMD_ESSAY`, `engine/tools/essay-qa.js`; stepped players + still use `?manual` + `advance()`): `seek(scene, beat, t)`, `trans(scene, p)` and `perf(scene)`, returning repeatable stills of any beat or any point in a transition. Used by fresh-eyes review (`brief/CRAFT.md` §11) and by `tools/html_to_mp4.py`. - [ ] **MP4 of an essay:** play by itself at a fixed step, capture frames, and lay in the offline render of the event log, frame-exact. Extends `tools/html_to_mp4.py`. -- [ ] **Fresh-eyes review of transitions:** stills at 0.25, 0.5 and 0.75 of every transition, plus a flash-rate +- [x] **Fresh-eyes review of transitions** (v0.2.0: `essay-qa.js` writes the stills and measures flashes): stills at 0.25, 0.5 and 0.75 of every transition, plus a flash-rate check. ## 7. Roll out what's already built diff --git a/engine/CLAUDE.md b/engine/CLAUDE.md index 2182486..7c4cf3b 100644 --- a/engine/CLAUDE.md +++ b/engine/CLAUDE.md @@ -6,8 +6,13 @@ inside `engine/`, e.g. `node tools/build-player.js`). - `engine/src/audio/dsp.js` is the DSP every player uses: a change to it follows the regression rule in `audio/CLAUDE.md`. -- `engine/src/fx/lens.js` and `engine/src/audio/dsp.js` are copied into `kit/` for ProofEr: after changing either, run - `tools/build_kit.py` and commit `kit/` too (CI fails on a stale copy). A release also bumps `kit/KIT.json`'s version - and adds a `kit/CHANGELOG.md` section. +- Kit sources (copied into `kit/` for ProofEr): `src/fx/lens.js`, `src/audio/dsp.js`, `src/essay/*.js` (beats, + player shell, words layer), `src/gl/*.js` (WebGL2 toolkit, scenes, transitions, compositor) and `tools/essay-qa.js`. + After changing any, run `tools/build_kit.py` and commit `kit/` too (CI fails on a stale copy). A release also bumps + `kit/KIT.json`'s version and adds a `kit/CHANGELOG.md` section. +- **No three.js, no libraries:** everything is plain WebGL2 in the `DHS` namespace, single-offline-HTML friendly. +- The motion-essay engine: `src/essay/beats.js` keeps the whole essay a pure function of the playhead; scene shaders + write linear light; transitions change each part of the screen once (check with `tools/essay-qa.js`). The demo + essay is `essay-demo/` (placeholder content only; real essays and their figures live in ProofEr). - `engine/tools/html_to_mp4.py` is the original MP4 script; use `tools/html_to_mp4.py` instead. - Don't open `engine/` for living-poster or jukebox work (only `dsp.js`, for DSP internals). diff --git a/index.html b/index.html index 1d5c5e5..f3bdf6e 100644 --- a/index.html +++ b/index.html @@ -127,6 +127,13 @@

Players

timer. Press Start the loop for the music. + Motion essay demo (the kit)The essay engine EOMD builds for ProofEr: shader scenes, quiet transitions and words over the picture. The + words and numbers are placeholders, not facts. Click or press the arrow keys to move on.

Make your own

diff --git a/kit/CHANGELOG.md b/kit/CHANGELOG.md index 37f2999..ea2bf83 100644 --- a/kit/CHANGELOG.md +++ b/kit/CHANGELOG.md @@ -1,5 +1,41 @@ # Kit changelog +## 0.2.0 (2026-12-01) + +The essay engine: what ProofEr needs to build its first motion essay. Minor bump: new files, and one new entry point +on the lens; nothing in 0.1.0 changed behaviour. + +- `essay/beats.js` (`DHS.beats`): scenes as lists of beats (`delay`, `dur`, `hold`), holds from reading time + (2.6 s + 0.31 s a word, 5.2 to 16 s), eases, `k(beat, t0, t1, ease)`, a fixed-step 1/60 s clock and a seeded + random generator. The whole essay is a pure function of the playhead, so seeks, stills and exports replay exactly. +- `essay/player.js` (`DHS.essay.mount`): the player shell. Start screen (with sound / silently when the essay has + sound; "Begin" otherwise), plays by itself or waits for clicks (A), click / keys / swipe / right-click, back runs + 2.4x faster, progress bar with gaps between chapters, `#scene-beat` links with the back button, help card (?), + black screen (.), controls hidden until the mouse moves and fading after 3 s, safe-area padding, a live region for + screen readers, and a no-WebGL2 path that still plays the words and numbers. Test hooks on `window.EOMD_ESSAY`: + `seek(scene, beat, t)`, `trans(scene, p)`, `at(t)`, `perf(scene)`, `flashCheck(scene)`, `contrast()`; `?manual` + starts paused with no start screen. Presenter notes (N) are not in yet. +- `essay/text.js` (`DHS.essayText`): HTML words over the picture. Named positions, a soft dark patch behind each + group, word-by-word fade-in, data labels from the scene, prefers-reduced-motion, and a WCAG check per paragraph + against the brightest and darkest picture under it, with the patch and the text's opacity composited in. +- `gl/gl.js` (`DHS.gl`): plain WebGL2 helpers (context, programs, half-float targets) and a shared GLSL preamble: + hash, value noise, fbm, distance-field shapes, smooth min, and a fake studio light. +- `gl/scenes.js`: shader scene cartridges with plain-JS layout: `field` (quiet backdrop), `bars` (start at zero, + height linear in the value, one bar can be brought forward), `tally` (one dot per unit), `areas` (circle area + proportional to the value), and `plain` (the fallback when a shader won't build). +- `gl/transitions.js`: cut, crossfade, dip (through black), wipe, dissolve, push. Each changes every part of the + screen once (dip: down and up once over 2 s); worst case white to black measures 0 flashes a second. Under + prefers-reduced-motion, wipe, dissolve and push become a crossfade. +- `gl/host.js` (`DHS.gl.host`): the compositor. Outgoing and incoming scenes into two half-float buffers, a + transition shader between them, then the lens on the GPU texture (or a plain presenter with dither). +- `fx/lens.js`: `DHS.lens.create(knobs, { gl })` shares a WebGL2 context, and `L.drawTexture(texture, w, h, t)` + takes a linear-light texture (highlights above 1 keep their strength). The 2D path is unchanged and still passes + through pixel-exact with every knob at 0. +- `tools/essay-qa.js`: Node + Playwright, not for inlining. Stills of every beat and every transition at 0.25, 0.5 + and 0.75, the flash check, the contrast check and ms a frame per scene, as `report.md` + `report.json`. + +Next (not in this kit): GPU letter-by-letter type, sound hits and beds, MP4 export of an essay, presenter tools. + ## 0.1.0 (2026-11-28) First kit. diff --git a/kit/KIT.json b/kit/KIT.json index 245baac..4a84e78 100644 --- a/kit/KIT.json +++ b/kit/KIT.json @@ -1,10 +1,18 @@ { - "version": "0.1.0", + "version": "0.2.0", "license": "AGPL-3.0-only", "files": { - "CHANGELOG.md": "4bc8fa8ef1065d54aba8e337409917cbb415307fcdca164cb83a0e11710c5549", - "README.md": "b5ce6fc04654eaeeb5300f647d1ca2634b9aa6cbc8b1dd62b974b073eac97234", + "CHANGELOG.md": "1547225027831550678c749e1cc6cc195c6e38421145a77b1ec8193fd6eb1ef5", + "README.md": "fbcd43d6423fb02703a6f86599413863c50528e24bcb00919fd8543e9a51c914", "audio/dsp.js": "0d12522bbf01dce3ac69b2cc76e8a677ab396d422afbe642a58d566873d2992e", - "fx/lens.js": "c7dad14003011acc4677bd586be8a66aceeb438150f4d365c90e15d2a59d1176" + "essay/beats.js": "79fb73a34693ac610de6b29db1ba8f1d33940dc78c3d5abe18f30db63e6f7b74", + "essay/player.js": "fcf99547c7e11f7af0a37ada488dc7c4089951bc9f7a2e3c14658268118ed46e", + "essay/text.js": "da0e53ae511b540fe4abfb58afe8ca8e0cd516556c81e45149a775d6d2691e0c", + "fx/lens.js": "0eda5b4e85ea57131acdb7f90adb794744f29c29291e7cf5a03e8fbe0a41b674", + "gl/gl.js": "2a939e8ac5e4b9fec4e19f97dc6cf5694dd2b4c9c5c6701926ae241a969a84f6", + "gl/host.js": "c5396ec9d00f363a6553725ad1e00217340e6fff05bf4a003b9b56be4289b2c9", + "gl/scenes.js": "4239f4f922b99943b948686d0f29bac6a16d890f6178f54d558ae14287570e2f", + "gl/transitions.js": "66f9534be61589d62e150492234b9c9235ec75947deec7be5475bbc894047e92", + "tools/essay-qa.js": "73859d8f6ba709500dbebed8ff3b6621cd921e5fa59193e882f7cf576190d407" } } diff --git a/kit/README.md b/kit/README.md index b4a64e6..ac923ce 100644 --- a/kit/README.md +++ b/kit/README.md @@ -1,8 +1,8 @@ # The EOMD kit EOMD's engine parts, packaged for other projects. ProofEr copies a pinned version into `vendor/eomd-kit/` with its -sync script. Every file runs in a browser with no libraries. Each one needs only the shared `DHS` namespace -(`globalThis.DHS`), which it creates if it isn't there. +sync script. Every file except `tools/essay-qa.js` (a Node + Playwright check) runs in a browser with no libraries. +Each one needs only the shared `DHS` namespace (`globalThis.DHS`), which it creates if it isn't there. **Don't edit these copies.** Each JavaScript file is generated from an engine source named in its header. Change the source in EOMD, then run `tools/build_kit.py`. CI fails if a copy and its source differ, or if `KIT.json` doesn't @@ -14,12 +14,56 @@ match the files. |---|---|---| | `fx/lens.js` | `DHS.lens`: a WebGL2 finish over any 2D canvas. Glow, halation, streak, colour fringe, tone curve (none, ACES, AgX) and grade, vignette, grain, anti-banding dither. A pure function of the frame and `t`. Without WebGL2 it reports `ok: false` and the caller shows the plain canvas. | `engine/src/fx/lens.js` | | `audio/dsp.js` | `DHS.dsp`: sample-by-sample synthesis and mixing on circular buffers (oscillators, filters, envelopes, reverb, delay), BS.1770 loudness, true peak, a true-peak limiter, and WAV-ready buses. `P.steps.*` are the same steps as generators; `P.runAsync` runs a generator in ~8 ms slices, so a page making sound on its main thread keeps drawing. | `engine/src/audio/dsp.js` | +| `essay/beats.js` | `DHS.beats`: the essay's time model. Scenes as lists of beats (`delay`, `dur`, `hold`), reading-time holds, eases, a fixed-step clock and a seeded random generator. Everything is a pure function of the playhead. | `engine/src/essay/beats.js` | +| `essay/player.js` | `DHS.essay.mount(essay)`: the player shell (start screen, keys, swipe, progress bar with chapter gaps, `#scene-beat` links, help card, no-WebGL2 path) and the test hooks on `window.EOMD_ESSAY`. | `engine/src/essay/player.js` | +| `essay/text.js` | `DHS.essayText`: HTML words over the picture, at named positions with a soft dark patch, arriving word by word; data labels; the WCAG contrast check. | `engine/src/essay/text.js` | +| `gl/gl.js` | `DHS.gl`: plain WebGL2 helpers and the shared GLSL preamble (noise, distance fields, studio light). | `engine/src/gl/gl.js` | +| `gl/scenes.js` | Shader scenes: `field`, `bars`, `tally`, `areas`, `plain`. | `engine/src/gl/scenes.js` | +| `gl/transitions.js` | Transitions: `cut`, `crossfade`, `dip`, `wipe`, `dissolve`, `push`. | `engine/src/gl/transitions.js` | +| `gl/host.js` | `DHS.gl.host`: draws scenes into buffers, runs the transition, then the lens on the GPU texture. | `engine/src/gl/host.js` | +| `tools/essay-qa.js` | Node + Playwright (not for the page): stills of every beat and transition, flash, contrast and speed report. | `engine/tools/essay-qa.js` | ## Using it Inline the files into the page, as every EOMD player is a single offline HTML file. Load `audio/dsp.js` before any code that uses `DHS.dsp`; `fx/lens.js` stands alone. +### A motion essay + +Inline in this order: `essay/beats.js`, `fx/lens.js`, `gl/gl.js`, `gl/transitions.js`, `gl/scenes.js`, +`gl/host.js`, `essay/text.js`, `essay/player.js`. Then: + +```js +DHS.essay.mount({ + title: 'Title', subtitle: 'One line under it', lang: 'en', + lens: { bloom: 0.12, streak: 0, vignette: 0.28 }, // or null for no lens + scenes: [ + { id: 'opening', chapter: 'Opening', scene: 'field', transition: { type: 'dip', dur: 2 }, + beats: [{ dur: 2.4, text: [{ pos: 'chapter', kind: 'chapter', text: 'Chapter title' }] }] }, + { id: 'bars', chapter: 'Part one', scene: 'bars', transition: 'crossfade', + data: { values: [12, 30], labels: ['A', 'B'], max: 50, grow: 1, note: 'Source: ...' }, + beats: [ + { dur: 1.2, text: [{ pos: 'top-left', kind: 'headline', text: 'Headline' }] }, + { dur: 3.2, text: [{ pos: 'top-left', kind: 'body', text: 'The bars grow in this beat (data.grow: 1).' }] }, + { dur: 1.6, focus: 1 }, // bring bar 1 forward + ] }, + ], +}); +``` + +- A beat: `dur` (seconds to arrive), `delay`, `hold` (default: reading time from its words), `ease`, `text`, and for + data scenes `focus`. Text is shown exactly as written. +- Text positions: `center`, `chapter`, `quote` (these share the middle), `lower-third`, `top-left`, `top-right`, + `bottom-left`, `bottom-right`. Kinds: `body`, `headline`, `chapter`, `quote`, `source`, `number`, `note`. Restyle + with CSS variables on `.eo-root`: `--eo-ink`, `--eo-bg`, `--eo-font`, `--eo-display`, `--eo-serif`, `--eo-accent`. +- A new scene is a cartridge in `DHS.gl.scenes` (`frag`, `layout`, `labels`); a new transition is a shader in + `DHS.gl.transitions`. The comments at the top of `gl/scenes.js` and `gl/transitions.js` give the contract. +- Before review: `node tools/essay-qa.js essay.html out/` writes the stills and a pass/fail report (flashes, + WCAG contrast, page errors). EOMD's demo essay (`engine/essay-demo/`, built by `tools/build_essay_demo.py` into + `players/essay-demo.html`) shows every part with placeholder words and made-up numbers. + +### The lens and the DSP + ```js // Lens over a 2D canvas: knobs from DHS.lens.DEFAULTS; null when it's off or can't start const L = DHS.lens.attach(canvas, { bloom: 0.25, tone: 'none' }); @@ -27,6 +71,9 @@ function frame(t) { drawScene(ctx, t); if (L && L.ok) L.draw(canvas, t); } +// Lens on a GPU texture in your own WebGL2 context (linear light, no upload) +const L2 = DHS.lens.create({ bloom: 0.2 }, { gl }); +L2.drawTexture(texture, width, height, t); // Sound made on the main thread without freezing the page: write the render as a generator of P.steps const P = DHS.dsp; diff --git a/kit/essay/beats.js b/kit/essay/beats.js new file mode 100644 index 0000000..4af8293 --- /dev/null +++ b/kit/essay/beats.js @@ -0,0 +1,221 @@ +/* EOMD kit: essay/beats.js. Copyright (C) 2026 Bryan Patrick Murphy. SPDX-License-Identifier: AGPL-3.0-only + Copied from engine/src/essay/beats.js (https://github.com/BPMData/EOMD) by tools/build_kit.py: change the source in EOMD, not this copy. */ +/* BEATS: the time model of an essay. A scene is a list of beats; each beat has + delay seconds of quiet before it starts arriving + dur seconds it takes to arrive (its progress runs 0 -> 1, eased) + hold seconds it stays before the next beat (default: reading time from its words) + Scenes are joined by transitions that take their own time (the outgoing scene stays at its last beat, the incoming + one at its first beat's progress 0). Everything is a pure function of the playhead t (seconds from the start): + seek, stills and an MP4 export replay exactly. No Math.random: use DHS.beats.rng(seed). + + const TL = DHS.beats.compile(essay, { transDur: (type) => 1.2 }); + const s = TL.at(t); // { t, scene, beat, beatT, raw[], p[], trans, k(beat, t0, t1, ease) } + const C = DHS.beats.clock(); C.advance(realDt); C.t // fixed 1/60 s steps; C.set(t) to seek + + Reading time (Q-Day's rule): hold = 2.6 s + 0.31 s a word, kept between 5.2 and 16 s, for a beat with words. + The words themselves are never changed; only the timing comes from them. + + Standalone: needs only the DHS namespace. */ +(function (G) { + 'use strict'; + const DHS = (G.DHS = G.DHS || {}); + + const clamp = (x, a, b) => (x < a ? a : x > b ? b : x); + const clamp01 = (x) => clamp(x, 0, 1); + + // Ease curves, all f(0) = 0 and f(1) = 1 + const EASE = { + linear: (x) => x, + in: (x) => x * x * x, + out: (x) => 1 - (1 - x) ** 3, + inOut: (x) => (x < 0.5 ? 4 * x * x * x : 1 - (-2 * x + 2) ** 3 / 2), + sine: (x) => 0.5 - 0.5 * Math.cos(Math.PI * x), + slow: (x) => 1 - (1 - x) ** 5, // long, gentle settle: the default for a solemn essay + }; + const ease = (e) => (typeof e === 'function' ? e : EASE[e] || EASE.slow); + + // ---- reading time + const READING = { base: 2.6, perWord: 0.31, min: 5.2, max: 16 }; + const countWords = (s) => (String(s || '').match(/\S+/g) || []).length; + const beatWords = (b) => (b.text || []).reduce((n, x) => n + countWords(typeof x === 'string' ? x : x.text), 0); + const readingHold = (n, r = READING) => (n > 0 ? clamp(r.base + r.perWord * n, r.min, r.max) : 0); + + // ---- seeded random (mulberry32) and a string hash (FNV-1a) to make seeds from names + const hash = (...parts) => { + let h = 2166136261; + const s = parts.join('\u0001'); + for (let i = 0; i < s.length; i++) { + h ^= s.charCodeAt(i); + h = Math.imul(h, 16777619); + } + return h >>> 0; + }; + const rng = (seed) => { + let a = (typeof seed === 'number' ? seed : hash(seed)) >>> 0; + const r = () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; + r.range = (lo, hi) => lo + (hi - lo) * r(); + r.int = (lo, hi) => Math.floor(lo + (hi - lo + 1) * r()); + r.pick = (arr) => arr[Math.floor(r() * arr.length)]; + return r; + }; + + // ---- the timeline + // essay: { scenes: [{ id, chapter, transition: 'crossfade' | { type, dur }, beats: [{ dur, delay, hold, text }] }] } + // opts.transDur(type): a transition's default length (the essay player passes the transition library's) + function compile(essay, opts = {}) { + const transDur = opts.transDur || (() => 1); + const reading = Object.assign({}, READING, opts.reading || {}); + const scenes = []; + let t = 0; + essay.scenes.forEach((sc, i) => { + const tr = typeof sc.transition === 'string' ? { type: sc.transition } : Object.assign({}, sc.transition || {}); + tr.type = tr.type || (i ? 'crossfade' : 'dip'); + tr.dur = tr.type === 'cut' ? 0 : tr.dur != null ? tr.dur : transDur(tr.type); + const S = { index: i, id: sc.id || 's' + (i + 1), chapter: sc.chapter || '', start: t, trans: tr, beats: [] }; + t += tr.dur; + S.body = t; + (sc.beats && sc.beats.length ? sc.beats : [{}]).forEach((b, j) => { + const words = beatWords(b); + const B = { + index: j, + delay: b.delay != null ? b.delay : 0, + dur: b.dur != null ? b.dur : 1.6, + hold: b.hold != null ? b.hold : Math.max(readingHold(words, reading), j === 0 && !words ? 1.5 : 0), + ease: ease(b.ease), + words, + start: t, + }; + B.arrive = B.start + B.delay; + B.shown = B.arrive + B.dur; + B.end = B.shown + B.hold; + t = B.end; + S.beats.push(B); + }); + S.end = t; + scenes.push(S); + }); + const total = t; + + // the chapters, in order, with their time spans (for the progress bar) + const chapters = []; + scenes.forEach((S) => { + const last = chapters[chapters.length - 1]; + if (last && last.name === S.chapter) last.end = S.end; + else chapters.push({ name: S.chapter, start: S.start, end: S.end, scene: S.index }); + }); + + const sceneAt = (t) => { + let lo = 0, + hi = scenes.length - 1; + while (lo < hi) { + const m = (lo + hi + 1) >> 1; + if (scenes[m].start <= t) lo = m; + else hi = m - 1; + } + return lo; + }; + + // reduced motion: arrivals take at most `quick` seconds (same timeline length, so links and seeks still match) + function at(t, o = {}) { + t = clamp(t, 0, total); + const i = sceneAt(t), + S = scenes[i]; + const quick = o.reduced ? 0.35 : Infinity; + let beat = -1; + const raw = S.beats.map((B, j) => { + if (t >= B.arrive) beat = j; + return clamp01((t - B.arrive) / Math.max(1e-6, Math.min(B.dur, quick))); + }); + if (t < S.body) beat = -1; + else if (beat < 0) beat = 0; + const p = raw.map((r, j) => S.beats[j].ease(r)); + const trans = + t < S.body && S.trans.dur > 0 + ? { + type: S.trans.type, + from: i - 1, + to: i, + p: clamp01((t - S.start) / S.trans.dur), + dur: S.trans.dur, + fromT: i ? t - scenes[i - 1].body : 0, + } + : null; + const B = beat >= 0 ? S.beats[beat] : null; + return { + t, + total, + scene: i, + id: S.id, + chapter: S.chapter, + beat, + beatT: B ? t - B.start : 0, + sceneT: t - S.body, + raw, + p, + trans, + // progress of a move inside a beat: k(beat, 0.2, 0.8, 'out') runs 0 -> 1 while the beat goes 20% -> 80% + k: (j, t0 = 0, t1 = 1, e = 'inOut') => ease(e)(clamp01(((raw[j] || 0) - t0) / Math.max(1e-6, t1 - t0))), + }; + } + + // time of a beat's moments: 'start', 'arrive', 'shown' (fully in, hold begins), 'end' + const timeOf = (i, j = 0, where = 'shown') => { + const S = scenes[clamp(i, 0, scenes.length - 1)]; + if (j < 0) return S.start; + return S.beats[clamp(j, 0, S.beats.length - 1)][where]; + }; + // flat list of beats in order: [{ scene, beat }], for next/back + const flat = []; + scenes.forEach((S) => S.beats.forEach((B) => flat.push({ scene: S.index, beat: B.index, B }))); + const flatIndex = (t) => { + let k = 0; + for (let n = 0; n < flat.length; n++) if (flat[n].B.start <= t + 1e-9) k = n; + return k; + }; + const sceneIndex = (idOrIndex) => + typeof idOrIndex === 'number' + ? clamp(idOrIndex, 0, scenes.length - 1) + : scenes.findIndex((S) => S.id === idOrIndex); + + return { scenes, chapters, total, at, timeOf, flat, flatIndex, sceneIndex, sceneAt }; + } + + // Fixed-step clock: real time goes in, whole 1/fps steps come out, so frame rate never changes what is shown + // at a given t, and an export stepping at 1/60 s sees exactly the frames a viewer saw. + function clock(fps = 60) { + let base = 0, + n = 0, + acc = 0; + return { + fps, + get t() { + return base + n / fps; + }, + // a seek lands exactly on t; steps continue from there in whole 1/fps steps + set(t) { + base = t; + n = 0; + acc = 0; + }, + // dt in seconds of real time (capped, so a sleeping tab doesn't jump); rate: 1 forward, -2.4 rewinding + advance(dt, rate = 1) { + acc += Math.min(Math.max(dt, 0), 0.25) * rate; + const k = acc >= 0 ? Math.floor(acc * fps + 1e-9) : Math.ceil(acc * fps - 1e-9); + n += k; + acc -= k / fps; + return k; + }, + step(k = 1) { + n += k; + }, + }; + } + + DHS.beats = { EASE, READING, countWords, beatWords, readingHold, hash, rng, compile, clock, clamp, clamp01 }; +})(globalThis); diff --git a/kit/essay/player.js b/kit/essay/player.js new file mode 100644 index 0000000..65cb5b0 --- /dev/null +++ b/kit/essay/player.js @@ -0,0 +1,611 @@ +/* EOMD kit: essay/player.js. Copyright (C) 2026 Bryan Patrick Murphy. SPDX-License-Identifier: AGPL-3.0-only + Copied from engine/src/essay/player.js (https://github.com/BPMData/EOMD) by tools/build_kit.py: change the source in EOMD, not this copy. */ +/* ESSAY PLAYER: the shell around a motion essay (a sourced essay that plays like a film). It owns time, controls and + links; the picture (DHS.gl.host) and the words (DHS.essayText) draw what it tells them. Needs DHS.beats; uses + DHS.gl.host and DHS.essayText when they are inlined, and still plays the words without them (or without WebGL2). + + const E = DHS.essay.mount(essay, { root: document.body, sound: null }); + essay: { title, subtitle, lang, lens: knobs | null, scenes: [{ id, chapter, scene: 'bars', data: {...}, + transition: 'crossfade' | { type, dur }, beats: [{ dur, delay, hold, text: [{ pos, kind, text }] }] }] } + + Viewer controls: + click, Space, Right arrow, Page Down, swipe left next beat (finishes the current one first) + right-click, Left arrow, Page Up, Backspace, swipe back (runs back 2.4x faster than it came) + A play by itself / wait for clicks K pause . black screen F full screen ? help card + Home / End first / last beat; #scene-beat links (e.g. #bars-2) open at that beat; the back button works. + Controls are hidden until the mouse moves or the screen is tapped, and fade after 3 s. + + Sound (optional): opts.sound = { start(audioContext), update(t, playing) }. With it, the start screen offers + "Begin with sound" and "Begin silently"; without it, just "Begin". + + Test hooks (stills, fresh-eyes review, MP4): E.seek(scene, beat, t), E.trans(scene, p), E.perf(scene), E.state(), + E.textBoxes(), E.hideGlyphs(on). Also on window.EOMD_ESSAY. Add ?manual to the URL to start paused with no start + screen (what the stills and MP4 tools use). */ +(function (G) { + 'use strict'; + const DHS = (G.DHS = G.DHS || {}); + const doc = G.document; + + const CSS = ` +.eo-root{position:fixed;inset:0;background:var(--eo-bg,#050506);color:var(--eo-ink,#f3f0e8);overflow:hidden; + font-family:var(--eo-font,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif);-webkit-tap-highlight-color:transparent; + user-select:none;-webkit-user-select:none;touch-action:none} +.eo-root.eo-nogl{background:var(--eo-fallback-bg,radial-gradient(120% 90% at 50% 40%,#1b1c22 0%,#08080a 70%))} +.eo-gl{position:absolute;inset:0;width:100%;height:100%;display:block} +.eo-black{position:absolute;inset:0;background:#000;opacity:0;pointer-events:none;transition:opacity .6s} +.eo-black.on{opacity:1} +.eo-ui{position:absolute;left:0;right:0;bottom:0;padding:0 max(16px,env(safe-area-inset-right)) max(14px,env(safe-area-inset-bottom)) max(16px,env(safe-area-inset-left)); + opacity:1;transition:opacity .5s;background:linear-gradient(transparent,rgba(0,0,0,.55));padding-top:40px} +.eo-root:not(.eo-on) .eo-ui{display:none} +.eo-idle .eo-ui{opacity:0;pointer-events:none}.eo-idle{cursor:none} +.eo-bar{display:flex;gap:6px;height:18px;align-items:center;cursor:pointer} +.eo-seg{position:relative;height:4px;background:rgba(255,255,255,.22);border-radius:2px;overflow:hidden} +.eo-seg i{position:absolute;inset:0;right:auto;background:var(--eo-accent,#e9e4d8);width:0} +.eo-row{display:flex;align-items:center;gap:10px;margin-top:6px;font-size:14px} +.eo-row button,.eo-start button,.eo-help button{font:inherit;color:inherit;background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.28); + border-radius:6px;padding:7px 12px;cursor:pointer;min-height:36px} +.eo-row button:hover,.eo-start button:hover{background:rgba(255,255,255,.18)} +.eo-row button:focus-visible,.eo-start button:focus-visible,.eo-help button:focus-visible{outline:2px solid var(--eo-accent,#e9e4d8);outline-offset:2px} +.eo-where{flex:1;opacity:.85;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} +.eo-start,.eo-help{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;flex-direction:column; + text-align:center;padding:max(24px,env(safe-area-inset-top)) 24px max(24px,env(safe-area-inset-bottom));background:rgba(5,5,6,.82)} +.eo-start h1{font-family:var(--eo-display,inherit);font-weight:500;font-size:clamp(28px,5vw,64px);margin:0 0 .3em;max-width:20ch;line-height:1.1} +.eo-start p{margin:0 0 1.6em;opacity:.8;max-width:46ch;font-size:clamp(15px,1.6vw,20px);line-height:1.45} +.eo-start .eo-go{display:flex;gap:12px;flex-wrap:wrap;justify-content:center} +.eo-start button{font-size:18px;padding:12px 22px} +.eo-start small{margin-top:1.6em;opacity:.6;font-size:13px} +.eo-help[hidden],.eo-start[hidden],.eo-note[hidden]{display:none} +.eo-help .eo-card{background:#111114;border:1px solid rgba(255,255,255,.2);border-radius:10px;padding:22px 26px;text-align:left;max-width:520px;font-size:15px;line-height:1.5} +.eo-help h2{margin:0 0 .6em;font-size:18px;font-weight:600} +.eo-help dl{display:grid;grid-template-columns:auto 1fr;gap:4px 16px;margin:0 0 1em} +.eo-help dt{font-weight:600;white-space:nowrap}.eo-help dd{margin:0;opacity:.85} +.eo-note{position:absolute;top:max(14px,env(safe-area-inset-top));left:50%;transform:translateX(-50%);max-width:min(560px,90vw); + background:rgba(0,0,0,.7);border:1px solid rgba(255,255,255,.25);border-radius:8px;padding:10px 14px;font-size:14px;line-height:1.4;text-align:center} +.eo-sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap} +@media (prefers-reduced-motion: reduce){.eo-ui,.eo-black{transition:none}} +`; + + const el = (tag, cls, parent, html) => { + const e = doc.createElement(tag); + if (cls) e.className = cls; + if (html != null) e.innerHTML = html; + if (parent) parent.appendChild(e); + return e; + }; + const esc = (s) => + String(s == null ? '' : s).replace( + /[&<>"]/g, + (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c] + ); + + // A plain words layer for when DHS.essayText isn't inlined: each beat's text, no positions or fades. + function plainText(root, TL, essay) { + const box = el('div', '', root); + box.style.cssText = + 'position:absolute;left:8vw;right:8vw;bottom:18vh;font-size:clamp(18px,2.2vw,30px);line-height:1.4'; + let last = ''; + return { + render(s) { + const sc = essay.scenes[s.scene], + b = sc.beats && sc.beats[Math.max(0, s.beat)]; + const html = + b && !s.trans + ? (b.text || []).map((x) => '

' + esc(typeof x === 'string' ? x : x.text) + '

').join('') + : ''; + if (html !== last) box.innerHTML = last = html; + }, + boxes: () => [], + hideGlyphs() {}, + }; + } + + // series: one array of cell luminances (0..1) per frame at `fps`. A change is a swing of at least 0.1 from the last + // turning point with the darker side under 0.8; a flash is a pair of opposing changes (WCAG 2.3.1). + // Returns the most flashes in any one second in any cell, and the biggest frame-to-frame step. + function flashCount(series, fps = 60) { + let maxPerSecond = 0, + maxStep = 0; + const cells = series.length ? series[0].length : 0; + for (let c = 0; c < cells; c++) { + const changes = []; + let ext = series[0][c], + dir = 0; + for (let f = 1; f < series.length; f++) { + const v = series[f][c]; + maxStep = Math.max(maxStep, Math.abs(v - series[f - 1][c])); + if ((dir > 0 && v > ext) || (dir < 0 && v < ext)) + ext = v; // still moving the same way + else if (Math.abs(v - ext) >= 0.1 && Math.min(v, ext) < 0.8) { + changes.push(f); + dir = v > ext ? 1 : -1; + ext = v; + } + } + for (let a = 0; a < changes.length; a++) { + let b = a; + while (b + 1 < changes.length && changes[b + 1] - changes[a] < fps) b++; + maxPerSecond = Math.max(maxPerSecond, Math.floor((b - a + 1) / 2)); + } + } + return { maxPerSecond, maxStep }; + } + + function mount(essay, opts = {}) { + const B = DHS.beats; + const root = el('div', 'eo-root', opts.root || doc.body); + if (essay.lang) root.lang = essay.lang; + if (!doc.getElementById('eo-css')) el('style', '', doc.head, CSS).id = 'eo-css'; + const params = new URLSearchParams(G.location ? G.location.search : ''); + const manual = params.has('manual'); + const reducedMQ = G.matchMedia ? G.matchMedia('(prefers-reduced-motion: reduce)') : { matches: false }; + const reduced = () => reducedMQ.matches || params.get('reduced') === '1'; + + // ---- picture + const canvas = el('canvas', 'eo-gl', root); + canvas.setAttribute('aria-hidden', 'true'); + const lensKnobs = DHS.lens ? DHS.lens.fromQuery(G.location ? G.location.search : '', essay.lens || null) : null; + const host = + DHS.gl && DHS.gl.host && params.get('gl') !== '0' + ? DHS.gl.host(canvas, { essay, lens: lensKnobs, reduced }) + : null; + const transDur = (type) => + DHS.gl && DHS.gl.transitions && DHS.gl.transitions[type] ? DHS.gl.transitions[type].dur : 1; + const TL = B.compile(essay, { transDur }); + + // ---- words + const textRoot = el('div', 'eo-textroot', root); + textRoot.style.cssText = 'position:absolute;inset:0;pointer-events:none'; + textRoot.setAttribute('aria-hidden', 'true'); + const text = DHS.essayText + ? DHS.essayText.create(textRoot, TL, essay, { reduced, host }) + : plainText(textRoot, TL, essay); + const live = el('div', 'eo-sr', root); // screen readers hear each beat's words once + live.setAttribute('aria-live', 'polite'); + + const black = el('div', 'eo-black', root); + const note = el( + 'div', + 'eo-note', + root, + "This screen can't draw the moving pictures. The words and numbers still play." + ); + note.setAttribute('role', 'status'); + const nogl = () => { + root.classList.add('eo-nogl'); + canvas.style.display = 'none'; + note.hidden = false; + }; + note.hidden = true; + if (!host || !host.ok) nogl(); + if (host) host.onfail = nogl; + + // ---- controls + const ui = el('div', 'eo-ui', root); + const bar = el('div', 'eo-bar', ui); + bar.setAttribute('role', 'slider'); + bar.setAttribute('aria-label', 'Progress'); + bar.tabIndex = -1; + const segs = TL.chapters.map((c) => { + const s = el('div', 'eo-seg', bar); + s.style.flex = String(Math.max(0.001, c.end - c.start)); + s.title = c.name; + return { c, fill: el('i', '', s) }; + }); + const row = el('div', 'eo-row', ui); + const bBack = el('button', '', row, '←'); + bBack.setAttribute('aria-label', 'Back'); + const bPlay = el('button', '', row, 'Pause'); + const bNext = el('button', '', row, '→'); + bNext.setAttribute('aria-label', 'Next'); + const where = el('div', 'eo-where', row); + const bAuto = el('button', '', row); + const bHelp = el('button', '', row, '?'); + bHelp.setAttribute('aria-label', 'Keys and help'); + const bFull = el('button', '', row, 'Full screen'); + + const help = el('div', 'eo-help', root); + help.hidden = true; + help.innerHTML = ``; + + const start = el('div', 'eo-start', root); + start.innerHTML = + `

${esc(essay.title || '')}

` + + (essay.subtitle ? `

${esc(essay.subtitle)}

` : '') + + `
${opts.sound ? '' : ''}
` + + `Press ? for keys`; + if (manual) { + start.hidden = true; + root.classList.add('eo-on', 'eo-idle'); // stills: no controls until the mouse moves + } + + // ---- state + const clock = B.clock(60); + const st = { + started: manual, + playing: !manual, + auto: essay.autoplay !== false, + rate: 1, + stopAt: null, + target: null, + lastKey: '', + dirty: true, + audio: null, + }; + const setAuto = (a) => { + st.auto = a; + bAuto.textContent = a ? 'Plays by itself' : 'Waits for clicks'; + bAuto.setAttribute('aria-pressed', String(a)); + }; + setAuto(st.auto); + const setPlaying = (p) => { + st.playing = p; + bPlay.textContent = p ? 'Pause' : 'Play'; + }; + + const S = () => TL.at(clock.t, { reduced: reduced() }); + const fi = () => TL.flatIndex(clock.t); + const keyOf = (s) => TL.scenes[s.scene].id + '-' + (Math.max(0, s.beat) + 1); + + // jump straight to a time (seeks, links, long backs) + const jump = (t) => { + clock.set(t); + st.target = null; + st.rate = 1; + st.dirty = true; + }; + // where "next" plays to: finish the current beat; else play the next one in (its scene's transition first) + const next = (user = true) => { + const s = S(), + F = TL.flat, + k = fi(), + cur = F[k].B; + st.target = null; + st.rate = 1; + if (clock.t < cur.shown - 1e-3) jump(cur.shown); + else if (k + 1 < F.length) { + const n = F[k + 1]; + jump(n.beat === 0 ? TL.scenes[n.scene].start : n.B.start); + st.stopAt = st.auto ? null : n.B.shown; + } else jump(TL.total); + st.nav = user; + setPlaying(true); + void s; + }; + // back: run back at 2.4x to the previous beat, fully shown (jump if that would take more than 3 s) + const back = () => { + const F = TL.flat, + k = Math.max(0, fi() - 1); + const to = F[k].B.shown; + if (to >= clock.t) return jump(to); + st.nav = true; + if ((clock.t - to) / 2.4 > 3 || reduced()) jump(to); + else { + st.target = to; + st.rate = -2.4; + } + st.stopAt = st.auto ? null : to; + setPlaying(true); + }; + const goBeat = (i, j, where = 'shown') => { + jump(TL.timeOf(i, j, where)); + st.stopAt = null; + }; + const fromHash = () => { + const m = /^#(.+)-(\d+)$/.exec((G.location && G.location.hash) || ''); + if (!m) return false; + const i = TL.sceneIndex(decodeURIComponent(m[1])); + if (i < 0) return false; + goBeat(i, +m[2] - 1); + return true; + }; + + // ---- the frame + let lastKey = '', + lastLive = ''; + const draw = () => { + const s = S(); + if (host && host.ok) host.render(s); + text.render(s); + // progress, place, link + segs.forEach( + ({ c, fill }) => + (fill.style.width = (100 * B.clamp01((s.t - c.start) / Math.max(1e-6, c.end - c.start))).toFixed(2) + '%') + ); + bar.setAttribute('aria-valuenow', String(Math.round((100 * s.t) / TL.total))); + const key = keyOf(s); + if (key !== lastKey && st.started) { + lastKey = key; + const sc = TL.scenes[s.scene]; + where.textContent = + (sc.chapter ? sc.chapter + ' · ' : '') + 'part ' + (s.scene + 1) + ' of ' + TL.scenes.length; + if (G.history && G.location && !manual) { + const url = '#' + encodeURIComponent(sc.id) + '-' + (Math.max(0, s.beat) + 1); + if (G.location.hash !== url) G.history[st.nav ? 'pushState' : 'replaceState'](null, '', url); + } + st.nav = false; + const b = essay.scenes[s.scene].beats && essay.scenes[s.scene].beats[Math.max(0, s.beat)]; + const said = b ? (b.text || []).map((x) => (typeof x === 'string' ? x : x.text)).join(' ') : ''; + if (said && said !== lastLive) live.textContent = lastLive = said; + } + if (opts.sound && st.audio) opts.sound.update(s.t, st.playing); + }; + + let prev = 0; + const frame = (now) => { + G.requestAnimationFrame(frame); + const dt = prev ? (now - prev) / 1000 : 0; + prev = now; + if (st.started && st.playing) { + const before = clock.t; + clock.advance(dt, st.rate); + if (st.target != null && clock.t <= st.target) { + clock.set(st.target); + st.target = null; + st.rate = 1; + if (!st.auto) setPlaying(false); + } + if (st.stopAt != null && clock.t >= st.stopAt && st.rate > 0) { + clock.set(st.stopAt); + st.stopAt = null; + setPlaying(false); + } + // waiting for clicks: stop when the current beat is fully shown + if (!st.auto && st.rate > 0 && st.stopAt == null) { + const cur = TL.flat[fi()].B; + if (before < cur.shown && clock.t >= cur.shown) { + clock.set(cur.shown); + setPlaying(false); + } + } + if (clock.t >= TL.total) { + clock.set(TL.total); + setPlaying(false); + bPlay.textContent = 'Play again'; + } + if (clock.t !== before) st.dirty = true; + } + if (st.dirty) { + st.dirty = false; + draw(); + } + }; + + // ---- resize (pixel density capped at 2, picture capped at 2560 x 1600) + const resize = () => { + const r = root.getBoundingClientRect(); + let d = Math.min(2, G.devicePixelRatio || 1); + d = Math.min(d, 2560 / Math.max(1, r.width), 1600 / Math.max(1, r.height), d); + if (host && host.ok) + host.resize(Math.max(2, Math.round(r.width * d)), Math.max(2, Math.round(r.height * d)), r.width, r.height); + if (text.resize) text.resize(r.width, r.height); + st.dirty = true; + }; + G.addEventListener('resize', resize); + + // ---- input + let idleT = 0; + const wake = () => { + root.classList.remove('eo-idle'); + G.clearTimeout(idleT); + idleT = G.setTimeout(() => { + if (help.hidden && st.started) root.classList.add('eo-idle'); + }, 3000); + }; + root.addEventListener('mousemove', wake); + const inUI = (e) => e.target.closest && e.target.closest('.eo-ui,.eo-help,.eo-start'); + root.addEventListener('click', (e) => { + if (!st.started || inUI(e) || e.pointerType === 'touch') return; + next(); + }); + root.addEventListener('contextmenu', (e) => { + if (!st.started || inUI(e)) return; + e.preventDefault(); + back(); + }); + let tx = null, + ty = 0; + root.addEventListener('touchstart', (e) => { + tx = e.touches[0].clientX; + ty = e.touches[0].clientY; + }); + root.addEventListener('touchend', (e) => { + if (tx == null || !st.started) return; + const t = e.changedTouches[0], + dx = t.clientX - tx, + dy = t.clientY - ty; + tx = null; + if (inUI(e)) return; + if (Math.abs(dx) > 50 && Math.abs(dx) > Math.abs(dy)) dx < 0 ? next() : back(); + else wake(); // a tap shows the controls + }); + const toggleHelp = (on = help.hidden) => { + help.hidden = !on; + if (on) help.querySelector('button').focus(); + wake(); + }; + const fullscreen = () => { + if (doc.fullscreenElement) doc.exitFullscreen(); + else if (root.requestFullscreen) root.requestFullscreen().catch(() => {}); + }; + G.addEventListener('keydown', (e) => { + if (e.ctrlKey || e.metaKey || e.altKey) return; + if (!st.started) return; + const k = e.key; + if (!help.hidden && (k === 'Escape' || k === '?')) return toggleHelp(false); + if (e.target.tagName === 'BUTTON' && (k === ' ' || k === 'Enter')) return; + const act = { + ' ': next, + ArrowRight: next, + PageDown: next, + Enter: next, + ArrowLeft: back, + PageUp: back, + Backspace: back, + a: () => setAuto(!st.auto), + A: () => setAuto(!st.auto), + k: () => setPlaying(!st.playing), + K: () => setPlaying(!st.playing), + '.': () => black.classList.toggle('on'), + f: fullscreen, + F: fullscreen, + '?': () => toggleHelp(), + h: () => toggleHelp(), + Home: () => goBeat(0, 0), + End: () => goBeat(TL.scenes.length - 1, 1e9), + }[k]; + if (act) { + e.preventDefault(); + act(); + wake(); + } + }); + bBack.onclick = () => back(); + bNext.onclick = () => next(); + bPlay.onclick = () => { + if (clock.t >= TL.total) jump(0); + setPlaying(!st.playing); + }; + bAuto.onclick = () => setAuto(!st.auto); + bHelp.onclick = () => toggleHelp(); + bFull.onclick = fullscreen; + help.querySelector('button').onclick = () => toggleHelp(false); + bar.addEventListener('click', (e) => { + const r = bar.getBoundingClientRect(), + x = (e.clientX - r.left) / r.width; + // the segments have gaps, so find the chapter under the pointer and the fraction inside it + let t = x * TL.total; + for (const { c } of segs) { + const sr = segs.find((q) => q.c === c).fill.parentNode.getBoundingClientRect(); + if (e.clientX >= sr.left - 3 && e.clientX <= sr.right + 3) + t = c.start + B.clamp01((e.clientX - sr.left) / sr.width) * (c.end - c.start); + } + const k = TL.flatIndex(t); + st.nav = true; + goBeat(TL.flat[k].scene, TL.flat[k].beat, 'shown'); + }); + G.addEventListener('popstate', () => fromHash()); + G.addEventListener('hashchange', () => fromHash()); + + const begin = (withSound) => { + start.hidden = true; + st.started = true; + root.classList.add('eo-on'); + if (withSound && opts.sound) { + try { + const AC = G.AudioContext || G.webkitAudioContext; + st.audio = new AC({ sampleRate: 48000 }); + opts.sound.start(st.audio); + } catch (err) { + console.warn('essay: no sound', err); + } + } + if (!fromHash()) jump(0); + setPlaying(true); + if (!note.hidden) G.setTimeout(() => (note.hidden = true), 8000); // said once; then out of the words' way + fullscreen(); + wake(); + }; + start.querySelectorAll('button').forEach((b) => (b.onclick = () => begin(b.dataset.s === '1'))); + + // ---- test hooks: repeatable stills of any beat or any point in a transition + const E = { + TL, + host, + // scene: index or id; beat: index (-1 = the start of its transition); t: seconds after the beat starts, + // or 'shown' (fully in) / 'end' (the last frame of its hold) + seek(scene, beat = 0, t = 'shown') { + const i = TL.sceneIndex(scene), + Sc = TL.scenes[i]; + if (beat < 0) jump(Sc.start); + else { + const b = Sc.beats[Math.min(beat, Sc.beats.length - 1)]; + jump(t === 'shown' ? b.shown : t === 'end' ? b.end - 1e-3 : b.start + t); + } + setPlaying(false); + draw(); + return E.state(); + }, + // the transition into scene `scene` at progress p (0..1) + trans(scene, p) { + const Sc = TL.scenes[TL.sceneIndex(scene)]; + jump(Sc.start + B.clamp01(p) * Sc.trans.dur * 0.99999); + setPlaying(false); + draw(); + return E.state(); + }, + at(t) { + jump(t); + setPlaying(false); + draw(); + return E.state(); + }, + // ms per frame for a scene (GPU finished each frame), drawn n times at its last beat + perf(scene, n = 60) { + if (!host || !host.ok) return null; + E.seek(scene, 1e9, 'shown'); + const s = S(); + const t0 = G.performance.now(); + for (let f = 0; f < n; f++) { + host.render(Object.assign({}, s, { sceneT: s.sceneT + f / 60, t: s.t + f / 60 })); + host.finish(); // wait for the GPU each frame (reads one pixel: finish alone may not wait) + } + return (G.performance.now() - t0) / n; + }, + // the 3-flashes-a-second rule (WCAG 2.3.1) for the transition into `scene`: the picture is stepped at 60 fps + // from 0.5 s before to 0.5 s after; in each cell of a 16 x 9 grid, a change is a swing in relative luminance + // of at least 0.1 with the darker side under 0.8, and a flash is two opposing changes + flashCheck(scene, cols = 16, rows = 9) { + if (!host || !host.ok) return null; + const Sc = TL.scenes[TL.sceneIndex(scene)], + t0 = Math.max(0, Sc.start - 0.5), + t1 = Math.min(TL.total, Sc.body + 0.5), + n = Math.round((t1 - t0) * 60); + const series = []; + for (let f = 0; f <= n; f++) { + host.render(TL.at(t0 + f / 60, { reduced: reduced() })); + series.push(host.lumaGrid(cols, rows)); + } + const { maxPerSecond, maxStep } = flashCount(series); + draw(); + return { maxPerSecond, maxStep, frames: series.length, pass: maxPerSecond <= 3 }; + }, + state() { + const s = S(); + return { + t: s.t, + total: TL.total, + scene: s.scene, + id: s.id, + beat: s.beat, + trans: s.trans, + gl: !!(host && host.ok), + reduced: reduced(), + }; + }, + textBoxes: () => text.boxes(), + contrast: () => (text.contrast ? text.contrast() : []), + hideGlyphs: (on) => { + text.hideGlyphs(on); + }, + next, + back, + begin, + setAuto, + }; + G.EOMD_ESSAY = E; + + resize(); + if (manual) { + setPlaying(false); + draw(); + } + G.requestAnimationFrame(frame); + return E; + } + + DHS.essay = { mount, flashCount }; +})(globalThis); diff --git a/kit/essay/text.js b/kit/essay/text.js new file mode 100644 index 0000000..55af317 --- /dev/null +++ b/kit/essay/text.js @@ -0,0 +1,349 @@ +/* EOMD kit: essay/text.js. Copyright (C) 2026 Bryan Patrick Murphy. SPDX-License-Identifier: AGPL-3.0-only + Copied from engine/src/essay/text.js (https://github.com/BPMData/EOMD) by tools/build_kit.py: change the source in EOMD, not this copy. */ +/* ESSAY TEXT: the words over the picture, in HTML (sharp at any size, selectable by screen readers through the + player's live region, and still there without WebGL2). A beat's text is a list of blocks: + { pos, kind, text } + pos center, chapter, quote (these three share the middle), lower-third, top-left, top-right, bottom-left, + bottom-right. Several blocks of one beat at one position stack (a big number and its caption). + kind body, headline, chapter, quote, source, number, note + The text is shown exactly as written; only its timing comes from it. + + Timing (a pure function of t, so seeks and stills match playback): + - a beat's blocks at one position arrive word by word when the beat arrives (each word fades in over 0.6 s, + about 0.09 s apart; a number arrives whole); + - they stay until a later beat puts text at the same position (then they fade out over 0.5 s while the new + text fades in), or until the scene ends (they fade out in the first 40% of the next transition); + - prefers-reduced-motion: each group fades in whole over 0.3 s, nothing moves. + Behind each group is a soft dark patch (a dark rounded box with soft edges, no glow) so the words hold on any picture. + Data labels from the scene (DHS.gl.sceneLabels: values, categories, the placeholder note) are drawn here too. + + const X = DHS.essayText.create(root, timeline, essay, { reduced, host }); + X.render(state); X.resize(w, h); X.boxes(); X.hideGlyphs(on); + X.contrast() -> [{ key, text, kind, ratio, need, against, pass }] WCAG contrast of each visible group against + the brightest and darkest picture pixels under it, with the patch composited in + Restyle with CSS variables on the player root: --eo-ink, --eo-font, --eo-display, --eo-serif, --eo-patch. */ +(function (G) { + 'use strict'; + const DHS = (G.DHS = G.DHS || {}); + const doc = G.document; + + const SLOT = { center: 'middle', chapter: 'middle', quote: 'middle' }; + const PATCH = { + body: 0.55, + headline: 0.5, + chapter: 0.42, + quote: 0.5, + source: 0.55, + number: 0.45, + note: 0.55, + label: 0.5, + }; + const CSS = ` +.eo-text{position:absolute;inset:0;pointer-events:none;color:var(--eo-ink,#f3f0e8);--m:max(5vw,env(safe-area-inset-left));--mt:max(8vh,env(safe-area-inset-top));--mb:calc(max(8vh,env(safe-area-inset-bottom)) + 44px)} +.eo-pos{position:absolute;display:grid} +.eo-pos>.eo-g{grid-area:1/1;position:relative;padding:.9em 1.3em} +.eo-g>.eo-patch{position:absolute;inset:0;z-index:-1;border-radius:1.4em;background:rgba(0,0,0,var(--a));box-shadow:0 0 2.6em 1.2em rgba(0,0,0,var(--a))} +.eo-pos{z-index:0;isolation:isolate} +.eo-p-middle{left:50%;top:50%;transform:translate(-50%,-50%);width:min(30em,84vw);text-align:center} +.eo-g.eo-gp-quote{text-align:left} +.eo-p-lower-third{left:var(--m);right:var(--m);bottom:var(--mb);max-width:40em} +.eo-p-top-left{left:var(--m);top:var(--mt);width:min(28em,52vw)} +.eo-p-top-right{right:var(--m);top:var(--mt);width:min(28em,52vw)} +.eo-p-bottom-left{left:var(--m);bottom:var(--mb);width:min(28em,52vw)} +.eo-p-bottom-right{right:var(--m);bottom:var(--mb);width:min(28em,52vw);text-align:right} +.eo-b{margin:0}.eo-b+.eo-b{margin-top:.5em} +.eo-k-body{font-size:var(--eo-body,clamp(18px,1.1vw + 1.1vmin,34px));line-height:1.42;font-weight:400} +.eo-k-headline{font-family:var(--eo-display,inherit);font-size:clamp(26px,2vw + 2vmin,60px);line-height:1.12;font-weight:600;letter-spacing:-.01em} +.eo-k-chapter{font-family:var(--eo-display,inherit);font-size:clamp(30px,2.6vw + 2.4vmin,76px);line-height:1.1;font-weight:500;letter-spacing:.01em} +.eo-k-quote{font-family:var(--eo-serif,Georgia,"Times New Roman",serif);font-style:italic;font-size:clamp(22px,1.5vw + 1.5vmin,44px);line-height:1.35} +.eo-k-source{font-size:clamp(14px,.6vw + .8vmin,20px);line-height:1.4;opacity:.92} +.eo-k-number{font-family:var(--eo-display,inherit);font-size:clamp(44px,5vw + 4vmin,150px);line-height:1;font-weight:600;font-variant-numeric:tabular-nums;letter-spacing:-.02em} +.eo-w{display:inline-block;will-change:opacity} +.eo-hide .eo-w,.eo-hide .eo-lb{color:transparent!important} +.eo-lb{position:absolute;left:0;top:0;white-space:nowrap;font-size:clamp(13px,.5vw + .9vmin,22px);font-variant-numeric:tabular-nums;padding:.25em .6em; + border-radius:.8em; + background:rgba(0,0,0,${PATCH.label});box-shadow:0 0 .9em .4em rgba(0,0,0,${PATCH.label})} +.eo-lb.eo-k-value{font-weight:600;font-size:clamp(15px,.7vw + 1vmin,26px)} +.eo-lb.eo-k-note{font-size:clamp(12px,.4vw + .8vmin,17px);opacity:.95} +@media (max-width:700px){.eo-p-top-left,.eo-p-top-right,.eo-p-bottom-left,.eo-p-bottom-right{width:auto;left:var(--m);right:var(--m)}} +`; + + const el = (tag, cls, parent) => { + const e = doc.createElement(tag); + if (cls) e.className = cls; + if (parent) parent.appendChild(e); + return e; + }; + const clamp01 = (x) => (x < 0 ? 0 : x > 1 ? 1 : x); + const smooth = (x) => ((x = clamp01(x)), x * x * (3 - 2 * x)); + + function create(root, TL, essay, opts = {}) { + const reduced = opts.reduced || (() => false), + host = opts.host; + if (!doc.getElementById('eo-text-css')) { + const st = el('style', '', doc.head); + st.id = 'eo-text-css'; + st.textContent = CSS; + } + const layer = el('div', 'eo-text', root); + layer.setAttribute('aria-hidden', 'true'); // the player's live region reads the words once + let W = 1, + H = 1; + + // build every scene's groups once + const scenes = essay.scenes.map((spec, i) => { + const S = TL.scenes[i], + box = el('div', '', layer); + box.style.display = 'none'; + const posEls = {}, + groups = []; + (spec.beats || []).forEach((b, j) => { + const byPos = {}; + (b.text || []).forEach((x) => { + const blk = typeof x === 'string' ? { text: x } : x; + const pos = blk.pos || 'lower-third'; + (byPos[pos] = byPos[pos] || []).push(blk); + }); + Object.keys(byPos).forEach((pos) => { + // center, chapter and quote share the middle of the screen: a later one there replaces an earlier one + const slot = SLOT[pos] || pos; + if (!posEls[slot]) posEls[slot] = el('div', 'eo-pos eo-p-' + slot, box); + const g = el('div', 'eo-g eo-gp-' + pos, posEls[slot]), + patch = el('div', 'eo-patch', g); + const kind0 = byPos[pos][0].kind || 'body'; + const alpha = Math.max(...byPos[pos].map((x) => PATCH[x.kind || 'body'] || 0.5)); + patch.style.setProperty('--a', String(alpha)); + const words = [], + blocks = []; + byPos[pos].forEach((blk) => { + const kind = blk.kind || 'body', + p = el('p', 'eo-b eo-k-' + kind, g), + bw = []; + blocks.push({ kind, text: String(blk.text), words: bw }); + // exact text: words become spans, the whitespace between them is kept as it was + String(blk.text) + .split(/(\s+)/) + .forEach((part) => { + if (!part) return; + if (/^\s+$/.test(part)) return p.appendChild(doc.createTextNode(part)); + const w = el('span', 'eo-w', p); + w.textContent = part; + words.push({ el: w, whole: kind === 'number', last: '' }); + bw.push(w); + }); + }); + groups.push({ + pos: slot, + beat: j, + g, + patch, + words, + blocks, + alpha, + kind: kind0, + text: byPos[pos].map((x) => x.text).join(' '), + start: S.beats[j].arrive, + out: null, + last: '', + }); + }); + }); + // when each group leaves: the next group at the same position, or the next scene's transition + const nextS = TL.scenes[i + 1]; + groups.forEach((gr, k) => { + const later = groups.slice(k + 1).find((x) => x.pos === gr.pos && x.beat > gr.beat); + if (later) gr.out = [later.start, later.start + 0.5]; + else if (nextS) + gr.out = + nextS.trans.dur > 0 + ? [nextS.start, nextS.start + 0.4 * nextS.trans.dur] + : [nextS.start - 1e-6, nextS.start]; + else gr.out = null; // the last scene's words stay to the end + }); + return { box, groups, labels: [], lbBox: el('div', '', box) }; + }); + + const setOp = (o, e, v) => { + const s = v.toFixed(3); + if (o.last !== s) { + e.style.opacity = s; + o.last = s; + } + }; + const groupOp = (gr, t) => { + const red = reduced(); + if (t < gr.start) return 0; + const inn = red ? clamp01((t - gr.start) / 0.3) : 1; + return gr.out ? inn * (1 - smooth((t - gr.out[0]) / Math.max(1e-6, gr.out[1] - gr.out[0]))) : inn; + }; + const drawScene = (i, t, s, labelFade, p) => { + const sc = scenes[i], + red = reduced(); + sc.box.style.display = ''; + sc.groups.forEach((gr) => { + const op = groupOp(gr, t); + setOp(gr, gr.g, op); + gr.g.style.visibility = op > 0 ? 'visible' : 'hidden'; + const n = gr.words.length, + stag = red ? 0 : Math.min(0.09, 2.2 / Math.max(1, n)); + gr.words.forEach((w, k) => setOp(w, w.el, red ? 1 : clamp01((t - gr.start - (w.whole ? 0 : k * stag)) / 0.6))); + }); + // data labels + const spec = essay.scenes[i]; + const L = DHS.gl && DHS.gl.sceneLabels ? DHS.gl.sceneLabels(spec, p, W / H) : []; + while (sc.labels.length < L.length) + sc.labels.push({ el: el('div', 'eo-lb', sc.lbBox), last: '', txt: null, pos: '' }); + sc.labels.forEach((lb, k) => { + const d = L[k]; + if (!d) return (lb.el.style.display = 'none'); + lb.el.style.display = ''; + if (lb.txt !== d.text) lb.el.textContent = lb.txt = d.text; + lb.el.className = 'eo-lb eo-k-' + d.kind; + const x = (d.x / (W / H) + 0.5) * W, + y = (0.5 - d.y) * H, + ax = d.align === 'right' ? '-100%' : d.align === 'left' ? '0' : '-50%'; + const pos = `translate(${x.toFixed(1)}px,${y.toFixed(1)}px) translate(${ax},-50%)`; + if (lb.pos !== pos) lb.el.style.transform = lb.pos = pos; + lb.data = d; + setOp(lb, lb.el, d.alpha * labelFade); + }); + }; + let shown = new Set(); + const X = { + render(s) { + const now = new Set([s.scene]); + if (s.trans && s.trans.from >= 0) now.add(s.trans.from); + shown.forEach((i) => !now.has(i) && (scenes[i].box.style.display = 'none')); + shown = now; + if (s.trans && s.trans.from >= 0) { + const f = s.trans.from; + drawScene( + f, + s.t, + s, + 1 - smooth(s.trans.p / 0.4), + TL.scenes[f].beats.map(() => 1) + ); + } + drawScene(s.scene, s.t, s, s.trans ? smooth((s.trans.p - 0.6) / 0.4) : 1, s.p); + }, + resize(w, h) { + W = Math.max(1, w); + H = Math.max(1, h); + }, + hideGlyphs(on) { + layer.classList.toggle('eo-hide', !!on); + }, + // visible groups and labels with their screen rectangles (CSS pixels) + boxes() { + const out = []; + shown.forEach((i) => { + scenes[i].groups.forEach((gr) => { + if (+gr.last > 0.5) { + const pr = gr.patch.getBoundingClientRect(); + // one entry per paragraph: a big number and its small caption need different ratios + gr.blocks.forEach((b, n) => { + if (!b.words.length) return; + const wr = b.words.map((w) => w.getBoundingClientRect()); + out.push({ + key: i + ':' + gr.beat + ':' + gr.pos + ':' + n, + text: b.text, + kind: b.kind, + rect: b.words[0].parentNode.getBoundingClientRect(), + patch: pr, + alpha: gr.alpha * +gr.last, + words: wr, + el: b.words[0], + }); + }); + } + }); + scenes[i].labels.forEach((lb, k) => { + if (lb.el.style.display !== 'none' && +lb.last > 0.5) { + const r = lb.el.getBoundingClientRect(); + out.push({ + key: i + ':label:' + k, + text: lb.txt, + kind: lb.data.kind, + rect: r, + patch: r, + alpha: PATCH.label * +lb.last, + words: [r], + el: lb.el, + }); + } + }); + }); + return out; + }, + contrast() { + const px = host && host.ok ? host.pixels() : null; + const rootR = layer.getBoundingClientRect(); + const sx = px ? px.w / rootR.width : 1, + sy = px ? px.h / rootR.height : 1; + const lum = DHS.gl.relLum, + con = DHS.gl.contrast; + // with no picture (no WebGL2), the fallback background's lightest colour + const fallback = [0x1b, 0x1c, 0x22]; + return X.boxes().map((b) => { + const cs = G.getComputedStyle(b.el), + ink = cs.color.match(/[\d.]+/g).map(Number); + // the text's own opacity (fades, dimmed labels, a lighter source line), up to the layer + let op = 1; + for (let e = b.el; e && e !== layer; e = e.parentElement) op *= +G.getComputedStyle(e).opacity; + const size = parseFloat(cs.fontSize), + bold = +cs.fontWeight >= 600; + const need = size >= 24 || (bold && size >= 18.66) ? 3 : 4.5; + let worst = Infinity, + against = '', + lo = Infinity, + hi = -Infinity; + const samples = []; + b.words.forEach((r) => { + const step = Math.max(1, Math.floor(Math.min(r.width, r.height) / 6)); + for (let y = r.top; y <= r.bottom; y += step) + for (let x = r.left; x <= r.right; x += step) { + // inside the patch box the patch is solid (its soft edge lies outside, past the words) + const inside = x >= b.patch.left && x <= b.patch.right && y >= b.patch.top && y <= b.patch.bottom; + const a = inside ? b.alpha : 0; + let c = fallback; + if (px) { + const X0 = Math.min(px.w - 1, Math.max(0, Math.round((x - rootR.left) * sx))), + Y0 = Math.min(px.h - 1, Math.max(0, Math.round((y - rootR.top) * sy))); + const k = ((px.h - 1 - Y0) * px.w + X0) * 4; + c = [px.data[k], px.data[k + 1], px.data[k + 2]]; + } + const bg = c.map((v) => v * (1 - a)); + const l = lum(bg[0], bg[1], bg[2]); + lo = Math.min(lo, l); + hi = Math.max(hi, l); + samples.push([bg, l]); + } + }); + samples.forEach(([bg, l]) => { + // text drawn at opacity op over this pixel (CSS blends in sRGB) + const t = ink.slice(0, 3).map((v, i) => v * op + bg[i] * (1 - op)); + const r = con(lum(t[0], t[1], t[2]), l); + if (r < worst) { + worst = r; + against = l >= (lo + hi) / 2 ? 'brightest' : 'darkest'; + } + }); + return { + key: b.key, + text: b.text, + kind: b.kind, + ratio: worst, + need, + against, + opacity: +op.toFixed(3), + pass: worst >= need, + }; + }); + }, + }; + return X; + } + + DHS.essayText = { create, PATCH }; +})(globalThis); diff --git a/kit/fx/lens.js b/kit/fx/lens.js index 288c8b9..5a5efb1 100644 --- a/kit/fx/lens.js +++ b/kit/fx/lens.js @@ -20,6 +20,11 @@ L.draw(canvas, t); // every frame, after the 2D canvas is drawn L.set({ bloom: 0.5 }); L.onfail = () => {...}; L.dispose(); + On a GPU texture (kit 0.2.0): share the scene's WebGL2 context and pass its texture, so nothing is uploaded and + linear-light highlights above 1 reach the glow and tone curve at full strength: + const L = DHS.lens.create(knobs, { gl }); // draws into gl's default framebuffer + L.drawTexture(texture, w, h, t); // texture: linear light (e.g. a half-float render target) + Standalone: needs only the DHS namespace, so any build (CD-ROM, living posters, gen) can inline it. */ (function (G) { 'use strict'; @@ -60,9 +65,10 @@ float h13(vec3 p){p=fract(p*.1031);p+=dot(p,p.zyx+31.32);return fract((p.x+p.y)* // 13-tap downsample (sRGB source on the first level, with the soft threshold); linear light after that const DOWN = HEAD + - `uniform sampler2D S;uniform vec2 uPx;uniform float uFirst,uTh,uKnee; + `uniform sampler2D S;uniform vec2 uPx;uniform float uFirst,uTh,uKnee,uLin; vec3 s(vec2 d){vec3 c=texture(S,v+d*uPx).rgb; - if(uFirst>.5){float m=max(c.r,max(c.g,c.b));c=toLin(c)*smoothstep(uTh-uKnee,uTh+uKnee,m);c/=1.+luma(c)*.12;} + if(uFirst>.5){vec3 g=uLin>.5?toSrgb(min(c,1.)):c;float m=max(g.r,max(g.g,g.b)); + c=(uLin>.5?max(c,0.):toLin(c))*smoothstep(uTh-uKnee,uTh+uKnee,m);c/=1.+luma(c)*.12;} return c;} void main(){vec3 c=s(vec2(0))*.125; c+=(s(vec2(-1,-1))+s(vec2(1,-1))+s(vec2(-1,1))+s(vec2(1,1)))*.125; @@ -79,7 +85,7 @@ void main(){vec3 c=vec3(0); const POST = HEAD + `uniform sampler2D S,B,SB;uniform vec2 R;uniform vec3 uTint,uLift,uGain; -uniform float uExp,uBloom,uHal,uStreak,uFringe,uTone,uCon,uSat,uVig,uGrain,uDither,uSeed; +uniform float uExp,uBloom,uHal,uStreak,uFringe,uTone,uCon,uSat,uVig,uGrain,uDither,uSeed,uLin; vec3 aces(vec3 x){return clamp((x*(2.51*x+.03))/(x*(2.43*x+.59)+.14),0.,1.);} vec3 agx(vec3 v){const mat3 M=mat3(.842479062253094,.0423282422610123,.0423756549057051,.0784335999999992,.878468636469772,.0784336,.0792237451477643,.0791661274605434,.879142973793104); v=M*v;v=clamp(log2(max(v,1e-10)),-12.47393,4.026069);v=(v+12.47393)/(4.026069+12.47393); @@ -89,9 +95,9 @@ vec3 agx(vec3 v){const mat3 M=mat3(.842479062253094,.0423282422610123,.042375654 void main(){vec2 q=v-.5; vec3 src=texture(S,v).rgb,c=src; if(uFringe>0.){vec2 off=q*1.41421*(dot(q,q)*2.)*uFringe/R;c.r=texture(S,v+off).r;c.b=texture(S,v-off).b;} - bool touched=uExp!=1.||uBloom>0.||uStreak>0.||uTone>.5; + bool touched=uLin>.5||uExp!=1.||uBloom>0.||uStreak>0.||uTone>.5; if(touched){ - c=toLin(c)*uExp; + c=(uLin>.5?max(c,0.):toLin(c))*uExp; if(uBloom>0.)c+=texture(B,v).rgb*uBloom*vec3(1.+uHal*.35,1.-uHal*.05,1.-uHal*.35); if(uStreak>0.){vec3 st=vec3(0);float ws=0.; for(int i=1;i<17;i++){float fi=float(i),w=exp(-fi*.21);ws+=2.*w; @@ -113,22 +119,25 @@ void main(){vec2 q=v-.5; const reduced = () => !!(G.matchMedia && G.matchMedia('(prefers-reduced-motion: reduce)').matches); const TONE = { none: 0, aces: 1, film: 1, agx: 2 }; - function create(knobs = {}) { + function create(knobs = {}, shared = null) { const k = Object.assign({}, DEFAULTS, knobs); - const canvas = G.document ? G.document.createElement('canvas') : null; + const canvas = shared && shared.gl ? shared.gl.canvas : G.document ? G.document.createElement('canvas') : null; const api = { canvas, ok: false, knobs: k, onfail: null }; api.set = (o) => Object.assign(k, o); api.draw = () => false; api.dispose = () => {}; if (!canvas) return api; // preserveDrawingBuffer: stills and MP4 frames (page screenshots, toDataURL) always see the last frame - const gl = canvas.getContext('webgl2', { - alpha: false, - antialias: false, - depth: false, - stencil: false, - preserveDrawingBuffer: true, - }); + const gl = + shared && shared.gl + ? shared.gl + : canvas.getContext('webgl2', { + alpha: false, + antialias: false, + depth: false, + stencil: false, + preserveDrawingBuffer: true, + }); if (!gl) return api; const mk = (fs) => { @@ -190,6 +199,7 @@ void main(){vec2 q=v-.5; const BLOOM_K = 0.5; // calibration: bloom 0.25 matches the first lens next to a bright edge, with a wider, softer tail let P = null, src = null, + vao = null, down = [], up = [], W = 0, @@ -206,7 +216,7 @@ void main(){vec2 q=v-.5; if (!P.down || !P.up || !P.post) return false; half = !!gl.getExtension('EXT_color_buffer_float') || !!gl.getExtension('EXT_color_buffer_half_float'); gl.getExtension('OES_texture_float_linear'); - const vao = gl.createVertexArray(); + vao = gl.createVertexArray(); gl.bindVertexArray(vao); gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer()); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW); // one triangle over the screen @@ -250,17 +260,14 @@ void main(){vec2 q=v-.5; }; const tri = () => gl.drawArrays(gl.TRIANGLES, 0, 3); - // source: any canvas, image or video. t: seconds (seeds grain and dither). - api.draw = (source, t = 0) => { - if (!api.ok || lost) return false; - const w = source.width, - h = source.height; - if (!w || !h) return false; + const size = (w, h) => { if (w !== W || h !== H) { W = w; H = h; - canvas.width = w; - canvas.height = h; + if (!shared) { + canvas.width = w; + canvas.height = h; + } freeAll(); for (let l = 0; l < MAXL; l++) { const s = 2 << l, @@ -270,11 +277,29 @@ void main(){vec2 q=v-.5; up.push(target(lw, lh)); } } + }; + // source: any canvas, image or video. t: seconds (seeds grain and dither). + api.draw = (source, t = 0) => { + if (!api.ok || lost) return false; + const w = source.width, + h = source.height; + if (!w || !h) return false; + size(w, h); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, src); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); + return run(src, t, 0); + }; + // texture: a GPU texture in this context holding linear light, w x h (the output size) + api.drawTexture = (texture, w, h, t = 0) => { + if (!api.ok || lost || !w || !h) return false; + size(w, h); + return run(texture, t, 1); + }; + const run = (srcTex, t, lin) => { + gl.bindVertexArray(vao); const glow = k.bloom > 0 || k.streak > 0, L = Math.max(1, Math.min(MAXL, Math.round(k.levels))); @@ -282,13 +307,14 @@ void main(){vec2 q=v-.5; streakTex = down[0].t, streakN = 1; if (glow) { - let prev = src, + let prev = srcTex, pw = W, ph = H; for (let l = 0; l < L; l++) { pass(P.down, down[l], [['S', prev]]); setf(P.down.u, 'uPx', 1 / pw, 1 / ph); setf(P.down.u, 'uFirst', l ? 0 : 1); + setf(P.down.u, 'uLin', lin); setf(P.down.u, 'uTh', k.threshold); setf(P.down.u, 'uKnee', Math.max(1e-3, k.knee)); tri(); @@ -315,12 +341,13 @@ void main(){vec2 q=v-.5; const u = P.post.u, seedN = reduced() ? 0 : Math.floor(Math.max(0, t) * k.grainFps); pass(P.post, null, [ - ['S', src], + ['S', srcTex], ['B', glowTex], ['SB', streakTex], ]); setf(u, 'R', W, H); setf(u, 'uExp', k.exposure); + setf(u, 'uLin', lin); setf(u, 'uBloom', glow ? (k.bloom * BLOOM_K) / L : 0); setf(u, 'uHal', k.halation); setf(u, 'uStreak', glow ? k.streak / streakN : 0); @@ -340,6 +367,7 @@ void main(){vec2 q=v-.5; }; api.dispose = () => { freeAll(); + if (shared) return void (api.ok = false); const x = gl.getExtension('WEBGL_lose_context'); if (x) x.loseContext(); api.ok = false; diff --git a/kit/gl/gl.js b/kit/gl/gl.js new file mode 100644 index 0000000..9b57cca --- /dev/null +++ b/kit/gl/gl.js @@ -0,0 +1,144 @@ +/* EOMD kit: gl/gl.js. Copyright (C) 2026 Bryan Patrick Murphy. SPDX-License-Identifier: AGPL-3.0-only + Copied from engine/src/gl/gl.js (https://github.com/BPMData/EOMD) by tools/build_kit.py: change the source in EOMD, not this copy. */ +/* GL: the small plain-WebGL2 toolkit under the essay picture (no three.js, no libraries). + DHS.gl.context(canvas) a WebGL2 context for stills and export (preserveDrawingBuffer), or null + DHS.gl.program(gl, fs[, vs]) { p, u } with every uniform location, or null (the log goes to the console) + DHS.gl.target(gl, w, h) a render target { t, f, w, h }: half-float when the GPU can, so scenes keep + their full range (highlights above 1 reach the lens's glow and tone curve) + DHS.gl.tri(gl) binds a vertex array with one triangle over the screen; draw with + gl.drawArrays(gl.TRIANGLES, 0, 3) + DHS.gl.LIB the shared GLSL preamble for scenes and transitions (below) + Scenes write linear light; the lens (or the plain presenter in the host) turns it into screen colour. + + GLSL preamble (DHS.gl.LIB): + toLin, toSrgb, luma colour space helpers + h11, h21, h22, noise(vec2), fbm(vec2, octaves) hash and value noise, all deterministic + sdCircle, sdBox, sdRoundBox, sdCapsule, sdTorus, smin distance-field shapes (2D, torus in 3D) + aa(d, px) antialiased coverage of a distance field + studio(n, base) a fake studio light on a surface normal: softbox key from upper left, a soft + fill, a rim from behind, and a floor bounce. The "real object under studio + light" look without image files. + Standalone: needs only the DHS namespace. */ +(function (G) { + 'use strict'; + const DHS = (G.DHS = G.DHS || {}); + const GL = (DHS.gl = DHS.gl || {}); + + GL.VS = `#version 300 es +in vec2 a;out vec2 v;void main(){v=a*.5+.5;gl_Position=vec4(a,0.,1.);}`; + + GL.LIB = ` +vec3 toLin(vec3 c){return mix(c/12.92,pow((c+.055)/1.055,vec3(2.4)),step(.04045,c));} +vec3 toSrgb(vec3 c){c=max(c,0.);return mix(c*12.92,1.055*pow(c,vec3(1./2.4))-.055,step(.0031308,c));} +float luma(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} +float h11(float p){p=fract(p*.1031);p*=p+33.33;p*=p+p;return fract(p);} +float h21(vec2 p){vec3 q=fract(vec3(p.xyx)*.1031);q+=dot(q,q.yzx+33.33);return fract((q.x+q.y)*q.z);} +vec2 h22(vec2 p){vec3 q=fract(vec3(p.xyx)*vec3(.1031,.103,.0973));q+=dot(q,q.yzx+33.33);return fract((q.xx+q.yz)*q.zy);} +float noise(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);} +float fbm(vec2 p,int oct){float s=0.,a=.5;for(int i=0;i<8;i++){if(i>=oct)break;s+=a*noise(p);p=p*2.03+vec2(17.1,9.7);a*=.5;}return s;} +float sdCircle(vec2 p,float r){return length(p)-r;} +float sdBox(vec2 p,vec2 b){vec2 d=abs(p)-b;return length(max(d,0.))+min(max(d.x,d.y),0.);} +float sdRoundBox(vec2 p,vec2 b,float r){return sdBox(p,b-r)-r;} +float sdCapsule(vec2 p,vec2 a,vec2 b,float r){vec2 pa=p-a,ba=b-a;float h=clamp(dot(pa,ba)/dot(ba,ba),0.,1.);return length(pa-ba*h)-r;} +float sdTorus(vec3 p,vec2 t){vec2 q=vec2(length(p.xz)-t.x,p.y);return length(q)-t.y;} +float smin(float a,float b,float k){float h=clamp(.5+.5*(b-a)/k,0.,1.);return mix(b,a,h)-k*h*(1.-h);} +float aa(float d,float px){return clamp(.5-d/px,0.,1.);} +vec3 studio(vec3 n,vec3 base){ + vec3 key=normalize(vec3(-.55,.65,.6)),fill=normalize(vec3(.7,.1,.7)); + float k=max(dot(n,key),0.),f=max(dot(n,fill),0.),rim=pow(1.-max(n.z,0.),3.),bounce=max(-n.y,0.)*.5+.5; + vec3 r=reflect(vec3(0,0,-1),n); + float box=smoothstep(.55,.95,dot(r,key)); /* the softbox seen in the surface */ + return base*(.06+.85*k+.18*f)*mix(.8,1.,bounce)+vec3(1.,.97,.92)*(box*.9+rim*.12);} +`; + + GL.context = (canvas) => { + const gl = canvas.getContext('webgl2', { + alpha: false, + antialias: false, + depth: false, + stencil: false, + preserveDrawingBuffer: true, + }); + if (!gl) return null; + gl.half = !!gl.getExtension('EXT_color_buffer_float') || !!gl.getExtension('EXT_color_buffer_half_float'); + gl.getExtension('OES_texture_float_linear'); + return gl; + }; + + GL.program = (gl, fs, vs = GL.VS, label = 'gl') => { + const p = gl.createProgram(); + for (const [ty, src] of [ + [gl.VERTEX_SHADER, vs], + [gl.FRAGMENT_SHADER, fs], + ]) { + const sh = gl.createShader(ty); + gl.shaderSource(sh, src); + gl.compileShader(sh); + if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS) && !gl.isContextLost()) { + console.error(label + ':', gl.getShaderInfoLog(sh)); + return null; + } + gl.attachShader(p, sh); + } + gl.bindAttribLocation(p, 0, 'a'); + gl.linkProgram(p); + if (!gl.getProgramParameter(p, gl.LINK_STATUS)) { + if (!gl.isContextLost()) console.error(label + ':', gl.getProgramInfoLog(p)); + return null; + } + const u = {}, + n = gl.getProgramParameter(p, gl.ACTIVE_UNIFORMS); + for (let i = 0; i < n; i++) { + const inf = gl.getActiveUniform(p, i); + u[inf.name.replace(/\[0\]$/, '')] = gl.getUniformLocation(p, inf.name); + } + return { p, u }; + }; + + GL.target = (gl, w, h) => { + const t = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, t); + for (const [k, v] of [ + [gl.TEXTURE_MIN_FILTER, gl.LINEAR], + [gl.TEXTURE_MAG_FILTER, gl.LINEAR], + [gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE], + [gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE], + ]) + gl.texParameteri(gl.TEXTURE_2D, k, v); + if (gl.half) gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA16F, w, h, 0, gl.RGBA, gl.HALF_FLOAT, null); + else gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + const f = gl.createFramebuffer(); + gl.bindFramebuffer(gl.FRAMEBUFFER, f); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, t, 0); + return { t, f, w, h, free: () => (gl.deleteTexture(t), gl.deleteFramebuffer(f)) }; + }; + + GL.tri = (gl) => { + if (!gl._tri) { + gl._tri = gl.createVertexArray(); + gl.bindVertexArray(gl._tri); + 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); + } + gl.bindVertexArray(gl._tri); + }; + + // set a uniform from a JS value: number, [x,y], [x,y,z], [x,y,z,w], or a flat Float32Array for vec4 arrays + GL.set = (gl, u, name, v) => { + const l = u[name]; + if (l == null) return; + if (typeof v === 'number') gl.uniform1f(l, v); + else if (v instanceof Float32Array) gl.uniform4fv(l, v); + else gl['uniform' + v.length + 'f'](l, ...v); + }; + + // WCAG relative luminance and contrast ratio, for checks (sRGB 0..255 or 0..1) + GL.relLum = (r, g, b, max = 255) => { + const f = (c) => ((c /= max) <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4); + return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b); + }; + GL.contrast = (l1, l2) => (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05); +})(globalThis); diff --git a/kit/gl/host.js b/kit/gl/host.js new file mode 100644 index 0000000..e9252e4 --- /dev/null +++ b/kit/gl/host.js @@ -0,0 +1,230 @@ +/* EOMD kit: gl/host.js. Copyright (C) 2026 Bryan Patrick Murphy. SPDX-License-Identifier: AGPL-3.0-only + Copied from engine/src/gl/host.js (https://github.com/BPMData/EOMD) by tools/build_kit.py: change the source in EOMD, not this copy. */ +/* HOST: the essay picture. Draws the current scene (or, during a transition, the outgoing and incoming scenes into + two buffers and a transition shader between them) into a half-float buffer, then finishes it with the lens on the + GPU texture (DHS.lens with a shared context: no 2D upload, full range kept) or a plain presenter. + + const H = DHS.gl.host(canvas, { essay, lens: knobs | null, reduced: () => bool }); + H.ok false without WebGL2 (the player then shows the words on a plain background) + H.render(state) state from DHS.beats timeline .at(t) + H.resize(w, h) drawing-buffer pixels + H.lumaGrid(cols, rows) mean relative luminance per screen cell of the last frame (flash checks) + H.pixels() { w, h, data } of the last frame, RGBA bottom row first (contrast checks) + H.transitionFor(type) the transition actually used (prefers-reduced-motion swaps some for a crossfade) + H.finish(), H.onfail + Scene shaders are built on first use; one that won't build falls back to the plain scene (logged once). + Needs DHS.gl (gl.js, scenes.js, transitions.js); DHS.lens is optional. */ +(function (G) { + 'use strict'; + const DHS = (G.DHS = G.DHS || {}); + const GL = (DHS.gl = DHS.gl || {}); + + const SCENE_HEAD = `#version 300 es +precision highp float;in vec2 v;out vec4 o; +uniform vec2 R;uniform float T,uMotion,uSeed,uG,uN;uniform float uP[8];uniform vec2 uF;uniform vec4 uD[16]; +`; + const SCENE_MAIN = ` +void main(){vec2 p=(v-.5)*vec2(R.x/R.y,1.);o=vec4(max(scene(p),0.),1.);}`; + const TRANS_HEAD = `#version 300 es +precision highp float;in vec2 v;out vec4 o;uniform sampler2D SA,SB;uniform vec2 R;uniform float uP,uSeed; +vec3 A(vec2 uv){return texture(SA,uv).rgb;}vec3 B(vec2 uv){return texture(SB,uv).rgb;} +`; + const TRANS_MAIN = ` +void main(){o=vec4(trans(v,uP),1.);}`; + // no lens: linear light to the screen, with a one-shade dither so dark gradients don't band + const PRESENT = `#version 300 es +precision highp float;in vec2 v;out vec4 o;uniform sampler2D S;uniform float uSeed; +`; + + GL.host = (canvas, opts = {}) => { + const essay = opts.essay, + reduced = opts.reduced || (() => false); + const H = { ok: false, onfail: null }; + H.render = H.resize = H.finish = () => {}; + H.lumaGrid = () => null; + H.pixels = () => null; + H.transitionFor = (type) => (reduced() ? GL.reducedTransition(type) : type); + const gl = GL.context(canvas); + if (!gl) return H; + H.gl = gl; + + const progs = {}, + failed = {}; + const scenesUsed = new Set(essay.scenes.map((s) => s.scene || 'plain')); + const sceneProg = (name) => { + if (progs['s:' + name]) return progs['s:' + name]; + const def = GL.scenes[name]; + let pr = def ? GL.program(gl, SCENE_HEAD + GL.LIB + def.frag + SCENE_MAIN, GL.VS, 'scene ' + name) : null; + if (!pr) { + if (!failed[name]) console.warn('essay: scene "' + name + '" did not build; showing the plain scene'); + failed[name] = true; + if (name !== 'plain') pr = sceneProg('plain'); + } + return (progs['s:' + name] = pr); + }; + const transProg = (type) => { + const k = 't:' + type; + if (progs[k] !== undefined) return progs[k]; + const def = GL.transitions[type] || GL.transitions.crossfade; + return (progs[k] = + GL.program(gl, TRANS_HEAD + GL.LIB + def.frag + TRANS_MAIN, GL.VS, 'transition ' + type) || + (type !== 'crossfade' ? transProg('crossfade') : null)); + }; + const present = GL.program( + gl, + PRESENT + + GL.LIB + + `void main(){vec3 c=toSrgb(texture(S,v).rgb);c+=(h21(gl_FragCoord.xy+uSeed)+h21(gl_FragCoord.xy+uSeed+17.)-1.)/255.;o=vec4(clamp(c,0.,1.),1.);}`, + GL.VS, + 'present' + ); + if (!present || !sceneProg('plain')) return H; + // build every scene and transition the essay uses now, so the first cut doesn't stutter + scenesUsed.forEach(sceneProg); + essay.scenes.forEach((s) => + transProg( + H.transitionFor( + typeof s.transition === 'string' ? s.transition : (s.transition && s.transition.type) || 'crossfade' + ) + ) + ); + + const lens = opts.lens && DHS.lens ? DHS.lens.create(opts.lens, { gl }) : null; + + let W = 0, + Hh = 0, + bufs = []; + const layouts = new Map(); + H.resize = (w, h) => { + if (w === W && h === Hh) return; + W = canvas.width = w; + Hh = canvas.height = h; + bufs.forEach((b) => b.free()); + bufs = [GL.target(gl, w, h), GL.target(gl, w, h), GL.target(gl, w, h)]; + layouts.clear(); + }; + const layoutOf = (i) => { + const k = i + ':' + (W / Hh).toFixed(4); + if (!layouts.has(k)) { + const spec = essay.scenes[i], + def = GL.scenes[spec.scene] || GL.scenes.plain; + layouts.set(k, def.layout(spec.data || {}, W / Hh)); + } + return layouts.get(k); + }; + + // draw scene i with beat progress p (array) at scene time T into target out + const drawScene = (i, p, T, out) => { + const spec = essay.scenes[i], + pr = sceneProg(spec.scene || 'plain'), + L = layoutOf(i), + vars = GL.sceneVars(spec, p); + gl.bindFramebuffer(gl.FRAMEBUFFER, out.f); + gl.viewport(0, 0, W, Hh); + gl.useProgram(pr.p); + const u = pr.u, + P8 = new Float32Array(8); + p.slice(0, 8).forEach((x, j) => (P8[j] = x)); + GL.set(gl, u, 'R', [W, Hh]); + GL.set(gl, u, 'T', T); + GL.set(gl, u, 'uMotion', reduced() ? 0.15 : 1); + GL.set(gl, u, 'uSeed', (DHS.beats ? DHS.beats.hash(spec.id || i) : i) % 1000); + GL.set(gl, u, 'uG', vars.g); + GL.set(gl, u, 'uF', vars.f); + GL.set(gl, u, 'uN', L.n || 0); + if (u.uP != null) gl.uniform1fv(u.uP, P8); + GL.set(gl, u, 'uD', L.d); + gl.drawArrays(gl.TRIANGLES, 0, 3); + }; + const ones = (i) => essay.scenes[i].beats.map(() => 1); + const zeros = (i) => essay.scenes[i].beats.map(() => 0); + const black = (out) => { + gl.bindFramebuffer(gl.FRAMEBUFFER, out.f); + gl.viewport(0, 0, W, Hh); + gl.clearColor(0, 0, 0, 1); + gl.clear(gl.COLOR_BUFFER_BIT); + }; + + H.render = (s) => { + if (!H.ok || !W) return; + GL.tri(gl); + gl.disable(gl.BLEND); + const [A, B, C] = bufs; + let out = C; + const tr = s.trans; + if (tr) { + const type = H.transitionFor(tr.type), + from = tr.from, + to = tr.to; + // the outgoing scene keeps moving (its own clock), shown at its last beat; the incoming one waits at beat 0 + if (from >= 0) drawScene(from, ones(from), tr.fromT, A); + else black(A); + drawScene(to, zeros(to), s.sceneT, B); + const pr = transProg(type); + gl.bindFramebuffer(gl.FRAMEBUFFER, C.f); + gl.viewport(0, 0, W, Hh); + gl.useProgram(pr.p); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, A.t); + gl.uniform1i(pr.u.SA, 0); + gl.activeTexture(gl.TEXTURE1); + gl.bindTexture(gl.TEXTURE_2D, B.t); + gl.uniform1i(pr.u.SB, 1); + GL.set(gl, pr.u, 'R', [W, Hh]); + GL.set(gl, pr.u, 'uP', tr.p); + GL.set(gl, pr.u, 'uSeed', to * 7.31); + gl.drawArrays(gl.TRIANGLES, 0, 3); + } else drawScene(s.scene, s.p, s.sceneT, C); + + if (lens && lens.ok) lens.drawTexture(out.t, W, Hh, s.t); + else { + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + gl.viewport(0, 0, W, Hh); + gl.useProgram(present.p); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, out.t); + gl.uniform1i(present.u.S, 0); + GL.set(gl, present.u, 'uSeed', reduced() ? 0 : (Math.floor(s.t * 24) % 61) * 1.37); + GL.tri(gl); + gl.drawArrays(gl.TRIANGLES, 0, 3); + } + }; + H.finish = () => { + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(4)); + }; + H.pixels = () => { + if (!W) return null; + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + const data = new Uint8Array(W * Hh * 4); + gl.readPixels(0, 0, W, Hh, gl.RGBA, gl.UNSIGNED_BYTE, data); + return { w: W, h: Hh, data }; + }; + H.lumaGrid = (cols = 16, rows = 9) => { + const px = H.pixels(); + if (!px) return null; + const sum = new Float64Array(cols * rows), + cnt = new Float64Array(cols * rows), + lut = new Float64Array(256); + for (let i = 0; i < 256; i++) lut[i] = GL.relLum(i, 0, 0) / 0.2126; + for (let y = 0; y < px.h; y++) + for (let x = 0; x < px.w; x++) { + const k = (y * px.w + x) * 4, + c = + Math.min(cols - 1, Math.floor((x / px.w) * cols)) + + cols * Math.min(rows - 1, Math.floor(((px.h - 1 - y) / px.h) * rows)); + sum[c] += 0.2126 * lut[px.data[k]] + 0.7152 * lut[px.data[k + 1]] + 0.0722 * lut[px.data[k + 2]]; + cnt[c]++; + } + return Array.from(sum, (s, i) => s / Math.max(1, cnt[i])); + }; + H.labels = (s, aspect) => (GL.sceneLabels ? GL.sceneLabels(essay.scenes[s.scene], s.p, aspect) : []); + canvas.addEventListener('webglcontextlost', (e) => { + e.preventDefault(); + H.ok = false; + if (H.onfail) H.onfail(); + }); + H.ok = true; + return H; + }; +})(globalThis); diff --git a/kit/gl/scenes.js b/kit/gl/scenes.js new file mode 100644 index 0000000..f6cbe70 --- /dev/null +++ b/kit/gl/scenes.js @@ -0,0 +1,230 @@ +/* EOMD kit: gl/scenes.js. Copyright (C) 2026 Bryan Patrick Murphy. SPDX-License-Identifier: AGPL-3.0-only + Copied from engine/src/gl/scenes.js (https://github.com/BPMData/EOMD) by tools/build_kit.py: change the source in EOMD, not this copy. */ +/* SCENES: shader scene cartridges for the essay picture. Each scene is one fragment shader over the whole screen + that writes linear light, plus plain-JS layout so the words layer can put labels exactly where the shapes are + (and still show them, with every number, when there is no WebGL2). + + A cartridge: + frag GLSL defining vec3 scene(vec2 p) with p in screen units: y from -0.5 (bottom) to 0.5 (top), x from + -aspect/2 to aspect/2. It can use DHS.gl.LIB and these uniforms: + R (pixels), T (seconds into the scene), uMotion (1, or 0.15 under prefers-reduced-motion), + uP[8] (each beat's eased progress), uG (progress of the beat that grows the data: data.grow, + default 0), uF (x: the index brought forward, y: how far), uD[16] (vec4 data from layout), uN + layout(data, aspect) -> { d: Float32Array(64), n } pure: the same data always gives the same shapes + labels(data, L, v, aspect) -> [{ x, y, text, kind, align, alpha }] in the same units as p + + Honest charts: bars start at zero and their height is linear in the value; areas are proportional to the value + (radius goes with the square root). Each data scene shows data.note (e.g. "Made-up placeholder numbers") in its + corner when the essay gives one. + + Scenes here: field (quiet backdrop for titles and quotes), bars, tally (one dot per unit), areas (circles). + Standalone: needs only the DHS namespace (DHS.gl.LIB at draw time). */ +(function (G) { + 'use strict'; + const DHS = (G.DHS = G.DHS || {}); + const GL = (DHS.gl = DHS.gl || {}); + const S = (GL.scenes = GL.scenes || {}); + const fmt = (data, v) => (data.format ? data.format(v) : String(v)); + const note = (data, aspect) => + data.note ? [{ x: aspect / 2 - 0.04, y: -0.4, text: data.note, kind: 'note', align: 'right', alpha: 1 }] : []; + const ease = (x) => 1 - (1 - Math.min(1, Math.max(0, x))) ** 3; + // stagger: item i of n starts at i/(n-1) * spread of the grow beat; GLSL twin is stag() below + const stag = (g, i, n, spread = 0.35) => ease((g - (n > 1 ? (i / (n - 1)) * spread : 0)) / (1 - spread)); + const STAG = `float stag(float g,float i,float n){float sp=.35;float s=n>1.?i/(n-1.)*sp:0.;float x=clamp((g-s)/(1.-sp),0.,1.);return 1.-pow(1.-x,3.);} +float bevel(float d,float w){return clamp(-d/w,0.,1.);} +vec3 bevelN(float d,float w){vec2 g=vec2(dFdx(d),dFdy(d));float l=length(g);g=l>0.?g/l:vec2(0);float t=bevel(d,w);return normalize(vec3(g*(1.-t)*1.4,.35+t));} +vec3 backdrop(vec2 p,vec3 tint){vec2 q=p-vec2(-.15,.22);float pool=exp(-dot(q,q)*2.6); + return vec3(.006,.006,.007)+tint*(.022*pool+.006*(.5-p.y));} +`; + + // quiet backdrop: slow haze and a few motes drifting up; data: { tint: [r,g,b], drift } + S.field = { + frag: + STAG + + `vec3 scene(vec2 p){vec3 tint=uD[0].xyz;float drift=uD[0].w; + float t=T*uMotion*drift; + vec3 c=backdrop(p,tint); + float h=fbm(p*1.4+vec2(t*.03,-t*.012),5); + c+=tint*.03*smoothstep(.35,.9,h)*(1.-smoothstep(-.1,.6,abs(p.y+.05))); + for(int L=0;L<2;L++){float sc=6.+float(L)*5.;vec2 g=p*sc+vec2(0.,-t*(.25+.15*float(L)));vec2 id=floor(g);vec2 r=h22(id+float(L)*31.); + if(r.x>.84){vec2 c2=id+.2+.6*h22(id+7.);float d=length(g-c2)/sc;c+=tint*.22*(.4+.6*r.y)*exp(-d*d*2.6e4/(1.+float(L)));}} + return c;}`, + layout: (data) => { + const d = new Float32Array(64), + t = data.tint || [0.9, 0.87, 0.82]; + d.set([t[0], t[1], t[2], data.drift != null ? data.drift : 1], 0); + return { d, n: 0 }; + }, + labels: () => [], + }; + + // bars from zero; data: { values, labels, max (top of the scale; default the largest value), grow, note, format } + S.bars = { + frag: + STAG + + `vec4 bar(vec2 p,int i,out vec3 n){vec4 b=uD[1+i];float base=uD[0].x,H=uD[0].y,hw=uD[0].z; + float g=stag(uG,float(i),uN),h=H*b.y*g;n=vec3(0,0,1);if(h<=0.)return vec4(0); + vec2 cc=vec2(b.x,base+h*.5);float r=min(.006,h*.5);float d=sdRoundBox(p-cc,vec2(hw,h*.5),r); + n=bevelN(d,.012);return vec4(d,g,h,0);} +vec3 scene(vec2 p){vec3 c=backdrop(p,vec3(1.,.95,.88));float base=uD[0].x,px=1.4/R.y; + float w=uD[0].w;c+=vec3(.16)*aa(abs(p.y-base)-.5/R.y,px)*step(abs(p.x),w)*clamp(uP[0]*3.+uG*3.,0.,1.); + for(int i=0;i<8;i++){if(float(i)>=uN)break; + bool foc=int(uF.x+.5)==i;float dim=uF.x<0.?1.:foc?1.+.25*uF.y:1.-.6*uF.y; + vec3 base3=mix(vec3(.30,.29,.27),vec3(.55,.42,.28),foc?uF.y:0.)*dim; + vec3 n;vec4 b=bar(p,i,n); + if(b.z>0.){float cov=aa(b.x,px);c=mix(c,studio(n,base3)*mix(.8,1.,dim),cov);} + vec3 n2;vec4 m=bar(vec2(p.x,2.*base-p.y),i,n2); + if(m.z>0.&&p.y { + const g = stag(v.g, i, L.n), + h = (L.H * Math.max(0, data.values[i])) / L.max; + const dim = v.f[0] < 0 ? 1 : v.f[0] === i ? 1 : 1 - 0.45 * v.f[1]; + out.push({ + x, + y: L.base + h * g + 0.035, + text: fmt(data, data.values[i]), + kind: 'value', + align: 'center', + alpha: Math.min(1, Math.max(0, (g - 0.85) / 0.15)) * dim, + }); + if (data.labels && data.labels[i] != null) + out.push({ + x, + y: L.base - 0.045, + text: data.labels[i], + kind: 'category', + align: 'center', + alpha: Math.min(1, v.g * 4) * dim, + }); + }); + return out.concat(note(data, aspect)); + }, + }; + + // one dot per unit, filling row by row at a steady pace; data: { count, cols, grow, note, box } + // box: [left, top, right, bottom] as fractions of the screen, to leave room for words (default: the middle) + S.tally = { + frag: + STAG + + `vec3 scene(vec2 p){vec3 c=backdrop(p,vec3(.95,.92,.86));float N=uD[0].x,cols=uD[0].y,s=uD[0].z,rows=uD[1].z; + vec2 q=(p-uD[1].xy)/s;q.y=-q.y;vec2 id=floor(q); + if(id.x>=0.&&id.x=0.&&id.y note(data, aspect), + }; + + // circles with area proportional to value, side by side on one line; data: { values, labels, grow, note, format } + S.areas = { + frag: + STAG + + `vec3 scene(vec2 p){vec3 c=backdrop(p,vec3(.9,.92,1.));float px=1.4/R.y,base=uD[0].x; + for(int i=0;i<6;i++){if(float(i)>=uN)break;vec4 b=uD[1+i]; + float g=stag(uG,float(i),uN),r=b.z*sqrt(g);if(r<=0.)continue; + float d=sdCircle(p-vec2(b.x,base+b.z),r); + vec3 n=bevelN(d,.01);c=mix(c,studio(n,vec3(.26,.28,.31)),aa(d,px));} + return c;}`, + layout(data, aspect) { + const v = (data.values || []).slice(0, 6), + n = v.length, + vmax = Math.max(...v, 1e-9), + gap = 0.07; + let R = 0.22; + let rs = v.map((x) => R * Math.sqrt(Math.max(0, x) / vmax)); + const total = rs.reduce((a, r) => a + 2 * r, 0) + gap * (n - 1), + fit = aspect * 0.82; + if (total > fit) rs = rs.map((r) => (r * (fit - gap * (n - 1))) / (total - gap * (n - 1))); + const width = rs.reduce((a, r) => a + 2 * r, 0) + gap * (n - 1); + const base = -0.24, + d = new Float32Array(64), + xs = []; + d.set([base, 0, 0, 0], 0); + let x = -width / 2; + rs.forEach((r, i) => { + xs.push(x + r); + d.set([x + r, 0, r, 0], 4 * (1 + i)); + x += 2 * r + gap; + }); + return { d, n, xs, rs, base }; + }, + labels(data, L, v, aspect) { + const out = []; + L.xs.forEach((x, i) => { + const g = stag(v.g, i, L.n); + const name = data.labels && data.labels[i] != null ? data.labels[i] + ': ' : ''; + out.push({ + x, + y: L.base - 0.05, + text: name + fmt(data, data.values[i]), + kind: 'category', + align: 'center', + alpha: Math.min(1, Math.max(0, (g - 0.6) / 0.4)), + }); + }); + return out.concat(note(data, aspect)); + }, + }; + + // shown when a scene's shader won't build (or its name is unknown): a dark backdrop, labels still drawn + S.plain = { + frag: STAG + 'vec3 scene(vec2 p){return backdrop(p,vec3(1.));}', + layout: () => ({ d: new Float32Array(64), n: 0 }), + labels: (data, L, v, a) => note(data, a), + }; + + // the values every scene reads from the beat state: g = the grow beat's progress, f = [index forward, progress] + GL.sceneVars = (spec, p) => { + const data = spec.data || {}; + let f = [-1, 0]; + (spec.beats || []).forEach((b, j) => { + if (b.focus != null && (p[j] || 0) > 0) f = [b.focus, p[j]]; + }); + return { g: p[data.grow || 0] || 0, f }; + }; + // labels for a scene spec at this beat state (no GL needed) + GL.sceneLabels = (spec, p, aspect) => { + const def = S[spec.scene] || S.plain, + data = spec.data || {}; + return def.labels(data, def.layout(data, aspect), GL.sceneVars(spec, p), aspect); + }; +})(globalThis); diff --git a/kit/gl/transitions.js b/kit/gl/transitions.js new file mode 100644 index 0000000..19bef82 --- /dev/null +++ b/kit/gl/transitions.js @@ -0,0 +1,54 @@ +/* EOMD kit: gl/transitions.js. Copyright (C) 2026 Bryan Patrick Murphy. SPDX-License-Identifier: AGPL-3.0-only + Copied from engine/src/gl/transitions.js (https://github.com/BPMData/EOMD) by tools/build_kit.py: change the source in EOMD, not this copy. */ +/* TRANSITIONS: how one essay scene gives way to the next. Each is a shader + vec3 trans(vec2 uv, float p) uv 0..1 on screen, p 0..1 through the transition + reading the outgoing picture with A(uv) and the incoming one with B(uv) (both linear light), plus R (pixels). + Every one changes each part of the screen in one direction only, or (dip) down once and up once over 2 s, so none + comes near the 3-flashes-a-second limit; the essay QA tool measures it anyway (engine/tools/essay-qa.js). + Quiet ones first: a solemn essay mostly wants cut, crossfade and dip. + + cut instant (no shader) + crossfade slow mix in linear light (no muddy dip in the middle) + dip fade to black, a breath of black, fade up + wipe a soft edge crossing the screen at a slight angle + dissolve cells change one by one, each once, in a seeded order + push the new scene slides in and moves the old one out, the old one dimming + + Under prefers-reduced-motion, wipe, dissolve and push become a crossfade (DHS.gl.reducedTransition). + Standalone: needs only the DHS namespace. */ +(function (G) { + 'use strict'; + const DHS = (G.DHS = G.DHS || {}); + const GL = (DHS.gl = DHS.gl || {}); + const SM = 'float sm(float a,float b,float x){return smoothstep(a,b,x);}float ease(float x){return x*x*(3.-2.*x);}\n'; + GL.transitions = { + cut: { dur: 0, frag: 'vec3 trans(vec2 uv,float p){return p<1.?A(uv):B(uv);}' }, + crossfade: { dur: 2, frag: SM + 'vec3 trans(vec2 uv,float p){return mix(A(uv),B(uv),ease(p));}' }, + dip: { + dur: 2, + frag: SM + 'vec3 trans(vec2 uv,float p){return A(uv)*(1.-ease(sm(0.,.45,p)))+B(uv)*ease(sm(.55,1.,p));}', + }, + wipe: { + dur: 1.8, + frag: + SM + + `vec3 trans(vec2 uv,float p){float a=R.x/R.y,x=uv.x*a+(uv.y-.5)*.18;float e=mix(-.25,a+.25,ease(p)); + float m=sm(e-.12,e+.12,x);return mix(B(uv),A(uv),m);}`, + }, + dissolve: { + dur: 2.2, + frag: + SM + + `vec3 trans(vec2 uv,float p){vec2 c=floor(uv*R/max(8.,R.y/36.));float r=h21(c+uSeed)*.8; + return mix(A(uv),B(uv),ease(sm(r,r+.2,p)));}`, + }, + push: { + dur: 1.6, + frag: + SM + + `vec3 trans(vec2 uv,float p){float e=ease(ease(p));float x=uv.x+e; + if(x<1.)return A(vec2(x,uv.y))*(1.-.6*e);return B(vec2(x-1.,uv.y));}`, + }, + }; + GL.reducedTransition = (type) => (type === 'cut' || type === 'dip' ? type : 'crossfade'); +})(globalThis); diff --git a/kit/tools/essay-qa.js b/kit/tools/essay-qa.js new file mode 100644 index 0000000..cf8cd9b --- /dev/null +++ b/kit/tools/essay-qa.js @@ -0,0 +1,157 @@ +/* EOMD kit: tools/essay-qa.js. Copyright (C) 2026 Bryan Patrick Murphy. SPDX-License-Identifier: AGPL-3.0-only + Copied from engine/tools/essay-qa.js (https://github.com/BPMData/EOMD) by tools/build_kit.py: change the source in EOMD, not this copy. */ +// ESSAY QA: stills and checks for an essay player (the kit's DHS.essay), for fresh-eyes review (brief/CRAFT.md §11) +// and before an MP4. Uses the player's test hooks (?manual, window.EOMD_ESSAY: seek, trans, perf, flashCheck, contrast). +// node tools/essay-qa.js [W H] +// Writes to outDir: +// s--b-shown.png / -end.png every beat, fully arrived and at the end of its hold +// s--trans-25.png / 50 / 75 every transition at 0.25, 0.5, 0.75 +// report.md + report.json flash check per transition (3-per-second rule), WCAG contrast of +// every text block against the brightest and darkest picture under it +// (sampled through the beat), ms per frame per scene, page errors +// Exit code 1 if anything fails (a page error, a flash, contrast under AA). +const { chromium } = require('playwright'); +const path = require('path'); +const fs = require('fs'); + +(async () => { + const [, , file, outDir, W = '1280', H = '720'] = process.argv; + if (!file || !outDir) { + console.log('usage: node tools/essay-qa.js [W H]'); + process.exit(2); + } + fs.mkdirSync(outDir, { recursive: true }); + const b = await chromium.launch({ + args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'], + }); + const errors = []; + const open = async (query, opts = {}) => { + const p = await b.newPage({ + viewport: { width: +W, height: +H }, + reducedMotion: opts.reduced ? 'reduce' : 'no-preference', + }); + p.on('pageerror', (e) => errors.push(e.message)); + p.on('console', (m) => m.type() === 'error' && errors.push(m.text())); + await p.goto('file://' + path.resolve(file) + query); + await p.waitForFunction('window.EOMD_ESSAY', null, { timeout: 30000 }); + return p; + }; + const p = await open('?manual'); + const info = await p.evaluate(() => { + const E = window.EOMD_ESSAY; + return { + gl: !!(E.host && E.host.ok), + scenes: E.TL.scenes.map((S) => ({ + id: S.id, + trans: S.trans, + beats: S.beats.map((B) => ({ start: B.start, shown: B.shown, end: B.end, hold: B.hold })), + })), + total: E.TL.total, + }; + }); + const report = { + file, + size: [+W, +H], + gl: info.gl, + total: info.total, + stills: [], + flashes: [], + contrast: [], + perf: [], + errors, + }; + const name = (i, rest) => `s${String(i + 1).padStart(2, '0')}-${info.scenes[i].id}-${rest}.png`; + + for (let i = 0; i < info.scenes.length; i++) { + const S = info.scenes[i]; + if (S.trans.dur > 0) + for (const q of [0.25, 0.5, 0.75]) { + await p.evaluate(([i, q]) => window.EOMD_ESSAY.trans(i, q), [i, q]); + const f = name(i, 'trans-' + Math.round(q * 100)); + await p.screenshot({ path: path.join(outDir, f) }); + report.stills.push(f); + } + for (let j = 0; j < S.beats.length; j++) { + for (const w of ['shown', 'end']) { + await p.evaluate(([i, j, w]) => window.EOMD_ESSAY.seek(i, j, w), [i, j, w]); + const f = name(i, `b${j + 1}-${w}`); + await p.screenshot({ path: path.join(outDir, f) }); + report.stills.push(f); + } + // contrast: sample through the beat (arrival done .. end of hold), keep the worst + const c = await p.evaluate( + ([i, j, B]) => { + const E = window.EOMD_ESSAY; + if (!E.contrast) return null; + const worst = {}; + for (let k = 0; k <= 4; k++) { + E.at(B.shown + ((B.end - 1e-3 - B.shown) * k) / 4); + for (const r of E.contrast()) { + if (!worst[r.key] || r.ratio < worst[r.key].ratio) worst[r.key] = r; + } + } + return Object.values(worst); + }, + [i, j, S.beats[j]] + ); + if (c) c.forEach((r) => report.contrast.push(Object.assign({ scene: S.id, beat: j + 1 }, r))); + } + if (info.gl) + report.perf.push({ scene: S.id, msPerFrame: await p.evaluate((i) => window.EOMD_ESSAY.perf(i, 30), i) }); + } + // flash check: each transition stepped at 60 fps (the picture only; the text layer is checked by its own rules) + if (info.gl) { + const small = await open('?manual'); + await small.setViewportSize({ width: 320, height: 180 }); + for (let i = 0; i < info.scenes.length; i++) { + if (!info.scenes[i].trans.dur) continue; + const r = await small.evaluate((i) => window.EOMD_ESSAY.flashCheck && window.EOMD_ESSAY.flashCheck(i), i); + if (r) report.flashes.push(Object.assign({ scene: info.scenes[i].id, type: info.scenes[i].trans.type }, r)); + } + // reduced motion: the transitions the viewer actually gets + const red = await open('?manual', { reduced: true }); + report.reducedMotion = await red.evaluate(() => + window.EOMD_ESSAY.TL.scenes.map((S) => + window.EOMD_ESSAY.host.transitionFor ? window.EOMD_ESSAY.host.transitionFor(S.trans.type) : S.trans.type + ) + ); + } + await b.close(); + + const bad = []; + if (errors.length) bad.push(errors.length + ' page error(s)'); + report.flashes.filter((f) => !f.pass).forEach((f) => bad.push(`flash: ${f.scene} (${f.type}) ${f.maxPerSecond}/s`)); + report.contrast + .filter((c) => !c.pass) + .forEach((c) => + bad.push(`contrast: ${c.scene} beat ${c.beat} "${c.text}" ${c.ratio.toFixed(2)}:1 (needs ${c.need}:1)`) + ); + report.pass = !bad.length; + fs.writeFileSync(path.join(outDir, 'report.json'), JSON.stringify(report, null, 2)); + const md = [ + `# Essay QA: ${path.basename(file)}`, + ``, + `${report.pass ? 'PASS' : 'FAIL'} · ${W}x${H} · WebGL2 ${info.gl ? 'yes' : 'no (fallback)'} · ${info.total.toFixed(1)} s · ${report.stills.length} stills`, + ...bad.map((x) => '- ' + x), + ``, + `## Flashes (at most 3 a second; WCAG 2.3.1, picture luminance in a 16x9 grid)`, + ...report.flashes.map( + (f) => + `- ${f.scene} (${f.type}): ${f.maxPerSecond} per second, biggest step ${f.maxStep.toFixed(3)} ${f.pass ? 'ok' : 'FAIL'}` + ), + ``, + `## Contrast (worst frame of each beat; AA: 4.5:1, large text 3:1)`, + ...report.contrast.map( + (c) => + `- ${c.scene} b${c.beat} ${c.kind} "${c.text.slice(0, 40)}": ${c.ratio.toFixed(2)}:1 against the ${c.against} pixel ${c.pass ? 'ok' : 'FAIL'}` + ), + ``, + `## Speed (ms a frame on this machine's GPU; SwiftShader in CI is far slower than a real one)`, + ...report.perf.map((x) => `- ${x.scene}: ${x.msPerFrame == null ? '-' : x.msPerFrame.toFixed(1)}`), + ``, + `Reduced motion transitions: ${(report.reducedMotion || []).join(', ')}`, + ].join('\n'); + fs.writeFileSync(path.join(outDir, 'report.md'), md + '\n'); + console.log(md); + process.exit(report.pass ? 0 : 1); +})(); diff --git a/players/essay-demo.html b/players/essay-demo.html new file mode 100644 index 0000000..b0b03a0 --- /dev/null +++ b/players/essay-demo.html @@ -0,0 +1,2350 @@ + + + + + + Placeholder Motion Essay (EOMD kit demo) + + + + + + + + + + + + + + diff --git a/tools/CLAUDE.md b/tools/CLAUDE.md index 0fba943..10f69e7 100644 --- a/tools/CLAUDE.md +++ b/tools/CLAUDE.md @@ -20,6 +20,7 @@ Status, the regression history and known limits: `tools/STATUS.md`. | `calibrate.py`, `porter.py`, `midi.py`, `regress.py` | Music library tools (`audio/CLAUDE.md`) | | `hershey_words.py` | Makes the `living/words*.json` files for any word list (`VARIANT`) | | `build_kit.py` | Builds `kit/` (engine parts ProofEr copies in) from their engine sources, with headers, and rewrites `kit/KIT.json` (sha256 of every file; the version is set by hand, with a `kit/CHANGELOG.md` section). `MODE = 'check'` changes nothing and lists problems; CI runs it | +| `build_essay_demo.py` | The kit's demo motion essay: `engine/essay-demo/` with the kit copies inlined → `dist/essay-demo.html`, copied to `players/essay-demo.html`. Stops if the kit is stale (run `build_kit.py` first). Check it with `node engine/tools/essay-qa.js players/essay-demo.html ` | | `check_stage_reads.py` | The peeking audit: restricted reads before a new piece's toolbox gate, from the stage logs `proj/*/access.jsonl` (written by the hook `.claude/hooks/stage_log.py`). Warnings only; CI runs it | | `eval_new_piece.py` | The first-question eval: a one-sentence new-piece request on a copy of the repo (Sonnet, read-only, capped at $0.50), checking files opened, context and cost before the first question; PASS/FAIL. CI runs it (`.github/workflows/eval.yml`) when the context files change and an `ANTHROPIC_API_KEY` secret exists | @@ -31,7 +32,7 @@ Never render an MP4 by hand in a sandbox: use `html_to_mp4.py` (it drives `?manu ## Publishing a build `players/` holds published copies of `dist/jukebox.html`, `pltw-cse.html`, `cdrom-player.html`, `cdrom-ambient.html`, -`living-player.html`, `living-player-cs.html`, `living-player-ex.html`, `danbury-academies-clock.html` and `sanctioned-corporate-calm.html` (their build copies them there itself), `gen/dist/gen-player.html` and +`living-player.html`, `living-player-cs.html`, `living-player-ex.html`, `danbury-academies-clock.html`, `sanctioned-corporate-calm.html` and `essay-demo.html` (their build copies them there itself), `gen/dist/gen-player.html` and `proj/cse-loop/cse-loop.html` (built in place by `proj/cse-loop/build.py`, published as `players/cse-loop.html`). After rebuilding one, copy it into `players/` and commit, so the public copies don't go stale. Only publish a build that loads without script errors. Adding or renaming a player: update `index.html` (the Pages landing page; `.nojekyll` must stay, or Pages diff --git a/tools/build_essay_demo.py b/tools/build_essay_demo.py new file mode 100644 index 0000000..f35f99c --- /dev/null +++ b/tools/build_essay_demo.py @@ -0,0 +1,70 @@ +# tools/build_essay_demo.py: BUILD THE DEMO ESSAY. Run in Thonny (the Run button; no command-line arguments). +# The demo shows what the kit's essay engine does, with placeholder words and made-up numbers (labelled so on +# screen). It inlines the KIT copies (kit/, what ProofEr gets) into engine/essay-demo/dev.html, so it is built the +# way a ProofEr essay would be: one offline HTML file, nothing loaded from the internet. +# engine/essay-demo/dev.html + essay.js + kit/*.js -> dist/essay-demo.html, copied to players/essay-demo.html +# Run tools/build_kit.py first after changing an engine source (this script stops if a kit copy is stale). +import os, re, shutil, sys + +# ===================== SETTINGS ===================== +PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # the repo root +DEV_PAGE = os.path.join(PROJECT_DIR, 'engine', 'essay-demo', 'dev.html') +OUT = os.path.join(PROJECT_DIR, 'dist', 'essay-demo.html') +PUBLISH = os.path.join(PROJECT_DIR, 'players', 'essay-demo.html') # None to skip publishing +TITLE = 'Placeholder Motion Essay (EOMD kit demo)' +# ==================================================== + +# a dev-page script path -> the kit file inlined in its place +KIT_FOR = { + '../src/essay/beats.js': 'essay/beats.js', + '../src/fx/lens.js': 'fx/lens.js', + '../src/gl/gl.js': 'gl/gl.js', + '../src/gl/transitions.js': 'gl/transitions.js', + '../src/gl/scenes.js': 'gl/scenes.js', + '../src/gl/host.js': 'gl/host.js', + '../src/essay/text.js': 'essay/text.js', + '../src/essay/player.js': 'essay/player.js', +} + + +def main(): + sys.path.insert(0, os.path.join(PROJECT_DIR, 'tools')) + import build_kit + + problems = build_kit.check(log=lambda m: None) + if problems: + print('Stopped: the kit is not up to date. Run tools/build_kit.py first:') + for p in problems: + print(' ' + p) + return False + with open(DEV_PAGE, encoding='utf-8') as f: + html = f.read() + + def inline(m): + src = m.group(1) + if src in KIT_FOR: + path = os.path.join(PROJECT_DIR, 'kit', *KIT_FOR[src].split('/')) + else: + path = os.path.join(os.path.dirname(DEV_PAGE), src) + with open(path, encoding='utf-8') as f: + code = f.read() + return '' + + html = re.sub(r'', inline, html) + html = re.sub(r'.*?', '' + TITLE + '', html) + html = re.sub(r'\n', '', html, flags=re.S) + if re.search(r'(src|href)="(https?:)?//', html): + print('Stopped: the page would load something from the internet.') + return False + os.makedirs(os.path.dirname(OUT), exist_ok=True) + with open(OUT, 'w', encoding='utf-8', newline='\n') as f: + f.write(html) + print(f'Built {os.path.relpath(OUT, PROJECT_DIR)} ({len(html) // 1024} KB)') + if PUBLISH: + shutil.copyfile(OUT, PUBLISH) + print(f'Published {os.path.relpath(PUBLISH, PROJECT_DIR)}') + return True + + +if __name__ == '__main__': + main() diff --git a/tools/build_kit.py b/tools/build_kit.py index 0e04180..633f795 100644 --- a/tools/build_kit.py +++ b/tools/build_kit.py @@ -17,6 +17,14 @@ PARTS = { 'fx/lens.js': 'engine/src/fx/lens.js', 'audio/dsp.js': 'engine/src/audio/dsp.js', + 'essay/beats.js': 'engine/src/essay/beats.js', + 'essay/text.js': 'engine/src/essay/text.js', + 'essay/player.js': 'engine/src/essay/player.js', + 'gl/gl.js': 'engine/src/gl/gl.js', + 'gl/transitions.js': 'engine/src/gl/transitions.js', + 'gl/scenes.js': 'engine/src/gl/scenes.js', + 'gl/host.js': 'engine/src/gl/host.js', + 'tools/essay-qa.js': 'engine/tools/essay-qa.js', } # Hand-written kit files (listed and hashed in KIT.json, never generated) DOCS = ['README.md', 'CHANGELOG.md'] From b5212aa0a061dcdd880b7acceaf79b7155903fcf Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 17:22:29 +0000 Subject: [PATCH 08/13] stage_log hook: skip Bash commands made only of git bookkeeping (port of ProofEr 5929024) The hook logged every Bash command, including the git commit itself, so proj//access.jsonl was dirty again right after every commit and the cloud stop hook never settled. add/commit/push/status plus cd/echo are now skipped; show, diff, log and everything else stay logged for the stage-read audit. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Ad4FSZyShDwuPQbAcgGJY3 --- .claude/hooks/stage_log.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/.claude/hooks/stage_log.py b/.claude/hooks/stage_log.py index e0793e1..c91c13b 100644 --- a/.claude/hooks/stage_log.py +++ b/.claude/hooks/stage_log.py @@ -3,6 +3,8 @@ After every Read, Grep, Glob or Bash call, if a new piece is in a design stage (the newest proj/*/brief.md whose status line says Stage: interview, brief, concepts or storyboard), append one JSON line to proj//access.jsonl: time, stage, mode, tool and the paths touched (for Bash, the command). tools/check_stage_reads.py reads the logs. +Bash commands made only of git bookkeeping (add, commit, push, status) plus cd/echo are skipped: they read no piece +content, and logging them left the log dirty after every commit. Other git commands (show, diff, log) are logged. Any error is swallowed: the hook must never get in the way of the session. """ import json, os, re, sys, time, glob @@ -28,6 +30,16 @@ def piece_in_design(root): return best +BOOKKEEPING = re.compile(r'^(cd\b|echo\b|git\s+(add|commit|push|status)\b)') + + +def bookkeeping_only(cmd): + # Drop quoted text (commit messages) first, then every segment must be bookkeeping. + bare = re.sub(r'"(?:\\.|[^"\\])*"|\'[^\']*\'', '""', cmd) + segments = [s.strip() for s in re.split(r'&&|\|\||;|\||\n', bare)] + return all(not s or BOOKKEEPING.match(s) for s in segments) + + def rel(root, p): if not p: return p @@ -42,6 +54,8 @@ def main(): tool = ev.get('tool_name', '') if tool not in ('Read', 'Grep', 'Glob', 'Bash'): return + if tool == 'Bash' and bookkeeping_only(str((ev.get('tool_input') or {}).get('command', ''))): + return found = piece_in_design(root) if not found: return From 9cd1ca6f4f50092a3b0dcf2c64f5b92960579cf0 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 17:40:04 +0000 Subject: [PATCH 09/13] Essay engine addendum (ProofEr): portrait layouts, pause button + Space, per-language text tracks (essay/track.js), data-row scene templates + nested scene, drone bed (audio/bed.js), sources chapter + takeaway, layout check in essay-qa Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Ad4FSZyShDwuPQbAcgGJY3 --- engine/src/audio/bed.js | 182 ++++++++++++++++ engine/src/essay/beats.js | 18 +- engine/src/essay/player.js | 417 ++++++++++++++++++++++++++----------- engine/src/essay/text.js | 112 ++++++++-- engine/src/essay/track.js | 240 +++++++++++++++++++++ engine/src/gl/host.js | 10 +- engine/src/gl/scenes.js | 273 +++++++++++++++++------- engine/tools/essay-qa.js | 76 ++++++- engine/tools/render-bed.js | 34 +++ 9 files changed, 1133 insertions(+), 229 deletions(-) create mode 100644 engine/src/audio/bed.js create mode 100644 engine/src/essay/track.js create mode 100644 engine/tools/render-bed.js diff --git a/engine/src/audio/bed.js b/engine/src/audio/bed.js new file mode 100644 index 0000000..6437c49 --- /dev/null +++ b/engine/src/audio/bed.js @@ -0,0 +1,182 @@ +/* BED: one quiet generative ambient drone (near silence) for an essay, made with EOMD's DSP (DHS.dsp) in the page. + A seamless loop: every partial and every slow swell has a whole number of cycles in the loop, the air (filtered + noise) and the room are processed circularly, so the loop point can't be heard. Normalised to a loudness target + (BS.1770 integrated, LUFS) and true-peak limited (default ceiling -1.5 dBTP). Same seed and knobs, same samples. + + const out = DHS.dsp.drain(DHS.bed.steps(knobs)); // { L, R, sr, seconds, lufs, truePeakDb, gainDb } + DHS.bed.renderAsync(knobs).then(...) // in ~8 ms slices on the main thread (page keeps drawing) + const sound = DHS.bed.sound(knobs); // the essay player's sound hook (DHS.essay.mount opts.sound) + sound.prepare() starts rendering now (the player calls it when it mounts) + sound.start(audioContext) when rendered, loops it with a slow fade in + sound.update(t, playing) fades out on pause, back in on play + sound.setMuted(on) the player's sound button + Needs DHS.dsp (audio/dsp.js). Hits and effects are not here yet (kit TODO). */ +(function (G) { + 'use strict'; + const DHS = (G.DHS = G.DHS || {}); + + const DEFAULTS = { + seed: 7, + seconds: 30, // loop length + sr: 48000, + root: 38, // MIDI note of the lowest tone (38 = D2) + chord: [0, 7, 12, 19], // semitones above the root + lufs: -36, // integrated loudness target: near silence on laptop and phone speakers; the brief can change it + ceiling: -1.5, // true-peak ceiling, dBTP + air: 0.25, // filtered-noise level relative to the tones (0 = none) + brightness: 700, // lowpass on the tones and air, Hz + room: 0.35, // reverb send + fade: 4, // seconds of fade in when sound starts + measure: false, // true: also measure the exact true peak (slow; tools/render-bed.js sets it for the ffmpeg check) + }; + + function* steps(knobs = {}) { + const P = DHS.dsp, + k = Object.assign({}, DEFAULTS, knobs); + const sr = k.sr, + N = Math.round(k.seconds * sr), + L = N / sr, + TAU = Math.PI * 2; + const rnd = P.rng(k.seed); + const bus = P.bus(N); + // tones: each a pair of sines a whole number of cycles apart over the loop (a slow beating), with a soft + // second harmonic, swelling at 1 or 2 cycles a loop + const cyc = (f) => Math.max(1, Math.round(f * L)) / L; + for (let v = 0; v < k.chord.length; v++) { + const f = cyc(P.mtof(k.root + k.chord[v])), + f2 = f + (1 + v) / L, + sw = 1 + (v % 2), + ph = (rnd() + 1) * Math.PI, + amp = 0.25 / (1 + v * 0.6), + pan = v % 2 ? 0.35 : -0.35; + const buf = new Float32Array(N); + for (let i = 0; i < N; i++) { + const t = i / sr; + const s = Math.sin(TAU * f * t) + 0.7 * Math.sin(TAU * f2 * t + ph) + 0.12 * Math.sin(TAU * 2 * f * t); + buf[i] = s * amp * (0.55 + 0.45 * Math.sin((TAU * sw * t) / L + ph)); + if ((i & 32767) === 32767) yield; + } + P.write(bus, buf, 0, 1, pan); + } + // air: noise, lowpassed (circular, so its filter state is continuous across the loop) + if (k.air > 0) { + const air = P.bus(N); + for (let i = 0; i < N; i++) { + air.L[i] = rnd() * k.air * 0.2; + air.R[i] = rnd() * k.air * 0.2; + } + yield; + const f = yield* P.steps.circular(air, () => { + const a = P.svf(), + b = P.svf(); + return (l, r) => [a(l, k.brightness * 0.6, 0.6, sr), b(r, k.brightness * 0.6, 0.6, sr)]; + }); + P.mixInto(bus, f); + } + // tone colour, then the room + let out = yield* P.steps.circular(bus, () => { + const a = P.svf(), + b = P.svf(); + return (l, r) => [a(l, k.brightness, 0.5, sr), b(r, k.brightness, 0.5, sr)]; + }); + if (k.room > 0) { + const wet = yield* P.steps.circular(out, P.reverb({ sr, size: 0.86, damp: 0.5, lp: k.brightness * 3 })); + P.mixInto(out, wet, k.room * 2.5); + } + // loudness target, then the true-peak limiter. The tones are lowpassed, so the true peak sits within a few dB of + // the sample peak: when the sample peak is more than 6 dB under the ceiling the limiter can't act, and its + // (slow) oversampled pass is skipped. + const measured = yield* P.steps.lufs(out, sr); + const gainDb = k.lufs - measured, + g = P.db(gainDb); + let peak = 0; + for (let i = 0; i < N; i++) { + out.L[i] *= g; + out.R[i] *= g; + peak = Math.max(peak, Math.abs(out.L[i]), Math.abs(out.R[i])); + } + yield; + let limited = false; + if (P.todb(peak) > k.ceiling - 6) { + out = (yield* P.steps.limit(out, sr, P.db(k.ceiling))).bus; + limited = true; + } + return { + L: out.L, + R: out.R, + sr, + seconds: L, + lufs: yield* P.steps.lufs(out, sr), // measured again after the gain (and the limiter, if it ran) + samplePeakDb: P.todb(peak), + truePeakDb: k.measure ? P.todb(P.truePeak(out)) : null, + limited, + gainDb, + }; + } + + const renderAsync = (knobs) => DHS.dsp.runAsync(steps(knobs), { budgetMs: 8 }); + + // The essay player's sound hook. Rendering takes a second or two of sliced work after "Begin with sound". + function sound(knobs = {}) { + const k = Object.assign({}, DEFAULTS, knobs); + const S = { ctx: null, gain: null, src: null, muted: false, playing: false, status: 'idle', result: null }; + const level = () => (S.muted || !S.playing ? 0 : 1); + const ramp = (secs) => { + if (!S.gain) return; + const now = S.ctx.currentTime; + S.gain.gain.cancelScheduledValues(now); + S.gain.gain.setValueAtTime(S.gain.gain.value, now); + S.gain.gain.linearRampToValueAtTime(level(), now + secs); + }; + // start rendering before anyone asks (the player calls this when it mounts): by the time the viewer has read + // the start screen the bed is usually ready + let job = null; + S.prepare = () => { + if (!job) { + S.status = 'rendering'; + job = renderAsync(k); + } + return job; + }; + S.start = (ctx) => { + if (S.ctx) return; + S.ctx = ctx; + if (ctx.state === 'suspended') ctx.resume(); + return S.prepare().then( + (r) => { + S.result = r; + const b = ctx.createBuffer(2, r.L.length, r.sr); + b.copyToChannel(r.L, 0); + b.copyToChannel(r.R, 1); + S.gain = ctx.createGain(); + S.gain.gain.value = 0; + S.gain.connect(ctx.destination); + S.src = ctx.createBufferSource(); + S.src.buffer = b; + S.src.loop = true; + S.src.connect(S.gain); + S.src.start(); + S.status = 'playing'; + ramp(k.fade); + }, + (err) => { + S.status = 'failed'; + console.warn('bed: no sound', err); + } + ); + }; + S.update = (t, playing) => { + if (playing !== S.playing) { + S.playing = playing; + ramp(playing ? 1.5 : 0.6); + } + }; + S.setMuted = (m) => { + S.muted = !!m; + ramp(0.5); + }; + return S; + } + + DHS.bed = { DEFAULTS, steps, renderAsync, sound }; +})(globalThis); diff --git a/engine/src/essay/beats.js b/engine/src/essay/beats.js index 2596e9b..395dbf7 100644 --- a/engine/src/essay/beats.js +++ b/engine/src/essay/beats.js @@ -10,7 +10,8 @@ const s = TL.at(t); // { t, scene, beat, beatT, raw[], p[], trans, k(beat, t0, t1, ease) } const C = DHS.beats.clock(); C.advance(realDt); C.t // fixed 1/60 s steps; C.set(t) to seek - Reading time (Q-Day's rule): hold = 2.6 s + 0.31 s a word, kept between 5.2 and 16 s, for a beat with words. + Reading time (Q-Day's rule): hold = 2.6 s + 0.31 s a word, kept between 5.2 and 16 s, for a beat with words + (a beat can change the limits with reading: { max: 40 }, as a page of sources does). The words themselves are never changed; only the timing comes from them. Standalone: needs only the DHS namespace. */ @@ -35,7 +36,12 @@ // ---- reading time const READING = { base: 2.6, perWord: 0.31, min: 5.2, max: 16 }; const countWords = (s) => (String(s || '').match(/\S+/g) || []).length; - const beatWords = (b) => (b.text || []).reduce((n, x) => n + countWords(typeof x === 'string' ? x : x.text), 0); + // words in a beat: text blocks, plus the titles and notes of a sources list + const blockWords = (x) => + typeof x === 'string' + ? countWords(x) + : countWords(x.text) + (x.items || []).reduce((n, it) => n + countWords(it.title) + countWords(it.note), 0); + const beatWords = (b) => (b.text || []).reduce((n, x) => n + blockWords(x), 0); const readingHold = (n, r = READING) => (n > 0 ? clamp(r.base + r.perWord * n, r.min, r.max) : 0); // ---- seeded random (mulberry32) and a string hash (FNV-1a) to make seeds from names @@ -84,7 +90,13 @@ index: j, delay: b.delay != null ? b.delay : 0, dur: b.dur != null ? b.dur : 1.6, - hold: b.hold != null ? b.hold : Math.max(readingHold(words, reading), j === 0 && !words ? 1.5 : 0), + hold: + b.hold != null + ? b.hold + : Math.max( + readingHold(words, b.reading ? Object.assign({}, reading, b.reading) : reading), + j === 0 && !words ? 1.5 : 0 + ), ease: ease(b.ease), words, start: t, diff --git a/engine/src/essay/player.js b/engine/src/essay/player.js index 41a1f2c..69b7891 100644 --- a/engine/src/essay/player.js +++ b/engine/src/essay/player.js @@ -2,22 +2,28 @@ links; the picture (DHS.gl.host) and the words (DHS.essayText) draw what it tells them. Needs DHS.beats; uses DHS.gl.host and DHS.essayText when they are inlined, and still plays the words without them (or without WebGL2). - const E = DHS.essay.mount(essay, { root: document.body, sound: null }); - essay: { title, subtitle, lang, lens: knobs | null, scenes: [{ id, chapter, scene: 'bars', data: {...}, - transition: 'crossfade' | { type, dur }, beats: [{ dur, delay, hold, text: [{ pos, kind, text }] }] }] } + DHS.essay.start(essay, { root: document.body }) // loads the language tracks, then mounts; or: + const E = DHS.essay.mount(essay, { root, tracks: { en: {...} }, sound }); + essay: { lang, lens: knobs | null, sound: { bed: knobs } | null, autoplay, templates, scenes: [{ id, chapter, + scene: 'bars', data: {...}, transition: 'crossfade' | { type, dur }, beats: [{ dur, delay, hold }] }] } + The words come from per-language tracks (DHS.essayTrack: JSON keyed by scene id and beat; ?lang=es picks one, + and a language menu appears when there are several). Holds follow the active language's words. Viewer controls: - click, Space, Right arrow, Page Down, swipe left next beat (finishes the current one first) + Space, K, the round button (top right, always shown) pause / play + click, Right arrow, Page Down, Enter, swipe left next beat (finishes the current one first) right-click, Left arrow, Page Up, Backspace, swipe back (runs back 2.4x faster than it came) - A play by itself / wait for clicks K pause . black screen F full screen ? help card + A play by itself (the default) / wait for clicks M sound on / off . black screen F full screen + ? help card Home / End first / last beat; #scene-beat links (e.g. #bars-2) open at that beat; the back button works. Controls are hidden until the mouse moves or the screen is tapped, and fade after 3 s. - Sound (optional): opts.sound = { start(audioContext), update(t, playing) }. With it, the start screen offers - "Begin with sound" and "Begin silently"; without it, just "Begin". + Sound (optional): essay.sound = { bed: knobs } plays DHS.bed's quiet drone; or opts.sound = { start(audioContext), + update(t, playing), setMuted(on), status }. With sound, the start screen offers "Begin with sound" and "Begin + silently", and the sound button (M) turns it on or off at any time; without it, just "Begin". Test hooks (stills, fresh-eyes review, MP4): E.seek(scene, beat, t), E.trans(scene, p), E.perf(scene), E.state(), - E.textBoxes(), E.hideGlyphs(on). Also on window.EOMD_ESSAY. Add ?manual to the URL to start paused with no start + E.flashCheck(scene), E.contrast(), E.layoutCheck(), E.setLang(lang). Also on window.EOMD_ESSAY. Add ?manual to the URL to start paused with no start screen (what the stills and MP4 tools use). */ (function (G) { 'use strict'; @@ -53,6 +59,14 @@ .eo-start button{font-size:18px;padding:12px 22px} .eo-start small{margin-top:1.6em;opacity:.6;font-size:13px} .eo-help[hidden],.eo-start[hidden],.eo-note[hidden]{display:none} +.eo-pp{position:absolute;top:max(12px,env(safe-area-inset-top));right:max(12px,env(safe-area-inset-right));width:48px;height:48px;border-radius:50%; + display:none;align-items:center;justify-content:center;padding:0;cursor:pointer;color:var(--eo-ink,#f3f0e8);background:rgba(0,0,0,.45); + border:1px solid rgba(255,255,255,.35);opacity:.75;transition:opacity .3s} +.eo-pp svg{fill:currentColor}.eo-pp:hover,.eo-pp:focus-visible{opacity:1}.eo-pp:focus-visible{outline:2px solid var(--eo-accent,#e9e4d8);outline-offset:2px} +.eo-on .eo-pp{display:flex} +.eo-lang{font:inherit;color:inherit;background:#111114;border:1px solid rgba(255,255,255,.28);border-radius:6px;padding:6px 8px;min-height:36px} +.eo-langrow{margin-top:1.2em} +@media (max-width:600px){.eo-row{flex-wrap:wrap}.eo-where{flex-basis:100%;order:-1}.eo-row button{padding:6px 9px}} .eo-help .eo-card{background:#111114;border:1px solid rgba(255,255,255,.2);border-radius:10px;padding:22px 26px;text-align:left;max-width:520px;font-size:15px;line-height:1.5} .eo-help h2{margin:0 0 .6em;font-size:18px;font-weight:600} .eo-help dl{display:grid;grid-template-columns:auto 1fr;gap:4px 16px;margin:0 0 1em} @@ -76,6 +90,37 @@ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c] ); + // button and note words when DHS.essayTrack isn't inlined (it holds the full list, translatable per track) + const FALLBACK_UI = { + begin: 'Begin', + withSound: 'Begin with sound', + silently: 'Begin silently', + pause: 'Pause', + play: 'Play', + playAgain: 'Play again', + next: 'Next', + back: 'Back', + keys: 'Keys', + close: 'Close', + fullscreen: 'Full screen', + soundOn: 'Sound on', + soundOff: 'Sound off', + soundLoading: 'Preparing sound\u2026', + auto: 'Plays by itself', + waits: 'Waits for clicks', + part: 'part {n} of {total}', + pressKeys: 'Press ? for keys', + language: 'Language', + progress: 'Progress', + noGL: "This screen can't draw the moving pictures. The words and numbers still play.", + help: [ + ['Space', 'Pause or play'], + ['Click, \u2192', 'Next'], + ['Right-click, \u2190', 'Back'], + ['?', 'This card'], + ], + }; + // A plain words layer for when DHS.essayText isn't inlined: each beat's text, no positions or fades. function plainText(root, TL, essay) { const box = el('div', '', root); @@ -128,137 +173,195 @@ return { maxPerSecond, maxStep }; } - function mount(essay, opts = {}) { - const B = DHS.beats; + function mount(source, opts = {}) { + const B = DHS.beats, + Tk = DHS.essayTrack; const root = el('div', 'eo-root', opts.root || doc.body); - if (essay.lang) root.lang = essay.lang; if (!doc.getElementById('eo-css')) el('style', '', doc.head, CSS).id = 'eo-css'; const params = new URLSearchParams(G.location ? G.location.search : ''); const manual = params.has('manual'); const reducedMQ = G.matchMedia ? G.matchMedia('(prefers-reduced-motion: reduce)') : { matches: false }; const reduced = () => reducedMQ.matches || params.get('reduced') === '1'; + // ---- words: the language's track, resolved into plain scenes (sequences expanded, sources paged) + const tracks = opts.tracks || (Tk ? Tk.fromPage(doc) : {}); + const langs = Object.keys(tracks); + let lang = Tk ? Tk.pick(tracks, params.get('lang'), source.lang) : source.lang || 'en'; + const resolveLang = (l) => { + const R = Tk ? Tk.resolve(source, tracks[l] || {}) : { essay: source, ui: FALLBACK_UI, warnings: [] }; + R.warnings.forEach((w) => console.warn('essay:', w)); + return R; + }; + let R = resolveLang(lang), + essay = R.essay, + ui = R.ui; + root.lang = lang; + // ---- picture const canvas = el('canvas', 'eo-gl', root); canvas.setAttribute('aria-hidden', 'true'); - const lensKnobs = DHS.lens ? DHS.lens.fromQuery(G.location ? G.location.search : '', essay.lens || null) : null; + const lensKnobs = DHS.lens ? DHS.lens.fromQuery(G.location ? G.location.search : '', source.lens || null) : null; const host = DHS.gl && DHS.gl.host && params.get('gl') !== '0' ? DHS.gl.host(canvas, { essay, lens: lensKnobs, reduced }) : null; const transDur = (type) => DHS.gl && DHS.gl.transitions && DHS.gl.transitions[type] ? DHS.gl.transitions[type].dur : 1; - const TL = B.compile(essay, { transDur }); - // ---- words const textRoot = el('div', 'eo-textroot', root); textRoot.style.cssText = 'position:absolute;inset:0;pointer-events:none'; - textRoot.setAttribute('aria-hidden', 'true'); - const text = DHS.essayText - ? DHS.essayText.create(textRoot, TL, essay, { reduced, host }) - : plainText(textRoot, TL, essay); const live = el('div', 'eo-sr', root); // screen readers hear each beat's words once live.setAttribute('aria-live', 'polite'); - const black = el('div', 'eo-black', root); - const note = el( - 'div', - 'eo-note', - root, - "This screen can't draw the moving pictures. The words and numbers still play." - ); + const note = el('div', 'eo-note', root); note.setAttribute('role', 'status'); + note.hidden = true; const nogl = () => { root.classList.add('eo-nogl'); canvas.style.display = 'none'; note.hidden = false; }; - note.hidden = true; - if (!host || !host.ok) nogl(); - if (host) host.onfail = nogl; + + // ---- sound: the essay's drone bed (DHS.bed) unless the page passes its own hook + const sound = + opts.sound || (source.sound && DHS.bed && DHS.dsp ? DHS.bed.sound(source.sound.bed || source.sound) : null); + if (sound && sound.prepare && !manual) sound.prepare().then(() => setSoundLabel()); // ---- controls - const ui = el('div', 'eo-ui', root); - const bar = el('div', 'eo-bar', ui); + const ui0 = el('div', 'eo-ui', root); + const bar = el('div', 'eo-bar', ui0); bar.setAttribute('role', 'slider'); - bar.setAttribute('aria-label', 'Progress'); bar.tabIndex = -1; - const segs = TL.chapters.map((c) => { - const s = el('div', 'eo-seg', bar); - s.style.flex = String(Math.max(0.001, c.end - c.start)); - s.title = c.name; - return { c, fill: el('i', '', s) }; - }); - const row = el('div', 'eo-row', ui); + const row = el('div', 'eo-row', ui0); const bBack = el('button', '', row, '←'); - bBack.setAttribute('aria-label', 'Back'); - const bPlay = el('button', '', row, 'Pause'); const bNext = el('button', '', row, '→'); - bNext.setAttribute('aria-label', 'Next'); const where = el('div', 'eo-where', row); + const bSound = sound ? el('button', '', row) : null; + const langSel = langs.length > 1 ? el('select', 'eo-lang', row) : null; const bAuto = el('button', '', row); const bHelp = el('button', '', row, '?'); - bHelp.setAttribute('aria-label', 'Keys and help'); - const bFull = el('button', '', row, 'Full screen'); - + const bFull = el('button', '', row); + // the pause button stays on screen while the essay plays (controls fade; this doesn't) + const bPP = el('button', 'eo-pp', root); const help = el('div', 'eo-help', root); help.hidden = true; - help.innerHTML = ``; - const start = el('div', 'eo-start', root); - start.innerHTML = - `

${esc(essay.title || '')}

` + - (essay.subtitle ? `

${esc(essay.subtitle)}

` : '') + - `
${opts.sound ? '' : ''}
` + - `Press ? for keys`; if (manual) { start.hidden = true; root.classList.add('eo-on', 'eo-idle'); // stills: no controls until the mouse moves } + if (langSel) + langs.forEach((l) => { + const o = el('option', '', langSel); + o.value = l; + o.textContent = (tracks[l].name || l) + (tracks[l].draft ? ' (draft)' : ''); + }); // ---- state const clock = B.clock(60); const st = { started: manual, playing: !manual, - auto: essay.autoplay !== false, + auto: source.autoplay !== false, rate: 1, stopAt: null, target: null, - lastKey: '', dirty: true, audio: null, + soundOn: false, + nav: false, + }; + let TL, text, segs; + + const label = (b, txt, aria) => { + b.textContent = txt; + if (aria) b.setAttribute('aria-label', aria); }; const setAuto = (a) => { st.auto = a; - bAuto.textContent = a ? 'Plays by itself' : 'Waits for clicks'; + label(bAuto, a ? ui.auto : ui.waits); bAuto.setAttribute('aria-pressed', String(a)); }; - setAuto(st.auto); + const PP_PAUSE = + ''; + const PP_PLAY = + ''; const setPlaying = (p) => { st.playing = p; - bPlay.textContent = p ? 'Pause' : 'Play'; + const end = TL && clock.t >= TL.total; + bPP.innerHTML = p ? PP_PAUSE : PP_PLAY; + bPP.setAttribute('aria-label', p ? ui.pause : end ? ui.playAgain : ui.play); + bPP.title = bPP.getAttribute('aria-label') + ' (Space)'; + }; + const setSoundLabel = () => { + if (!bSound) return; + const busy = sound.status === 'rendering'; + label(bSound, busy ? ui.soundLoading : st.soundOn ? ui.soundOn : ui.soundOff); + bSound.setAttribute('aria-pressed', String(st.soundOn)); + }; + + // (re)build everything that holds words: timeline, words layer, progress bar, labels, start screen, help card + const build = () => { + TL = B.compile(essay, { transDur }); + textRoot.innerHTML = ''; + text = DHS.essayText + ? DHS.essayText.create(textRoot, TL, essay, { reduced, host }) + : plainText(textRoot, TL, essay); + bar.innerHTML = ''; + bar.setAttribute('aria-label', ui.progress); + segs = TL.chapters.map((c) => { + const sg = el('div', 'eo-seg', bar); + sg.style.flex = String(Math.max(0.001, c.end - c.start)); + sg.title = essay.scenes[c.scene].chapterName || c.name; + return { c, sg, fill: el('i', '', sg) }; + }); + label(bBack, '←', ui.back); + label(bNext, '→', ui.next); + label(bHelp, '?', ui.keys); + label(bFull, ui.fullscreen); + if (langSel) { + langSel.value = lang; + langSel.setAttribute('aria-label', ui.language); + } + setAuto(st.auto); + setPlaying(st.playing); + setSoundLabel(); + note.textContent = ui.noGL; + help.innerHTML = + ``; + help.querySelector('button').onclick = () => toggleHelp(false); + start.innerHTML = + `

${esc(essay.title || '')}

` + + (essay.subtitle ? `

${esc(essay.subtitle)}

` : '') + + `
${sound ? `` : ``}
` + + (langSel ? '
' : '') + + `${esc(ui.pressKeys)}`; + start.querySelectorAll('button').forEach((b) => (b.onclick = () => begin(b.dataset.s === '1'))); + if (langSel) { + const s2 = langSel.cloneNode(true); + s2.value = lang; + s2.onchange = () => setLang(s2.value); + start.querySelector('.eo-langrow').appendChild(s2); + } + lastKey = ''; + if (host && host.ok) host.setEssay(essay); + st.dirty = true; }; const S = () => TL.at(clock.t, { reduced: reduced() }); const fi = () => TL.flatIndex(clock.t); - const keyOf = (s) => TL.scenes[s.scene].id + '-' + (Math.max(0, s.beat) + 1); - // jump straight to a time (seeks, links, long backs) const jump = (t) => { clock.set(t); st.target = null; st.rate = 1; st.dirty = true; }; - // where "next" plays to: finish the current beat; else play the next one in (its scene's transition first) - const next = (user = true) => { - const s = S(), - F = TL.flat, + // next: finish the current beat; else play the next one in (its scene's transition first) + const next = () => { + const F = TL.flat, k = fi(), cur = F[k].B; st.target = null; @@ -269,9 +372,8 @@ jump(n.beat === 0 ? TL.scenes[n.scene].start : n.B.start); st.stopAt = st.auto ? null : n.B.shown; } else jump(TL.total); - st.nav = user; + st.nav = true; setPlaying(true); - void s; }; // back: run back at 2.4x to the previous beat, fully shown (jump if that would take more than 3 s) const back = () => { @@ -288,8 +390,13 @@ st.stopAt = st.auto ? null : to; setPlaying(true); }; - const goBeat = (i, j, where = 'shown') => { - jump(TL.timeOf(i, j, where)); + const togglePlay = () => { + if (clock.t >= TL.total) jump(0); + setPlaying(!st.playing); + wake(); + }; + const goBeat = (i, j, where2 = 'shown') => { + jump(TL.timeOf(i, j, where2)); st.stopAt = null; }; const fromHash = () => { @@ -300,6 +407,49 @@ goBeat(i, +m[2] - 1); return true; }; + // switch language at the same scene and beat (the timeline changes: holds follow the new words) + const setLang = (l) => { + if (!tracks[l] || l === lang) return; + const s = S(), + id = s.id, + beat = Math.max(0, s.beat); + lang = l; + R = resolveLang(l); + essay = R.essay; + ui = R.ui; + root.lang = l; + build(); + const i = TL.sceneIndex(id); + goBeat(i < 0 ? 0 : i, beat); + if (G.history && G.location && !manual) { + const u = new URL(G.location.href); + u.searchParams.set('lang', l); + G.history.replaceState(null, '', u.toString()); + } + draw(); + }; + if (langSel) langSel.onchange = () => setLang(langSel.value); + + // ---- sound + const ensureAudio = () => { + if (!sound || st.audio) return; + try { + const AC = G.AudioContext || G.webkitAudioContext; + st.audio = new AC({ sampleRate: 48000 }); + const pr = sound.start(st.audio); + setSoundLabel(); + if (pr && pr.then) pr.then(setSoundLabel); + } catch (err) { + console.warn('essay: no sound', err); + } + }; + const setSound = (on) => { + if (!sound) return; + st.soundOn = on; + if (on) ensureAudio(); + if (sound.setMuted) sound.setMuted(!on); + setSoundLabel(); + }; // ---- the frame let lastKey = '', @@ -308,28 +458,35 @@ const s = S(); if (host && host.ok) host.render(s); text.render(s); - // progress, place, link segs.forEach( ({ c, fill }) => (fill.style.width = (100 * B.clamp01((s.t - c.start) / Math.max(1e-6, c.end - c.start))).toFixed(2) + '%') ); bar.setAttribute('aria-valuenow', String(Math.round((100 * s.t) / TL.total))); - const key = keyOf(s); + const key = TL.scenes[s.scene].id + '-' + (Math.max(0, s.beat) + 1); if (key !== lastKey && st.started) { lastKey = key; - const sc = TL.scenes[s.scene]; + const sc = TL.scenes[s.scene], + spec = essay.scenes[s.scene]; where.textContent = - (sc.chapter ? sc.chapter + ' · ' : '') + 'part ' + (s.scene + 1) + ' of ' + TL.scenes.length; + (spec.chapterName ? spec.chapterName + ' · ' : '') + + ui.part.replace('{n}', s.scene + 1).replace('{total}', TL.scenes.length); if (G.history && G.location && !manual) { const url = '#' + encodeURIComponent(sc.id) + '-' + (Math.max(0, s.beat) + 1); if (G.location.hash !== url) G.history[st.nav ? 'pushState' : 'replaceState'](null, '', url); } st.nav = false; - const b = essay.scenes[s.scene].beats && essay.scenes[s.scene].beats[Math.max(0, s.beat)]; - const said = b ? (b.text || []).map((x) => (typeof x === 'string' ? x : x.text)).join(' ') : ''; + const b = spec.beats && spec.beats[Math.max(0, s.beat)]; + // the sources list is read where it is (its links are real); the live region says the rest once + const said = b + ? (b.text || []) + .filter((x) => !x.items) + .map((x) => (typeof x === 'string' ? x : x.text)) + .join(' ') + : ''; if (said && said !== lastLive) live.textContent = lastLive = said; } - if (opts.sound && st.audio) opts.sound.update(s.t, st.playing); + if (sound && st.audio && sound.update) sound.update(s.t, st.playing && st.soundOn); }; let prev = 0; @@ -362,7 +519,6 @@ if (clock.t >= TL.total) { clock.set(TL.total); setPlaying(false); - bPlay.textContent = 'Play again'; } if (clock.t !== before) st.dirty = true; } @@ -372,13 +528,13 @@ } }; - // ---- resize (pixel density capped at 2, picture capped at 2560 x 1600) + // ---- resize (pixel density capped at 2, picture capped at 2560 x 1600 either way round) const resize = () => { const r = root.getBoundingClientRect(); - let d = Math.min(2, G.devicePixelRatio || 1); - d = Math.min(d, 2560 / Math.max(1, r.width), 1600 / Math.max(1, r.height), d); - if (host && host.ok) - host.resize(Math.max(2, Math.round(r.width * d)), Math.max(2, Math.round(r.height * d)), r.width, r.height); + const big = Math.max(r.width, r.height), + small = Math.min(r.width, r.height); + const d = Math.min(2, G.devicePixelRatio || 1, 2560 / Math.max(1, big), 1600 / Math.max(1, small)); + if (host && host.ok) host.resize(Math.max(2, Math.round(r.width * d)), Math.max(2, Math.round(r.height * d))); if (text.resize) text.resize(r.width, r.height); st.dirty = true; }; @@ -394,7 +550,7 @@ }, 3000); }; root.addEventListener('mousemove', wake); - const inUI = (e) => e.target.closest && e.target.closest('.eo-ui,.eo-help,.eo-start'); + const inUI = (e) => e.target.closest && e.target.closest('.eo-ui,.eo-help,.eo-start,.eo-pp,a,select'); root.addEventListener('click', (e) => { if (!st.started || inUI(e) || e.pointerType === 'touch') return; next(); @@ -430,13 +586,16 @@ else if (root.requestFullscreen) root.requestFullscreen().catch(() => {}); }; G.addEventListener('keydown', (e) => { - if (e.ctrlKey || e.metaKey || e.altKey) return; - if (!st.started) return; - const k = e.key; + if (e.ctrlKey || e.metaKey || e.altKey || !st.started) return; + const k = e.key, + tag = e.target.tagName; if (!help.hidden && (k === 'Escape' || k === '?')) return toggleHelp(false); - if (e.target.tagName === 'BUTTON' && (k === ' ' || k === 'Enter')) return; + if ((tag === 'BUTTON' || tag === 'A') && (k === ' ' || k === 'Enter')) return; + if (tag === 'SELECT') return; const act = { - ' ': next, + ' ': togglePlay, + k: togglePlay, + K: togglePlay, ArrowRight: next, PageDown: next, Enter: next, @@ -445,8 +604,8 @@ Backspace: back, a: () => setAuto(!st.auto), A: () => setAuto(!st.auto), - k: () => setPlaying(!st.playing), - K: () => setPlaying(!st.playing), + m: () => setSound(!st.soundOn), + M: () => setSound(!st.soundOn), '.': () => black.classList.toggle('on'), f: fullscreen, F: fullscreen, @@ -463,21 +622,15 @@ }); bBack.onclick = () => back(); bNext.onclick = () => next(); - bPlay.onclick = () => { - if (clock.t >= TL.total) jump(0); - setPlaying(!st.playing); - }; + bPP.onclick = togglePlay; bAuto.onclick = () => setAuto(!st.auto); bHelp.onclick = () => toggleHelp(); bFull.onclick = fullscreen; - help.querySelector('button').onclick = () => toggleHelp(false); + if (bSound) bSound.onclick = () => setSound(!st.soundOn); bar.addEventListener('click', (e) => { - const r = bar.getBoundingClientRect(), - x = (e.clientX - r.left) / r.width; - // the segments have gaps, so find the chapter under the pointer and the fraction inside it - let t = x * TL.total; - for (const { c } of segs) { - const sr = segs.find((q) => q.c === c).fill.parentNode.getBoundingClientRect(); + let t = 0; + for (const { c, sg } of segs) { + const sr = sg.getBoundingClientRect(); if (e.clientX >= sr.left - 3 && e.clientX <= sr.right + 3) t = c.start + B.clamp01((e.clientX - sr.left) / sr.width) * (c.end - c.start); } @@ -492,27 +645,28 @@ start.hidden = true; st.started = true; root.classList.add('eo-on'); - if (withSound && opts.sound) { - try { - const AC = G.AudioContext || G.webkitAudioContext; - st.audio = new AC({ sampleRate: 48000 }); - opts.sound.start(st.audio); - } catch (err) { - console.warn('essay: no sound', err); - } - } + if (withSound) setSound(true); if (!fromHash()) jump(0); setPlaying(true); - if (!note.hidden) G.setTimeout(() => (note.hidden = true), 8000); // said once; then out of the words' way fullscreen(); wake(); + if (!note.hidden) G.setTimeout(() => (note.hidden = true), 8000); // said once; then out of the words' way }; - start.querySelectorAll('button').forEach((b) => (b.onclick = () => begin(b.dataset.s === '1'))); // ---- test hooks: repeatable stills of any beat or any point in a transition const E = { - TL, + get TL() { + return TL; + }, + get essay() { + return essay; + }, + get lang() { + return lang; + }, + langs, host, + sound, // scene: index or id; beat: index (-1 = the start of its transition); t: seconds after the beat starts, // or 'shown' (fully in) / 'end' (the last frame of its hold) seek(scene, beat = 0, t = 'shown') { @@ -541,7 +695,7 @@ draw(); return E.state(); }, - // ms per frame for a scene (GPU finished each frame), drawn n times at its last beat + // ms per frame for a scene (waiting for the GPU each frame), drawn n times at its last beat perf(scene, n = 60) { if (!host || !host.ok) return null; E.seek(scene, 1e9, 'shown'); @@ -549,13 +703,12 @@ const t0 = G.performance.now(); for (let f = 0; f < n; f++) { host.render(Object.assign({}, s, { sceneT: s.sceneT + f / 60, t: s.t + f / 60 })); - host.finish(); // wait for the GPU each frame (reads one pixel: finish alone may not wait) + host.finish(); } return (G.performance.now() - t0) / n; }, // the 3-flashes-a-second rule (WCAG 2.3.1) for the transition into `scene`: the picture is stepped at 60 fps - // from 0.5 s before to 0.5 s after; in each cell of a 16 x 9 grid, a change is a swing in relative luminance - // of at least 0.1 with the darker side under 0.8, and a flash is two opposing changes + // from 0.5 s before to 0.5 s after; flashes counted per cell of a 16 x 9 grid (DHS.essay.flashCount) flashCheck(scene, cols = 16, rows = 9) { if (!host || !host.ok) return null; const Sc = TL.scenes[TL.sceneIndex(scene)], @@ -582,28 +735,40 @@ trans: s.trans, gl: !!(host && host.ok), reduced: reduced(), + lang, + playing: st.playing, + sound: sound ? sound.status : null, }; }, textBoxes: () => text.boxes(), contrast: () => (text.contrast ? text.contrast() : []), - hideGlyphs: (on) => { - text.hideGlyphs(on); - }, + layoutCheck: () => (text.layoutCheck ? text.layoutCheck() : []), + hideGlyphs: (on) => text.hideGlyphs(on), next, back, begin, setAuto, + setLang, + setSound, + togglePlay, }; G.EOMD_ESSAY = E; + build(); + if (!host || !host.ok) nogl(); + if (host) host.onfail = nogl; resize(); - if (manual) { - setPlaying(false); - draw(); - } + setPlaying(st.playing); + if (manual) draw(); G.requestAnimationFrame(frame); return E; } - DHS.essay = { mount, flashCount }; + // Loads the language tracks (inline JSON, or data-src when served over http), then mounts. + const start = async (essay, opts = {}) => { + const tracks = opts.tracks || (DHS.essayTrack ? await DHS.essayTrack.load(doc) : {}); + return mount(essay, Object.assign({}, opts, { tracks })); + }; + + DHS.essay = { mount, start, flashCount }; })(globalThis); diff --git a/engine/src/essay/text.js b/engine/src/essay/text.js index 94b9042..713c476 100644 --- a/engine/src/essay/text.js +++ b/engine/src/essay/text.js @@ -3,12 +3,13 @@ { pos, kind, text } pos center, chapter, quote (these three share the middle), lower-third, top-left, top-right, bottom-left, bottom-right. Several blocks of one beat at one position stack (a big number and its caption). - kind body, headline, chapter, quote, source, number, note + sources: a list of { title, url, note }; titles are working links (http/https), with their site shown + kind body, headline, chapter, quote, source, number, note, takeaway (the closing statement), sources The text is shown exactly as written; only its timing comes from it. Timing (a pure function of t, so seeks and stills match playback): - a beat's blocks at one position arrive word by word when the beat arrives (each word fades in over 0.6 s, - about 0.09 s apart; a number arrives whole); + about 0.09 s apart, closer for long text so all are in by the end of the beat's dur; a number arrives whole); - they stay until a later beat puts text at the same position (then they fade out over 0.5 s while the new text fades in), or until the scene ends (they fade out in the first 40% of the next transition); - prefers-reduced-motion: each group fades in whole over 0.3 s, nothing moves. @@ -27,6 +28,8 @@ const SLOT = { center: 'middle', chapter: 'middle', quote: 'middle' }; const PATCH = { + sources: 0.6, + takeaway: 0.45, body: 0.55, headline: 0.5, chapter: 0.42, @@ -34,10 +37,10 @@ source: 0.55, number: 0.45, note: 0.55, - label: 0.5, + label: 0.68, }; const CSS = ` -.eo-text{position:absolute;inset:0;pointer-events:none;color:var(--eo-ink,#f3f0e8);--m:max(5vw,env(safe-area-inset-left));--mt:max(8vh,env(safe-area-inset-top));--mb:calc(max(8vh,env(safe-area-inset-bottom)) + 44px)} +.eo-text{position:absolute;inset:0;pointer-events:none;color:var(--eo-ink,#f3f0e8);--m:max(5vw,env(safe-area-inset-left));--mt:max(8vh,calc(env(safe-area-inset-top) + 66px));--mb:calc(max(8vh,env(safe-area-inset-bottom)) + 44px)} .eo-pos{position:absolute;display:grid} .eo-pos>.eo-g{grid-area:1/1;position:relative;padding:.9em 1.3em} .eo-g>.eo-patch{position:absolute;inset:0;z-index:-1;border-radius:1.4em;background:rgba(0,0,0,var(--a));box-shadow:0 0 2.6em 1.2em rgba(0,0,0,var(--a))} @@ -63,7 +66,19 @@ background:rgba(0,0,0,${PATCH.label});box-shadow:0 0 .9em .4em rgba(0,0,0,${PATCH.label})} .eo-lb.eo-k-value{font-weight:600;font-size:clamp(15px,.7vw + 1vmin,26px)} .eo-lb.eo-k-note{font-size:clamp(12px,.4vw + .8vmin,17px);opacity:.95} -@media (max-width:700px){.eo-p-top-left,.eo-p-top-right,.eo-p-bottom-left,.eo-p-bottom-right{width:auto;left:var(--m);right:var(--m)}} +.eo-text a{pointer-events:auto;color:inherit;text-decoration:underline;text-decoration-thickness:1px;text-underline-offset:.18em} +.eo-text a:focus-visible{outline:2px solid var(--eo-accent,#e9e4d8);outline-offset:3px;border-radius:2px} +.eo-p-sources{left:var(--m);top:var(--mt);bottom:var(--mb);width:min(44em,90vw);align-content:start} +.eo-src{margin:.4em 0 0;padding-left:1.3em;font-size:clamp(15px,.55vw + .9vmin,22px);line-height:1.38} +.eo-src li{margin:0 0 .75em} +.eo-src-title{font-weight:600} +.eo-src-site{font-size:.86em} +.eo-src-note{display:block;margin-top:.15em} +.eo-k-takeaway{font-family:var(--eo-display,inherit);font-size:clamp(26px,2.2vw + 2.2vmin,64px);line-height:1.2;font-weight:500} +/* portrait phones and tablets: corner positions go full width (the data band sits between them) */ +@media (orientation:portrait){.eo-text{--m:max(6vw,env(safe-area-inset-left));--mt:max(6vh,calc(env(safe-area-inset-top) + 66px));--mb:calc(max(4vh,env(safe-area-inset-bottom)) + 92px)} + .eo-p-top-left,.eo-p-top-right,.eo-p-bottom-left,.eo-p-bottom-right{width:auto;left:var(--m);right:var(--m);text-align:left} + .eo-p-middle{width:88vw}.eo-pos>.eo-g{padding:.7em 1em}} `; const el = (tag, cls, parent) => { @@ -84,7 +99,6 @@ st.textContent = CSS; } const layer = el('div', 'eo-text', root); - layer.setAttribute('aria-hidden', 'true'); // the player's live region reads the words once let W = 1, H = 1; @@ -113,23 +127,52 @@ patch.style.setProperty('--a', String(alpha)); const words = [], blocks = []; - byPos[pos].forEach((blk) => { - const kind = blk.kind || 'body', - p = el('p', 'eo-b eo-k-' + kind, g), - bw = []; - blocks.push({ kind, text: String(blk.text), words: bw }); - // exact text: words become spans, the whitespace between them is kept as it was - String(blk.text) + // exact text: words become spans, the whitespace between them is kept as it was + const addWords = (parent, str, kind) => { + const bw = []; + String(str == null ? '' : str) .split(/(\s+)/) .forEach((part) => { if (!part) return; - if (/^\s+$/.test(part)) return p.appendChild(doc.createTextNode(part)); - const w = el('span', 'eo-w', p); + if (/^\s+$/.test(part)) return parent.appendChild(doc.createTextNode(part)); + const w = el('span', 'eo-w', parent); w.textContent = part; words.push({ el: w, whole: kind === 'number', last: '' }); bw.push(w); }); + blocks.push({ kind, text: String(str), words: bw }); + }; + byPos[pos].forEach((blk) => { + const kind = blk.kind || 'body'; + if (blk.items) { + // a sources list: each title is a working link (http and https only), its site, and a short note + const ol = el('ol', 'eo-b eo-src', g); + blk.items.forEach((it) => { + const li = el('li', '', ol), + ok = /^https?:\/\//i.test(it.url || ''); + const t = el(ok ? 'a' : 'span', 'eo-src-title', li); + if (ok) { + t.href = it.url; + t.target = '_blank'; + t.rel = 'noopener noreferrer'; + } + addWords(t, it.title, 'source-title'); + if (ok) { + li.appendChild(doc.createTextNode(' ')); + addWords( + el('span', 'eo-src-site', li), + new URL(it.url).hostname.replace(/^www\./, ''), + 'source-site' + ); + } + if (it.note) addWords(el('span', 'eo-src-note', li), it.note, 'source-note'); + }); + return; + } + addWords(el('p', 'eo-b eo-k-' + kind, g), blk.text, kind); }); + // the sources list is read by screen readers where it is (links); other words come from the live region + if (!byPos[pos].some((b) => b.items)) g.setAttribute('aria-hidden', 'true'); groups.push({ pos: slot, beat: j, @@ -141,6 +184,7 @@ kind: kind0, text: byPos[pos].map((x) => x.text).join(' '), start: S.beats[j].arrive, + reveal: Math.max(1.2, S.beats[j].dur), out: null, last: '', }); @@ -183,7 +227,8 @@ setOp(gr, gr.g, op); gr.g.style.visibility = op > 0 ? 'visible' : 'hidden'; const n = gr.words.length, - stag = red ? 0 : Math.min(0.09, 2.2 / Math.max(1, n)); + // every word is in by the time the beat has arrived (a long sources list reveals faster) + stag = red ? 0 : Math.min(0.09, Math.max(0, gr.reveal - 0.6) / Math.max(1, n - 1)); gr.words.forEach((w, k) => setOp(w, w.el, red ? 1 : clamp01((t - gr.start - (w.whole ? 0 : k * stag)) / 0.6))); }); // data labels @@ -274,6 +319,41 @@ }); return out; }, + // problems a viewer would see: words or labels on top of each other, or cut off at the screen's edge + layoutCheck() { + const rootR = layer.getBoundingClientRect(), + out = []; + const items = []; + shown.forEach((i) => { + scenes[i].groups.forEach((gr) => { + if (+gr.last > 0.5) + items.push({ key: i + ':' + gr.beat + ':' + gr.pos, text: gr.text, r: gr.g.getBoundingClientRect() }); + }); + scenes[i].labels.forEach((lb, k) => { + if (lb.el.style.display !== 'none' && +lb.last > 0.5) + items.push({ key: i + ':label:' + k, text: lb.txt, r: lb.el.getBoundingClientRect(), label: true }); + }); + }); + // groups have padding round their words: shrink them a little so touching patches aren't counted + const pad = (r, p) => ({ left: r.left + p, right: r.right - p, top: r.top + p, bottom: r.bottom - p }); + items.forEach((a, n) => { + const r = a.r; + if ( + r.left < rootR.left - 1 || + r.top < rootR.top - 1 || + r.right > rootR.right + 1 || + r.bottom > rootR.bottom + 1 + ) + out.push({ problem: 'off screen', a: a.text }); + items.slice(n + 1).forEach((b) => { + const A = pad(a.r, a.label ? 2 : 10), + Bb = pad(b.r, b.label ? 2 : 10); + if (A.left < Bb.right && Bb.left < A.right && A.top < Bb.bottom && Bb.top < A.bottom) + out.push({ problem: 'overlap', a: a.text, b: b.text }); + }); + }); + return out; + }, contrast() { const px = host && host.ok ? host.pixels() : null; const rootR = layer.getBoundingClientRect(); diff --git a/engine/src/essay/track.js b/engine/src/essay/track.js new file mode 100644 index 0000000..cd4f80f --- /dev/null +++ b/engine/src/essay/track.js @@ -0,0 +1,240 @@ +/* TRACK: an essay's on-screen words as a separate track, one JSON per language, never baked into the picture. + The essay file holds the structure (scenes, scene templates, data rows, timing); a track holds the words, keyed + by scene id and beat number. Reading-time holds are computed from the active track's words, so each language + gets its own pacing. Copy is shown exactly as written; numbers come from the data, formatted for the language. + + A track: + { + "lang": "en", "draft": false, draft: a translation nobody has checked yet (shown in the console) + "title": "...", "subtitle": "...", + "ui": { "begin": "Begin", ... }, player buttons and notes (DHS.essayTrack.UI has every key) + "chapters": { "opening": "Opening" }, chapter names by chapter id + "fields": { "population": "Population" }, data field names, used as chart labels + "text": { + "opening": { "1": [{ "pos": "chapter", "kind": "chapter", "text": "..." }], "2": [ ... ] }, + "bars": { "1": [ ... ], "labels": ["A", "B"], "note": "Source: ..." }, + "country#1": { "1": [{ "pos": "top-left", "kind": "headline", "text": "{name}" }], "note": "..." }, + "sources": { "1": [{ "kind": "headline", "text": "Sources" }] } + }, + "sources": [{ "title": "...", "url": "https://...", "note": "..." }] + } + "country#1" is step 1 of the scene template "country": {field} in its text is filled from each data row. + + Scene entries in the essay that this expands: + { sequence: 'country', rows: [row, ...], scale: 'row' | 'all', transition } + one short run of scenes per row from essay.templates.country.steps: [{ scene, fields, data, beats, + transition }]. A step's chart values are row[field] for its fields (a missing field stays missing, never + zero); scale 'all' puts every row on one scale (comparable bars across countries). + { id: 'sources', type: 'sources', perPage: 3 } + the sources chapter: the track's sources, perPage to a beat, as a list with working links. + + DHS.essayTrack.resolve(essay, track) -> { essay (plain scenes with text), ui, warnings } + DHS.essayTrack.fromPage(document) -> { lang: track } from + + + + @@ -18,7 +23,7 @@ diff --git a/engine/essay-demo/essay.js b/engine/essay-demo/essay.js index 9f65305..df63c9d 100644 --- a/engine/essay-demo/essay.js +++ b/engine/essay-demo/essay.js @@ -1,63 +1,42 @@ -/* DEMO ESSAY: placeholder content only. It shows what the kit's essay player can do; ProofEr owns real essays, their - copy, figures and design. Every number here is MADE UP and labelled so on screen. No real figures belong here: - those live in ProofEr's checked figures table. */ +/* DEMO ESSAY: placeholder content only. It shows what the kit's essay engine does; ProofEr owns real essays, their + copy, figures and design. Every number here is MADE UP and labelled so on screen; no real figures belong here + (they live in ProofEr's checked figures table). The words are in tracks/.json, not in this file. */ +// Made-up rows: what a per-country data row looks like (part2 of row B is missing on purpose: drawn as no figure) +const ROWS = [ + { id: 'a', name: 'Placeholder country A', total: 1000, part1: 600, part2: 300 }, + { id: 'b', name: 'Placeholder country B', total: 400, part1: 120, part2: null }, +]; // prettier-ignore const ESSAY = { - title: 'Placeholder Motion Essay', - subtitle: 'A demo of the EOMD kit. The words and numbers are placeholders, not facts.', lang: 'en', lens: { bloom: 0.12, threshold: 0.85, streak: 0, fringe: 0.3, vignette: 0.28, grain: 0.015, tone: 'none' }, - scenes: [ - { - id: 'opening', chapter: 'Opening', scene: 'field', data: { tint: [0.9, 0.86, 0.8] }, - transition: { type: 'dip', dur: 2 }, - beats: [ - { dur: 2.4, text: [{ pos: 'chapter', kind: 'chapter', text: 'Placeholder chapter title' }] }, - { dur: 1.6, text: [{ pos: 'center', kind: 'body', text: 'This sentence stands in for the opening line of an essay. A real essay brings its own words, word for word.' }] }, - ], - }, - { - id: 'bars', chapter: 'Part one', scene: 'bars', - data: { values: [12, 30, 21, 45, 8], labels: ['A', 'B', 'C', 'D', 'E'], max: 50, grow: 1, note: 'Made-up placeholder numbers' }, - transition: { type: 'crossfade', dur: 2.2 }, - beats: [ - { dur: 1.2, text: [{ pos: 'top-left', kind: 'headline', text: 'Five made-up values' }] }, - { dur: 3.2, text: [{ pos: 'top-left', kind: 'body', text: 'Each bar starts at zero and its height is exactly proportional to its value.' }] }, - { dur: 1.6, focus: 3, text: [{ pos: 'top-left', kind: 'body', text: 'One bar can be brought forward while the others step back.' }] }, - ], - }, - { - id: 'tally', chapter: 'Part one', scene: 'tally', - data: { count: 640, cols: 40, grow: 1, box: [0.4, 0.3, 0.94, 0.76], note: 'Made-up placeholder count: one dot is one unit' }, - transition: { type: 'wipe', dur: 1.8 }, - beats: [ - { dur: 1.2, text: [{ pos: 'bottom-left', kind: 'number', text: '640' }, { pos: 'bottom-left', kind: 'body', text: 'A made-up count, one dot for each unit.' }] }, - { dur: 6, ease: 'linear', text: [{ pos: 'top-right', kind: 'body', text: 'The dots arrive slowly, at a steady pace, so the number has time to register.' }] }, - ], - }, - { - id: 'areas', chapter: 'Part two', scene: 'areas', - data: { values: [100, 400, 25], labels: ['Placeholder X', 'Placeholder Y', 'Placeholder Z'], note: 'Made-up placeholder numbers' }, - transition: { type: 'dissolve', dur: 2.4 }, - beats: [ - { dur: 2.6, text: [{ pos: 'top-left', kind: 'headline', text: 'Areas, not widths' }] }, - { dur: 1.4, text: [{ pos: 'top-left', kind: 'body', text: 'A circle with four times the value has four times the area, so it is twice as wide, not four times.' }] }, - ], - }, - { - id: 'quote', chapter: 'Part two', scene: 'field', data: { tint: [0.75, 0.8, 0.9], drift: 0.4 }, - transition: { type: 'push', dur: 2 }, - beats: [ - { dur: 2, text: [{ pos: 'quote', kind: 'quote', text: '“A placeholder quotation sits here, set apart from the running text, with room around it.”' }, { pos: 'quote', kind: 'source', text: 'Placeholder source, placeholder date' }] }, - ], - }, - { - id: 'close', chapter: 'Close', scene: 'field', data: { tint: [0.9, 0.86, 0.8], drift: 0.2 }, - transition: 'cut', - beats: [ - { dur: 1.2, text: [{ pos: 'center', kind: 'body', text: 'A hard cut ends the essay on a still frame.' }] }, - { dur: 1, text: [{ pos: 'bottom-left', kind: 'source', text: 'Sources: placeholder. A real essay lists every source here.' }] }, + sound: { bed: { seed: 7, lufs: -36 } }, + // a scene template: each data row becomes a short run of scenes (its words: track text "country#1", "country#2") + templates: { + country: { + steps: [ + { scene: 'bars', fields: ['total', 'part1', 'part2'], data: { grow: 1 }, transition: { type: 'crossfade', dur: 2.2 }, + beats: [{ dur: 1.2 }, { dur: 3.2 }, { dur: 1.6, focus: 1 }] }, + { scene: 'nested', fields: ['total', 'part1'], data: { grow: 0 }, transition: { type: 'dissolve', dur: 2.2 }, + beats: [{ dur: 3 }] }, ], }, + }, + scenes: [ + { id: 'opening', chapter: 'opening', scene: 'field', data: { tint: [0.9, 0.86, 0.8] }, transition: { type: 'dip', dur: 2 }, + beats: [{ dur: 2.4 }, { dur: 1.6 }] }, + { sequence: 'country', rows: ROWS, scale: 'all', transition: { type: 'crossfade', dur: 2.2 } }, + { id: 'tally', chapter: 'part1', scene: 'tally', transition: { type: 'wipe', dur: 1.8 }, + data: { count: 640, cols: 40, grow: 1, box: [0.4, 0.3, 0.94, 0.76] }, + beats: [{ dur: 1.2 }, { dur: 6, ease: 'linear' }] }, + { id: 'areas', chapter: 'part2', scene: 'areas', transition: { type: 'dissolve', dur: 2.4 }, + data: { values: [100, 400, 25] }, + beats: [{ dur: 2.6 }, { dur: 1.4 }] }, + { id: 'quote', chapter: 'part2', scene: 'field', data: { tint: [0.75, 0.8, 0.9], drift: 0.4 }, transition: { type: 'push', dur: 2 }, + beats: [{ dur: 2 }] }, + { id: 'sources', chapter: 'sources', type: 'sources', perPage: 3, data: { tint: [0.8, 0.8, 0.8], drift: 0.2 }, + transition: { type: 'dip', dur: 2 } }, + { id: 'takeaway', chapter: 'close', scene: 'field', data: { tint: [0.9, 0.86, 0.8], drift: 0.2 }, transition: { type: 'crossfade', dur: 2.4 }, + beats: [{ dur: 2.4 }] }, ], }; diff --git a/engine/essay-demo/tracks/en.json b/engine/essay-demo/tracks/en.json new file mode 100644 index 0000000..b9a5ca5 --- /dev/null +++ b/engine/essay-demo/tracks/en.json @@ -0,0 +1,120 @@ +{ + "lang": "en", + "name": "English", + "title": "Placeholder Motion Essay", + "subtitle": "A demo of the EOMD kit. The words and numbers are placeholders, not facts.", + "chapters": { + "opening": "Opening", + "part1": "Part one", + "part2": "Part two", + "sources": "Sources", + "close": "Close" + }, + "fields": { "total": "Placeholder total", "part1": "Placeholder part 1", "part2": "Placeholder part 2" }, + "text": { + "opening": { + "1": [{ "pos": "chapter", "kind": "chapter", "text": "Placeholder chapter title" }], + "2": [ + { + "pos": "center", + "kind": "body", + "text": "This sentence stands in for the opening line of an essay. A real essay brings its own words, word for word." + } + ] + }, + "country": { "chapter": "{name}" }, + "country#1": { + "1": [{ "pos": "top-left", "kind": "headline", "text": "{name}" }], + "2": [ + { + "pos": "top-left", + "kind": "body", + "text": "Three made-up values for {name}. Each bar starts at zero; all rows share one scale." + } + ], + "3": [{ "pos": "top-left", "kind": "body", "text": "One bar is brought forward while the others step back." }], + "note": "Made-up placeholder numbers" + }, + "country#2": { + "1": [ + { + "pos": "top-left", + "kind": "body", + "text": "A made-up part of {part1} inside a made-up whole of {total}. The areas are proportional." + } + ], + "note": "Made-up placeholder numbers" + }, + "tally": { + "1": [ + { "pos": "bottom-left", "kind": "number", "text": "640" }, + { "pos": "bottom-left", "kind": "body", "text": "A made-up count, one dot for each unit." } + ], + "2": [ + { + "pos": "top-right", + "kind": "body", + "text": "The dots arrive slowly, at a steady pace, so the number has time to register." + } + ], + "note": "Made-up placeholder count: one dot is one unit" + }, + "areas": { + "1": [{ "pos": "top-left", "kind": "headline", "text": "Areas, not widths" }], + "2": [ + { + "pos": "top-left", + "kind": "body", + "text": "A circle with four times the value has four times the area, so it is twice as wide, not four times." + } + ], + "labels": ["Placeholder X", "Placeholder Y", "Placeholder Z"], + "note": "Made-up placeholder numbers" + }, + "quote": { + "1": [ + { + "pos": "quote", + "kind": "quote", + "text": "“A placeholder quotation sits here, set apart from the running text, with room around it.”" + }, + { "pos": "quote", "kind": "source", "text": "Placeholder source, placeholder date" } + ] + }, + "sources": { + "1": [{ "kind": "headline", "text": "Sources" }], + "2": [{ "kind": "headline", "text": "Sources (continued)" }] + }, + "takeaway": { + "1": [ + { + "pos": "center", + "kind": "takeaway", + "text": "A placeholder takeaway: the one sentence a viewer should leave with." + } + ] + } + }, + "sources": [ + { + "title": "Placeholder source one", + "url": "https://example.org/placeholder-source-1", + "note": "A short explanation of what this source supports goes here." + }, + { + "title": "Placeholder source two", + "url": "https://example.org/placeholder-source-2", + "note": "Each title is a working link in the HTML player." + }, + { + "title": "Placeholder source three", + "url": "https://example.org/placeholder-source-3", + "note": "The site's name is shown too, for anyone watching a recording." + }, + { + "title": "Placeholder source four", + "url": "https://example.org/placeholder-source-4", + "note": "A long list is split across pages, each held long enough to read." + } + ] +} diff --git a/engine/essay-demo/tracks/es.json b/engine/essay-demo/tracks/es.json new file mode 100644 index 0000000..265a76b --- /dev/null +++ b/engine/essay-demo/tracks/es.json @@ -0,0 +1,157 @@ +{ + "lang": "es", + "name": "Español", + "draft": true, + "title": "Ensayo animado de muestra", + "subtitle": "Una demostración del kit de EOMD. Las palabras y los números son de muestra, no son datos reales.", + "ui": { + "begin": "Empezar", + "withSound": "Empezar con sonido", + "silently": "Empezar sin sonido", + "pause": "Pausa", + "play": "Reproducir", + "playAgain": "Ver de nuevo", + "next": "Siguiente", + "back": "Atrás", + "keys": "Teclas", + "close": "Cerrar", + "fullscreen": "Pantalla completa", + "soundOn": "Sonido activado", + "soundOff": "Sonido desactivado", + "soundLoading": "Preparando el sonido…", + "auto": "Se reproduce solo", + "waits": "Espera clics", + "part": "parte {n} de {total}", + "pressKeys": "Pulsa ? para ver las teclas", + "language": "Idioma", + "progress": "Progreso", + "noGL": "Esta pantalla no puede mostrar las imágenes en movimiento. Las palabras y los números se siguen viendo.", + "noData": "sin dato", + "help": [ + ["Espacio, K", "Pausa o reproducir"], + ["Clic, →", "Siguiente"], + ["Clic derecho, ←", "Atrás"], + ["Deslizar", "Siguiente o atrás"], + ["A", "Se reproduce solo o espera clics"], + ["M", "Sonido sí o no"], + [".", "Pantalla negra"], + ["F", "Pantalla completa"], + ["Inicio, Fin", "Primera o última parte"], + ["?", "Esta tarjeta"] + ] + }, + "chapters": { + "opening": "Inicio", + "part1": "Primera parte", + "part2": "Segunda parte", + "sources": "Fuentes", + "close": "Cierre" + }, + "fields": { "total": "Total de muestra", "part1": "Parte 1 de muestra", "part2": "Parte 2 de muestra" }, + "text": { + "opening": { + "1": [{ "pos": "chapter", "kind": "chapter", "text": "Título de capítulo de muestra" }], + "2": [ + { + "pos": "center", + "kind": "body", + "text": "Esta frase ocupa el lugar de la primera línea de un ensayo. Un ensayo real trae sus propias palabras, tal cual." + } + ] + }, + "country": { "chapter": "{name}" }, + "country#1": { + "1": [{ "pos": "top-left", "kind": "headline", "text": "{name}" }], + "2": [ + { + "pos": "top-left", + "kind": "body", + "text": "Tres valores inventados para {name}. Cada barra empieza en cero; todas las filas comparten una escala." + } + ], + "3": [{ "pos": "top-left", "kind": "body", "text": "Una barra pasa al frente mientras las demás se apartan." }], + "note": "Números de muestra inventados" + }, + "country#2": { + "1": [ + { + "pos": "top-left", + "kind": "body", + "text": "Una parte inventada de {part1} dentro de un total inventado de {total}. Las áreas son proporcionales." + } + ], + "note": "Números de muestra inventados" + }, + "tally": { + "1": [ + { "pos": "bottom-left", "kind": "number", "text": "640" }, + { "pos": "bottom-left", "kind": "body", "text": "Un recuento inventado, un punto por unidad." } + ], + "2": [ + { + "pos": "top-right", + "kind": "body", + "text": "Los puntos llegan despacio, a un ritmo constante, para que el número tenga tiempo de calar." + } + ], + "note": "Recuento de muestra inventado: un punto es una unidad" + }, + "areas": { + "1": [{ "pos": "top-left", "kind": "headline", "text": "Áreas, no anchos" }], + "2": [ + { + "pos": "top-left", + "kind": "body", + "text": "Un círculo con el cuádruple del valor tiene el cuádruple del área, así que es el doble de ancho, no el cuádruple." + } + ], + "labels": ["Muestra X", "Muestra Y", "Muestra Z"], + "note": "Números de muestra inventados" + }, + "quote": { + "1": [ + { + "pos": "quote", + "kind": "quote", + "text": "«Aquí va una cita de muestra, separada del texto, con espacio a su alrededor.»" + }, + { "pos": "quote", "kind": "source", "text": "Fuente de muestra, fecha de muestra" } + ] + }, + "sources": { + "1": [{ "kind": "headline", "text": "Fuentes" }], + "2": [{ "kind": "headline", "text": "Fuentes (continuación)" }] + }, + "takeaway": { + "1": [ + { + "pos": "center", + "kind": "takeaway", + "text": "Una conclusión de muestra: la frase que el espectador debería llevarse." + } + ] + } + }, + "sources": [ + { + "title": "Fuente de muestra uno", + "url": "https://example.org/placeholder-source-1", + "note": "Aquí va una breve explicación de lo que respalda esta fuente." + }, + { + "title": "Fuente de muestra dos", + "url": "https://example.org/placeholder-source-2", + "note": "Cada título es un enlace que funciona en el reproductor HTML." + }, + { + "title": "Fuente de muestra tres", + "url": "https://example.org/placeholder-source-3", + "note": "También se muestra el nombre del sitio, para quien vea una grabación." + }, + { + "title": "Fuente de muestra cuatro", + "url": "https://example.org/placeholder-source-4", + "note": "Una lista larga se reparte en páginas, cada una el tiempo necesario para leerla." + } + ] +} diff --git a/players/essay-demo.html b/players/essay-demo.html index b0b03a0..d32227e 100644 --- a/players/essay-demo.html +++ b/players/essay-demo.html @@ -6,6 +6,8 @@ Placeholder Motion Essay (EOMD kit demo) + + + + + diff --git a/tools/build_essay_demo.py b/tools/build_essay_demo.py index f35f99c..b8ca3f2 100644 --- a/tools/build_essay_demo.py +++ b/tools/build_essay_demo.py @@ -1,10 +1,10 @@ # tools/build_essay_demo.py: BUILD THE DEMO ESSAY. Run in Thonny (the Run button; no command-line arguments). # The demo shows what the kit's essay engine does, with placeholder words and made-up numbers (labelled so on -# screen). It inlines the KIT copies (kit/, what ProofEr gets) into engine/essay-demo/dev.html, so it is built the +# screen). Its words are language tracks (engine/essay-demo/tracks/*.json), inlined as JSON. It inlines the KIT copies (kit/, what ProofEr gets) into engine/essay-demo/dev.html, so it is built the # way a ProofEr essay would be: one offline HTML file, nothing loaded from the internet. # engine/essay-demo/dev.html + essay.js + kit/*.js -> dist/essay-demo.html, copied to players/essay-demo.html # Run tools/build_kit.py first after changing an engine source (this script stops if a kit copy is stale). -import os, re, shutil, sys +import os, re, json, shutil, sys # ===================== SETTINGS ===================== PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # the repo root @@ -17,6 +17,9 @@ # a dev-page script path -> the kit file inlined in its place KIT_FOR = { '../src/essay/beats.js': 'essay/beats.js', + '../src/essay/track.js': 'essay/track.js', + '../src/audio/dsp.js': 'audio/dsp.js', + '../src/audio/bed.js': 'audio/bed.js', '../src/fx/lens.js': 'fx/lens.js', '../src/gl/gl.js': 'gl/gl.js', '../src/gl/transitions.js': 'gl/transitions.js', @@ -51,6 +54,15 @@ def inline(m): return '' html = re.sub(r'', inline, html) + + # language tracks: the JSON goes inside its tag (a single file can't fetch files next to it) + def track(m): + with open(os.path.join(os.path.dirname(DEV_PAGE), m.group(2)), encoding='utf-8') as f: + data = json.load(f) + body = json.dumps(data, ensure_ascii=False, separators=(',', ':')).replace('{body}' + + html = re.sub(r'', track, html) html = re.sub(r'.*?', '' + TITLE + '', html) html = re.sub(r'\n', '', html, flags=re.S) if re.search(r'(src|href)="(https?:)?//', html): From 7f867edbe9b4339153e80c42b70494db54602234 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 17:40:04 +0000 Subject: [PATCH 11/13] Kit v0.3.0 (ProofEr addendum): new audio/bed.js, essay/track.js, tools/render-bed.js; changelog, kit README, TODO, STATUS Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Ad4FSZyShDwuPQbAcgGJY3 --- README.md | 2 +- STATUS.md | 4 +- TODO.md | 23 ++- engine/CLAUDE.md | 8 +- kit/CHANGELOG.md | 33 ++++ kit/KIT.json | 21 +- kit/README.md | 90 ++++++--- kit/audio/bed.js | 184 ++++++++++++++++++ kit/essay/beats.js | 18 +- kit/essay/player.js | 417 ++++++++++++++++++++++++++++------------ kit/essay/text.js | 112 +++++++++-- kit/essay/track.js | 242 +++++++++++++++++++++++ kit/gl/host.js | 10 +- kit/gl/scenes.js | 273 +++++++++++++++++++------- kit/tools/essay-qa.js | 76 ++++++-- kit/tools/render-bed.js | 36 ++++ tools/build_kit.py | 3 + 17 files changed, 1275 insertions(+), 277 deletions(-) create mode 100644 kit/audio/bed.js create mode 100644 kit/essay/track.js create mode 100644 kit/tools/render-bed.js diff --git a/README.md b/README.md index 172c46f..82dcd01 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,7 @@ Start sound for the music. Move the mouse to see the controls. | `players/danbury-academies-clock.html` | The Academies film below with a wall clock and a session timer, for a classroom screen | | `players/sanctioned-corporate-calm.html` | Sanctioned Corporate Calm: a 20-minute seamless study loop built from the Academies film's tunes, with a wall clock and a session timer | | `players/gen-player.html` | The generative library below as one self-contained file (USB-stick ready) | -| `players/essay-demo.html` | The motion-essay engine in the kit (for ProofEr): shader scenes (bars from zero, a dot tally, proportional areas), quiet transitions, words over the picture. Placeholder words and made-up numbers, labelled so. Built by `tools/build_essay_demo.py` | +| `players/essay-demo.html` | The motion-essay engine in the kit (for ProofEr): shader scenes (bars from zero, a dot tally, proportional and nested areas) built from data rows, quiet transitions, words over the picture from per-language tracks (English, draft Spanish), a quiet drone, a sources chapter with links. Lays out for phones held upright too. Placeholder words and made-up numbers, labelled so. Built by `tools/build_essay_demo.py` | - **Generative motion library:** double-click **`gen/player.html`**. Press **G** for the gallery of ready-made cartridges (Truchet tiles, 3D dot meshes, dot swarms that fly into words, flow fields, Julia sets, tunnels, diff --git a/STATUS.md b/STATUS.md index 961158b..e90a9c8 100644 --- a/STATUS.md +++ b/STATUS.md @@ -3,7 +3,7 @@ > **Visitors:** this is the project's working log, kept for the people and AI assistants working on it. For what > EOMD is and how to use it, start with [README.md](README.md). -_Last updated: Dec 1, 2026 (kit v0.2.0: the motion-essay engine for ProofEr: beat model + fixed-step clock, essay player shell, test hooks + `engine/tools/essay-qa.js`, plain-WebGL2 scene host + compositor with the lens on a GPU texture, 4 scenes, 6 transitions, HTML text with a WCAG check; demo at `players/essay-demo.html`. Nov 28: kit v0.1.0: `kit/` + `tools/build_kit.py` for ProofEr; both repos are AGPLv3, so no licence obstacle; video-essay plan in `TODO.md`; lens upgraded: 6-level glow, halation, AgX/ACES, grade, dither; engine audio fallback renders in slices and works when the worker is blocked. Nov 27: optional WebGL2 lens finish, ideas taken from the Q-Day player; before that Nov 21: CD-ROM link options `?start=`, `?go`, `?airship`; before that Nov 4: fresh-eyes review added to the design stages; Academies film: clock + timer version). Each piece's history, limits and open questions live in its +_Last updated: Dec 1, 2026 (kit v0.3.0, ProofEr's addendum: portrait layouts, pause button, per-language text tracks, data-row sequences, drone bed, sources chapter; kit v0.2.0: the motion-essay engine for ProofEr: beat model + fixed-step clock, essay player shell, test hooks + `engine/tools/essay-qa.js`, plain-WebGL2 scene host + compositor with the lens on a GPU texture, 4 scenes, 6 transitions, HTML text with a WCAG check; demo at `players/essay-demo.html`. Nov 28: kit v0.1.0: `kit/` + `tools/build_kit.py` for ProofEr; both repos are AGPLv3, so no licence obstacle; video-essay plan in `TODO.md`; lens upgraded: 6-level glow, halation, AgX/ACES, grade, dither; engine audio fallback renders in slices and works when the worker is blocked. Nov 27: optional WebGL2 lens finish, ideas taken from the Q-Day player; before that Nov 21: CD-ROM link options `?start=`, `?go`, `?airship`; before that Nov 4: fresh-eyes review added to the design stages; Academies film: clock + timer version). Each piece's history, limits and open questions live in its folder's `STATUS.md`; repo-wide history in `notes/history.md`._ ## Pieces @@ -15,7 +15,7 @@ folder's `STATUS.md`; repo-wide history in `notes/history.md`._ | CSE hallway loop (new, full creative) | Done; published Oct 25 (`players/cse-loop.html`) | ES/PT check; real-TV check | `proj/cse-loop/STATUS.md` | | PLTW CSE promo | r2 published ("cheesy as hell, but exactly what I asked for") | The PLTW test below | `proj/pltw/STATUS.md` | | Engine lens finish (`engine/src/fx/lens.js`) | Built Nov 27, upgraded Nov 28; in the engine's dev, kiosk, stills and MP4 paths; off by default | Not yet seen on a real TV; not yet inlined in CD-ROM, living or gen | -| Video essays (Q-Day / Last Boring Slide level) | Kit v0.2.0 (Dec 1): the essay engine (`engine/src/essay/`, `engine/src/gl/`), demo `players/essay-demo.html` (placeholder words, made-up numbers), QA PASS at 1280×720 (0–1 flashes/s, every text block AA, worst 5.2:1). EOMD builds the engine; ProofEr hosts motion essays (TODO §0) | ProofEr syncs 0.2.0 and builds its first essay; next here (`TODO.md` top): GPU letter type, sound hits/beds, essay MP4, presenter tools. Not yet seen on a real GPU or TV (tested in SwiftShader) | +| Video essays (Q-Day / Last Boring Slide level) | Kit v0.3.0 (Dec 1): the essay engine (`engine/src/essay/`, `engine/src/gl/`, `engine/src/audio/bed.js`) with ProofEr's addendum for holocaust-by-country (portrait, text tracks, data-row sequences, drone bed, sources). Demo `players/essay-demo.html` (placeholder words, made-up numbers, EN + DRAFT ES track). EOMD builds the engine; ProofEr hosts motion essays (TODO §0) | ProofEr syncs 0.3.0; next here (`TODO.md` top): GPU letter type, sound hits, essay MP4. Not yet seen on a real GPU, phone or TV (tested in SwiftShader) | | gen library (incl. Dust Type) | Working; `tools/gen_export.py` | Check Dust Type knobs | `gen/STATUS.md` | | Jukebox | 15 cartridges | Redesign its look | `jukebox/STATUS.md` | diff --git a/TODO.md b/TODO.md index 050a69d..aa5c9b1 100644 --- a/TODO.md +++ b/TODO.md @@ -17,13 +17,21 @@ hooks + `engine/tools/essay-qa.js` (§6), WebGL2 toolkit, scene host, render-to- texture (§1), six transitions (§1), HTML text over the picture (§3), and a demo essay with placeholder content (`players/essay-demo.html`, built by `tools/build_essay_demo.py`). Sources: `engine/src/essay/`, `engine/src/gl/`. +**Kit v0.3.0 (Dec 1, 2026): ProofEr's addendum** for its first motion essay (holocaust-by-country, watched on +viewers' own laptops, tablets and phones): portrait layouts for every scene and text position (QA at 390×844 and +1920×1080), plays by itself with an always-visible pause button (Space), words as per-language JSON tracks with +holds per language (`engine/src/essay/track.js`), data-row scene templates and the `nested` scene, one quiet drone +bed (`engine/src/audio/bed.js`, −36 LUFS, ffmpeg-checked), a sources chapter with working links, and a takeaway. + **Next, in order** (not started): 1. **GPU letter-by-letter type** (§3). -2. **Sound hits and beds that know the cut** (§4), with the live-mix loudness plan; then the start screen's "Begin with - sound" gets a real sound (the shell already takes `opts.sound`). -3. **MP4 export of an essay** (§6): `tools/html_to_mp4.py` stepping the fixed clock via `EOMD_ESSAY.at(t)`. -4. **Presenter tools** (§5): notes (N), a second window (P), the scene grid (O), a talk timer. -5. Adaptive quality and warm-up (§5); linked/portal transitions and scene snapshots (§1); scrambled headlines (§3). +2. **Sound hits and effects** (§4); beds that know the cut. One drone bed is done (v0.3.0). +3. **MP4 export of an essay** (§6): `tools/html_to_mp4.py` stepping the fixed clock via `EOMD_ESSAY.at(t)`, with the + bed rendered offline (`DHS.bed.steps`). +4. Adaptive quality and warm-up (§5); linked/portal transitions and scene snapshots (§1); scrambled headlines (§3). + +**Dropped from the essay player (ProofEr, Dec 1):** presenter notes (N), the second window (P) and the scene grid +(O). Essays play by themselves; revisit only if a presented talk comes along. Ordered by what unblocks the most. Each item says where it would live. "Essay player" means the player shell EOMD builds for the kit (§0), which ProofEr uses for motion essays. @@ -189,9 +197,10 @@ tokens today). - progress bar with gaps between chapters; - keyboard, swipe and right-click to go back; plays by itself (A); black screen (.); help card (?); - `#scene-beat` links that work with the back button. -- [ ] **Presenter tools:** notes for every beat (N), notes in a second window kept in step (P), a grid of all scenes +- [ ] **Presenter tools** (dropped for essays, Dec 1: see the top of this file): notes for every beat (N), notes in a second window kept in step (P), a grid of all scenes with thumbnails (O), and a talk timer. -- [ ] **Fill the screen without black bars:** lay out in 1920×1080 design units and widen the view to the screen's +- [x] **Fill the screen without black bars** (essays, v0.2.0/0.3.0: the GL canvas fills the screen and scenes lay out + for its shape, portrait included; the 2D runtime still letterboxes): lay out in 1920×1080 design units and widen the view to the screen's shape (`engine/src/player/runtime.js` letterboxes today). - [ ] **Quality that adapts.** - Render-scale steps 1 / 0.84 / 0.70 / 0.58: drop a step after about 1.2 s of slow frames, climb back only after diff --git a/engine/CLAUDE.md b/engine/CLAUDE.md index 7c4cf3b..95f490b 100644 --- a/engine/CLAUDE.md +++ b/engine/CLAUDE.md @@ -6,13 +6,15 @@ inside `engine/`, e.g. `node tools/build-player.js`). - `engine/src/audio/dsp.js` is the DSP every player uses: a change to it follows the regression rule in `audio/CLAUDE.md`. -- Kit sources (copied into `kit/` for ProofEr): `src/fx/lens.js`, `src/audio/dsp.js`, `src/essay/*.js` (beats, - player shell, words layer), `src/gl/*.js` (WebGL2 toolkit, scenes, transitions, compositor) and `tools/essay-qa.js`. +- Kit sources (copied into `kit/` for ProofEr): `src/fx/lens.js`, `src/audio/dsp.js`, `src/audio/bed.js`, + `src/essay/*.js` (beats, text tracks, player shell, words layer), `src/gl/*.js` (WebGL2 toolkit, scenes, transitions, compositor), `tools/essay-qa.js` and + `tools/render-bed.js`. After changing any, run `tools/build_kit.py` and commit `kit/` too (CI fails on a stale copy). A release also bumps `kit/KIT.json`'s version and adds a `kit/CHANGELOG.md` section. - **No three.js, no libraries:** everything is plain WebGL2 in the `DHS` namespace, single-offline-HTML friendly. - The motion-essay engine: `src/essay/beats.js` keeps the whole essay a pure function of the playhead; scene shaders - write linear light; transitions change each part of the screen once (check with `tools/essay-qa.js`). The demo + write linear light and lay out for portrait too; words live in per-language tracks, never in shaders; + transitions change each part of the screen once. Check with `tools/essay-qa.js` at 1920 1080 and 390 844. The demo essay is `essay-demo/` (placeholder content only; real essays and their figures live in ProofEr). - `engine/tools/html_to_mp4.py` is the original MP4 script; use `tools/html_to_mp4.py` instead. - Don't open `engine/` for living-poster or jukebox work (only `dsp.js`, for DSP internals). diff --git a/kit/CHANGELOG.md b/kit/CHANGELOG.md index ea2bf83..eb4301b 100644 --- a/kit/CHANGELOG.md +++ b/kit/CHANGELOG.md @@ -1,5 +1,38 @@ # Kit changelog +## 0.3.0 (2026-12-01) + +ProofEr's addendum for its first motion essay, which plays on viewers' own laptops, tablets and phones. Minor bump: +new files and options. Essays written for 0.2.0 still play (words inside the essay still work). The one change in +behaviour: Space now pauses and plays instead of going to the next beat. + +- **Portrait is a first-class layout.** Scenes lay out again when the screen is taller than wide: bars turn + horizontal (labels above, values at the end), dots and circles re-pack into a band across the middle, and corner + text goes full width above and below it. `essay-qa.js` is run at 390x844 and 1920x1080, and now flags words or + labels that overlap or are cut off (`E.layoutCheck()`). +- **Plays by itself with a pause button that stays on screen** (top right, round), Space or K to pause and play. + Presenter notes and the scene grid are not part of the essay player. +- `essay/track.js` (`DHS.essayTrack`): **on-screen words as a separate track**, one JSON per language, keyed by + scene id and beat number, loaded by the player (inline ` + +``` + +The essay holds the structure, the data and the timing; the tracks hold every word: ```js -DHS.essay.mount({ - title: 'Title', subtitle: 'One line under it', lang: 'en', - lens: { bloom: 0.12, streak: 0, vignette: 0.28 }, // or null for no lens +const ESSAY = { + lang: 'en', // used when no track matches the viewer + lens: { bloom: 0.12, streak: 0, vignette: 0.28 }, // or null for no lens + sound: { bed: { lufs: -36 } }, // or null: no sound, the start screen says "Begin" + templates: { + country: { steps: [ + { scene: 'bars', fields: ['population', 'murdered', 'survived'], data: { grow: 1 }, beats: [{ dur: 1.2 }, { dur: 3 }] }, + { scene: 'nested', fields: ['population', 'murdered'], transition: 'dissolve', beats: [{ dur: 3 }] }, + ] }, + }, scenes: [ - { id: 'opening', chapter: 'Opening', scene: 'field', transition: { type: 'dip', dur: 2 }, - beats: [{ dur: 2.4, text: [{ pos: 'chapter', kind: 'chapter', text: 'Chapter title' }] }] }, - { id: 'bars', chapter: 'Part one', scene: 'bars', transition: 'crossfade', - data: { values: [12, 30], labels: ['A', 'B'], max: 50, grow: 1, note: 'Source: ...' }, - beats: [ - { dur: 1.2, text: [{ pos: 'top-left', kind: 'headline', text: 'Headline' }] }, - { dur: 3.2, text: [{ pos: 'top-left', kind: 'body', text: 'The bars grow in this beat (data.grow: 1).' }] }, - { dur: 1.6, focus: 1 }, // bring bar 1 forward - ] }, + { id: 'opening', chapter: 'opening', scene: 'field', transition: { type: 'dip', dur: 2 }, beats: [{ dur: 2.4 }] }, + { sequence: 'country', rows: ROWS, scale: 'all' }, // one short run of scenes per data row + { id: 'sources', chapter: 'sources', type: 'sources', perPage: 3 }, + { id: 'takeaway', chapter: 'close', scene: 'field', beats: [{ dur: 2.4 }] }, ], -}); +}; +``` + +```json +{ "lang": "en", "title": "...", "subtitle": "...", + "chapters": { "opening": "Opening", "sources": "Sources" }, + "fields": { "population": "Population", "murdered": "Murdered", "survived": "Survived" }, + "text": { + "opening": { "1": [{ "pos": "chapter", "kind": "chapter", "text": "..." }] }, + "country": { "chapter": "{name}" }, + "country#1": { "1": [{ "pos": "top-left", "kind": "headline", "text": "{name}" }], "note": "Source: ..." }, + "sources": { "1": [{ "kind": "headline", "text": "Sources" }] }, + "takeaway": { "1": [{ "pos": "center", "kind": "takeaway", "text": "..." }] } }, + "sources": [{ "title": "...", "url": "https://...", "note": "..." }], + "ui": { "begin": "..." } } ``` -- A beat: `dur` (seconds to arrive), `delay`, `hold` (default: reading time from its words), `ease`, `text`, and for - data scenes `focus`. Text is shown exactly as written. +- A beat: `dur` (seconds to arrive), `delay`, `hold` (default: reading time from the active language's words), + `ease`, and for data scenes `focus`. Its words are the track's `text[sceneId][beatNumber]`, shown exactly as + written; `{field}` in a template step's words is filled from the row (numbers formatted for the language). +- A row's missing value (`null`) is drawn as nothing and labelled with `ui.noData`, never as zero. `scale: 'all'` + puts every row on one scale. - Text positions: `center`, `chapter`, `quote` (these share the middle), `lower-third`, `top-left`, `top-right`, - `bottom-left`, `bottom-right`. Kinds: `body`, `headline`, `chapter`, `quote`, `source`, `number`, `note`. Restyle - with CSS variables on `.eo-root`: `--eo-ink`, `--eo-bg`, `--eo-font`, `--eo-display`, `--eo-serif`, `--eo-accent`. -- A new scene is a cartridge in `DHS.gl.scenes` (`frag`, `layout`, `labels`); a new transition is a shader in + `bottom-left`, `bottom-right` (full width on portrait screens). Kinds: `body`, `headline`, `chapter`, `quote`, + `source`, `number`, `note`, `takeaway`. Restyle with CSS variables on `.eo-root`: `--eo-ink`, `--eo-bg`, + `--eo-font`, `--eo-display`, `--eo-serif`, `--eo-accent`. +- `?lang=es` picks a track; with several tracks a language menu appears. A track marked `"draft": true` shows as + "(draft)" in the menu and is reported in the console. +- A new scene is a cartridge in `DHS.gl.scenes` (`frag`, `layout(data, aspect)`, `labels`); lay it out for both + `aspect >= 1` and portrait (`DHS.gl.band(aspect)` is the shared data area). A new transition is a shader in `DHS.gl.transitions`. The comments at the top of `gl/scenes.js` and `gl/transitions.js` give the contract. -- Before review: `node tools/essay-qa.js essay.html out/` writes the stills and a pass/fail report (flashes, - WCAG contrast, page errors). EOMD's demo essay (`engine/essay-demo/`, built by `tools/build_essay_demo.py` into - `players/essay-demo.html`) shows every part with placeholder words and made-up numbers. +- Before review, at both shapes: `node tools/essay-qa.js essay.html out-wide/ 1920 1080` and + `node tools/essay-qa.js essay.html out-phone/ 390 844` (add `lang=es` as a fifth argument for another track). + Each writes the stills and a pass/fail report: flashes, WCAG contrast, overlaps and cut-off words, the sound bed + starting, page errors. The bed's loudness: `node tools/render-bed.js bed.wav`, then + `ffmpeg -nostats -i bed.wav -filter_complex ebur128=peak=true:framelog=quiet -f null -`. +- EOMD's demo essay (`engine/essay-demo/`, built by `tools/build_essay_demo.py` into `players/essay-demo.html`) shows + every part with placeholder words and made-up numbers, in English and a draft Spanish track. ### The lens and the DSP diff --git a/kit/audio/bed.js b/kit/audio/bed.js new file mode 100644 index 0000000..2622544 --- /dev/null +++ b/kit/audio/bed.js @@ -0,0 +1,184 @@ +/* EOMD kit: audio/bed.js. Copyright (C) 2026 Bryan Patrick Murphy. SPDX-License-Identifier: AGPL-3.0-only + Copied from engine/src/audio/bed.js (https://github.com/BPMData/EOMD) by tools/build_kit.py: change the source in EOMD, not this copy. */ +/* BED: one quiet generative ambient drone (near silence) for an essay, made with EOMD's DSP (DHS.dsp) in the page. + A seamless loop: every partial and every slow swell has a whole number of cycles in the loop, the air (filtered + noise) and the room are processed circularly, so the loop point can't be heard. Normalised to a loudness target + (BS.1770 integrated, LUFS) and true-peak limited (default ceiling -1.5 dBTP). Same seed and knobs, same samples. + + const out = DHS.dsp.drain(DHS.bed.steps(knobs)); // { L, R, sr, seconds, lufs, truePeakDb, gainDb } + DHS.bed.renderAsync(knobs).then(...) // in ~8 ms slices on the main thread (page keeps drawing) + const sound = DHS.bed.sound(knobs); // the essay player's sound hook (DHS.essay.mount opts.sound) + sound.prepare() starts rendering now (the player calls it when it mounts) + sound.start(audioContext) when rendered, loops it with a slow fade in + sound.update(t, playing) fades out on pause, back in on play + sound.setMuted(on) the player's sound button + Needs DHS.dsp (audio/dsp.js). Hits and effects are not here yet (kit TODO). */ +(function (G) { + 'use strict'; + const DHS = (G.DHS = G.DHS || {}); + + const DEFAULTS = { + seed: 7, + seconds: 30, // loop length + sr: 48000, + root: 38, // MIDI note of the lowest tone (38 = D2) + chord: [0, 7, 12, 19], // semitones above the root + lufs: -36, // integrated loudness target: near silence on laptop and phone speakers; the brief can change it + ceiling: -1.5, // true-peak ceiling, dBTP + air: 0.25, // filtered-noise level relative to the tones (0 = none) + brightness: 700, // lowpass on the tones and air, Hz + room: 0.35, // reverb send + fade: 4, // seconds of fade in when sound starts + measure: false, // true: also measure the exact true peak (slow; tools/render-bed.js sets it for the ffmpeg check) + }; + + function* steps(knobs = {}) { + const P = DHS.dsp, + k = Object.assign({}, DEFAULTS, knobs); + const sr = k.sr, + N = Math.round(k.seconds * sr), + L = N / sr, + TAU = Math.PI * 2; + const rnd = P.rng(k.seed); + const bus = P.bus(N); + // tones: each a pair of sines a whole number of cycles apart over the loop (a slow beating), with a soft + // second harmonic, swelling at 1 or 2 cycles a loop + const cyc = (f) => Math.max(1, Math.round(f * L)) / L; + for (let v = 0; v < k.chord.length; v++) { + const f = cyc(P.mtof(k.root + k.chord[v])), + f2 = f + (1 + v) / L, + sw = 1 + (v % 2), + ph = (rnd() + 1) * Math.PI, + amp = 0.25 / (1 + v * 0.6), + pan = v % 2 ? 0.35 : -0.35; + const buf = new Float32Array(N); + for (let i = 0; i < N; i++) { + const t = i / sr; + const s = Math.sin(TAU * f * t) + 0.7 * Math.sin(TAU * f2 * t + ph) + 0.12 * Math.sin(TAU * 2 * f * t); + buf[i] = s * amp * (0.55 + 0.45 * Math.sin((TAU * sw * t) / L + ph)); + if ((i & 32767) === 32767) yield; + } + P.write(bus, buf, 0, 1, pan); + } + // air: noise, lowpassed (circular, so its filter state is continuous across the loop) + if (k.air > 0) { + const air = P.bus(N); + for (let i = 0; i < N; i++) { + air.L[i] = rnd() * k.air * 0.2; + air.R[i] = rnd() * k.air * 0.2; + } + yield; + const f = yield* P.steps.circular(air, () => { + const a = P.svf(), + b = P.svf(); + return (l, r) => [a(l, k.brightness * 0.6, 0.6, sr), b(r, k.brightness * 0.6, 0.6, sr)]; + }); + P.mixInto(bus, f); + } + // tone colour, then the room + let out = yield* P.steps.circular(bus, () => { + const a = P.svf(), + b = P.svf(); + return (l, r) => [a(l, k.brightness, 0.5, sr), b(r, k.brightness, 0.5, sr)]; + }); + if (k.room > 0) { + const wet = yield* P.steps.circular(out, P.reverb({ sr, size: 0.86, damp: 0.5, lp: k.brightness * 3 })); + P.mixInto(out, wet, k.room * 2.5); + } + // loudness target, then the true-peak limiter. The tones are lowpassed, so the true peak sits within a few dB of + // the sample peak: when the sample peak is more than 6 dB under the ceiling the limiter can't act, and its + // (slow) oversampled pass is skipped. + const measured = yield* P.steps.lufs(out, sr); + const gainDb = k.lufs - measured, + g = P.db(gainDb); + let peak = 0; + for (let i = 0; i < N; i++) { + out.L[i] *= g; + out.R[i] *= g; + peak = Math.max(peak, Math.abs(out.L[i]), Math.abs(out.R[i])); + } + yield; + let limited = false; + if (P.todb(peak) > k.ceiling - 6) { + out = (yield* P.steps.limit(out, sr, P.db(k.ceiling))).bus; + limited = true; + } + return { + L: out.L, + R: out.R, + sr, + seconds: L, + lufs: yield* P.steps.lufs(out, sr), // measured again after the gain (and the limiter, if it ran) + samplePeakDb: P.todb(peak), + truePeakDb: k.measure ? P.todb(P.truePeak(out)) : null, + limited, + gainDb, + }; + } + + const renderAsync = (knobs) => DHS.dsp.runAsync(steps(knobs), { budgetMs: 8 }); + + // The essay player's sound hook. Rendering takes a second or two of sliced work after "Begin with sound". + function sound(knobs = {}) { + const k = Object.assign({}, DEFAULTS, knobs); + const S = { ctx: null, gain: null, src: null, muted: false, playing: false, status: 'idle', result: null }; + const level = () => (S.muted || !S.playing ? 0 : 1); + const ramp = (secs) => { + if (!S.gain) return; + const now = S.ctx.currentTime; + S.gain.gain.cancelScheduledValues(now); + S.gain.gain.setValueAtTime(S.gain.gain.value, now); + S.gain.gain.linearRampToValueAtTime(level(), now + secs); + }; + // start rendering before anyone asks (the player calls this when it mounts): by the time the viewer has read + // the start screen the bed is usually ready + let job = null; + S.prepare = () => { + if (!job) { + S.status = 'rendering'; + job = renderAsync(k); + } + return job; + }; + S.start = (ctx) => { + if (S.ctx) return; + S.ctx = ctx; + if (ctx.state === 'suspended') ctx.resume(); + return S.prepare().then( + (r) => { + S.result = r; + const b = ctx.createBuffer(2, r.L.length, r.sr); + b.copyToChannel(r.L, 0); + b.copyToChannel(r.R, 1); + S.gain = ctx.createGain(); + S.gain.gain.value = 0; + S.gain.connect(ctx.destination); + S.src = ctx.createBufferSource(); + S.src.buffer = b; + S.src.loop = true; + S.src.connect(S.gain); + S.src.start(); + S.status = 'playing'; + ramp(k.fade); + }, + (err) => { + S.status = 'failed'; + console.warn('bed: no sound', err); + } + ); + }; + S.update = (t, playing) => { + if (playing !== S.playing) { + S.playing = playing; + ramp(playing ? 1.5 : 0.6); + } + }; + S.setMuted = (m) => { + S.muted = !!m; + ramp(0.5); + }; + return S; + } + + DHS.bed = { DEFAULTS, steps, renderAsync, sound }; +})(globalThis); diff --git a/kit/essay/beats.js b/kit/essay/beats.js index 4af8293..c570009 100644 --- a/kit/essay/beats.js +++ b/kit/essay/beats.js @@ -12,7 +12,8 @@ const s = TL.at(t); // { t, scene, beat, beatT, raw[], p[], trans, k(beat, t0, t1, ease) } const C = DHS.beats.clock(); C.advance(realDt); C.t // fixed 1/60 s steps; C.set(t) to seek - Reading time (Q-Day's rule): hold = 2.6 s + 0.31 s a word, kept between 5.2 and 16 s, for a beat with words. + Reading time (Q-Day's rule): hold = 2.6 s + 0.31 s a word, kept between 5.2 and 16 s, for a beat with words + (a beat can change the limits with reading: { max: 40 }, as a page of sources does). The words themselves are never changed; only the timing comes from them. Standalone: needs only the DHS namespace. */ @@ -37,7 +38,12 @@ // ---- reading time const READING = { base: 2.6, perWord: 0.31, min: 5.2, max: 16 }; const countWords = (s) => (String(s || '').match(/\S+/g) || []).length; - const beatWords = (b) => (b.text || []).reduce((n, x) => n + countWords(typeof x === 'string' ? x : x.text), 0); + // words in a beat: text blocks, plus the titles and notes of a sources list + const blockWords = (x) => + typeof x === 'string' + ? countWords(x) + : countWords(x.text) + (x.items || []).reduce((n, it) => n + countWords(it.title) + countWords(it.note), 0); + const beatWords = (b) => (b.text || []).reduce((n, x) => n + blockWords(x), 0); const readingHold = (n, r = READING) => (n > 0 ? clamp(r.base + r.perWord * n, r.min, r.max) : 0); // ---- seeded random (mulberry32) and a string hash (FNV-1a) to make seeds from names @@ -86,7 +92,13 @@ index: j, delay: b.delay != null ? b.delay : 0, dur: b.dur != null ? b.dur : 1.6, - hold: b.hold != null ? b.hold : Math.max(readingHold(words, reading), j === 0 && !words ? 1.5 : 0), + hold: + b.hold != null + ? b.hold + : Math.max( + readingHold(words, b.reading ? Object.assign({}, reading, b.reading) : reading), + j === 0 && !words ? 1.5 : 0 + ), ease: ease(b.ease), words, start: t, diff --git a/kit/essay/player.js b/kit/essay/player.js index 65cb5b0..dd16316 100644 --- a/kit/essay/player.js +++ b/kit/essay/player.js @@ -4,22 +4,28 @@ links; the picture (DHS.gl.host) and the words (DHS.essayText) draw what it tells them. Needs DHS.beats; uses DHS.gl.host and DHS.essayText when they are inlined, and still plays the words without them (or without WebGL2). - const E = DHS.essay.mount(essay, { root: document.body, sound: null }); - essay: { title, subtitle, lang, lens: knobs | null, scenes: [{ id, chapter, scene: 'bars', data: {...}, - transition: 'crossfade' | { type, dur }, beats: [{ dur, delay, hold, text: [{ pos, kind, text }] }] }] } + DHS.essay.start(essay, { root: document.body }) // loads the language tracks, then mounts; or: + const E = DHS.essay.mount(essay, { root, tracks: { en: {...} }, sound }); + essay: { lang, lens: knobs | null, sound: { bed: knobs } | null, autoplay, templates, scenes: [{ id, chapter, + scene: 'bars', data: {...}, transition: 'crossfade' | { type, dur }, beats: [{ dur, delay, hold }] }] } + The words come from per-language tracks (DHS.essayTrack: JSON keyed by scene id and beat; ?lang=es picks one, + and a language menu appears when there are several). Holds follow the active language's words. Viewer controls: - click, Space, Right arrow, Page Down, swipe left next beat (finishes the current one first) + Space, K, the round button (top right, always shown) pause / play + click, Right arrow, Page Down, Enter, swipe left next beat (finishes the current one first) right-click, Left arrow, Page Up, Backspace, swipe back (runs back 2.4x faster than it came) - A play by itself / wait for clicks K pause . black screen F full screen ? help card + A play by itself (the default) / wait for clicks M sound on / off . black screen F full screen + ? help card Home / End first / last beat; #scene-beat links (e.g. #bars-2) open at that beat; the back button works. Controls are hidden until the mouse moves or the screen is tapped, and fade after 3 s. - Sound (optional): opts.sound = { start(audioContext), update(t, playing) }. With it, the start screen offers - "Begin with sound" and "Begin silently"; without it, just "Begin". + Sound (optional): essay.sound = { bed: knobs } plays DHS.bed's quiet drone; or opts.sound = { start(audioContext), + update(t, playing), setMuted(on), status }. With sound, the start screen offers "Begin with sound" and "Begin + silently", and the sound button (M) turns it on or off at any time; without it, just "Begin". Test hooks (stills, fresh-eyes review, MP4): E.seek(scene, beat, t), E.trans(scene, p), E.perf(scene), E.state(), - E.textBoxes(), E.hideGlyphs(on). Also on window.EOMD_ESSAY. Add ?manual to the URL to start paused with no start + E.flashCheck(scene), E.contrast(), E.layoutCheck(), E.setLang(lang). Also on window.EOMD_ESSAY. Add ?manual to the URL to start paused with no start screen (what the stills and MP4 tools use). */ (function (G) { 'use strict'; @@ -55,6 +61,14 @@ .eo-start button{font-size:18px;padding:12px 22px} .eo-start small{margin-top:1.6em;opacity:.6;font-size:13px} .eo-help[hidden],.eo-start[hidden],.eo-note[hidden]{display:none} +.eo-pp{position:absolute;top:max(12px,env(safe-area-inset-top));right:max(12px,env(safe-area-inset-right));width:48px;height:48px;border-radius:50%; + display:none;align-items:center;justify-content:center;padding:0;cursor:pointer;color:var(--eo-ink,#f3f0e8);background:rgba(0,0,0,.45); + border:1px solid rgba(255,255,255,.35);opacity:.75;transition:opacity .3s} +.eo-pp svg{fill:currentColor}.eo-pp:hover,.eo-pp:focus-visible{opacity:1}.eo-pp:focus-visible{outline:2px solid var(--eo-accent,#e9e4d8);outline-offset:2px} +.eo-on .eo-pp{display:flex} +.eo-lang{font:inherit;color:inherit;background:#111114;border:1px solid rgba(255,255,255,.28);border-radius:6px;padding:6px 8px;min-height:36px} +.eo-langrow{margin-top:1.2em} +@media (max-width:600px){.eo-row{flex-wrap:wrap}.eo-where{flex-basis:100%;order:-1}.eo-row button{padding:6px 9px}} .eo-help .eo-card{background:#111114;border:1px solid rgba(255,255,255,.2);border-radius:10px;padding:22px 26px;text-align:left;max-width:520px;font-size:15px;line-height:1.5} .eo-help h2{margin:0 0 .6em;font-size:18px;font-weight:600} .eo-help dl{display:grid;grid-template-columns:auto 1fr;gap:4px 16px;margin:0 0 1em} @@ -78,6 +92,37 @@ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c] ); + // button and note words when DHS.essayTrack isn't inlined (it holds the full list, translatable per track) + const FALLBACK_UI = { + begin: 'Begin', + withSound: 'Begin with sound', + silently: 'Begin silently', + pause: 'Pause', + play: 'Play', + playAgain: 'Play again', + next: 'Next', + back: 'Back', + keys: 'Keys', + close: 'Close', + fullscreen: 'Full screen', + soundOn: 'Sound on', + soundOff: 'Sound off', + soundLoading: 'Preparing sound\u2026', + auto: 'Plays by itself', + waits: 'Waits for clicks', + part: 'part {n} of {total}', + pressKeys: 'Press ? for keys', + language: 'Language', + progress: 'Progress', + noGL: "This screen can't draw the moving pictures. The words and numbers still play.", + help: [ + ['Space', 'Pause or play'], + ['Click, \u2192', 'Next'], + ['Right-click, \u2190', 'Back'], + ['?', 'This card'], + ], + }; + // A plain words layer for when DHS.essayText isn't inlined: each beat's text, no positions or fades. function plainText(root, TL, essay) { const box = el('div', '', root); @@ -130,137 +175,195 @@ return { maxPerSecond, maxStep }; } - function mount(essay, opts = {}) { - const B = DHS.beats; + function mount(source, opts = {}) { + const B = DHS.beats, + Tk = DHS.essayTrack; const root = el('div', 'eo-root', opts.root || doc.body); - if (essay.lang) root.lang = essay.lang; if (!doc.getElementById('eo-css')) el('style', '', doc.head, CSS).id = 'eo-css'; const params = new URLSearchParams(G.location ? G.location.search : ''); const manual = params.has('manual'); const reducedMQ = G.matchMedia ? G.matchMedia('(prefers-reduced-motion: reduce)') : { matches: false }; const reduced = () => reducedMQ.matches || params.get('reduced') === '1'; + // ---- words: the language's track, resolved into plain scenes (sequences expanded, sources paged) + const tracks = opts.tracks || (Tk ? Tk.fromPage(doc) : {}); + const langs = Object.keys(tracks); + let lang = Tk ? Tk.pick(tracks, params.get('lang'), source.lang) : source.lang || 'en'; + const resolveLang = (l) => { + const R = Tk ? Tk.resolve(source, tracks[l] || {}) : { essay: source, ui: FALLBACK_UI, warnings: [] }; + R.warnings.forEach((w) => console.warn('essay:', w)); + return R; + }; + let R = resolveLang(lang), + essay = R.essay, + ui = R.ui; + root.lang = lang; + // ---- picture const canvas = el('canvas', 'eo-gl', root); canvas.setAttribute('aria-hidden', 'true'); - const lensKnobs = DHS.lens ? DHS.lens.fromQuery(G.location ? G.location.search : '', essay.lens || null) : null; + const lensKnobs = DHS.lens ? DHS.lens.fromQuery(G.location ? G.location.search : '', source.lens || null) : null; const host = DHS.gl && DHS.gl.host && params.get('gl') !== '0' ? DHS.gl.host(canvas, { essay, lens: lensKnobs, reduced }) : null; const transDur = (type) => DHS.gl && DHS.gl.transitions && DHS.gl.transitions[type] ? DHS.gl.transitions[type].dur : 1; - const TL = B.compile(essay, { transDur }); - // ---- words const textRoot = el('div', 'eo-textroot', root); textRoot.style.cssText = 'position:absolute;inset:0;pointer-events:none'; - textRoot.setAttribute('aria-hidden', 'true'); - const text = DHS.essayText - ? DHS.essayText.create(textRoot, TL, essay, { reduced, host }) - : plainText(textRoot, TL, essay); const live = el('div', 'eo-sr', root); // screen readers hear each beat's words once live.setAttribute('aria-live', 'polite'); - const black = el('div', 'eo-black', root); - const note = el( - 'div', - 'eo-note', - root, - "This screen can't draw the moving pictures. The words and numbers still play." - ); + const note = el('div', 'eo-note', root); note.setAttribute('role', 'status'); + note.hidden = true; const nogl = () => { root.classList.add('eo-nogl'); canvas.style.display = 'none'; note.hidden = false; }; - note.hidden = true; - if (!host || !host.ok) nogl(); - if (host) host.onfail = nogl; + + // ---- sound: the essay's drone bed (DHS.bed) unless the page passes its own hook + const sound = + opts.sound || (source.sound && DHS.bed && DHS.dsp ? DHS.bed.sound(source.sound.bed || source.sound) : null); + if (sound && sound.prepare && !manual) sound.prepare().then(() => setSoundLabel()); // ---- controls - const ui = el('div', 'eo-ui', root); - const bar = el('div', 'eo-bar', ui); + const ui0 = el('div', 'eo-ui', root); + const bar = el('div', 'eo-bar', ui0); bar.setAttribute('role', 'slider'); - bar.setAttribute('aria-label', 'Progress'); bar.tabIndex = -1; - const segs = TL.chapters.map((c) => { - const s = el('div', 'eo-seg', bar); - s.style.flex = String(Math.max(0.001, c.end - c.start)); - s.title = c.name; - return { c, fill: el('i', '', s) }; - }); - const row = el('div', 'eo-row', ui); + const row = el('div', 'eo-row', ui0); const bBack = el('button', '', row, '←'); - bBack.setAttribute('aria-label', 'Back'); - const bPlay = el('button', '', row, 'Pause'); const bNext = el('button', '', row, '→'); - bNext.setAttribute('aria-label', 'Next'); const where = el('div', 'eo-where', row); + const bSound = sound ? el('button', '', row) : null; + const langSel = langs.length > 1 ? el('select', 'eo-lang', row) : null; const bAuto = el('button', '', row); const bHelp = el('button', '', row, '?'); - bHelp.setAttribute('aria-label', 'Keys and help'); - const bFull = el('button', '', row, 'Full screen'); - + const bFull = el('button', '', row); + // the pause button stays on screen while the essay plays (controls fade; this doesn't) + const bPP = el('button', 'eo-pp', root); const help = el('div', 'eo-help', root); help.hidden = true; - help.innerHTML = ``; - const start = el('div', 'eo-start', root); - start.innerHTML = - `

${esc(essay.title || '')}

` + - (essay.subtitle ? `

${esc(essay.subtitle)}

` : '') + - `
${opts.sound ? '' : ''}
` + - `Press ? for keys`; if (manual) { start.hidden = true; root.classList.add('eo-on', 'eo-idle'); // stills: no controls until the mouse moves } + if (langSel) + langs.forEach((l) => { + const o = el('option', '', langSel); + o.value = l; + o.textContent = (tracks[l].name || l) + (tracks[l].draft ? ' (draft)' : ''); + }); // ---- state const clock = B.clock(60); const st = { started: manual, playing: !manual, - auto: essay.autoplay !== false, + auto: source.autoplay !== false, rate: 1, stopAt: null, target: null, - lastKey: '', dirty: true, audio: null, + soundOn: false, + nav: false, + }; + let TL, text, segs; + + const label = (b, txt, aria) => { + b.textContent = txt; + if (aria) b.setAttribute('aria-label', aria); }; const setAuto = (a) => { st.auto = a; - bAuto.textContent = a ? 'Plays by itself' : 'Waits for clicks'; + label(bAuto, a ? ui.auto : ui.waits); bAuto.setAttribute('aria-pressed', String(a)); }; - setAuto(st.auto); + const PP_PAUSE = + ''; + const PP_PLAY = + ''; const setPlaying = (p) => { st.playing = p; - bPlay.textContent = p ? 'Pause' : 'Play'; + const end = TL && clock.t >= TL.total; + bPP.innerHTML = p ? PP_PAUSE : PP_PLAY; + bPP.setAttribute('aria-label', p ? ui.pause : end ? ui.playAgain : ui.play); + bPP.title = bPP.getAttribute('aria-label') + ' (Space)'; + }; + const setSoundLabel = () => { + if (!bSound) return; + const busy = sound.status === 'rendering'; + label(bSound, busy ? ui.soundLoading : st.soundOn ? ui.soundOn : ui.soundOff); + bSound.setAttribute('aria-pressed', String(st.soundOn)); + }; + + // (re)build everything that holds words: timeline, words layer, progress bar, labels, start screen, help card + const build = () => { + TL = B.compile(essay, { transDur }); + textRoot.innerHTML = ''; + text = DHS.essayText + ? DHS.essayText.create(textRoot, TL, essay, { reduced, host }) + : plainText(textRoot, TL, essay); + bar.innerHTML = ''; + bar.setAttribute('aria-label', ui.progress); + segs = TL.chapters.map((c) => { + const sg = el('div', 'eo-seg', bar); + sg.style.flex = String(Math.max(0.001, c.end - c.start)); + sg.title = essay.scenes[c.scene].chapterName || c.name; + return { c, sg, fill: el('i', '', sg) }; + }); + label(bBack, '←', ui.back); + label(bNext, '→', ui.next); + label(bHelp, '?', ui.keys); + label(bFull, ui.fullscreen); + if (langSel) { + langSel.value = lang; + langSel.setAttribute('aria-label', ui.language); + } + setAuto(st.auto); + setPlaying(st.playing); + setSoundLabel(); + note.textContent = ui.noGL; + help.innerHTML = + ``; + help.querySelector('button').onclick = () => toggleHelp(false); + start.innerHTML = + `

${esc(essay.title || '')}

` + + (essay.subtitle ? `

${esc(essay.subtitle)}

` : '') + + `
${sound ? `` : ``}
` + + (langSel ? '
' : '') + + `${esc(ui.pressKeys)}`; + start.querySelectorAll('button').forEach((b) => (b.onclick = () => begin(b.dataset.s === '1'))); + if (langSel) { + const s2 = langSel.cloneNode(true); + s2.value = lang; + s2.onchange = () => setLang(s2.value); + start.querySelector('.eo-langrow').appendChild(s2); + } + lastKey = ''; + if (host && host.ok) host.setEssay(essay); + st.dirty = true; }; const S = () => TL.at(clock.t, { reduced: reduced() }); const fi = () => TL.flatIndex(clock.t); - const keyOf = (s) => TL.scenes[s.scene].id + '-' + (Math.max(0, s.beat) + 1); - // jump straight to a time (seeks, links, long backs) const jump = (t) => { clock.set(t); st.target = null; st.rate = 1; st.dirty = true; }; - // where "next" plays to: finish the current beat; else play the next one in (its scene's transition first) - const next = (user = true) => { - const s = S(), - F = TL.flat, + // next: finish the current beat; else play the next one in (its scene's transition first) + const next = () => { + const F = TL.flat, k = fi(), cur = F[k].B; st.target = null; @@ -271,9 +374,8 @@ jump(n.beat === 0 ? TL.scenes[n.scene].start : n.B.start); st.stopAt = st.auto ? null : n.B.shown; } else jump(TL.total); - st.nav = user; + st.nav = true; setPlaying(true); - void s; }; // back: run back at 2.4x to the previous beat, fully shown (jump if that would take more than 3 s) const back = () => { @@ -290,8 +392,13 @@ st.stopAt = st.auto ? null : to; setPlaying(true); }; - const goBeat = (i, j, where = 'shown') => { - jump(TL.timeOf(i, j, where)); + const togglePlay = () => { + if (clock.t >= TL.total) jump(0); + setPlaying(!st.playing); + wake(); + }; + const goBeat = (i, j, where2 = 'shown') => { + jump(TL.timeOf(i, j, where2)); st.stopAt = null; }; const fromHash = () => { @@ -302,6 +409,49 @@ goBeat(i, +m[2] - 1); return true; }; + // switch language at the same scene and beat (the timeline changes: holds follow the new words) + const setLang = (l) => { + if (!tracks[l] || l === lang) return; + const s = S(), + id = s.id, + beat = Math.max(0, s.beat); + lang = l; + R = resolveLang(l); + essay = R.essay; + ui = R.ui; + root.lang = l; + build(); + const i = TL.sceneIndex(id); + goBeat(i < 0 ? 0 : i, beat); + if (G.history && G.location && !manual) { + const u = new URL(G.location.href); + u.searchParams.set('lang', l); + G.history.replaceState(null, '', u.toString()); + } + draw(); + }; + if (langSel) langSel.onchange = () => setLang(langSel.value); + + // ---- sound + const ensureAudio = () => { + if (!sound || st.audio) return; + try { + const AC = G.AudioContext || G.webkitAudioContext; + st.audio = new AC({ sampleRate: 48000 }); + const pr = sound.start(st.audio); + setSoundLabel(); + if (pr && pr.then) pr.then(setSoundLabel); + } catch (err) { + console.warn('essay: no sound', err); + } + }; + const setSound = (on) => { + if (!sound) return; + st.soundOn = on; + if (on) ensureAudio(); + if (sound.setMuted) sound.setMuted(!on); + setSoundLabel(); + }; // ---- the frame let lastKey = '', @@ -310,28 +460,35 @@ const s = S(); if (host && host.ok) host.render(s); text.render(s); - // progress, place, link segs.forEach( ({ c, fill }) => (fill.style.width = (100 * B.clamp01((s.t - c.start) / Math.max(1e-6, c.end - c.start))).toFixed(2) + '%') ); bar.setAttribute('aria-valuenow', String(Math.round((100 * s.t) / TL.total))); - const key = keyOf(s); + const key = TL.scenes[s.scene].id + '-' + (Math.max(0, s.beat) + 1); if (key !== lastKey && st.started) { lastKey = key; - const sc = TL.scenes[s.scene]; + const sc = TL.scenes[s.scene], + spec = essay.scenes[s.scene]; where.textContent = - (sc.chapter ? sc.chapter + ' · ' : '') + 'part ' + (s.scene + 1) + ' of ' + TL.scenes.length; + (spec.chapterName ? spec.chapterName + ' · ' : '') + + ui.part.replace('{n}', s.scene + 1).replace('{total}', TL.scenes.length); if (G.history && G.location && !manual) { const url = '#' + encodeURIComponent(sc.id) + '-' + (Math.max(0, s.beat) + 1); if (G.location.hash !== url) G.history[st.nav ? 'pushState' : 'replaceState'](null, '', url); } st.nav = false; - const b = essay.scenes[s.scene].beats && essay.scenes[s.scene].beats[Math.max(0, s.beat)]; - const said = b ? (b.text || []).map((x) => (typeof x === 'string' ? x : x.text)).join(' ') : ''; + const b = spec.beats && spec.beats[Math.max(0, s.beat)]; + // the sources list is read where it is (its links are real); the live region says the rest once + const said = b + ? (b.text || []) + .filter((x) => !x.items) + .map((x) => (typeof x === 'string' ? x : x.text)) + .join(' ') + : ''; if (said && said !== lastLive) live.textContent = lastLive = said; } - if (opts.sound && st.audio) opts.sound.update(s.t, st.playing); + if (sound && st.audio && sound.update) sound.update(s.t, st.playing && st.soundOn); }; let prev = 0; @@ -364,7 +521,6 @@ if (clock.t >= TL.total) { clock.set(TL.total); setPlaying(false); - bPlay.textContent = 'Play again'; } if (clock.t !== before) st.dirty = true; } @@ -374,13 +530,13 @@ } }; - // ---- resize (pixel density capped at 2, picture capped at 2560 x 1600) + // ---- resize (pixel density capped at 2, picture capped at 2560 x 1600 either way round) const resize = () => { const r = root.getBoundingClientRect(); - let d = Math.min(2, G.devicePixelRatio || 1); - d = Math.min(d, 2560 / Math.max(1, r.width), 1600 / Math.max(1, r.height), d); - if (host && host.ok) - host.resize(Math.max(2, Math.round(r.width * d)), Math.max(2, Math.round(r.height * d)), r.width, r.height); + const big = Math.max(r.width, r.height), + small = Math.min(r.width, r.height); + const d = Math.min(2, G.devicePixelRatio || 1, 2560 / Math.max(1, big), 1600 / Math.max(1, small)); + if (host && host.ok) host.resize(Math.max(2, Math.round(r.width * d)), Math.max(2, Math.round(r.height * d))); if (text.resize) text.resize(r.width, r.height); st.dirty = true; }; @@ -396,7 +552,7 @@ }, 3000); }; root.addEventListener('mousemove', wake); - const inUI = (e) => e.target.closest && e.target.closest('.eo-ui,.eo-help,.eo-start'); + const inUI = (e) => e.target.closest && e.target.closest('.eo-ui,.eo-help,.eo-start,.eo-pp,a,select'); root.addEventListener('click', (e) => { if (!st.started || inUI(e) || e.pointerType === 'touch') return; next(); @@ -432,13 +588,16 @@ else if (root.requestFullscreen) root.requestFullscreen().catch(() => {}); }; G.addEventListener('keydown', (e) => { - if (e.ctrlKey || e.metaKey || e.altKey) return; - if (!st.started) return; - const k = e.key; + if (e.ctrlKey || e.metaKey || e.altKey || !st.started) return; + const k = e.key, + tag = e.target.tagName; if (!help.hidden && (k === 'Escape' || k === '?')) return toggleHelp(false); - if (e.target.tagName === 'BUTTON' && (k === ' ' || k === 'Enter')) return; + if ((tag === 'BUTTON' || tag === 'A') && (k === ' ' || k === 'Enter')) return; + if (tag === 'SELECT') return; const act = { - ' ': next, + ' ': togglePlay, + k: togglePlay, + K: togglePlay, ArrowRight: next, PageDown: next, Enter: next, @@ -447,8 +606,8 @@ Backspace: back, a: () => setAuto(!st.auto), A: () => setAuto(!st.auto), - k: () => setPlaying(!st.playing), - K: () => setPlaying(!st.playing), + m: () => setSound(!st.soundOn), + M: () => setSound(!st.soundOn), '.': () => black.classList.toggle('on'), f: fullscreen, F: fullscreen, @@ -465,21 +624,15 @@ }); bBack.onclick = () => back(); bNext.onclick = () => next(); - bPlay.onclick = () => { - if (clock.t >= TL.total) jump(0); - setPlaying(!st.playing); - }; + bPP.onclick = togglePlay; bAuto.onclick = () => setAuto(!st.auto); bHelp.onclick = () => toggleHelp(); bFull.onclick = fullscreen; - help.querySelector('button').onclick = () => toggleHelp(false); + if (bSound) bSound.onclick = () => setSound(!st.soundOn); bar.addEventListener('click', (e) => { - const r = bar.getBoundingClientRect(), - x = (e.clientX - r.left) / r.width; - // the segments have gaps, so find the chapter under the pointer and the fraction inside it - let t = x * TL.total; - for (const { c } of segs) { - const sr = segs.find((q) => q.c === c).fill.parentNode.getBoundingClientRect(); + let t = 0; + for (const { c, sg } of segs) { + const sr = sg.getBoundingClientRect(); if (e.clientX >= sr.left - 3 && e.clientX <= sr.right + 3) t = c.start + B.clamp01((e.clientX - sr.left) / sr.width) * (c.end - c.start); } @@ -494,27 +647,28 @@ start.hidden = true; st.started = true; root.classList.add('eo-on'); - if (withSound && opts.sound) { - try { - const AC = G.AudioContext || G.webkitAudioContext; - st.audio = new AC({ sampleRate: 48000 }); - opts.sound.start(st.audio); - } catch (err) { - console.warn('essay: no sound', err); - } - } + if (withSound) setSound(true); if (!fromHash()) jump(0); setPlaying(true); - if (!note.hidden) G.setTimeout(() => (note.hidden = true), 8000); // said once; then out of the words' way fullscreen(); wake(); + if (!note.hidden) G.setTimeout(() => (note.hidden = true), 8000); // said once; then out of the words' way }; - start.querySelectorAll('button').forEach((b) => (b.onclick = () => begin(b.dataset.s === '1'))); // ---- test hooks: repeatable stills of any beat or any point in a transition const E = { - TL, + get TL() { + return TL; + }, + get essay() { + return essay; + }, + get lang() { + return lang; + }, + langs, host, + sound, // scene: index or id; beat: index (-1 = the start of its transition); t: seconds after the beat starts, // or 'shown' (fully in) / 'end' (the last frame of its hold) seek(scene, beat = 0, t = 'shown') { @@ -543,7 +697,7 @@ draw(); return E.state(); }, - // ms per frame for a scene (GPU finished each frame), drawn n times at its last beat + // ms per frame for a scene (waiting for the GPU each frame), drawn n times at its last beat perf(scene, n = 60) { if (!host || !host.ok) return null; E.seek(scene, 1e9, 'shown'); @@ -551,13 +705,12 @@ const t0 = G.performance.now(); for (let f = 0; f < n; f++) { host.render(Object.assign({}, s, { sceneT: s.sceneT + f / 60, t: s.t + f / 60 })); - host.finish(); // wait for the GPU each frame (reads one pixel: finish alone may not wait) + host.finish(); } return (G.performance.now() - t0) / n; }, // the 3-flashes-a-second rule (WCAG 2.3.1) for the transition into `scene`: the picture is stepped at 60 fps - // from 0.5 s before to 0.5 s after; in each cell of a 16 x 9 grid, a change is a swing in relative luminance - // of at least 0.1 with the darker side under 0.8, and a flash is two opposing changes + // from 0.5 s before to 0.5 s after; flashes counted per cell of a 16 x 9 grid (DHS.essay.flashCount) flashCheck(scene, cols = 16, rows = 9) { if (!host || !host.ok) return null; const Sc = TL.scenes[TL.sceneIndex(scene)], @@ -584,28 +737,40 @@ trans: s.trans, gl: !!(host && host.ok), reduced: reduced(), + lang, + playing: st.playing, + sound: sound ? sound.status : null, }; }, textBoxes: () => text.boxes(), contrast: () => (text.contrast ? text.contrast() : []), - hideGlyphs: (on) => { - text.hideGlyphs(on); - }, + layoutCheck: () => (text.layoutCheck ? text.layoutCheck() : []), + hideGlyphs: (on) => text.hideGlyphs(on), next, back, begin, setAuto, + setLang, + setSound, + togglePlay, }; G.EOMD_ESSAY = E; + build(); + if (!host || !host.ok) nogl(); + if (host) host.onfail = nogl; resize(); - if (manual) { - setPlaying(false); - draw(); - } + setPlaying(st.playing); + if (manual) draw(); G.requestAnimationFrame(frame); return E; } - DHS.essay = { mount, flashCount }; + // Loads the language tracks (inline JSON, or data-src when served over http), then mounts. + const start = async (essay, opts = {}) => { + const tracks = opts.tracks || (DHS.essayTrack ? await DHS.essayTrack.load(doc) : {}); + return mount(essay, Object.assign({}, opts, { tracks })); + }; + + DHS.essay = { mount, start, flashCount }; })(globalThis); diff --git a/kit/essay/text.js b/kit/essay/text.js index 55af317..9bac09b 100644 --- a/kit/essay/text.js +++ b/kit/essay/text.js @@ -5,12 +5,13 @@ { pos, kind, text } pos center, chapter, quote (these three share the middle), lower-third, top-left, top-right, bottom-left, bottom-right. Several blocks of one beat at one position stack (a big number and its caption). - kind body, headline, chapter, quote, source, number, note + sources: a list of { title, url, note }; titles are working links (http/https), with their site shown + kind body, headline, chapter, quote, source, number, note, takeaway (the closing statement), sources The text is shown exactly as written; only its timing comes from it. Timing (a pure function of t, so seeks and stills match playback): - a beat's blocks at one position arrive word by word when the beat arrives (each word fades in over 0.6 s, - about 0.09 s apart; a number arrives whole); + about 0.09 s apart, closer for long text so all are in by the end of the beat's dur; a number arrives whole); - they stay until a later beat puts text at the same position (then they fade out over 0.5 s while the new text fades in), or until the scene ends (they fade out in the first 40% of the next transition); - prefers-reduced-motion: each group fades in whole over 0.3 s, nothing moves. @@ -29,6 +30,8 @@ const SLOT = { center: 'middle', chapter: 'middle', quote: 'middle' }; const PATCH = { + sources: 0.6, + takeaway: 0.45, body: 0.55, headline: 0.5, chapter: 0.42, @@ -36,10 +39,10 @@ source: 0.55, number: 0.45, note: 0.55, - label: 0.5, + label: 0.68, }; const CSS = ` -.eo-text{position:absolute;inset:0;pointer-events:none;color:var(--eo-ink,#f3f0e8);--m:max(5vw,env(safe-area-inset-left));--mt:max(8vh,env(safe-area-inset-top));--mb:calc(max(8vh,env(safe-area-inset-bottom)) + 44px)} +.eo-text{position:absolute;inset:0;pointer-events:none;color:var(--eo-ink,#f3f0e8);--m:max(5vw,env(safe-area-inset-left));--mt:max(8vh,calc(env(safe-area-inset-top) + 66px));--mb:calc(max(8vh,env(safe-area-inset-bottom)) + 44px)} .eo-pos{position:absolute;display:grid} .eo-pos>.eo-g{grid-area:1/1;position:relative;padding:.9em 1.3em} .eo-g>.eo-patch{position:absolute;inset:0;z-index:-1;border-radius:1.4em;background:rgba(0,0,0,var(--a));box-shadow:0 0 2.6em 1.2em rgba(0,0,0,var(--a))} @@ -65,7 +68,19 @@ background:rgba(0,0,0,${PATCH.label});box-shadow:0 0 .9em .4em rgba(0,0,0,${PATCH.label})} .eo-lb.eo-k-value{font-weight:600;font-size:clamp(15px,.7vw + 1vmin,26px)} .eo-lb.eo-k-note{font-size:clamp(12px,.4vw + .8vmin,17px);opacity:.95} -@media (max-width:700px){.eo-p-top-left,.eo-p-top-right,.eo-p-bottom-left,.eo-p-bottom-right{width:auto;left:var(--m);right:var(--m)}} +.eo-text a{pointer-events:auto;color:inherit;text-decoration:underline;text-decoration-thickness:1px;text-underline-offset:.18em} +.eo-text a:focus-visible{outline:2px solid var(--eo-accent,#e9e4d8);outline-offset:3px;border-radius:2px} +.eo-p-sources{left:var(--m);top:var(--mt);bottom:var(--mb);width:min(44em,90vw);align-content:start} +.eo-src{margin:.4em 0 0;padding-left:1.3em;font-size:clamp(15px,.55vw + .9vmin,22px);line-height:1.38} +.eo-src li{margin:0 0 .75em} +.eo-src-title{font-weight:600} +.eo-src-site{font-size:.86em} +.eo-src-note{display:block;margin-top:.15em} +.eo-k-takeaway{font-family:var(--eo-display,inherit);font-size:clamp(26px,2.2vw + 2.2vmin,64px);line-height:1.2;font-weight:500} +/* portrait phones and tablets: corner positions go full width (the data band sits between them) */ +@media (orientation:portrait){.eo-text{--m:max(6vw,env(safe-area-inset-left));--mt:max(6vh,calc(env(safe-area-inset-top) + 66px));--mb:calc(max(4vh,env(safe-area-inset-bottom)) + 92px)} + .eo-p-top-left,.eo-p-top-right,.eo-p-bottom-left,.eo-p-bottom-right{width:auto;left:var(--m);right:var(--m);text-align:left} + .eo-p-middle{width:88vw}.eo-pos>.eo-g{padding:.7em 1em}} `; const el = (tag, cls, parent) => { @@ -86,7 +101,6 @@ st.textContent = CSS; } const layer = el('div', 'eo-text', root); - layer.setAttribute('aria-hidden', 'true'); // the player's live region reads the words once let W = 1, H = 1; @@ -115,23 +129,52 @@ patch.style.setProperty('--a', String(alpha)); const words = [], blocks = []; - byPos[pos].forEach((blk) => { - const kind = blk.kind || 'body', - p = el('p', 'eo-b eo-k-' + kind, g), - bw = []; - blocks.push({ kind, text: String(blk.text), words: bw }); - // exact text: words become spans, the whitespace between them is kept as it was - String(blk.text) + // exact text: words become spans, the whitespace between them is kept as it was + const addWords = (parent, str, kind) => { + const bw = []; + String(str == null ? '' : str) .split(/(\s+)/) .forEach((part) => { if (!part) return; - if (/^\s+$/.test(part)) return p.appendChild(doc.createTextNode(part)); - const w = el('span', 'eo-w', p); + if (/^\s+$/.test(part)) return parent.appendChild(doc.createTextNode(part)); + const w = el('span', 'eo-w', parent); w.textContent = part; words.push({ el: w, whole: kind === 'number', last: '' }); bw.push(w); }); + blocks.push({ kind, text: String(str), words: bw }); + }; + byPos[pos].forEach((blk) => { + const kind = blk.kind || 'body'; + if (blk.items) { + // a sources list: each title is a working link (http and https only), its site, and a short note + const ol = el('ol', 'eo-b eo-src', g); + blk.items.forEach((it) => { + const li = el('li', '', ol), + ok = /^https?:\/\//i.test(it.url || ''); + const t = el(ok ? 'a' : 'span', 'eo-src-title', li); + if (ok) { + t.href = it.url; + t.target = '_blank'; + t.rel = 'noopener noreferrer'; + } + addWords(t, it.title, 'source-title'); + if (ok) { + li.appendChild(doc.createTextNode(' ')); + addWords( + el('span', 'eo-src-site', li), + new URL(it.url).hostname.replace(/^www\./, ''), + 'source-site' + ); + } + if (it.note) addWords(el('span', 'eo-src-note', li), it.note, 'source-note'); + }); + return; + } + addWords(el('p', 'eo-b eo-k-' + kind, g), blk.text, kind); }); + // the sources list is read by screen readers where it is (links); other words come from the live region + if (!byPos[pos].some((b) => b.items)) g.setAttribute('aria-hidden', 'true'); groups.push({ pos: slot, beat: j, @@ -143,6 +186,7 @@ kind: kind0, text: byPos[pos].map((x) => x.text).join(' '), start: S.beats[j].arrive, + reveal: Math.max(1.2, S.beats[j].dur), out: null, last: '', }); @@ -185,7 +229,8 @@ setOp(gr, gr.g, op); gr.g.style.visibility = op > 0 ? 'visible' : 'hidden'; const n = gr.words.length, - stag = red ? 0 : Math.min(0.09, 2.2 / Math.max(1, n)); + // every word is in by the time the beat has arrived (a long sources list reveals faster) + stag = red ? 0 : Math.min(0.09, Math.max(0, gr.reveal - 0.6) / Math.max(1, n - 1)); gr.words.forEach((w, k) => setOp(w, w.el, red ? 1 : clamp01((t - gr.start - (w.whole ? 0 : k * stag)) / 0.6))); }); // data labels @@ -276,6 +321,41 @@ }); return out; }, + // problems a viewer would see: words or labels on top of each other, or cut off at the screen's edge + layoutCheck() { + const rootR = layer.getBoundingClientRect(), + out = []; + const items = []; + shown.forEach((i) => { + scenes[i].groups.forEach((gr) => { + if (+gr.last > 0.5) + items.push({ key: i + ':' + gr.beat + ':' + gr.pos, text: gr.text, r: gr.g.getBoundingClientRect() }); + }); + scenes[i].labels.forEach((lb, k) => { + if (lb.el.style.display !== 'none' && +lb.last > 0.5) + items.push({ key: i + ':label:' + k, text: lb.txt, r: lb.el.getBoundingClientRect(), label: true }); + }); + }); + // groups have padding round their words: shrink them a little so touching patches aren't counted + const pad = (r, p) => ({ left: r.left + p, right: r.right - p, top: r.top + p, bottom: r.bottom - p }); + items.forEach((a, n) => { + const r = a.r; + if ( + r.left < rootR.left - 1 || + r.top < rootR.top - 1 || + r.right > rootR.right + 1 || + r.bottom > rootR.bottom + 1 + ) + out.push({ problem: 'off screen', a: a.text }); + items.slice(n + 1).forEach((b) => { + const A = pad(a.r, a.label ? 2 : 10), + Bb = pad(b.r, b.label ? 2 : 10); + if (A.left < Bb.right && Bb.left < A.right && A.top < Bb.bottom && Bb.top < A.bottom) + out.push({ problem: 'overlap', a: a.text, b: b.text }); + }); + }); + return out; + }, contrast() { const px = host && host.ok ? host.pixels() : null; const rootR = layer.getBoundingClientRect(); diff --git a/kit/essay/track.js b/kit/essay/track.js new file mode 100644 index 0000000..b47648e --- /dev/null +++ b/kit/essay/track.js @@ -0,0 +1,242 @@ +/* EOMD kit: essay/track.js. Copyright (C) 2026 Bryan Patrick Murphy. SPDX-License-Identifier: AGPL-3.0-only + Copied from engine/src/essay/track.js (https://github.com/BPMData/EOMD) by tools/build_kit.py: change the source in EOMD, not this copy. */ +/* TRACK: an essay's on-screen words as a separate track, one JSON per language, never baked into the picture. + The essay file holds the structure (scenes, scene templates, data rows, timing); a track holds the words, keyed + by scene id and beat number. Reading-time holds are computed from the active track's words, so each language + gets its own pacing. Copy is shown exactly as written; numbers come from the data, formatted for the language. + + A track: + { + "lang": "en", "draft": false, draft: a translation nobody has checked yet (shown in the console) + "title": "...", "subtitle": "...", + "ui": { "begin": "Begin", ... }, player buttons and notes (DHS.essayTrack.UI has every key) + "chapters": { "opening": "Opening" }, chapter names by chapter id + "fields": { "population": "Population" }, data field names, used as chart labels + "text": { + "opening": { "1": [{ "pos": "chapter", "kind": "chapter", "text": "..." }], "2": [ ... ] }, + "bars": { "1": [ ... ], "labels": ["A", "B"], "note": "Source: ..." }, + "country#1": { "1": [{ "pos": "top-left", "kind": "headline", "text": "{name}" }], "note": "..." }, + "sources": { "1": [{ "kind": "headline", "text": "Sources" }] } + }, + "sources": [{ "title": "...", "url": "https://...", "note": "..." }] + } + "country#1" is step 1 of the scene template "country": {field} in its text is filled from each data row. + + Scene entries in the essay that this expands: + { sequence: 'country', rows: [row, ...], scale: 'row' | 'all', transition } + one short run of scenes per row from essay.templates.country.steps: [{ scene, fields, data, beats, + transition }]. A step's chart values are row[field] for its fields (a missing field stays missing, never + zero); scale 'all' puts every row on one scale (comparable bars across countries). + { id: 'sources', type: 'sources', perPage: 3 } + the sources chapter: the track's sources, perPage to a beat, as a list with working links. + + DHS.essayTrack.resolve(essay, track) -> { essay (plain scenes with text), ui, warnings } + DHS.essayTrack.fromPage(document) -> { lang: track } from