Prototype lightning, twinkle and firefly particles in the visual lab

The Particles tab of the visual lab now previews three persistent particle
animations for mythic cards, drawn on a canvas inside the illustration or over
the whole card. Lightning bolts grow from the edges towards a random point near
the hero and pass behind a cut-out hero with the prismatic parallax. Twinkles
pop chosen motifs in and out with a light cross at their peak. Fireflies drift
on winding paths, pulse and move away from the pointer. Each animation offers a
palette, a zone and its own sliders, runs only on a large or hovered card, and
stays still under reduced motion. Nothing is saved on the variations yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Shinuwa 2026-11-22 16:07:22 +01:00
parent 9f70bea523
commit f77a0ca577
15 changed files with 1779 additions and 16 deletions

View file

@ -1,6 +1,10 @@
// Rôle : affiche les cartes Sokko TCG et pilote leur tilt, leurs finitions et leurs animations de révélation.
import { useEffect, useRef, useState } from "react";
import { CollectionCardBack } from "./CollectionCardBack.jsx";
import { resolveFlare } from "./holoFlares.js";
import { createFireflies } from "./holoFireflies.js";
import { createLightning } from "./holoLightning.js";
import { createTwinkle } from "./holoTwinkle.js";
import { MATCH_HOLO_PALETTE_ID, MATCH_HOLO_PALETTE_LABEL, resolveMythicOpeningStyle, resolveOpeningEffect } from "./openingEffects.js";
const STANDARD_CARD_LAYOUT = "standard";
@ -210,7 +214,66 @@ function particlePosition(index, count, intense, color) {
};
}
function CardFace({ entry, quantity, visual, size }) {
// Moteur de chaque animation de particules persistantes ; tous partagent la même interface.
const FLARE_ENGINES = { lightning: createLightning, twinkle: createTwinkle, fireflies: createFireflies };
// Particules d'une variation mythique : un canvas dans l'illustration ou sur toute la face, animé seulement quand la carte
// est affichée en grand ou survolée, visible et dans un onglet actif. Sous mouvement réduit, une image fixe. Sur toute la
// face, les éclairs visent toujours l'illustration, dont la boîte est mesurée dans le canvas.
function HoloFlareCanvas({ flare, behindSubject, size }) {
const canvasRef = useRef(null);
const colorsKey = flare.colors.join(",");
useEffect(() => {
const canvas = canvasRef.current;
const card = canvas?.closest(".nebula-card");
if (!canvas || !card) return undefined;
const engine = FLARE_ENGINES[flare.effect.id](canvas, { colors: colorsKey.split(","), core: flare.core, intensity: flare.intensity, level: flare.level, count: flare.count, motifId: flare.motifId, behindSubject });
const resize = () => {
const art = flare.scope === "card" ? canvas.parentElement?.querySelector(".nebula-card-art") : null;
const focus = art ? { x: art.offsetLeft, y: art.offsetTop, width: art.offsetWidth, height: art.offsetHeight } : null;
engine.resize(canvas.offsetWidth, canvas.offsetHeight, Math.min(2, window.devicePixelRatio || 1), focus);
};
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(canvas);
resize();
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
engine.renderStatic();
return () => { resizeObserver.disconnect(); engine.destroy(); };
}
let hovered = false;
let visible = true;
const update = () => engine.setActive(visible && !document.hidden && (size === "lg" || hovered));
const enter = () => { hovered = true; update(); };
const leave = () => { hovered = false; engine.setPointer(null); update(); };
const move = (event) => {
const bounds = canvas.getBoundingClientRect();
engine.setPointer({ x: (event.clientX - bounds.left) / bounds.width, y: (event.clientY - bounds.top) / bounds.height });
};
const intersection = new IntersectionObserver(([entry]) => { visible = entry.isIntersecting; update(); });
intersection.observe(canvas);
card.addEventListener("pointerenter", enter);
card.addEventListener("pointerleave", leave);
card.addEventListener("pointermove", move);
card.addEventListener("focus", enter);
card.addEventListener("blur", leave);
document.addEventListener("visibilitychange", update);
update();
return () => {
resizeObserver.disconnect();
intersection.disconnect();
card.removeEventListener("pointerenter", enter);
card.removeEventListener("pointerleave", leave);
card.removeEventListener("pointermove", move);
card.removeEventListener("focus", enter);
card.removeEventListener("blur", leave);
document.removeEventListener("visibilitychange", update);
engine.destroy();
};
}, [colorsKey, flare.effect.id, flare.core, flare.intensity, flare.level, flare.count, flare.motifId, flare.scope, behindSubject, size]);
return <canvas ref={canvasRef} className="nebula-card-flare" data-flare={flare.effect.id} data-flare-scope={flare.scope} data-behind-subject={behindSubject || undefined} aria-hidden="true" />;
}
function CardFace({ entry, quantity, visual, size, flare = null }) {
const { card, edition } = entry;
const finishIds = edition.finishIds || [];
const showName = size !== "sm";
@ -220,6 +283,12 @@ function CardFace({ entry, quantity, visual, size }) {
const image = (fullArt && card.fullImage) || card.image;
const parallax = PARALLAX_EFFECTS.has(visual.effectPreset?.id) ? resolveParallaxLayers(card, fullArt, image) : null;
const loading = size === "lg" ? "eager" : "lazy";
// Dans l'illustration, derrière un héros détouré, les éclairs passent entre le décor et lui ; scintillements et lucioles,
// eux, restent devant pour être vus. Sur toute la carte, les particules couvrent la face sous le texte, devant le héros.
const cardScope = flare?.scope === "card";
const behindSubject = Boolean(flare?.effect.id === "lightning" && !cardScope && parallax && parallax.layers.length > 1);
const flareCanvas = flare && <HoloFlareCanvas flare={flare} behindSubject={behindSubject} size={size} />;
const artFlare = cardScope ? null : flareCanvas;
return <div
className="nebula-card-face"
data-card-layout={visual.layout}
@ -230,17 +299,18 @@ function CardFace({ entry, quantity, visual, size }) {
>
<div className={`nebula-card-art ${image ? "has-image" : ""}`} data-parallax-setup={parallax?.setup} aria-hidden="true">
{/* Chaque calque porte sa profondeur ; son image sert aussi de masque au reflet prismatique qui ne touche que lui. */}
{parallax ? parallax.layers.map((layer, index) => <span
{parallax ? parallax.layers.flatMap((layer, index) => [layer.role === "subject" && behindSubject && artFlare ? <span key="flare" className="nebula-card-flare-plane">{artFlare}</span> : null, <span
key={layer.id}
className="nebula-card-depth-layer"
data-depth-layer={layer.id}
data-depth-role={layer.role}
style={{ "--layer-depth": layer.depth, "--layer-depth-abs": Math.abs(layer.depth), "--layer-index": index, "--layer-image": `url("${layer.src}")`, zIndex: index }}
style={{ "--layer-depth": layer.depth, "--layer-depth-abs": Math.abs(layer.depth), "--layer-index": index, "--layer-image": `url("${layer.src}")`, zIndex: index * 2 }}
>
<img src={layer.src} alt="" loading={loading} decoding="async" />
{layer.role === "backdrop" && <span className="nebula-card-depth-tint" />}
<span className="nebula-card-depth-foil" />
</span>) : image ? <img src={image} alt="" loading={loading} decoding="async" /> : <span className="nebula-card-placeholder-mark" />}
</span>]) : image ? <img src={image} alt="" loading={loading} decoding="async" /> : <span className="nebula-card-placeholder-mark" />}
{!behindSubject && artFlare}
</div>
{showName && <h3><span>{card.name}</span></h3>}
{showDetails && <div className="nebula-card-copy">
@ -256,6 +326,7 @@ function CardFace({ entry, quantity, visual, size }) {
{SHARD_FACETS.map((facet) => <i key={facet} data-facet={facet} />)}
</span>}
</>}
{cardScope && flareCanvas}
<span className="nebula-card-glare" aria-hidden="true" />
</div>;
}
@ -265,6 +336,7 @@ export function NebulaCard({ catalog, entry, quantity = 0, size = "lg", faceUp =
const rarity = entry.edition?.rarity || "common";
const finish = entry.edition?.finishIds?.join(" ") || "standard";
const visual = destinationVisual(entry.card, resolveFinishVisual(entry.edition, catalog));
const flare = resolveFlare(entry.edition, catalog, visual);
const openingVisual = resolveOpeningVisual(rarity, entry.card.id, entry.card.collectionId, catalog, visual);
// Les particules n'existent que pendant l'ouverture : une carte face visible n'en déclare aucune.
const displayedParticlePreset = faceUp ? null : openingVisual.particlePreset;
@ -284,6 +356,7 @@ export function NebulaCard({ catalog, entry, quantity = 0, size = "lg", faceUp =
// Paliers de la variation (intensité de la palette, palier propre à l'effet) : le palier central n'a pas d'attribut.
"data-holo-intensity": visual.effectPreset ? entry.edition?.holoIntensity : undefined,
"data-holo-level": visual.effectPreset?.level ? entry.edition?.holoLevel : undefined,
"data-flare": flare?.effect.id,
"data-particle-preset": displayedParticlePreset?.id,
"data-particle-shape": displayedParticleShape?.id,
"data-particle-palette": displayedParticlePalette?.id,
@ -390,7 +463,7 @@ export function NebulaCard({ catalog, entry, quantity = 0, size = "lg", faceUp =
data-has-image={backCollection?.back?.image ? "true" : undefined}
style={backCollection?.back?.image ? { "--card-back-image": `url("${backCollection.back.image}")` } : undefined}
><CollectionCardBack collection={backCollection} /></span>
<CardFace entry={entry} quantity={quantity} visual={visual} size={cardSize} />
<CardFace entry={entry} quantity={quantity} visual={visual} size={cardSize} flare={revealPhase === "revealed" ? flare : null} />
</span>
{newBadge && revealPhase === "revealed" && <span className="nds-badge nebula-card-new-badge" aria-hidden="true">{newBadge}</span>}
</span>
@ -398,7 +471,7 @@ export function NebulaCard({ catalog, entry, quantity = 0, size = "lg", faceUp =
{particlesVisible && <span className="nebula-card-particles" aria-hidden="true">{rarity === "mythic" && <><span className="nebula-card-particle-ring-glow" data-glow="outer"><span><span /></span></span><span className="nebula-card-particle-ring-glow" data-glow="inner"><span><span /></span></span></>}{Array.from({ length: openingVisual.particlePreset.count }, (_, index) => <i key={index} style={particlePosition(index, openingVisual.particlePreset.count, rarity === "legendary" || rarity === "mythic", openingVisual.particlePalette?.colors[index % openingVisual.particlePalette.colors.length])} />)}</span>}
</button>;
}
const content = <div className="nebula-card-tilt-surface"><CardFace entry={entry} quantity={quantity} visual={visual} size={cardSize} /></div>;
const content = <div className="nebula-card-tilt-surface"><CardFace entry={entry} quantity={quantity} visual={visual} size={cardSize} flare={flare} /></div>;
return onSelect
? <button ref={cardRef} className="nebula-card nebula-card-select" data-card-size={cardSize} data-card-layout={visual.layout} data-card-kind={entry.card.kind} data-rarity={rarity} data-finish={finish} {...visualAttributes} type="button" onClick={onSelect} aria-label={selectLabel || `Voir ${entry.card.name}`} aria-pressed={selected}>{content}</button>
: <article ref={cardRef} className="nebula-card" data-card-size={cardSize} data-card-layout={visual.layout} data-card-kind={entry.card.kind} data-rarity={rarity} data-finish={finish} {...visualAttributes}>{content}</article>;

View file

@ -2,6 +2,7 @@
import { useState } from "react";
import { NebulaCard } from "../NebulaCard.jsx";
import { MATCH_HOLO_PALETTE_ID, MATCH_HOLO_PALETTE_LABEL, withCardOpeningSetting } from "../openingEffects.js";
import { flareEditionFields, NO_FLARE } from "../holoFlares.js";
import { DEFAULT_TUNING, tuningEditionFields } from "./effectTuning.js";
import { availableEffects, fittingFormat } from "./finishAvailability.js";
import { SwatchDropdown } from "./SwatchDropdown.jsx";
@ -61,7 +62,7 @@ function HolographicBench({ catalog, effects: allEffects, previewCard }) {
const [effectId, setEffectId] = useState(effects[0]?.effect.id || "");
const [value, setValue] = useState(() => {
const finish = catalog.finishes.find((item) => item.effectPresetId === effectId);
return { formatId: "standard", paletteId: finish?.paletteId || catalog.effectPalettes[0]?.id || "", intensity: DEFAULT_TUNING, level: DEFAULT_TUNING };
return { formatId: "standard", paletteId: finish?.paletteId || catalog.effectPalettes[0]?.id || "", intensity: DEFAULT_TUNING, level: DEFAULT_TUNING, flare: NO_FLARE };
});
const { effect, editions } = effects.find((item) => item.effect.id === effectId) || effects[0] || {};
if (!effect) return null;
@ -70,7 +71,7 @@ function HolographicBench({ catalog, effects: allEffects, previewCard }) {
const formatId = fittingFormat(catalog, previewCard, preset.id, value.formatId);
const finish = catalog.finishes.find((item) => item.effectPresetId === preset.id && item.paletteId === value.paletteId && item.formatId === formatId)
|| catalog.finishes.find((item) => item.effectPresetId === preset.id);
return { id: `admin-effect-preview-${preset.id}`, cardId: previewCard.id, rarity: "mythic", finishIds: [finish?.id], promotional: false, ...tuningEditionFields(preset, value) };
return { id: `admin-effect-preview-${preset.id}`, cardId: previewCard.id, rarity: "mythic", finishIds: [finish?.id], promotional: false, ...tuningEditionFields(preset, value), ...flareEditionFields(value.flare) };
};
return <div className="nds-card nebula-admin-lab-bench">

View file

@ -2,7 +2,7 @@
// (vitesse, amplitude, taille des éclats) quand le catalogue lui en déclare un. Le niveau 3 est le rendu de référence.
import { DEFAULT_TUNING } from "./effectTuning.js";
function TuningRange({ scale, value, disabled, onChange }) {
export function TuningRange({ scale, value, disabled, onChange }) {
const valueLabel = scale.levels[value - 1];
return <label className="nebula-admin-tuning-range">
<span>{scale.label}<span className="nebula-admin-tuning-value">{valueLabel}</span></span>

View file

@ -3,7 +3,8 @@
import { useState } from "react";
import { SelectDropdown } from "../../../components/SelectDropdown.jsx";
import { Tabs } from "../../../components/Tabs.jsx";
import { EffectTuningFields } from "./EffectTuningFields.jsx";
import { DEFAULT_FLARE_SCOPE, DEFAULT_FLARE_TUNING, FLARE_EFFECTS, FLARE_SCOPES, MATCH_HOLO_FLARE_LABEL, MATCH_HOLO_FLARE_PALETTE } from "../holoFlares.js";
import { EffectTuningFields, TuningRange } from "./EffectTuningFields.jsx";
import { variationSummary } from "./effectTuning.js";
import { effectMissingHint, fittingFormat, formatMissingHint } from "./finishAvailability.js";
import { SwatchDropdown } from "./SwatchDropdown.jsx";
@ -16,6 +17,8 @@ const enabledFirst = (left, right) => Number(left.disabled) - Number(right.disab
// `value` : { formatId, effectPresetId, paletteId, intensity, level }. `showEffect` masque le menu d'effet quand l'effet se
// choisit ailleurs (miniatures de l'Atelier). Un format ou un effet dont la carte n'a pas les fichiers reste visible mais
// désactivé, en bas de liste, avec la liste des fichiers manquants.
// `value.flare` ({ id, motifId, paletteId, scope, intensity, level, count }) rend l'onglet Particules réglable ; sans lui (éditeur des variations,
// tant que les particules ne s'enregistrent pas), l'onglet reste en lecture seule.
// `children` reçoit les actions (Enregistrer, Annuler) sous le résumé.
export function VariationCustomizer({ catalog, card, value, showEffect = true, disabled = false, notice = null, onChange, children = null }) {
const [tab, setTab] = useState("holo");
@ -29,6 +32,9 @@ export function VariationCustomizer({ catalog, card, value, showEffect = true, d
const hint = effectMissingHint(catalog, card, item.id);
return { value: item.id, label: item.label, disabled: Boolean(hint), hint };
}).toSorted(enabledFirst);
const flare = value.flare;
const flareEffect = FLARE_EFFECTS.find((item) => item.id === flare?.id);
const changeFlare = (next) => onChange({ ...value, flare: { ...flare, ...next } });
const changeEffect = (effectPresetId) => onChange({ ...value, effectPresetId, formatId: fittingFormat(catalog, card, effectPresetId, value.formatId) });
return <div className="nebula-admin-customizer">
<Tabs className="nebula-admin-customizer-tabs" tabs={TABS} activeTab={tab} onChange={setTab} />
@ -40,9 +46,19 @@ export function VariationCustomizer({ catalog, card, value, showEffect = true, d
<SwatchDropdown className="nebula-admin-inline-field" label="Palette" accessibleLabel="Palette holographique" value={value.paletteId} options={catalog.effectPalettes} disabled={disabled} onChange={(paletteId) => onChange({ ...value, paletteId })} />
</div>
<EffectTuningFields catalog={catalog} effect={effect} value={value} disabled={disabled} onChange={(tuning) => onChange({ ...value, ...tuning })} />
</> : flare ? <>
<div className="nebula-admin-customizer-choices">
<SelectDropdown className="nebula-admin-inline-field" label="Animation" size="sm" value={flare.id} disabled={disabled} options={[{ value: "", label: "Aucune" }, ...FLARE_EFFECTS.map((item) => ({ value: item.id, label: item.label }))]} onChange={(id) => changeFlare({ id })} />
{flareEffect?.motifs && <SelectDropdown className="nebula-admin-inline-field" label="Motif" size="sm" value={flareEffect.motifs.some((item) => item.id === flare.motifId) ? flare.motifId : flareEffect.motifs[0].id} disabled={disabled} options={flareEffect.motifs.map((item) => ({ value: item.id, label: item.label }))} onChange={(motifId) => changeFlare({ motifId })} />}
{flareEffect && <SwatchDropdown className="nebula-admin-inline-field" label="Palette" accessibleLabel="Palette des particules" value={flare.paletteId} options={[{ id: MATCH_HOLO_FLARE_PALETTE, label: MATCH_HOLO_FLARE_LABEL }, ...catalog.effectPalettes]} disabled={disabled} onChange={(paletteId) => changeFlare({ paletteId })} />}
{flareEffect && <SelectDropdown className="nebula-admin-inline-field" label="Zone" size="sm" value={flare.scope || DEFAULT_FLARE_SCOPE} disabled={disabled} options={FLARE_SCOPES.map((item) => ({ value: item.id, label: item.label }))} onChange={(scope) => changeFlare({ scope })} />}
</div>
{flareEffect && <div className="nebula-admin-tuning">
{flareEffect.tunings.map((scale) => <TuningRange key={scale.key} scale={scale} value={flare[scale.key] || DEFAULT_FLARE_TUNING} disabled={disabled} onChange={(next) => changeFlare({ [scale.key]: next })} />)}
</div>}
</> : <>
<SelectDropdown className="nebula-admin-inline-field" label="Animation" size="sm" disabled value="" options={[{ value: "", label: "Aucune" }]} onChange={() => {}} />
<p className="nebula-form-help">Les animations de particules arrivent une par une.</p>
<p className="nebula-form-help">Les particules s’essaient d’abord dans l’Atelier visuel ; elles s’enregistreront ici une fois validées.</p>
</>}
</div>
{notice}

View file

@ -1,5 +1,7 @@
// Rôle : valeurs communes des paliers d'une variation mythique (intensité de la palette, palier propre à l'effet), de 1 à 5,
// et résumé d'une ligne de ses réglages.
import { FLARE_EFFECTS } from "../holoFlares.js";
export const DEFAULT_TUNING = 3;
// Un palier central n'est pas transmis : la carte garde son rendu de référence, sans attribut.
@ -24,6 +26,6 @@ export function variationSummary(catalog, card, value) {
card.fullImage && format?.label,
`${catalog.effectIntensity.label} ${lower(intensity)}`,
effect?.level && `${effect.level.label} ${lower(effect.level.levels[(value.level ?? DEFAULT_TUNING) - 1])}`,
"Particules : aucune"
`Particules : ${lower(FLARE_EFFECTS.find((item) => item.id === value.flare?.id)?.label) || "aucune"}`
].filter(Boolean).join(" · ");
}

View file

@ -0,0 +1,152 @@
// Rôle : sprites des motifs de particules persistantes (scintillements, lucioles) : silhouettes procédurales de rayon 1,
// rendues une fois par couleur avec halo et cœur clair, puis seulement recopiées à chaque image.
const TAU = Math.PI * 2;
export const SPRITE_SIZE = 96;
// Angle d'affichage d'un motif. La bulle ne tourne jamais : son reflet reste en haut à droite, comme la lumière qui
// l'éclaire. Le cœur reste à l'endroit, à peine incliné. Les autres motifs prennent l'angle libre qu'on leur donne.
export function motifAngle(motifId, angle) {
if (motifId === "bubble") return 0;
if (motifId === "heart") return Math.sin(angle) * 0.25;
return angle;
}
// Silhouette d'un motif centrée sur l'origine, de rayon 1 ; `stroke` pour les motifs en traits.
function motifPath(context, motifId) {
context.beginPath();
if (motifId === "four-point-star" || motifId === "glint") {
const k = motifId === "glint" ? 0.06 : 0.16;
context.moveTo(0, -1);
context.quadraticCurveTo(k, -k, 1, 0);
context.quadraticCurveTo(k, k, 0, 1);
context.quadraticCurveTo(-k, k, -1, 0);
context.quadraticCurveTo(-k, -k, 0, -1);
} else if (motifId === "star") {
for (let index = 0; index < 10; index++) {
const radius = index % 2 ? 0.45 : 1;
const angle = -Math.PI / 2 + (index * Math.PI) / 5;
context.lineTo(Math.cos(angle) * radius, Math.sin(angle) * radius);
}
context.closePath();
} else if (motifId === "diamond") {
context.moveTo(0, -1);
context.lineTo(0.62, 0);
context.lineTo(0, 1);
context.lineTo(-0.62, 0);
context.closePath();
} else if (motifId === "heart") {
context.moveTo(0, 0.9);
context.bezierCurveTo(-1.1, 0.1, -0.85, -0.85, 0, -0.35);
context.bezierCurveTo(0.85, -0.85, 1.1, 0.1, 0, 0.9);
} else if (motifId === "snowflake") {
for (let arm = 0; arm < 6; arm++) {
const angle = (arm * Math.PI) / 3;
const point = (radius, offset = 0) => [Math.cos(angle + offset) * radius, Math.sin(angle + offset) * radius];
context.moveTo(0, 0);
context.lineTo(...point(1));
context.moveTo(...point(0.55));
context.lineTo(...point(0.8, 0.32));
context.moveTo(...point(0.55));
context.lineTo(...point(0.8, -0.32));
}
} else if (motifId === "firefly") {
context.arc(0, 0, 0.55, 0, TAU);
} else {
context.arc(0, 0, 1, 0, TAU);
}
}
// Bulle : une sphère translucide (voile coloré et contour lumineux) avec son reflet clair décalé en haut à droite, aux
// bords à peine adoucis par un dégradé (un filtre de flou n'est pas pris en charge partout sur un canvas).
function bubble(context, radius, color, core) {
context.save();
context.scale(radius, radius);
context.beginPath();
context.arc(0, 0, 1, 0, TAU);
context.globalAlpha = 0.28;
context.fillStyle = color;
context.fill();
context.globalAlpha = 1;
context.lineWidth = 0.09;
context.strokeStyle = color;
context.shadowColor = color;
context.shadowBlur = 6;
context.stroke();
context.shadowBlur = 0;
const highlight = context.createRadialGradient(0.36, -0.36, 0, 0.36, -0.36, 0.3);
highlight.addColorStop(0, core);
highlight.addColorStop(0.75, core);
highlight.addColorStop(1, "transparent");
context.globalAlpha = 0.9;
context.fillStyle = highlight;
context.beginPath();
context.arc(0.36, -0.36, 0.3, 0, TAU);
context.fill();
context.restore();
}
// Sprite d'un motif dans une couleur : halo, silhouette colorée lumineuse, puis cœur clair. Rendu une seule fois (le flou y
// est permis), puis seulement recopié à chaque image.
export function motifSprite(motifId, color, core) {
const canvas = document.createElement("canvas");
canvas.width = SPRITE_SIZE;
canvas.height = SPRITE_SIZE;
const context = canvas.getContext("2d");
const half = SPRITE_SIZE / 2;
const halo = context.createRadialGradient(half, half, 0, half, half, half);
halo.addColorStop(0, color);
halo.addColorStop(0.2, color);
// La luciole rayonne plus loin que les motifs dessinés.
halo.addColorStop(motifId === "firefly" ? 1 : 0.75, "transparent");
// La luciole est surtout un halo : petit cœur, large lueur.
context.globalAlpha = motifId === "bubble" ? 0.3 : motifId === "firefly" ? 0.8 : 0.55;
context.fillStyle = halo;
context.fillRect(0, 0, SPRITE_SIZE, SPRITE_SIZE);
context.globalAlpha = 1;
context.translate(half, half);
if (motifId === "bubble") {
bubble(context, half * 0.34, color, core);
return canvas;
}
const stroked = motifId === "snowflake";
for (const [scale, style, blur, width] of [[0.34, color, 10, 0.16], [0.2, core, 4, 0.1]]) {
context.save();
context.scale(half * scale, half * scale);
context.shadowColor = color;
context.shadowBlur = blur;
motifPath(context, motifId);
if (stroked) {
context.lineCap = "round";
context.lineWidth = width;
context.strokeStyle = style;
context.stroke();
} else {
context.fillStyle = style;
context.fill();
}
context.restore();
}
return canvas;
}
// Éclat en croix de l'apogée : deux traits fins dégradés, clairs au centre.
export function streakSprite(color, core) {
const canvas = document.createElement("canvas");
canvas.width = SPRITE_SIZE * 2;
canvas.height = SPRITE_SIZE * 2;
const context = canvas.getContext("2d");
const size = SPRITE_SIZE * 2;
for (const vertical of [false, true]) {
const gradient = vertical ? context.createLinearGradient(0, 0, 0, size) : context.createLinearGradient(0, 0, size, 0);
gradient.addColorStop(0, "transparent");
gradient.addColorStop(0.4, color);
gradient.addColorStop(0.5, core);
gradient.addColorStop(0.6, color);
gradient.addColorStop(1, "transparent");
context.fillStyle = gradient;
const thickness = vertical ? 4 : 5;
if (vertical) context.fillRect(size / 2 - thickness / 2, size * 0.18, thickness, size * 0.64);
else context.fillRect(0, size / 2 - thickness / 2, size, thickness);
}
return canvas;
}

View file

@ -0,0 +1,200 @@
// Rôle : moteur des lucioles holographiques d'une carte mythique (Canvas 2D) : de petites lueurs qui flottent sur des
// trajectoires sinueuses, pulsent doucement, apparaissent et s'éteignent en chemin, et s'écartent du pointeur. Nombre moyen,
// vitesse et intensité réglables ; motifs partagés avec les scintillements ; temps réel ; aucune boucle au repos. Même
// interface que les autres moteurs de particules.
import { motifAngle, motifSprite, SPRITE_SIZE } from "./flareSprites.js";
const TAU = Math.PI * 2;
export const FIREFLY_MOTIFS = [
{ id: "firefly", label: "Luciole" },
{ id: "four-point-star", label: "Étoile à quatre branches" },
{ id: "star", label: "Étoile" },
{ id: "heart", label: "Cœur" },
{ id: "snowflake", label: "Flocon" },
{ id: "bubble", label: "Bulle" }
];
// Paliers 1 à 5 : nombre moyen de lucioles (illustration d'une carte `lg`), vitesse de vol en fraction de la largeur par
// seconde (et durée de vie qui raccourcit avec elle), intensité (taille et éclat).
export const FIREFLY_COUNTS = [4, 6, 8, 12, 16];
const SPEED = [0.03, 0.045, 0.065, 0.09, 0.125];
const LIFETIME_MS = [8000, 6800, 5600, 4600, 3800];
const INTENSITY_SCALE = [0.6, 0.75, 0.9, 1.1, 1.35];
const REFERENCE_AREA = 280 * 240;
// Opacité selon l'âge relatif : apparition sur 20 % de la vie, extinction sur les 25 derniers.
export function fireflyFade(t) {
if (t <= 0 || t >= 1) return 0;
if (t < 0.2) return t / 0.2;
if (t > 0.75) return (1 - t) / 0.25;
return 1;
}
// Cap d'une luciole : une direction de base que deux sinusoïdes de fréquences et phases propres font onduler.
export function fireflyHeading(firefly, seconds) {
return firefly.heading + Math.sin(seconds * firefly.wobble[0] + firefly.phase[0]) * 1.1 + Math.sin(seconds * firefly.wobble[1] + firefly.phase[1]) * 0.6;
}
export function createFireflies(canvas, options) {
const context = canvas.getContext("2d");
const random = options.random || Math.random;
let settings = { ...options };
let size = { width: 0, height: 0, ratio: 1 };
let sprites = [];
let flies = [];
let pointer = null;
let active = false;
let frame = 0;
let last = 0;
let nextSpawn = 0;
let destroyed = false;
const intensity = () => INTENSITY_SCALE[(settings.intensity || 3) - 1];
const lifetime = () => LIFETIME_MS[(settings.level || 3) - 1];
const speed = () => SPEED[(settings.level || 3) - 1] * size.width;
const areaFactor = () => Math.min(1.6, Math.max(0.3, (size.width * size.height) / REFERENCE_AREA));
const average = () => FIREFLY_COUNTS[(settings.count || 3) - 1] * areaFactor();
const sizeFactor = () => Math.min(1.2, Math.max(0.5, Math.min(size.width, size.height) / 240));
function buildSprites() {
sprites = settings.colors.map((color) => motifSprite(settings.motifId || "firefly", color, settings.core || "#ffffff"));
}
// `age` (0 à 1) permet de semer une première volée déjà en vol, pour qu'elles n'apparaissent pas toutes ensemble.
function spawn(now, age = 0) {
const life = lifetime() * (0.75 + random() * 0.5);
flies.push({
x: (0.08 + random() * 0.84) * size.width,
y: (0.1 + random() * 0.82) * size.height,
born: now - age * life,
life,
// Légère tendance à monter, comme une lueur portée par l'air chaud.
heading: -Math.PI / 2 + (random() - 0.5) * 2.6,
wobble: [0.35 + random() * 0.5, 0.9 + random() * 0.9],
phase: [random() * TAU, random() * TAU],
pulse: [1.4 + random() * 1.6, random() * TAU],
speed: 0.7 + random() * 0.6,
radius: (6 + random() ** 2 * 6) * intensity() * sizeFactor(),
color: Math.floor(random() * settings.colors.length),
rotation: random() * TAU
});
nextSpawn = now + (lifetime() / average()) * (0.5 + random());
}
function move(fly, now, elapsed) {
const seconds = now / 1000;
const heading = fireflyHeading(fly, seconds);
let vx = Math.cos(heading) * speed() * fly.speed;
let vy = Math.sin(heading) * speed() * fly.speed;
// Près des bords, elles reviennent doucement vers l'intérieur.
const margin = 0.08;
if (fly.x < size.width * margin) vx += speed();
if (fly.x > size.width * (1 - margin)) vx -= speed();
if (fly.y < size.height * margin) vy += speed();
if (fly.y > size.height * (1 - margin)) vy -= speed();
// Elles s'écartent du pointeur qui s'approche.
if (pointer) {
const dx = fly.x - pointer.x * size.width;
const dy = fly.y - pointer.y * size.height;
const distance = Math.hypot(dx, dy) || 1;
const reach = size.width * 0.22;
if (distance < reach) {
const push = (1 - distance / reach) * speed() * 3;
vx += (dx / distance) * push;
vy += (dy / distance) * push;
}
}
fly.x += (vx * elapsed) / 1000;
fly.y += (vy * elapsed) / 1000;
}
function drawFly(fly, alpha, glow) {
const spriteSize = (fly.radius * 2 * SPRITE_SIZE) / (SPRITE_SIZE * 0.34) * (0.85 + 0.15 * glow);
context.save();
context.translate(fly.x, fly.y);
context.rotate(motifAngle(settings.motifId, fly.rotation));
context.globalAlpha = alpha * (0.65 + 0.35 * glow);
context.drawImage(sprites[fly.color], -spriteSize / 2, -spriteSize / 2, spriteSize, spriteSize);
context.restore();
}
function draw(now) {
const { width, height, ratio } = size;
context.setTransform(ratio, 0, 0, ratio, 0, 0);
context.clearRect(0, 0, width, height);
context.globalCompositeOperation = "lighter";
const seconds = now / 1000;
for (const fly of flies) {
// Pulsation propre à chaque luciole : elle s'avive et se voile à son rythme.
const glow = 0.5 + 0.5 * Math.sin(seconds * fly.pulse[0] + fly.pulse[1]);
drawFly(fly, fireflyFade((now - fly.born) / fly.life), glow);
}
context.globalAlpha = 1;
context.globalCompositeOperation = "source-over";
}
function tick(now) {
frame = 0;
if (destroyed || !size.width) return;
const elapsed = last ? Math.min(50, now - last) : 16;
last = now;
if (active && !flies.length) {
const count = Math.round(average());
for (let index = 0; index < count; index++) spawn(now, random() * 0.6);
}
while (active && now >= nextSpawn && flies.length < average() * 1.6) spawn(now);
flies = flies.filter((fly) => now - fly.born < fly.life);
for (const fly of flies) move(fly, now, elapsed);
draw(now);
if (active || flies.length) frame = requestAnimationFrame(tick);
else {
last = 0;
context.clearRect(0, 0, size.width, size.height);
}
}
const schedule = () => {
if (!frame && !destroyed) frame = requestAnimationFrame(tick);
};
buildSprites();
return {
resize(width, height, ratio = 1) {
size = { width, height, ratio };
canvas.width = Math.max(1, Math.round(width * ratio));
canvas.height = Math.max(1, Math.round(height * ratio));
flies = [];
if (active) schedule();
},
setActive(next) {
active = next;
if (active) schedule();
},
setPointer(next) {
pointer = next;
},
setOptions(next) {
settings = { ...settings, ...next };
buildSprites();
},
// Mouvement réduit : quelques lueurs immobiles.
renderStatic() {
if (!size.width) return;
flies = [];
const count = Math.max(2, Math.round(average() / 2));
for (let index = 0; index < count; index++) spawn(0);
const { width, height, ratio } = size;
context.setTransform(ratio, 0, 0, ratio, 0, 0);
context.clearRect(0, 0, width, height);
context.globalCompositeOperation = "lighter";
for (const fly of flies) drawFly(fly, 0.7, 0.6);
context.globalCompositeOperation = "source-over";
flies = [];
},
destroy() {
destroyed = true;
cancelAnimationFrame(frame);
}
};
}

View file

@ -0,0 +1,85 @@
// Rôle : particules persistantes d'une variation mythique (distinctes des particules d'ouverture) : les animations
// disponibles, leurs réglages, et la résolution des réglages d'une édition (animation, motif, palette, zone, paliers).
// Prototype de l'Atelier visuel : les animations entreront au catalogue quand elles seront enregistrées sur les variations.
import { FIREFLY_COUNTS, FIREFLY_MOTIFS } from "./holoFireflies.js";
import { TWINKLE_COUNTS, TWINKLE_MOTIFS } from "./holoTwinkle.js";
export const DEFAULT_FLARE_TUNING = 3;
export const MATCH_HOLO_FLARE_PALETTE = "match-holo";
export const MATCH_HOLO_FLARE_LABEL = "Comme le holo";
const INTENSITY = { key: "intensity", label: "Intensité", levels: ["Très douce", "Douce", "Normale", "Intense", "Très intense"] };
// Chaque animation déclare ses curseurs (paliers de 1 à 5, le 3 au centre) et, le cas échéant, ses motifs.
export const FLARE_EFFECTS = [
{
id: "lightning",
label: "Éclairs",
tunings: [INTENSITY, { key: "level", label: "Fréquence", levels: ["Très rare", "Rare", "Normale", "Fréquente", "Déchaînée"] }]
},
{
id: "twinkle",
label: "Scintillements",
motifs: TWINKLE_MOTIFS,
tunings: [
{ key: "count", label: "Nombre", levels: TWINKLE_COUNTS.map((count) => `≈ ${count}`) },
{ key: "level", label: "Vitesse", levels: ["Très lente", "Lente", "Normale", "Rapide", "Très rapide"] },
INTENSITY
]
},
{
id: "fireflies",
label: "Lucioles",
motifs: FIREFLY_MOTIFS,
tunings: [
{ key: "count", label: "Nombre", levels: FIREFLY_COUNTS.map((count) => `≈ ${count}`) },
{ key: "level", label: "Vitesse", levels: ["Très lente", "Lente", "Normale", "Rapide", "Très rapide"] },
INTENSITY
]
}
];
// Zone des particules : l'illustration seule (par défaut) ou toute la carte, utile aux cartes à illustration carrée.
export const DEFAULT_FLARE_SCOPE = "art";
export const FLARE_SCOPES = [{ id: "art", label: "Illustration" }, { id: "card", label: "Toute la carte" }];
export const NO_FLARE = { id: "", motifId: "", paletteId: MATCH_HOLO_FLARE_PALETTE, intensity: DEFAULT_FLARE_TUNING, level: DEFAULT_FLARE_TUNING, count: DEFAULT_FLARE_TUNING, scope: DEFAULT_FLARE_SCOPE };
const TUNING_FIELDS = { intensity: "flareIntensity", level: "flareLevel", count: "flareCount" };
const effectOf = (id) => FLARE_EFFECTS.find((item) => item.id === id);
// Motif retenu : celui choisi s'il appartient à l'animation, sinon le premier de sa liste.
const motifOf = (effect, motifId) => (effect?.motifs ? (effect.motifs.some((item) => item.id === motifId) ? motifId : effect.motifs[0].id) : null);
// Champs portés par l'édition ; les paliers centraux, le motif par défaut, la palette héritée et la zone par défaut ne sont
// pas transmis, ni les réglages que l'animation n'a pas.
export function flareEditionFields(flare) {
const effect = effectOf(flare?.id);
if (!effect) return {};
const motifId = motifOf(effect, flare.motifId);
return {
flareId: effect.id,
...(motifId && motifId !== effect.motifs[0].id ? { flareMotifId: motifId } : {}),
...(flare.paletteId && flare.paletteId !== MATCH_HOLO_FLARE_PALETTE ? { flarePaletteId: flare.paletteId } : {}),
...Object.fromEntries(effect.tunings.filter(({ key }) => flare[key] && flare[key] !== DEFAULT_FLARE_TUNING).map(({ key }) => [TUNING_FIELDS[key], flare[key]])),
...(flare.scope && flare.scope !== DEFAULT_FLARE_SCOPE ? { flareScope: flare.scope } : {})
};
}
// Réglages affichés pour une édition, ou null : sans palette explicite, les particules prennent celle du holo.
export function resolveFlare(edition, catalog, finishVisual) {
const effect = effectOf(edition?.flareId);
if (!effect || !finishVisual?.effectPreset) return null;
const palette = edition.flarePaletteId ? catalog?.effectPalettes?.find((item) => item.id === edition.flarePaletteId) : finishVisual.palette;
if (!palette) return null;
const scope = FLARE_SCOPES.some((item) => item.id === edition.flareScope) ? edition.flareScope : DEFAULT_FLARE_SCOPE;
return {
effect,
motifId: motifOf(effect, edition.flareMotifId),
colors: palette.colors,
core: palette.highlight,
intensity: edition.flareIntensity || DEFAULT_FLARE_TUNING,
level: edition.flareLevel || DEFAULT_FLARE_TUNING,
count: edition.flareCount || DEFAULT_FLARE_TUNING,
scope
};
}

View file

@ -0,0 +1,237 @@
// Rôle : moteur des éclairs holographiques d'une carte mythique, dessinés sur un Canvas 2D posé dans l'illustration. Des
// éclairs fractals partent des bords, progressent vers un point libre autour du héros avec une pointe lumineuse, se
// ramifient, puis frappent dans un éclat bref avant de s'éteindre. Couleurs de la palette, temps réel (indépendant de
// la fréquence d'affichage), aucune boucle quand la carte est au repos.
const TAU = Math.PI * 2;
// Paliers 1 à 5 : intensité (épaisseur, halo, éclat d'impact) et fréquence (intervalle moyen entre deux éclairs, éclairs simultanés).
const INTENSITY_SCALE = [0.6, 0.8, 1, 1.25, 1.5];
const SPAWN_INTERVAL_MS = [1800, 1250, 850, 560, 360];
const MAX_BOLTS = [2, 2, 3, 3, 4];
const GROW_MS = [170, 260];
const HOLD_MS = 140;
const FADE_MS = [420, 620];
const IMPACT_MS = 320;
const between = (random, [min, max]) => min + random() * (max - min);
const pick = (random, items) => items[Math.floor(random() * items.length) % items.length];
// Tracé fractal par déplacement du point milieu : chaque subdivision décale le milieu perpendiculairement au segment, de
// moins en moins à chaque niveau. 2^depth segments (32 par défaut), extrémités conservées.
export function boltPath(start, end, random, { depth = 5, roughness = 0.24 } = {}) {
let points = [start, end];
let offset = Math.hypot(end.x - start.x, end.y - start.y) * roughness;
for (let level = 0; level < depth; level++) {
const next = [points[0]];
for (let index = 1; index < points.length; index++) {
const from = points[index - 1];
const to = points[index];
const dx = to.x - from.x;
const dy = to.y - from.y;
const length = Math.hypot(dx, dy) || 1;
const shift = (random() - 0.5) * offset;
next.push({ x: (from.x + to.x) / 2 - (dy / length) * shift, y: (from.y + to.y) / 2 + (dx / length) * shift }, to);
}
points = next;
offset *= 0.55;
}
return points;
}
// Point d'arrivée tiré dans une zone ovale autour du centre de l'illustration, à une distance comprise entre `min` et `max`
// (fractions de la largeur et de la hauteur) : un éclair peut s'arrêter plus haut, plus à droite, ou dépasser le milieu.
function targetIn(center, width, height, random, [min, max]) {
const angle = random() * TAU;
const distance = min + Math.sqrt(random()) * (max - min);
return { x: center.x + Math.cos(angle) * width * distance, y: center.y + Math.sin(angle) * height * distance * 0.9 };
}
// Géométrie d'un éclair dans une zone width x height : départ sur une ellipse qui déborde des bords (le canvas coupe),
// arrivée en un point libre de la zone centrale de `focus` (la boîte de l'illustration dans le canvas, tout le canvas par
// défaut : sur toute la carte, les éclairs partent des bords de la carte et visent toujours le héros). Derrière un héros détouré, la zone va jusqu'au cœur : le héros le
// recouvre. Sans héros détouré, elle garde un petit vide au centre pour épargner son visage.
export const TARGET_ZONE = { behind: [0, 0.32], flat: [0.14, 0.38] };
export function boltGeometry(width, height, angle, random, { behindSubject = false, focus = null } = {}) {
const box = focus || { x: 0, y: 0, width, height };
const center = { x: box.x + box.width / 2, y: box.y + box.height * 0.48 };
const zone = behindSubject ? TARGET_ZONE.behind : TARGET_ZONE.flat;
const startAngle = angle + (random() - 0.5) * 0.9;
const start = { x: width / 2 + Math.cos(startAngle) * width * 0.66, y: height / 2 + Math.sin(startAngle) * height * 0.62 };
const end = targetIn(center, box.width, box.height, random, zone);
const main = boltPath(start, end, random);
// Une ou deux ramifications partent du premier tiers du tronc vers un autre point de la zone, sans l'atteindre : elles
// s'écartent du tronc puis s'éteignent en chemin.
const branches = [];
const branchCount = random() < 0.7 ? (random() < 0.35 ? 2 : 1) : 0;
for (let index = 0; index < branchCount; index++) {
const from = main[Math.floor(main.length * (0.25 + random() * 0.3))];
const aim = targetIn(center, box.width, box.height, random, zone);
const reach = 0.45 + random() * 0.25;
branches.push(boltPath(from, { x: from.x + (aim.x - from.x) * reach, y: from.y + (aim.y - from.y) * reach }, random, { depth: 4, roughness: 0.2 }));
}
return { center, main, branches };
}
function partialPath(context, points, fraction) {
const span = (points.length - 1) * Math.min(1, fraction);
const whole = Math.floor(span);
context.beginPath();
context.moveTo(points[0].x, points[0].y);
for (let index = 1; index <= whole; index++) context.lineTo(points[index].x, points[index].y);
let tip = points[whole];
if (whole < points.length - 1) {
const next = points[whole + 1];
const rest = span - whole;
tip = { x: tip.x + (next.x - tip.x) * rest, y: tip.y + (next.y - tip.y) * rest };
context.lineTo(tip.x, tip.y);
}
return tip;
}
// Trois passes additives au lieu d'un `shadowBlur`, coûteux : halo large et pâle, gaine colorée, cœur clair.
function strokeBolt(context, points, fraction, { color, core, width, alpha }) {
const passes = [[width * 6, color, 0.2], [width * 2.6, color, 0.75], [width, core, 1]];
let tip = points[0];
for (const [lineWidth, strokeStyle, opacity] of passes) {
context.globalAlpha = alpha * opacity;
context.lineWidth = lineWidth;
context.strokeStyle = strokeStyle;
tip = partialPath(context, points, fraction);
context.stroke();
}
return tip;
}
function glow(context, x, y, radius, color, alpha) {
const gradient = context.createRadialGradient(x, y, 0, x, y, radius);
gradient.addColorStop(0, color);
gradient.addColorStop(1, "transparent");
context.globalAlpha = alpha;
context.fillStyle = gradient;
context.beginPath();
context.arc(x, y, radius, 0, TAU);
context.fill();
}
export function createLightning(canvas, options) {
const context = canvas.getContext("2d");
const random = options.random || Math.random;
let settings = { ...options };
let size = { width: 0, height: 0, ratio: 1 };
let bolts = [];
let impacts = [];
let pointer = null;
let active = false;
let frame = 0;
let nextSpawn = 0;
let destroyed = false;
const scale = () => INTENSITY_SCALE[(settings.intensity || 3) - 1];
const level = () => (settings.level || 3) - 1;
function spawn(now) {
// Une fois sur deux, l'éclair vient du côté où se trouve le pointeur : la carte « répond » à la main qui la tient.
const angle = pointer && random() < 0.5
? Math.atan2(pointer.y - 0.48, pointer.x - 0.5) + (random() - 0.5) * 0.8
: random() * TAU;
const color = pick(random, settings.colors);
bolts.push({ ...boltGeometry(size.width, size.height, angle, random, settings), color, born: now, grow: between(random, GROW_MS), fade: between(random, FADE_MS), struck: false, width: (2 + random() * 1.2) * scale() });
nextSpawn = now + SPAWN_INTERVAL_MS[level()] * (0.6 + random() * 0.8);
}
function draw(now) {
const { width, height, ratio } = size;
context.setTransform(ratio, 0, 0, ratio, 0, 0);
context.clearRect(0, 0, width, height);
context.globalCompositeOperation = "lighter";
context.lineCap = "round";
context.lineJoin = "round";
const core = settings.core || "#ffffff";
for (const bolt of bolts) {
const age = now - bolt.born;
const fraction = age / bolt.grow;
const fading = age - bolt.grow - HOLD_MS;
// Pendant le maintien, l'éclair vacille ; ensuite il s'éteint.
const alpha = fading > 0 ? Math.max(0, 1 - fading / bolt.fade) : fraction >= 1 ? 0.7 + 0.3 * random() : 1;
const style = { color: bolt.color, core, width: bolt.width, alpha };
const tip = strokeBolt(context, bolt.main, fraction, style);
// Les ramifications naissent quand le tronc les atteint.
for (const branch of bolt.branches) strokeBolt(context, branch, Math.max(0, fraction * 1.3 - 0.35), { ...style, width: bolt.width * 0.55, alpha: alpha * 0.85 });
if (fraction < 1) glow(context, tip.x, tip.y, bolt.width * 7, core, 1);
if (fraction >= 1 && !bolt.struck) {
bolt.struck = true;
impacts.push({ x: tip.x, y: tip.y, color: bolt.color, born: now });
}
}
for (const impact of impacts) {
const progress = (now - impact.born) / IMPACT_MS;
glow(context, impact.x, impact.y, (10 + progress * 26) * scale(), impact.color, Math.max(0, 1 - progress));
glow(context, impact.x, impact.y, (4 + progress * 8) * scale(), core, Math.max(0, 1 - progress * 1.3));
}
context.globalAlpha = 1;
context.globalCompositeOperation = "source-over";
}
function tick(now) {
frame = 0;
if (destroyed || !size.width) return;
if (active && now >= nextSpawn && bolts.length < MAX_BOLTS[level()]) spawn(now);
bolts = bolts.filter((bolt) => now - bolt.born < bolt.grow + HOLD_MS + bolt.fade);
impacts = impacts.filter((impact) => now - impact.born < IMPACT_MS);
draw(now);
// Au repos, on laisse les derniers éclairs s'éteindre puis la boucle s'arrête.
if (active || bolts.length || impacts.length) frame = requestAnimationFrame(tick);
else context.clearRect(0, 0, size.width, size.height);
}
const schedule = () => {
if (!frame && !destroyed) frame = requestAnimationFrame(tick);
};
return {
resize(width, height, ratio = 1, focus = null) {
size = { width, height, ratio };
settings = { ...settings, focus };
canvas.width = Math.max(1, Math.round(width * ratio));
canvas.height = Math.max(1, Math.round(height * ratio));
bolts = [];
impacts = [];
if (active) schedule();
},
setActive(next) {
// Un premier éclair part dès que la carte s'anime.
if (next && !active) nextSpawn = 0;
active = next;
if (active) schedule();
},
setPointer(next) {
pointer = next;
},
setOptions(next) {
settings = { ...settings, ...next };
},
// Mouvement réduit : une image fixe de deux éclairs posés, sans boucle.
renderStatic() {
if (!size.width) return;
const now = 0;
bolts = [0.8, 3.6].map((angle) => ({ ...boltGeometry(size.width, size.height, angle, random, settings), color: settings.colors[0], born: now - 10_000, grow: 1, fade: 1, struck: true, width: 1.3 * scale() }));
const { width, height, ratio } = size;
context.setTransform(ratio, 0, 0, ratio, 0, 0);
context.clearRect(0, 0, width, height);
context.globalCompositeOperation = "lighter";
context.lineCap = "round";
context.lineJoin = "round";
for (const bolt of bolts) {
strokeBolt(context, bolt.main, 1, { color: bolt.color, core: settings.core || "#ffffff", width: bolt.width, alpha: 0.55 });
}
context.globalCompositeOperation = "source-over";
bolts = [];
},
destroy() {
destroyed = true;
cancelAnimationFrame(frame);
}
};
}

View file

@ -0,0 +1,184 @@
// Rôle : moteur des scintillements holographiques d'une carte mythique (Canvas 2D) : des motifs lumineux (étoile, reflet,
// losange, cœur, flocon, bulle…) apparaissent en grossissant, vivent un instant avec un éclat en croix à leur apogée, puis
// disparaissent en rétrécissant. Nombre moyen à l'écran, vitesse et intensité réglables ; couleurs de la palette ; temps
// réel ; aucune boucle au repos. Même interface que le moteur des éclairs.
import { motifAngle, motifSprite, SPRITE_SIZE, streakSprite } from "./flareSprites.js";
const TAU = Math.PI * 2;
export const TWINKLE_MOTIFS = [
{ id: "four-point-star", label: "Étoile à quatre branches" },
{ id: "glint", label: "Reflet" },
{ id: "star", label: "Étoile" },
{ id: "diamond", label: "Losange" },
{ id: "heart", label: "Cœur" },
{ id: "snowflake", label: "Flocon" },
{ id: "bubble", label: "Bulle" }
];
// Paliers 1 à 5 : nombre moyen de motifs visibles (pour une illustration de carte `lg`), durée de vie d'un motif, intensité
// (taille et éclat).
export const TWINKLE_COUNTS = [2, 3, 4, 6, 9];
const LIFETIME_MS = [3400, 2600, 1900, 1350, 950];
const INTENSITY_SCALE = [0.55, 0.65, 0.8, 1, 1.25];
// Surface de référence : l'illustration d'une carte `lg`. Une carte plus petite montre moins de motifs, une zone « toute la
// carte » un peu plus.
const REFERENCE_AREA = 280 * 240;
const easeOutBack = (t) => 1 + 2.4 * (t - 1) ** 3 + 1.4 * (t - 1) ** 2;
// Phase d'un motif selon son âge relatif (0 à 1) : apparition (35 %) avec un léger dépassement, apogée (20 %), disparition.
export function twinkleState(t) {
if (t < 0.35) {
const p = t / 0.35;
return { scale: Math.max(0, easeOutBack(p)), alpha: Math.min(1, p * 1.6), peak: 0 };
}
if (t < 0.55) {
const p = (t - 0.35) / 0.2;
return { scale: 1, alpha: 1, peak: Math.sin(p * Math.PI) };
}
const p = Math.min(1, (t - 0.55) / 0.45);
return { scale: 1 - p * 0.75, alpha: 1 - p, peak: 0 };
}
export function createTwinkle(canvas, options) {
const context = canvas.getContext("2d");
const random = options.random || Math.random;
let settings = { ...options };
let size = { width: 0, height: 0, ratio: 1 };
let sprites = [];
let streaks = [];
let items = [];
let pointer = null;
let active = false;
let frame = 0;
let nextSpawn = 0;
let destroyed = false;
const intensity = () => INTENSITY_SCALE[(settings.intensity || 3) - 1];
const lifetime = () => LIFETIME_MS[(settings.level || 3) - 1];
const areaFactor = () => Math.min(1.6, Math.max(0.3, (size.width * size.height) / REFERENCE_AREA));
const average = () => TWINKLE_COUNTS[(settings.count || 3) - 1] * areaFactor();
const sizeFactor = () => Math.min(1.2, Math.max(0.5, Math.min(size.width, size.height) / 240));
function buildSprites() {
const core = settings.core || "#ffffff";
sprites = settings.colors.map((color) => motifSprite(settings.motifId || "four-point-star", color, core));
streaks = settings.colors.map((color) => streakSprite(color, core));
}
// Position libre : marges de 6 %, à distance des motifs vivants ; un tiers des motifs naissent près du pointeur, là où
// la lumière frappe.
function position(radius) {
let best = null;
for (let attempt = 0; attempt < 4; attempt++) {
const near = pointer && random() < 0.35;
const x = near ? (pointer.x + (random() - 0.5) * 0.36) * size.width : (0.06 + random() * 0.88) * size.width;
const y = near ? (pointer.y + (random() - 0.5) * 0.36) * size.height : (0.06 + random() * 0.88) * size.height;
const candidate = { x: Math.min(size.width * 0.96, Math.max(size.width * 0.04, x)), y: Math.min(size.height * 0.96, Math.max(size.height * 0.04, y)) };
const crowded = items.some((item) => Math.hypot(item.x - candidate.x, item.y - candidate.y) < (item.radius + radius) * 1.6);
best = candidate;
if (!crowded) break;
}
return best;
}
function spawn(now) {
// Tailles contrastées : surtout des motifs moyens, et de temps en temps un grand éclat qui attire l'œil.
const radius = (9 + random() ** 2.5 * 18) * intensity() * sizeFactor();
const color = Math.floor(random() * settings.colors.length);
const life = lifetime() * (0.75 + random() * 0.5);
items.push({ ...position(radius), radius, color, born: now, life, rotation: random() * TAU, spin: (random() - 0.5) * 1.2 });
// Intervalle moyen = durée de vie / nombre moyen voulu : le nombre visible se stabilise autour de la moyenne.
nextSpawn = now + (lifetime() / average()) * (0.4 + random() * 1.2);
}
function drawItem(item, state) {
const spriteSize = item.radius * 2 * (SPRITE_SIZE / (SPRITE_SIZE * 0.34)) * state.scale;
context.save();
context.translate(item.x, item.y);
context.rotate(motifAngle(settings.motifId, item.rotation + item.spin * state.age));
context.globalAlpha = state.alpha * Math.min(1, 0.75 + 0.25 * intensity());
context.drawImage(sprites[item.color], -spriteSize / 2, -spriteSize / 2, spriteSize, spriteSize);
// Le reflet garde sa croix de lumière toute sa vie ; les autres motifs la font jaillir à leur apogée.
const peak = settings.motifId === "glint" ? Math.max(state.peak, state.alpha * 0.7) : state.peak;
if (peak > 0 && settings.motifId !== "bubble") {
const streak = item.radius * 10 * (0.55 + 0.45 * peak) * Math.min(1.3, intensity());
context.globalAlpha = peak;
context.drawImage(streaks[item.color], -streak / 2, -streak / 2, streak, streak);
}
context.restore();
}
function draw(now) {
const { width, height, ratio } = size;
context.setTransform(ratio, 0, 0, ratio, 0, 0);
context.clearRect(0, 0, width, height);
context.globalCompositeOperation = "lighter";
for (const item of items) {
const age = (now - item.born) / item.life;
drawItem(item, { ...twinkleState(age), age });
}
context.globalAlpha = 1;
context.globalCompositeOperation = "source-over";
}
function tick(now) {
frame = 0;
if (destroyed || !size.width) return;
// Plusieurs naissances par image si la fréquence l'exige (beaucoup de motifs très rapides).
while (active && now >= nextSpawn && items.length < average() * 2.5) spawn(now);
items = items.filter((item) => now - item.born < item.life);
draw(now);
if (active || items.length) frame = requestAnimationFrame(tick);
else context.clearRect(0, 0, size.width, size.height);
}
const schedule = () => {
if (!frame && !destroyed) frame = requestAnimationFrame(tick);
};
buildSprites();
return {
resize(width, height, ratio = 1) {
size = { width, height, ratio };
canvas.width = Math.max(1, Math.round(width * ratio));
canvas.height = Math.max(1, Math.round(height * ratio));
items = [];
if (active) schedule();
},
setActive(next) {
if (next && !active) nextSpawn = 0;
active = next;
if (active) schedule();
},
setPointer(next) {
pointer = next;
},
setOptions(next) {
settings = { ...settings, ...next };
buildSprites();
},
// Mouvement réduit : quelques motifs fixes, à mi-éclat.
renderStatic() {
if (!size.width) return;
items = [];
const count = Math.max(2, Math.round(average() / 2));
for (let index = 0; index < count; index++) {
const radius = 10 * intensity() * sizeFactor();
items.push({ ...position(radius), radius, color: index % settings.colors.length, born: 0, life: 1, rotation: random() * TAU, spin: 0 });
}
const { width, height, ratio } = size;
context.setTransform(ratio, 0, 0, ratio, 0, 0);
context.clearRect(0, 0, width, height);
context.globalCompositeOperation = "lighter";
for (const item of items) drawItem(item, { scale: 0.85, alpha: 0.6, peak: 0, age: 0 });
context.globalCompositeOperation = "source-over";
items = [];
},
destroy() {
destroyed = true;
cancelAnimationFrame(frame);
}
};
}