// A POST ITEM's SLAM (umtool/docs/report-video.md, "A slam"; operator, 4 Nov: // "as a joke effect I'd like to see the japanese characters of 'fudoshin' // (不動心) pop in with three trailer hits like a corny effect, make the // characters gold with a black outline, starting large and shrinking before // hitting the page like standard trailer hits"; "three hits evenly spaced over // the pronunciation of the word, one for each character"; "do it above the // word on the page"; "do the same with baji quan (八极拳)"). // // entry.fx = [{ kind: "slam", // text: "不動心", // the glyphs that slam in (≤ SLAM_TEXT_MAX) // match?: "Fudōshin", // the word or phrase it lands on (as the card shows it) // target?: "post" | "quoted" | "parent:", // whose words (default the post's own) // occurrence?: n, // its n-th time in that text (default 1) // at?: , // the first hit; absent: the word's start in the take's words // gap?: s, // seconds between hits; absent: spread over the word's span // whole?: true, // the text as ONE unit and one hit (default: one per glyph) // hold?: s, fromScale?: x, // held after the last hit; how big a glyph starts // color?: "#rrggbb", outline?: "#rrggbb", outlineWidth?: px, // place?: "over-match" | "center", // above the matched words (default), or the card's middle // size?: px, // the glyphs' size at rest, px at 1080 (absent: by the word's line) // face?: "jp" | "sc" | "tc" | "kr", // the CJK face (Noto Sans CJK Black) // sfx?: "trailer-hit" | "off", volume?: x, swell?: true, // bar?: "fudōshin — \"immovable mind\"", // a translation bar the glyphs land ON (≤ SLAM_BAR_MAX) // barStyle?: "dark" | "gold" | "plain" }] // its look (default dark: the card's ground, a thin gold rule) // // WHEN: each glyph LANDS on a hit. Absent `at` and `gap`, the hits are spread // evenly over the matched words' SPOKEN span in the picked take's word timings // -- the first on its first word's start, the last on its last word's end // (a phrase: "Baji"'s start to "Quan"'s end) -- else the reading estimate's // start, `SLAM_GAP` apart. `at` moves the first hit; `gap` overrides the // spacing. A glyph is in from `hit` before its landing, huge (`fromScale`×) and // blurred, and SHRINKS onto its spot -- the teaser's slam (deck.mjs // TEASER_MOTION: power3.in down past rest to `under`, a power2.out settle up to // it, the blur focusing over hit + 0.12 s) -- with a flash, a dust ring and a // screen shake as it hits. After the last hit it holds `hold`, then fades. // // WHERE: a row of glyphs centred on the matched words and sitting just ABOVE // their line (below it when there is no room above in the frame; `center`: the // card's middle), each glyph huge and centred on its own landing spot. It // follows the card's pan (read-follow): every frame is placed by where the // words are drawn then. // // THE ONE EXEMPTION (deliberate, the gag): the landed row may cover the line // ABOVE the word -- for the slam's own window only (t0 → t3: its hits, its // hold, its fade; at most SLAM_LIMITS.hold + the hits' spread). It is drawn // OVER the card, never in it (no data-w, no data-post-block), so the read-follow // geometry and readInViewErrors are measured without it; what it may NOT cover // is checked here instead (slamCoverErrors): the matched words themselves, and // the words read at each hit. A row that would is placed below the line; when // neither place is clear the build refuses, in its own words. // // THE BAR (operator, 4 Nov: "have the characters appear above a bar with the // translation rather than have the tooltip pop up after"): with `bar`, the // glyph row lands ON a bar carrying the translation, centred on it -- the bar // rises in as the first glyph lands, holds through the hold and fades with // the glyphs. The row and the bar are placed as ONE unit by the same rules // (above the words' line; below it when that leaves the frame or covers a // word being read). The caption module is untouched: an item may still carry // one, and it waits for the slam as before. // // THE SOUND: one trailer hit per glyph at its landing (trailer-hits.mjs, the // teaser's generator, title tier), the tail's swell after the last with // `swell`, mixed into the segment's audio without ducking the read. // // Pure but for the DOM functions (mountSlams, setSlamState), which are // SELF-CONTAINED: the build passes them to a page (page.evaluate), Play calls // them on its card frame's document. import { alignWords, cardWordsOf, findMatch, readingEstimate, targetScope, targetTextOf } from "./word-zoom.mjs"; import { isNarrated, narrationSchedule, pickedTake } from "./post-narration.mjs"; import { cardWordTimes } from "./post-caption.mjs"; import { mixHex } from "./post-item.mjs"; import { TRAILER_HIT_TIERS, TRAILER_SWELL } from "./trailer-hits.mjs"; export const SLAM_PLACES = Object.freeze(["over-match", "center"]); export const SLAM_FACES = Object.freeze(["jp", "sc", "tc", "kr"]); export const SLAM_SFX = Object.freeze(["trailer-hit", "off"]); export const SLAM_DEFAULTS = Object.freeze({ target: "post", occurrence: 1, whole: false, hold: 1.6, fromScale: 3.5, color: "#f5c542", outline: "#000000", place: "over-match", face: "jp", sfx: "trailer-hit", volume: 1, swell: false, barStyle: "dark", }); export const SLAM_LIMITS = Object.freeze({ at: [0, 600], gap: [0.12, 2], hold: [0.3, 4], fromScale: [1.5, 8], outlineWidth: [0, 30], size: [40, 320], volume: [0, 3], occurrence: [1, 99], }); export const SLAM_TEXT_MAX = 12; /** The spacing between hits when there is no spoken span to spread them over (an `at`, the estimate). */ export const SLAM_GAP = 0.45; /** The tightest even spread: hits closer than this are SLAM_GAP_MIN apart. */ export const SLAM_GAP_MIN = 0.12; /** * THE MOTION -- the teaser's slam (deck.mjs TEASER_MOTION: `hit`, `under`, * `settle`, `blur`; a test holds them equal), from `fromScale` instead of its * 1.42: `fadeIn` its opacity's rise as it comes in, `out` the row's fade after * the hold, `flash` / `ring` / `dust` the impact's light, shock ring and dust * (seconds from the landing), `shake` the frame's punch (px at 1080, its time * constant, its span, its rate). */ export const SLAM_MOTION = Object.freeze({ hit: 0.2, under: 0.968, settle: 0.5, blur: 18, fadeIn: 0.06, out: 0.35, flash: 0.32, ring: 0.45, dust: 0.55, shake: Object.freeze({ amp: 9, tau: 0.075, span: 0.3, hz: 23 }), }); /** The faces: Noto Sans CJK at its Black weight, the region's forms first. */ export const SLAM_FACE_STACK = Object.freeze({ jp: "'Noto Sans CJK JP', 'Noto Sans CJK SC', 'Source Han Sans JP', sans-serif", sc: "'Noto Sans CJK SC', 'Noto Sans CJK JP', 'Source Han Sans CN', sans-serif", tc: "'Noto Sans CJK TC', 'Noto Sans CJK JP', 'Source Han Sans TW', sans-serif", kr: "'Noto Sans CJK KR', 'Noto Sans CJK JP', 'Source Han Sans KR', sans-serif", }); const KEYS = new Set(["kind", "text", "target", "match", "occurrence", "at", "gap", "whole", "hold", "fromScale", "color", "outline", "outlineWidth", "place", "size", "face", "sfx", "volume", "swell", "bar", "barStyle"]); export const SLAM_BAR_STYLES = Object.freeze(["dark", "gold", "plain"]); export const SLAM_BAR_MAX = 140; /** * THE BAR's motion and size: it rises `rise` × its height into place over `in` * seconds from `lead` before the first landing; its text `font` px at 1080, at * most `maxWidth` px wide (it wraps), the glyphs overlapping its top edge by * `overlap` × their size (0: their em box stands on its rule -- the ink and the * outline already reach it, so a bigger overlap hides its words). */ export const SLAM_BAR = Object.freeze({ lead: 0.04, in: 0.28, rise: 0.6, font: 30, maxWidth: 820, overlap: 0 }); const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const fin = (v) => typeof v === "number" && Number.isFinite(v); const numIn = (v, [lo, hi]) => fin(v) && v >= lo && v <= hi; const r3 = (v) => Math.round(v * 1000) / 1000; const HEX_RE = /^#[0-9a-fA-F]{6}$/; const MATCH_MAX = 120; /** * One slam with every default filled in. * @param {Record | null | undefined} fx * @returns {{ kind?: string, text: string, target: string, match: string, occurrence: number, at?: number, gap?: number, whole: boolean, hold: number, fromScale: number, color: string, outline: string, outlineWidth?: number, place: string, size?: number, face: string, sfx: string, volume: number, swell: boolean, bar?: string, barStyle: string }} */ export const resolveSlam = (fx) => ({ ...SLAM_DEFAULTS, ...Object.fromEntries(Object.entries(fx ?? {}).filter(([, v]) => v !== undefined && v !== null)) }); /** The slam's units: each glyph (whitespace dropped), or the whole text as one. */ export function slamUnits(fx) { const t = String(fx?.text ?? "").trim(); if (!t) return []; if (fx?.whole === true) return [t]; return Array.from(t).filter((c) => c.trim()); } const TARGET_NAME = (t) => (t === "post" ? "the post's words" : t === "quoted" ? "the quoted post's words" : `the words of the post it answers (${t})`); /** Every reason slam `fx` (entry `e`'s fx[i], named `fw`) cannot be built, as sentences. word-zoom.mjs validatePostFx calls it. */ export function slamErrors(e, fx, fw) { const errors = []; for (const k of Object.keys(fx)) if (!KEYS.has(k)) errors.push(`${fw}.${k} is not a slam key (${[...KEYS].join(", ")})`); if (typeof fx.text !== "string" || !fx.text.trim()) errors.push(`${fw}.text must be the glyphs that slam in ("不動心")`); else if (Array.from(fx.text.trim()).length > SLAM_TEXT_MAX) errors.push(`${fw}.text is longer than ${SLAM_TEXT_MAX} characters (a slam is a few glyphs, not a sentence)`); const place = fx.place ?? SLAM_DEFAULTS.place; if (fx.place !== undefined && !SLAM_PLACES.includes(fx.place)) errors.push(`${fw}.place must be one of ${SLAM_PLACES.join(", ")}`); const target = fx.target ?? "post"; if (fx.target !== undefined && !(typeof fx.target === "string" && /^(post|quoted|parent:\d+)$/.test(fx.target))) errors.push(`${fw}.target must be "post", "quoted" or "parent:"`); const text = typeof target === "string" ? targetTextOf(e, target) : null; if (fx.match === undefined) { if (!fin(fx.at)) errors.push(`${fw}: a slam needs its word (match) or its second (at)`); else if (place === "over-match") errors.push(`${fw}: a slam with no match has no word to land over (place "center", or set match)`); } else if (typeof fx.match !== "string" || !fx.match.trim()) errors.push(`${fw}.match must be the word or phrase the slam lands on, as the card shows it`); else if (fx.match.length > MATCH_MAX) errors.push(`${fw}.match is longer than ${MATCH_MAX} characters`); else if (text === null) errors.push(`${fw}.target ${target}: the card draws no such post (${target === "quoted" ? "it quotes none" : "it answers no post there"})`); else { const m = findMatch(text, fx.match, fx.occurrence ?? 1); if (m.error === "not in") errors.push(`${fw}.match "${fx.match}" is not in ${TARGET_NAME(target)}`); else if (m.error === "occurrence") errors.push(`${fw}.match "${fx.match}" is in ${TARGET_NAME(target)} ${m.count} time${m.count === 1 ? "" : "s"}: occurrence ${fx.occurrence} is not there`); else if (m.error) errors.push(`${fw}.match: ${m.error}`); } if (fx.occurrence !== undefined && !(Number.isInteger(fx.occurrence) && numIn(fx.occurrence, SLAM_LIMITS.occurrence))) errors.push(`${fw}.occurrence must be a whole number from 1 (its first time in the text)`); for (const k of ["at", "gap", "hold"]) if (fx[k] !== undefined && !numIn(fx[k], SLAM_LIMITS[k])) errors.push(`${fw}.${k} must be ${SLAM_LIMITS[k][0]}–${SLAM_LIMITS[k][1]} seconds`); if (fx.fromScale !== undefined && !numIn(fx.fromScale, SLAM_LIMITS.fromScale)) errors.push(`${fw}.fromScale must be ${SLAM_LIMITS.fromScale[0]}–${SLAM_LIMITS.fromScale[1]} (times its size at rest)`); for (const k of ["outlineWidth", "size"]) if (fx[k] !== undefined && !numIn(fx[k], SLAM_LIMITS[k])) errors.push(`${fw}.${k} must be ${SLAM_LIMITS[k][0]}–${SLAM_LIMITS[k][1]} px (at 1080)`); if (fx.volume !== undefined && !numIn(fx.volume, SLAM_LIMITS.volume)) errors.push(`${fw}.volume must be ${SLAM_LIMITS.volume[0]}–${SLAM_LIMITS.volume[1]} (times the trailer hit's level)`); for (const k of ["color", "outline"]) if (fx[k] !== undefined && !(typeof fx[k] === "string" && HEX_RE.test(fx[k]))) errors.push(`${fw}.${k} must be a colour (#rrggbb)`); if (fx.face !== undefined && !SLAM_FACES.includes(fx.face)) errors.push(`${fw}.face must be one of ${SLAM_FACES.join(", ")}`); if (fx.sfx !== undefined && !SLAM_SFX.includes(fx.sfx)) errors.push(`${fw}.sfx must be one of ${SLAM_SFX.join(", ")}`); for (const k of ["whole", "swell"]) if (fx[k] !== undefined && typeof fx[k] !== "boolean") errors.push(`${fw}.${k} must be true or false`); if (fx.bar !== undefined && !(typeof fx.bar === "string" && fx.bar.trim())) errors.push(`${fw}.bar must be the translation the glyphs land on (or absent)`); else if (typeof fx.bar === "string" && fx.bar.length > SLAM_BAR_MAX) errors.push(`${fw}.bar is longer than ${SLAM_BAR_MAX} characters (a bar is a line, not a paragraph)`); if (fx.barStyle !== undefined && !SLAM_BAR_STYLES.includes(fx.barStyle)) errors.push(`${fw}.barStyle must be one of ${SLAM_BAR_STYLES.join(", ")}`); if (fx.barStyle !== undefined && fx.bar === undefined) errors.push(`${fw}.barStyle: the slam has no bar (set bar)`); return errors; } // --------------------------------------------------------------------------- // WHEN. // --------------------------------------------------------------------------- /** * Each slam's moment, one per fx (another effect's row is `{ i, kind }`): * `{ i, t, end, source: "at"|"words"|"estimate" }` -- `t` its matched words' * spoken start (or `at`), `end` their spoken end (null when unknown: an `at` * with no words, the estimate) -- or `{ i, error }`. * @param {Record} entry * @param {Record} [render] * @param {Record | null} [schedule] * @returns {Array<{ i: number, t?: number, end?: number | null, source?: string, error?: string, kind?: string | null }>} */ export function slamTimes(entry, render = undefined, schedule = undefined) { const list = Array.isArray(entry?.fx) ? entry.fx : []; return list.map((fx0, i) => { if (!isObj(fx0) || fx0.kind !== "slam") return { i, kind: fx0?.kind ?? null }; const fx = resolveSlam(fx0); const w = `${entry?.id ?? "?"}: slam ${i + 1} ("${fx.text}")`; if (typeof fx0.match !== "string") return fin(fx0.at) ? { i, t: r3(fx0.at), end: null, source: "at" } : { i, error: `${w} has no time (set at, or match)` }; const text = targetTextOf(entry, fx.target); const m = findMatch(text, fx.match, fx.occurrence); if (m.error) return { i, error: `${w}: "${fx.match}" is not on the card` }; // The spoken span, from the take's word timings. let span = null; if (isNarrated(entry)) { const take = pickedTake(entry); const timed = Array.isArray(take?.words) && take.words.length ? take.words : null; if (timed) { const sch = schedule ?? narrationSchedule(entry, render); const rate = sch.rate || 1; const map = alignWords(cardWordsOf(text), timed.map((x) => x.w)); const ks = []; for (let k = m.from; k <= m.to; k += 1) if (map[k] >= 0) ks.push(map[k]); if (ks.length) { const a = timed[ks[0]]; const b = timed[ks[ks.length - 1]]; if (fin(a.start) && fin(b.end)) span = { t: r3(sch.at + a.start / rate), end: r3(sch.at + b.end / rate) }; } } } if (fin(fx0.at)) return { i, t: r3(fx0.at), end: span ? r3(fx0.at + (span.end - span.t)) : null, source: "at" }; if (span) return { i, t: span.t, end: span.end, source: "words" }; const wt = cardWordTimes(entry, render, fx.target, schedule); const t = wt?.times?.[m.from]; return { i, t: fin(t) ? r3(t) : readingEstimate(m.from), end: null, source: "estimate" }; }); } /** * Each unit's LANDING (where its hit sounds), item seconds: `gap` apart when the * slam sets one; else spread evenly from `t` to `end` (the first on the word's * start, the last on its end) when the span is known and there are two or more; * else SLAM_GAP apart. Never closer than SLAM_GAP_MIN. * @param {Record} fx0 * @param {{ t: number, end?: number | null }} time * @returns {number[]} */ export function slamLandings(fx0, { t, end = null }) { const n = slamUnits(resolveSlam(fx0)).length; if (!n) return []; let gap = SLAM_GAP; if (fin(fx0?.gap)) gap = fx0.gap; else if (fin(end) && n > 1 && end > t) gap = (end - t) / (n - 1); gap = Math.max(SLAM_GAP_MIN, gap); return Array.from({ length: n }, (_, k) => r3(t + k * gap)); } /** * One slam's span on the item's clock: in from t0 (its first glyph's start, * `hit` before its landing) through each landing, held to t2 (`hold` after the * last), out by t3 -- the hold shortened to end by `end` (the item's last * second, or a stack card's media phase). `{ t0, t2, t3, landings }` or `{ error }`. * @param {Record} fx0 * @param {number[]} landings * @param {{ end?: number }} [o] */ export function slamSpan(fx0, landings, { end = Infinity } = {}) { const fx = resolveSlam(fx0); if (!landings.length) return { error: "has no glyphs" }; const last = landings[landings.length - 1]; const t0 = Math.max(0, landings[0] - SLAM_MOTION.hit); if (last >= end - 0.05) return { error: `lands at ${r3(last)} s, at or after the item's ${r3(end)} s` }; let t2 = last + fx.hold; if (t2 + SLAM_MOTION.out > end) t2 = Math.max(last + 0.15, end - SLAM_MOTION.out); return { t0: r3(t0), t2: r3(t2), t3: r3(Math.min(end, t2 + SLAM_MOTION.out)), landings }; } const easeIn3 = (x) => Math.min(1, Math.max(0, x)) ** 3; const easeOut2 = (x) => 1 - (1 - Math.min(1, Math.max(0, x))) ** 2; /** * One unit's look at item second `s` (landing `L`): `{ scale, blur, opacity, * flash, ring, dust, ghost }` -- scale × its rest size, blur px at 1080, the * flash's and ghosts' strength 0–1, the ring's and dust's progress 0–1 (-1: * none) -- or null before it comes in. `fade` is the row's (1 → 0 over its out). * @param {number} L @param {number} s @param {{ fromScale?: number, fade?: number }} [o] */ export function slamUnitAt(L, s, { fromScale = SLAM_DEFAULTS.fromScale, fade = 1 } = {}) { const M = SLAM_MOTION; const u = s - (L - M.hit); if (u < 0) return null; let scale = 1; if (u < M.hit) scale = fromScale + (M.under - fromScale) * easeIn3(u / M.hit); else if (u < M.hit + M.settle) scale = M.under + (1 - M.under) * easeOut2((u - M.hit) / M.settle); const blur = M.blur * (1 - easeOut2(u / (M.hit + 0.12))); const opacity = Math.min(1, u / M.fadeIn) * fade; const v = s - L; const flash = v >= -0.03 && v < M.flash ? (v < 0 ? 1 + v / 0.03 : 1 - v / M.flash) * fade : 0; const ring = v >= 0 && v < M.ring ? v / M.ring : -1; const dust = v >= 0 && v < M.dust ? v / M.dust : -1; const ghost = u < M.hit ? (1 - u / M.hit) * fade : 0; return { scale: r3(scale), blur: Math.round(blur * 10) / 10, opacity: r3(opacity), flash: r3(Math.max(0, flash)), ring: r3(ring), dust: r3(dust), ghost: r3(ghost) }; } /** The row's fade at `s` (1 until its hold ends, 0 by t3). */ export const slamFadeAt = (span, s) => (s < span.t2 ? 1 : s >= span.t3 ? 0 : 1 - (s - span.t2) / Math.max(1e-6, span.t3 - span.t2)); /** * The slam's state at item second `s`: `{ units: [{ k, …slamUnitAt }] }` for * the units in, or null when it is not up. * @param {{ span: { t0: number, t2: number, t3: number, landings: number[] }, fromScale: number }} p * @param {number} s */ export function slamStateAt(p, s) { if (!p?.span || s < p.span.t0 || s >= p.span.t3) return null; const fade = slamFadeAt(p.span, s); const units = []; p.span.landings.forEach((L, k) => { const st = slamUnitAt(L, s, { fromScale: p.fromScale, fade }); if (st) units.push({ k, ...st }); }); return { units }; } /** * The bar's look at `s` (null when the slam has none, or before it comes in): * `{ opacity, rise }` -- `rise` the share of its height it still has to come up. * @param {{ t0: number, t2: number, t3: number, landings: number[] }} span */ export function slamBarAt(span, s) { const t = span.landings[0] - SLAM_BAR.lead; if (s < t || s >= span.t3) return null; const e = easeOut2((s - t) / SLAM_BAR.in); return { opacity: r3(e * slamFadeAt(span, s)), rise: r3((1 - e) * SLAM_BAR.rise) }; } /** The frame's punch at `s` (unit amplitudes: × SLAM_MOTION.shake.amp × k px): `{ x, y }`. */ export function slamShakeAt(landings, s) { const { tau, span, hz } = SLAM_MOTION.shake; let x = 0; let y = 0; for (const L of landings) { const v = s - L; if (v < 0 || v > span) continue; const e = Math.exp(-v / tau); x += e * Math.sin(2 * Math.PI * hz * v); y += e * 0.75 * Math.cos(2 * Math.PI * hz * 1.37 * v); } return { x: r3(x), y: r3(y) }; } /** slamShakeAt's `axis` as an ffmpeg expression of t, × `amp` px ("0" with no landings). */ export function slamShakeExpr(landings, axis, amp) { const { tau, span, hz } = SLAM_MOTION.shake; const n = (v) => String(r3(v)); const terms = landings.map((L) => { const u = `(t-${n(L)})`; const wave = axis === "x" ? `sin(${n(2 * Math.PI * hz)}*${u})` : `0.75*cos(${n(2 * Math.PI * hz * 1.37)}*${u})`; return `if(between(t,${n(L)},${n(L + span)}),exp(-${u}/${n(tau)})*${wave},0)`; }); return terms.length ? `${n(amp)}*(${terms.join("+")})` : "0"; } /** Two slams of one post up at once: their indices, or null. */ export function overlappingSlams(spans) { const s = spans.filter((x) => x && fin(x.t0)).sort((a, b) => a.t0 - b.t0); for (let k = 1; k < s.length; k += 1) if (s[k].t0 < s[k - 1].t3) return [s[k - 1].i, s[k].i]; return null; } // --------------------------------------------------------------------------- // THE SOUND. // --------------------------------------------------------------------------- /** * The slam's hits as trailer-hits.mjs reads them: one title-tier hit per * landing, the tail's swell after the last with `swell` (over the hold). Empty * with `sfx: "off"`. * @param {Record} fx0 * @param {{ t0: number, t2: number, landings: number[] }} span */ export function slamHits(fx0, span) { const fx = resolveSlam(fx0); if (fx.sfx === "off") return []; const out = span.landings.map((at) => ({ kind: "hit", at, role: "title", ...TRAILER_HIT_TIERS.title })); if (fx.swell === true) { const last = span.landings[span.landings.length - 1]; out.push({ kind: "swell", at: r3(last + 0.15), role: "tail", ...TRAILER_SWELL, dur: r3(Math.max(0.6, span.t2 - last)) }); } return out; } // --------------------------------------------------------------------------- // THE PLAN. // --------------------------------------------------------------------------- /** * Post item `entry`'s slams, resolved: `[{ i, units, scope, from, to, fx, * t, end, source, span, avoid }]` -- `avoid` the target's word indices read * near a hit (their start within SLAM_AVOID_WINDOW of one: the row covers * none of them), the matched words apart (always protected). `zooms`: the * item's word zooms' spans (a slam up with one is refused); `end`: the last * second a slam may be up. Throws in the build's words. * @param {Record} entry * @param {Record} [render] * @param {{ zooms?: Array>, end?: number, schedule?: Record }} [o] */ export function slamPlan(entry, render = undefined, { zooms = [], end = Infinity, schedule = undefined } = {}) { const list = Array.isArray(entry?.fx) ? entry.fx : []; if (!list.some((f) => f?.kind === "slam")) return []; const times = slamTimes(entry, render, schedule); const bad = times.filter((t) => t.error); if (bad.length) throw new Error(bad.map((t) => t.error).join("; ")); /** @type {any[]} */ const out = []; for (const [i, fx0] of list.entries()) { if (fx0?.kind !== "slam") continue; const fx = resolveSlam(fx0); const tm = times[i]; const landings = slamLandings(fx0, { t: Number(tm.t), end: tm.end ?? null }); const span = slamSpan(fx0, landings, { end }); if (span.error !== undefined) throw new Error(`${entry?.id ?? "?"}: slam ${i + 1} ("${fx.text}") ${span.error} (move its at)`); const z = zooms.find((zz) => fin(zz.t0) && fin(zz.t3) && zz.t0 < span.t3 && span.t0 < zz.t3); if (z) throw new Error(`${entry?.id ?? "?"}: slam ${i + 1} ("${fx.text}") is up while word zoom ${(z.i ?? 0) + 1} is (one at a time: move one's at)`); let scope = null, from = -1, to = -1, avoid = []; if (typeof fx0.match === "string") { const m = findMatch(targetTextOf(entry, fx.target), fx.match, fx.occurrence); scope = targetScope(fx.target); from = m.from; to = m.to; const read = cardWordTimes(entry, render, fx.target, schedule)?.times ?? []; avoid = read.map((s, k) => (fin(s) && (k < m.from || k > m.to) && landings.some((L) => Math.abs(s - L) <= SLAM_AVOID_WINDOW) ? k : -1)).filter((k) => k >= 0); } out.push({ i, units: slamUnits(fx), scope, from, to, fx, t: Number(tm.t), end: tm.end ?? null, source: String(tm.source), span: { ...span, i }, avoid }); } const clash = overlappingSlams(out.map((p) => p.span)); if (clash) throw new Error(`${entry?.id ?? "?"}: slams ${clash[0] + 1} and ${clash[1] + 1} are up at once (one at a time: move one's at)`); return out; } /** A word whose read starts this near a hit is being read as it lands: the row never covers it. */ export const SLAM_AVOID_WINDOW = 0.25; // --------------------------------------------------------------------------- // WHERE. // --------------------------------------------------------------------------- /** @typedef {{ x: number, y: number, width: number, height: number }} Rect */ /** @param {Rect} a @param {Rect} b */ const hits = (a, b) => Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x) > 0.5 && Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y) > 0.5; /** The glyphs' size at rest, px: the slam's `size` (at 1080, × k), else by the matched words' line (2.5×), in 64–170 px at 1080. */ export function slamSize(fx, word, k = 1) { if (fin(fx?.size)) return Math.round(fx.size * k); const h = word ? word.height : 50 * k; return Math.round(Math.min(170 * k, Math.max(64 * k, h * 2.5))); } /** * THE ROW's PLACE: the units (`units`: each one's box at rest, `{ width, * height }`, side by side) centred on the matched words (`word`) and sitting * `gap` above their line -- or, when that leaves the frame (`bounds`) or covers * a `protect`ed box (the matched words, the words read at a hit), `gap` below * it; `center`: the card's middle. Kept in the frame (moved in). `{ x, y, width, * height, centers: [{ x, y }], where: "above"|"below"|"center"|"clamped", * covers: n (the boxes of `obstacles` it lies over: the gag), blocked: bool * (it covers a protected box) }`. * With a BAR (a box among `units` whose `k` is -1): the row sits ON it -- * centred, overlapping its top by SLAM_BAR.overlap × the glyphs' height -- and * the row and the bar are placed as one block; `bar` is then its box and * centre (null without one). * @param {{ word?: Rect | null, card: Rect, bounds: Rect, units: Array<{ width: number, height: number, k?: number }>, place?: string, gap?: number, protect?: Rect[], obstacles?: Rect[] }} o */ export function slamLayout({ word = null, card, bounds, units: all, place = "over-match", gap = 8, protect = [], obstacles = [] }) { const barBox = all.find((u) => u.k === -1) ?? null; const units = all.filter((u) => u.k !== -1); const RW = units.reduce((a, u) => a + u.width, 0); const RH = Math.max(...units.map((u) => u.height)); // The block: the row, and under it the bar it lands on (centred on each other). const over = barBox ? Math.round(RH * SLAM_BAR.overlap) : 0; const W = barBox ? Math.max(RW, barBox.width) : RW; const H = barBox ? RH - over + barBox.height : RH; const clampX = (x) => Math.min(bounds.x + bounds.width - W, Math.max(bounds.x, x)); const clampY = (y) => Math.min(bounds.y + bounds.height - H, Math.max(bounds.y, y)); const tries = []; if (place === "center" || !word) tries.push({ x: clampX(card.x + card.width / 2 - W / 2), y: clampY(card.y + card.height / 2 - H / 2), where: "center" }); else { const x = clampX(word.x + word.width / 2 - W / 2); const above = word.y - gap - H; const below = word.y + word.height + gap; if (above >= bounds.y) tries.push({ x, y: above, where: "above" }); if (below + H <= bounds.y + bounds.height) tries.push({ x, y: below, where: "below" }); tries.push({ x, y: clampY(above), where: "clamped" }); } const judged = tries.map((t) => { const r = { x: t.x, y: t.y, width: W, height: H }; return { ...t, blocked: protect.some((p) => hits(r, p)), covers: obstacles.filter((o) => hits(r, o)).length }; }); const pick = judged.find((t) => !t.blocked) ?? judged[0]; let cx = pick.x + (W - RW) / 2; const centers = units.map((u) => { const c = { x: Math.round(cx + u.width / 2), y: Math.round(pick.y + RH / 2) }; cx += u.width; return c; }); const bar = barBox ? { x: Math.round(pick.x + (W - barBox.width) / 2), y: Math.round(pick.y + RH - over), width: Math.round(barBox.width), height: Math.round(barBox.height), cx: Math.round(pick.x + W / 2), cy: Math.round(pick.y + RH - over + barBox.height / 2) } : null; return { x: Math.round(pick.x), y: Math.round(pick.y), width: Math.round(W), height: Math.round(H), centers, bar, where: pick.where, covers: pick.covers, blocked: pick.blocked }; } /** * Why a placed row cannot be built, as sentences: it covers the matched words, * or a word read as a glyph lands (the one exemption -- the line above, for * the slam's window -- is the gag; these are not). */ export function slamCoverErrors(id, i, layout) { return layout.blocked ? [`${id}: slam ${i + 1} would cover the words being read as it lands (its matched words, or a word read at a hit) -- above and below its line alike: set place "center", a smaller size, or move it`] : []; } // --------------------------------------------------------------------------- // THE LOOK. // --------------------------------------------------------------------------- /** The CSS of the slams' layer (each unit's colours and face are its own inline variables). */ export function slamCss() { return ` [data-post-fx-slams] { position: absolute; left: 0; top: 0; width: 100%; height: 100%; pointer-events: none; z-index: 70; overflow: visible; } .pslam { position: absolute; left: 0; top: 0; line-height: 1; white-space: nowrap; transform-origin: 50% 50%; opacity: 0; font-weight: 900; font-synthesis: none; will-change: transform, opacity, filter; } .pslam-g { position: relative; display: block; } .pslam-back, .pslam-front, .pslam-ghost { display: block; } .pslam-back { color: var(--pslam-stroke); -webkit-text-stroke: var(--pslam-sw) var(--pslam-stroke); paint-order: stroke fill; filter: drop-shadow(0 0.05em 0.035em rgba(0,0,0,0.6)) drop-shadow(0 0.015em 0.01em rgba(0,0,0,0.5)); } .pslam-front { position: absolute; left: 0; top: 0; color: transparent; background: linear-gradient(180deg, var(--pslam-hi) 0%, var(--pslam-gold) 44%, var(--pslam-lo) 56%, var(--pslam-gold) 100%); -webkit-background-clip: text; background-clip: text; -webkit-text-stroke: max(1px, calc(var(--pslam-sw) * 0.12)) var(--pslam-lo); } .pslam-ghost { position: absolute; left: 0; top: 0; color: var(--pslam-gold); opacity: 0; transform-origin: 50% 50%; -webkit-text-stroke: var(--pslam-sw) var(--pslam-stroke); paint-order: stroke fill; } .pslam-flash { position: absolute; left: 50%; top: 50%; width: 2.4em; height: 2.4em; margin: -1.2em 0 0 -1.2em; border-radius: 50%; opacity: 0; background: radial-gradient(circle, rgba(255,252,232,0.95) 0%, var(--pslam-flash) 30%, rgba(0,0,0,0) 68%); } .pslam-ring { position: absolute; left: 50%; top: 50%; width: 1.5em; height: 1.5em; margin: -0.75em 0 0 -0.75em; border-radius: 50%; opacity: 0; border: 0.05em solid var(--pslam-hi); box-shadow: 0 0 0.12em var(--pslam-gold); } .pslam-dust { position: absolute; left: 50%; top: 62%; width: 0; height: 0; } .pslam-bar { position: absolute; left: 0; top: 0; opacity: 0; box-sizing: border-box; text-align: center; line-height: 1.3; font-synthesis: none; font-family: 'PostSans', 'Fira Sans', 'Noto Sans', 'Noto Sans CJK JP', sans-serif; will-change: transform, opacity; overflow-wrap: anywhere; } .pslam-bar b { font-family: 'PostSansBold', 'Fira Sans', 'Noto Sans', 'Noto Sans CJK JP', sans-serif; font-weight: 700; } .pslam-bar { text-wrap: balance; } .pslam-bar[data-style="dark"] { background: rgba(14,12,9,0.95); color: #f6f1e6; border-top: 2px solid var(--pslam-gold); border-bottom: 1px solid rgba(245,197,66,0.35); box-shadow: 0 0.3em 1em rgba(0,0,0,0.5); } .pslam-bar[data-style="dark"] b { color: var(--pslam-hi); } .pslam-bar[data-style="dark"] .pslam-bar-rest { color: #d9cfbd; } .pslam-bar[data-style="gold"] { background: linear-gradient(180deg, var(--pslam-hi), var(--pslam-gold)); color: #1a1206; border-top: 2px solid #fff6d2; border-bottom: 2px solid var(--pslam-lo); box-shadow: 0 0.3em 1em rgba(0,0,0,0.55); } .pslam-bar[data-style="plain"] { background: transparent; color: #fffaf0; text-shadow: 0 0.06em 0.2em rgba(0,0,0,0.95), 0 0 0.06em #000; } .pslam-bar[data-style="plain"] b { color: var(--pslam-hi); } .pslam-dust i { position: absolute; left: 0; top: 0; width: 0.07em; height: 0.07em; margin: -0.035em; border-radius: 50%; background: var(--pslam-hi); opacity: 0; } `; } /** A unit's colour variables: its gold's highlight, body and shadow, its outline and width (px at its size). */ export function slamVars(fx, size) { const f = resolveSlam(fx); const sw = fin(fx?.outlineWidth) ? fx.outlineWidth * (size / 120) : Math.max(4, size * 0.11); return { "--pslam-gold": f.color, "--pslam-hi": mixHex(f.color, "#ffffff", 0.62), "--pslam-lo": mixHex(f.color, "#5a3a00", 0.55), "--pslam-stroke": f.outline, "--pslam-sw": `${Math.round(sw * 10) / 10}px`, "--pslam-flash": `${f.color}aa`, }; } /** The bar's inner HTML: its text, the part before " — " bold (as a caption's). */ export function slamBarHtml(text) { const esc = (v) => String(v).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c] || c); const t = String(text ?? ""); const cut = t.indexOf(" — "); return cut > 0 ? `${esc(t.slice(0, cut))} — ${esc(t.slice(cut + 3))}` : esc(t); } /** A slam's bar as mountSlams takes it (null without one): its HTML, style, colours and size at `k` (px per 1080). */ export function slamBarOf(p, k = 1) { if (typeof p?.fx?.bar !== "string" || !p.fx.bar.trim()) return null; return { i: p.i, html: slamBarHtml(p.fx.bar), style: p.fx.barStyle ?? "dark", font: Math.round(SLAM_BAR.font * k), maxWidth: Math.round(SLAM_BAR.maxWidth * k), padX: Math.round(26 * k), padY: Math.round(9 * k), vars: slamVars(p.fx, 100) }; } /** The dust's directions (degrees): a fan up and out from the foot of the glyph. */ export const SLAM_DUST = Object.freeze([-170, -150, -128, -105, -80, -55, -32, -10, 200, 225]); /** * Mount the slams' units over the card page: `{ css, units: [{ i, k, text, * size, face, vars }] }`. Returns each one's box at rest `[{ i, k, width, * height }]` (its glyph's em box: line height 1). * `bars` (slamBarOf's): each slam's translation bar, measured too (its `k` is -1). * @param {{ css?: string, units?: Array<{ i: number, k: number, text: string, size: number, face: string, vars: Record }>, dust?: number[], bars?: Array<{ i: number, html: string, style: string, font: number, maxWidth: number, padX: number, padY: number, vars: Record }> } | null} arg * @param {Document} [doc] * @returns {Array<{ i: number, k: number, width: number, height: number }>} */ export function mountSlams(arg, doc = document) { doc.querySelectorAll("[data-post-fx-slams], style[data-post-fx-slams-css]").forEach((el) => el.remove()); const units = (arg && arg.units) || []; if (!units.length && !(arg && arg.bars && arg.bars.length)) return []; const style = doc.createElement("style"); style.setAttribute("data-post-fx-slams-css", ""); style.textContent = arg.css || ""; doc.head.appendChild(style); const layer = doc.createElement("div"); layer.setAttribute("data-post-fx-slams", ""); doc.body.appendChild(layer); const dust = (arg && arg.dust) || []; const bars = (arg && arg.bars) || []; const barBoxes = bars.map((b) => { const el = doc.createElement("div"); el.className = "pslam-bar"; el.setAttribute("data-post-fx-slam", `${b.i}:-1`); el.setAttribute("data-style", b.style); for (const [k, v] of Object.entries(b.vars || {})) el.style.setProperty(k, v); el.style.fontSize = `${b.font}px`; el.style.padding = `${b.padY}px ${b.padX}px`; el.style.maxWidth = `${b.maxWidth}px`; el.style.width = "max-content"; el.innerHTML = b.html; layer.appendChild(el); const r = el.getBoundingClientRect(); el.dataset.rw = String(r.width); el.dataset.rh = String(r.height); return { i: b.i, k: -1, width: Math.ceil(r.width), height: Math.ceil(r.height) }; }); const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c] || c); return units.map((u) => { const el = doc.createElement("div"); el.className = "pslam"; el.style.zIndex = "2"; el.setAttribute("data-post-fx-slam", `${u.i}:${u.k}`); el.style.fontSize = `${u.size}px`; el.style.fontFamily = u.face; for (const [k, v] of Object.entries(u.vars || {})) el.style.setProperty(k, v); const t = esc(u.text); el.innerHTML = `` + `${dust.map((a) => ``).join("")}` + `${t}${t}${t}` + `${t}${t}`; layer.appendChild(el); const b = el.getBoundingClientRect(); el.dataset.rw = String(b.width); el.dataset.rh = String(b.height); return { i: u.i, k: u.k, width: Math.ceil(b.width), height: Math.ceil(b.height) }; }).concat(barBoxes); } /** * Set the slams: `{ list: [{ i, k, x, y, scale, blur, opacity, flash, ring, * dust, ghost }], shake: { x, y } | null }` -- x, y the unit's centre (px); * a unit not listed is hidden. `shake` (Play) moves the page's body by that * many px (the build shakes the frame in ffmpeg instead). * @param {{ list?: Array>, shake?: { x: number, y: number } | null } | null} arg * @param {Document} [doc] */ export function setSlamState(arg, doc = document) { const list = (arg && arg.list) || []; const shake = arg && arg.shake; if (doc.body) doc.body.style.translate = shake && (shake.x || shake.y) ? `${Math.round(shake.x * 10) / 10}px ${Math.round(shake.y * 10) / 10}px` : ""; const layer = doc.querySelector("[data-post-fx-slams]"); if (!layer) return; for (const el of Array.from(layer.querySelectorAll(".pslam-bar"))) { const id = el.getAttribute("data-post-fx-slam") || ""; const st = list.find((x) => `${x.i}:${x.k}` === id); if (!st) { el.style.opacity = "0"; continue; } const w = Number(el.dataset.rw || 0); const h = Number(el.dataset.rh || 0); el.style.opacity = String(st.opacity); el.style.transform = `translate(${Math.round((st.x - w / 2) * 10) / 10}px, ${Math.round((st.y - h / 2 + (st.rise || 0) * h) * 10) / 10}px)`; } for (const el of Array.from(layer.querySelectorAll(".pslam"))) { const id = el.getAttribute("data-post-fx-slam") || ""; const st = list.find((x) => `${x.i}:${x.k}` === id); if (!st) { el.style.opacity = "0"; continue; } const w = Number(el.dataset.rw || 0); const h = Number(el.dataset.rh || 0); const size = parseFloat(el.style.fontSize) || 100; el.style.opacity = String(st.opacity); el.style.transform = `translate(${Math.round((st.x - w / 2) * 10) / 10}px, ${Math.round((st.y - h / 2) * 10) / 10}px) scale(${st.scale})`; const g = el.querySelector(".pslam-g"); // The teaser's blur (px on its title) scaled to this glyph and halved: a motion smear, never a blob. if (g) g.style.filter = st.blur > 0.2 ? `blur(${Math.round(st.blur * (size / 120) * 0.45 * 10) / 10}px)` : ""; // The ghosts: bigger copies trailing the shrink (where it came from), gone as it lands. Array.from(el.querySelectorAll(".pslam-ghost")).forEach((gh, j) => { gh.style.opacity = String(Math.round(st.ghost * (0.3 / (j + 1)) * 1000) / 1000); gh.style.transform = `scale(${Math.round((1 + 0.16 * (j + 1) * st.ghost) * 1000) / 1000})`; }); // The impact: a flash behind it (it is drawn under the glyph), a ring, the dust thrown up and out. const fl = el.querySelector(".pslam-flash"); if (fl) { fl.style.opacity = String(st.flash); fl.style.transform = `scale(${Math.round((0.7 + 0.5 * (1 - st.flash)) * 1000) / 1000})`; } const ring = el.querySelector(".pslam-ring"); if (ring) { ring.style.opacity = st.ring < 0 ? "0" : String(Math.round((1 - st.ring) * 0.9 * st.opacity * 1000) / 1000); ring.style.transform = `scale(${st.ring < 0 ? 0.4 : Math.round((0.45 + 1.5 * (1 - (1 - st.ring) ** 2)) * 1000) / 1000})`; } for (const d of Array.from(el.querySelectorAll(".pslam-dust i"))) { if (st.dust < 0) { d.style.opacity = "0"; continue; } const a = (Number(d.getAttribute("data-a")) * Math.PI) / 180; const p = 1 - (1 - st.dust) ** 2; const r = size * (0.25 + 0.75 * p); const fall = size * 0.35 * st.dust * st.dust; d.style.opacity = String(Math.round((1 - st.dust) * st.opacity * 1000) / 1000); d.style.transform = `translate(${Math.round(Math.cos(a) * r * 10) / 10}px, ${Math.round((Math.sin(a) * r * 0.55 + fall) * 10) / 10}px) scale(${Math.round((1.4 - st.dust) * 100) / 100})`; } } } /** * The units of a plan at item second `s` as setSlamState takes them: `p` a * slam (slamPlan's, with `centers` from its layout), `dx`/`dy` how far its * words have moved since it was placed (a pan). */ export function slamListAt(p, s, dx = 0, dy = 0) { const st = slamStateAt({ span: p.span, fromScale: p.fx.fromScale }, s); if (!st) return []; const out = st.units.map((u) => ({ i: p.i, ...u, x: p.centers[u.k].x + dx, y: p.centers[u.k].y + dy })); // Its bar (slamLayout's `bar`), under the glyphs: drawn first. const b = p.bar ? slamBarAt(p.span, s) : null; if (b) out.unshift({ i: p.i, k: -1, x: p.bar.cx + dx, y: p.bar.cy + dy, opacity: b.opacity, rise: b.rise }); return out; }