Repository Public
1import { createCanvas, type Canvas } from "@napi-rs/canvas";2import { clamp01, easeOutCubic, easeOutExpo, ensureFonts, prog, rng, type Ctx } from "./canvas";34/**5 * SYSTÈME DE DESIGN VIDÉO de SP CLIP — partagé par les animations (motion.ts), le carton de fin (brand.ts) et l'habillage des plans6 * réels (compose.ts).7 *8 * - Identité : fond de marque #0b0c0f, accent or #e8c27a, texte #f2f3f5. La profondeur vient d'un décor animé (`makeBackdrop`) :9 * lumière chaude (or) + contre-lumière froide (acier) qui dérivent lentement, géométrie fine en parallaxe, particules, grain fixe,10 * vignettage. Le décor reste sombre (luminance moyenne ≈ 20–30 / 255) : le texte clair garde un contraste élevé et le filigrane11 * sa plaque lisible.12 * - Typographie : Instrument Serif (titrage, citations, slogan) + Inter (texte, chiffres, étiquettes).13 * - Grille : zones sûres par ratio (`SAFE`), hors filigrane (haut) et hors sous-titres / interfaces sociales (bas).14 * - Mouvement : tout élément entre (masque + montée, courbe « expo out »), le décor ne s'arrête jamais, tout sort avant la coupe.15 * - Déterminisme : aucun Math.random ; tout l'aléa vient de `rng(seed)`.16 */1718export type Kind = "wide" | "tall" | "square";19export const kindOf = (w: number, h: number): Kind => (w / h > 1.2 ? "wide" : w / h < 0.85 ? "tall" : "square");2021export const INK = {22 bg: "#0b0c0f", gold: "#e8c27a", goldHi: "#f8e6bd", goldLo: "#c8964a", text: "#f2f3f5", soft: "#cdd2db", muted: "#9aa0ab", dim: "#6c7482",23 steel: "#8497b5", hair: "rgba(255,255,255,0.11)", track: "rgba(255,255,255,0.06)",24} as const;25export const rgba = (rgb: readonly [number, number, number], a: number) => `rgba(${rgb[0]},${rgb[1]},${rgb[2]},${a.toFixed(4)})`;26export const GOLD: readonly [number, number, number] = [232, 194, 122];27export const STEEL: readonly [number, number, number] = [86, 122, 184];28export const EMBER: readonly [number, number, number] = [214, 126, 72];2930/**31 * Zones sûres du CONTENU (fractions de la trame). Haut : sous le filigrane. Bas : au-dessus de la bande des sous-titres incrustés32 * (`captionBand` de compose.ts) et, en 9:16, des interfaces des applis sociales.33 */34export const SAFE: Record<Kind, { x: number; top: number; bottom: number }> = {35 wide: { x: 0.085, top: 0.15, bottom: 0.2 },36 tall: { x: 0.085, top: 0.17, bottom: 0.3 },37 square: { x: 0.08, top: 0.14, bottom: 0.235 },38};3940/** Multiplie l'opacité courante (les opacités s'emboîtent) le temps d'un dessin. */41export function withAlpha(ctx: Ctx, a: number, draw: () => void): void {42 if (a <= 0.003) return;43 ctx.save();44 ctx.globalAlpha *= Math.min(1, a);45 draw();46 ctx.restore();47}4849// ── grain ────────────────────────────────────────────────────────────────────50const GRAIN = 256;51let grainTile: Canvas | null = null;52function grain(): Canvas {53 if (grainTile) return grainTile;54 const c = createCanvas(GRAIN, GRAIN);55 const g = c.getContext("2d");56 const img = g.createImageData(GRAIN, GRAIN);57 const r = rng(0x5eed1e);58 for (let i = 0; i < GRAIN * GRAIN; i++) {59 const v = r();60 img.data[i * 4] = img.data[i * 4 + 1] = img.data[i * 4 + 2] = v < 0.5 ? 0 : 255;61 img.data[i * 4 + 3] = Math.round(r() * r() * 26);62 }63 g.putImageData(img, 0, 0);64 grainTile = c;65 return c;66}67/**68 * Grain fin FIXE (tramage : supprime les bandes des dégradés sombres et donne de la matière). Il ne change pas d'une trame à l'autre :69 * un grain renouvelé à chaque image est incompressible — mesuré à 75 Mb/s sur un master 1080p à CRF 18, contre quelques Mb/s ainsi —70 * et les échelons HLS le transformeraient en bouillie. `phase` décale la tuile (une valeur par scène, pas par trame).71 */72export function drawGrain(ctx: Ctx, W: number, H: number, phase = 0, strength = 1): void {73 if (strength <= 0) return;74 const r = rng(0x9e37 + phase * 7919);75 const ox = Math.floor(r() * GRAIN), oy = Math.floor(r() * GRAIN);76 ctx.save();77 ctx.globalAlpha *= Math.min(1, strength);78 ctx.translate(-ox, -oy);79 ctx.fillStyle = ctx.createPattern(grain(), "repeat") ?? "rgba(0,0,0,0)";80 ctx.fillRect(ox, oy, W, H);81 ctx.restore();82}8384// ── décor animé ──────────────────────────────────────────────────────────────85export type BackdropVariant = "orbits" | "grid" | "beams";86export interface Backdrop { draw: (ctx: Ctx, t: number) => void }87interface Light { x: number; y: number; r: number; rgb: readonly [number, number, number]; a: number; ax: number; ay: number; period: number; phase: number }8889/**90 * Décor de marque animé. `variant` change la géométrie en parallaxe, `seed` la position des lumières et des particules,91 * `energy` (0–1,5) la vitesse et la densité, `focus` (fractions) l'endroit où la lumière chaude se concentre (derrière le sujet).92 * `intro` (s) : le décor « s'allume » en ouverture de scène.93 */94export function makeBackdrop(o: { width: number; height: number; seed?: number; variant?: BackdropVariant; energy?: number; focus?: { x: number; y: number }; intro?: number; fps?: number }): Backdrop {95 ensureFonts();96 const { width: W, height: H } = o;97 const u = Math.min(W, H) / 1080, M = Math.max(W, H);98 const energy = o.energy ?? 1;99 const r = rng((o.seed ?? 1) * 2654435761);100 const variant = o.variant ?? "orbits";101 const S = 8, lw = Math.ceil(W / S), lh = Math.ceil(H / S);102 const low = createCanvas(lw, lh);103 const lc = low.getContext("2d");104 const fx = o.focus?.x ?? 0.7, fy = o.focus?.y ?? 0.36;105 const speed = 0.55 + 0.45 * energy;106 const lights: Light[] = [107 { x: fx, y: fy, r: 0.62, rgb: GOLD, a: 0.2, ax: 0.07, ay: 0.05, period: 13 / speed, phase: r() * 6.28 },108 { x: 1 - fx + (r() - 0.5) * 0.2, y: 0.92 - fy * 0.3, r: 0.7, rgb: STEEL, a: 0.2, ax: 0.08, ay: 0.06, period: 17 / speed, phase: r() * 6.28 },109 { x: 0.2 + r() * 0.6, y: 0.15 + r() * 0.7, r: 0.3, rgb: EMBER, a: 0.075, ax: 0.14, ay: 0.1, period: 9 / speed, phase: r() * 6.28 },110 ];111 const particles = Array.from({ length: Math.round((variant === "grid" ? 12 : 20) * Math.min(1.5, 0.5 + energy * 0.5)) }, () => {112 const depth = 0.35 + r() * 0.65;113 return { x: r(), y: r(), depth, size: (1.2 + depth * 3.2) * u, a: 0.07 + depth * 0.2 * r(), sway: r() * 6.28, gold: r() < 0.7, tw: 2 + r() * 4 };114 });115 const beams = Array.from({ length: 4 }, (_, i) => ({ x: (i + r()) / 4, w: 0.06 + r() * 0.1, a: 0.022 + r() * 0.03, v: (0.006 + r() * 0.01) * (r() < 0.5 ? -1 : 1) }));116 const orbit = { cx: W * (fx > 0.5 ? 0.86 : 0.14), cy: H * (0.5 + (r() - 0.5) * 0.3), a0: r() * 6.28 };117 const intro = o.intro ?? 0.9;118119 const draw = (ctx: Ctx, t: number) => {120 const lit = intro > 0 ? 0.4 + 0.6 * easeOutCubic(t / intro) : 1;121 // 1. lumières + vignettage, en basse résolution (très lisses) puis agrandies122 lc.globalCompositeOperation = "source-over";123 const base = lc.createLinearGradient(0, 0, 0, lh);124 base.addColorStop(0, "#0e1015");125 base.addColorStop(1, "#090a0d");126 lc.fillStyle = base;127 lc.fillRect(0, 0, lw, lh);128 lc.globalCompositeOperation = "lighter";129 for (const L of lights) {130 const w = (2 * Math.PI * t) / L.period + L.phase;131 const cx = (L.x + L.ax * Math.sin(w)) * lw, cy = (L.y + L.ay * Math.cos(w * 0.8)) * lh;132 const rad = (L.r * M) / S * (1 + 0.06 * Math.sin(w * 1.3));133 const g = lc.createRadialGradient(cx, cy, 0, cx, cy, rad);134 const a = L.a * lit;135 g.addColorStop(0, rgba(L.rgb, a));136 g.addColorStop(0.45, rgba(L.rgb, a * 0.36));137 g.addColorStop(1, rgba(L.rgb, 0));138 lc.fillStyle = g;139 lc.fillRect(0, 0, lw, lh);140 }141 if (variant === "beams") {142 lc.save();143 lc.translate(lw / 2, lh / 2);144 lc.rotate(-0.42);145 for (const b of beams) {146 const x = ((((b.x + b.v * t * speed) % 1) + 1) % 1 - 0.5) * lw * 1.8, bw = b.w * lw;147 const g = lc.createLinearGradient(x - bw, 0, x + bw, 0);148 g.addColorStop(0, "rgba(255,244,220,0)");149 g.addColorStop(0.5, `rgba(255,244,220,${(b.a * lit).toFixed(4)})`);150 g.addColorStop(1, "rgba(255,244,220,0)");151 lc.fillStyle = g;152 lc.fillRect(x - bw, -lh * 1.5, 2 * bw, lh * 3);153 }154 lc.restore();155 }156 lc.globalCompositeOperation = "source-over";157 const v = lc.createRadialGradient(lw / 2, lh / 2, Math.min(lw, lh) * 0.35, lw / 2, lh / 2, Math.hypot(lw, lh) * 0.56);158 v.addColorStop(0, "rgba(0,0,0,0)");159 v.addColorStop(1, "rgba(0,0,0,0.62)");160 lc.fillStyle = v;161 lc.fillRect(0, 0, lw, lh);162 ctx.save();163 ctx.globalAlpha = 1;164 ctx.imageSmoothingEnabled = true;165 ctx.imageSmoothingQuality = "low"; // agrandissement bilinéaire : suffisant pour des dégradés lisses (le grain masque le reste), 2× plus rapide166 ctx.drawImage(low, 0, 0, lw, lh, 0, 0, W, H);167168 // 2. géométrie fine en parallaxe169 if (variant === "orbits") {170 const rot = orbit.a0 + t * 0.05 * speed;171 ctx.lineWidth = Math.max(1, 1.4 * u);172 [0.2, 0.31, 0.44, 0.6].forEach((k, i) => {173 ctx.strokeStyle = `rgba(255,255,255,${(0.1 - i * 0.014) * lit})`;174 ctx.setLineDash(i === 1 ? [2 * u, 14 * u] : i === 3 ? [28 * u, 22 * u] : []);175 ctx.lineDashOffset = (i === 1 ? -1 : 1) * t * 9 * u * speed;176 ctx.beginPath();177 ctx.arc(orbit.cx, orbit.cy, k * M, 0, Math.PI * 2);178 ctx.stroke();179 });180 ctx.setLineDash([]);181 // deux satellites or182 [[0.31, 1, 0.16], [0.44, -0.6, 0.11]].forEach(([k, dir, sp], i) => {183 const a = rot * (dir as number) * 2.2 + i * 2.4 + t * (sp as number) * speed;184 const x = orbit.cx + Math.cos(a) * (k as number) * M, y = orbit.cy + Math.sin(a) * (k as number) * M;185 const g = ctx.createRadialGradient(x, y, 0, x, y, 26 * u);186 g.addColorStop(0, rgba(GOLD, 0.5 * lit));187 g.addColorStop(1, rgba(GOLD, 0));188 ctx.fillStyle = g;189 ctx.fillRect(x - 26 * u, y - 26 * u, 52 * u, 52 * u);190 ctx.fillStyle = rgba(GOLD, 0.9 * lit);191 ctx.beginPath();192 ctx.arc(x, y, 3.4 * u, 0, Math.PI * 2);193 ctx.fill();194 });195 } else if (variant === "grid") {196 const step = 64 * u, ox = (t * 7 * u * speed) % step, oy = (t * 4 * u * speed) % step;197 const hx = W * (fx + 0.08 * Math.sin(t * 0.3)), hy = H * (fy + 0.06 * Math.cos(t * 0.23));198 const reach = M * 0.75;199 for (let y = -step + oy; y < H + step; y += step) for (let x = -step + ox; x < W + step; x += step) {200 const d = Math.hypot(x - hx, y - hy) / reach;201 const a = (0.02 + 0.17 * Math.max(0, 1 - d) ** 2) * lit;202 ctx.fillStyle = `rgba(255,255,255,${a.toFixed(3)})`;203 ctx.fillRect(x - 1.3 * u, y - 1.3 * u, 2.6 * u, 2.6 * u);204 }205 } else {206 // filets diagonaux qui glissent207 ctx.lineWidth = Math.max(1, 1.2 * u);208 const gap = 150 * u, off = (t * 12 * u * speed) % gap;209 for (let x = -H + off; x < W + gap; x += gap) {210 ctx.strokeStyle = `rgba(255,255,255,${0.035 * lit})`;211 ctx.beginPath();212 ctx.moveTo(x, H);213 ctx.lineTo(x + H * 0.48, 0);214 ctx.stroke();215 }216 }217 // 3. particules (poussière dans la lumière) : montée lente, profondeur = taille, vitesse et opacité218 for (const p of particles) {219 const y = ((((p.y - (t * (0.012 + 0.03 * p.depth) * speed)) % 1) + 1) % 1) * (H + 40 * u) - 20 * u;220 const x = p.x * W + Math.sin(t * 0.5 * speed + p.sway) * 26 * u * p.depth;221 const a = p.a * (0.6 + 0.4 * Math.sin(t * 6.28 / p.tw + p.sway)) * lit;222 ctx.fillStyle = p.gold ? rgba(GOLD, a) : `rgba(255,255,255,${(a * 0.8).toFixed(3)})`;223 ctx.beginPath();224 ctx.arc(x, y, p.size, 0, Math.PI * 2);225 ctx.fill();226 }227 // 4. grain228 drawGrain(ctx, W, H, (o.seed ?? 1) % 97);229 ctx.restore();230 };231 return { draw };232}233234// ── texte cinétique ──────────────────────────────────────────────────────────235export interface WordBox { text: string; x: number; w: number; line: number; index: number; em: boolean }236export interface TextBlock { fontOf: (em: boolean) => string; size: number; lh: number; lines: string[]; words: WordBox[]; widths: number[]; width: number; height: number; tracking: number }237238/**239 * Met en page des lignes déjà coupées, mot par mot (positions relatives au bord gauche de chaque ligne, ou à son centre si240 * `align: "center"`). `emphasis(i, mot)` désigne les mots composés dans la variante d'emphase de la police (italique).241 */242export function layoutBlock(probe: Ctx, lines: string[], o: { fontOf: (em: boolean) => string; size: number; lineHeight: number; align?: "left" | "center"; tracking?: number; emphasis?: (index: number, word: string, total: number) => boolean }): TextBlock {243 const tracking = o.tracking ?? 0;244 const total = lines.reduce((a, l) => a + l.split(/\s+/).filter(Boolean).length, 0);245 const words: WordBox[] = [], widths: number[] = [];246 probe.letterSpacing = `${tracking.toFixed(2)}px`;247 probe.font = o.fontOf(false);248 const space = probe.measureText("n n").width - probe.measureText("nn").width;249 let index = 0;250 lines.forEach((line, li) => {251 let x = 0;252 const start = words.length;253 for (const text of line.split(/\s+/).filter(Boolean)) {254 const em = o.emphasis?.(index, text, total) ?? false;255 probe.font = o.fontOf(em);256 const w = probe.measureText(text).width;257 words.push({ text, x, w, line: li, index, em });258 x += w + space;259 index++;260 }261 const width = Math.max(0, x - space);262 widths.push(width);263 if (o.align === "center") for (let i = start; i < words.length; i++) words[i].x -= width / 2;264 });265 probe.letterSpacing = "0px";266 return { fontOf: o.fontOf, size: o.size, lh: o.size * o.lineHeight, lines, words, widths, width: Math.max(0, ...widths), height: lines.length * o.size * o.lineHeight, tracking };267}268269/**270 * Dessine un bloc en révélation cinétique : chaque unité (mot ou ligne) monte derrière un masque, avec fondu.271 * `x`, `y` = origine de la première ligne de base. `out` (0→1) : sortie (les unités redescendent derrière le masque).272 */273export function drawKinetic(ctx: Ctx, b: TextBlock, x: number, y: number, o: { t: number; start: number; stagger: number; dur: number; unit?: "word" | "line"; color: string | CanvasGradient | ((w: WordBox) => string | CanvasGradient); out?: number }): void {274 const out = clamp01(o.out ?? 0);275 ctx.save();276 ctx.textAlign = "left";277 ctx.textBaseline = "alphabetic";278 ctx.letterSpacing = `${b.tracking.toFixed(2)}px`;279 const pad = b.size * 0.14;280 for (const w of b.words) {281 const k = o.unit === "line" ? w.line : w.index;282 const p = easeOutExpo(prog(o.t, o.start + k * o.stagger, o.dur)) * (1 - out);283 if (p <= 0.001) continue;284 const ly = y + w.line * b.lh;285 ctx.save();286 ctx.beginPath();287 ctx.rect(x + w.x - pad, ly - b.size * 1.02, w.w + 2 * pad, b.size * 1.36);288 ctx.clip();289 ctx.globalAlpha *= Math.min(1, p * 1.5);290 ctx.font = b.fontOf(w.em);291 ctx.fillStyle = typeof o.color === "function" ? o.color(w) : o.color;292 ctx.fillText(w.text, x + w.x, ly + (1 - p) * b.size * 0.92);293 ctx.restore();294 }295 ctx.restore();296}297298/** Dégradé or avec un reflet qui traverse (`sweep` 0→1 : position du reflet ; hors de [0,1] = pas de reflet). */299export function goldFill(ctx: Ctx, x0: number, x1: number, sweep: number): CanvasGradient {300 const g = ctx.createLinearGradient(x0, 0, x1, 0);301 const s = sweep;302 g.addColorStop(0, INK.gold);303 if (s > 0.06 && s < 0.94) {304 g.addColorStop(s - 0.06, INK.gold);305 g.addColorStop(s, INK.goldHi);306 g.addColorStop(s + 0.06, INK.gold);307 }308 g.addColorStop(1, INK.gold);309 return g;310}311312/** Halo radial doux (lumière derrière un sujet). */313export function drawHalo(ctx: Ctx, x: number, y: number, radius: number, rgb: readonly [number, number, number], alpha: number): void {314 if (alpha <= 0.002 || radius <= 0) return;315 const g = ctx.createRadialGradient(x, y, 0, x, y, radius);316 g.addColorStop(0, rgba(rgb, alpha));317 g.addColorStop(0.5, rgba(rgb, alpha * 0.32));318 g.addColorStop(1, rgba(rgb, 0));319 ctx.fillStyle = g;320 ctx.fillRect(x - radius, y - radius, 2 * radius, 2 * radius);321}322