Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

fix(zoom): the tilt was a collapsing quadratic — round its shadow and unify the zoom scale

Etienne Lescot19198dc66a1a
diff --git a/AGENTS.md b/AGENTS.md
index 566132003..417f937e5 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -59,6 +59,8 @@ Unit/browser tests can't exercise real capture (native screen recording, a physi
**The HUD widget** (recording controller)
+- **It is invisible in screenshots by default.** The HUD (and the Notes window) call `setContentProtection(true)` so the recording controls never end up baked into a recording — the same `SetWindowDisplayAffinity` that WGC honours also hides them from *your* screenshots. The window is there, and clicks land, but you are aiming blind at a rectangle you cannot see. Set **`OPENSCREEN_DISABLE_CONTENT_PROTECTION=1`** in the app's environment to turn it off for a session; every skipped window logs a warning. Unset it before recording anything real, or the HUD ends up in the video.
+- The HUD is what opens the editor (clapper icon, tooltip *Open Studio*), so without that flag a whole slice of the app is unreachable from automation: killing the app to redeploy a native addon leaves you unable to reopen a project.
- Frameless, transparent, always-on-top, `skipTaskbar`, centered at the **bottom of the primary display** (`createHudOverlayWindow`, 600×160). It is **click-through** (`setIgnoreMouseEvents(true, { forward: true })`): moving the real cursor over an interactive control makes that region clickable and shows its tooltip, so `mouse_move` → screenshot → `left_click` works; a blind click on empty HUD area passes through to the desktop.
- Control row (left→right): layout preset, **source** button (`Screen`/`Window` → label becomes the picked source), system-audio toggle, mic toggle, **webcam toggle** (shows the detected camera name), cursor-highlight toggle, **record**, notes, open-editor, language, minimize, close. The record button is disabled until a source is chosen (tooltip: "Please select a source to record").
@@ -75,6 +77,11 @@ Unit/browser tests can't exercise real capture (native screen recording, a physi
4. Exercise the feature in the editor (e.g. Full Camera: press **C** to add a segment on the timeline, scrub to see the webcam grow to fullscreen and ease back; **Ctrl+Z** / **Ctrl+Shift+Z** undo/redo).
5. Capture a screenshot as proof. Clean up: stop `npm run dev`, remove temporary worktree junctions/lock.
+**Judging the rendered picture**
+
+- A preview screenshot is a **downscaled** view of the compositor's output (a 1920-wide render shown in a ~600px pane, then downscaled again by the screenshot). Fine detail — a corner radius, a 1° edge slope, a soft shadow — does not survive that, and squinting at it produces confident wrong conclusions. To decide anything about pixels, **export and measure**: `Export → MP4 1080p`, then `ffmpeg -ss <t> -i out.mp4 -frames:v 1 -c:v ppm frame.ppm` and walk the raw bytes (a P6 PPM is a 15-line parser) for the exact edges. That is what settled a "the tilt is truncated" report: measured right edge 1539 px against a computed corner at 1540 — no clipping at all, the real defect was elsewhere.
+- ffmpeg lives at `poc-d3d/thirdparty/ffmpeg-*/bin/ffmpeg.exe` (also needed on `PATH` for the compositor addon to load).
+
## PR & commit conventions
- Branch from `main`; never push to it directly.
diff --git a/electron/windows.ts b/electron/windows.ts
index 57b231bd9..26eeeade7 100644
--- a/electron/windows.ts
+++ b/electron/windows.ts
@@ -9,6 +9,28 @@ const VITE_DEV_SERVER_URL = process.env["VITE_DEV_SERVER_URL"];
const RENDERER_DIST = path.join(APP_ROOT, "dist");
const HEADLESS = process.env["HEADLESS"] === "true";
+// The HUD and Notes windows are excluded from every screen/window capture (WGC on Windows uses
+// the same SetWindowDisplayAffinity this sets), so the recording controls never end up baked into
+// the recorded video.
+//
+// The side effect is that they are equally invisible to an *agent's* screenshots, and the HUD is
+// what opens the editor — which makes a whole slice of the app unreachable from automation. Hence
+// this escape hatch, for testing only. It warns on every window it skips, because a recording made
+// while it is set WILL contain the HUD.
+const CONTENT_PROTECTION_DISABLED = process.env["OPENSCREEN_DISABLE_CONTENT_PROTECTION"] === "1";
+
+function applyContentProtection(win: BrowserWindow, label: string) {
+ if (CONTENT_PROTECTION_DISABLED) {
+ console.warn(
+ `[content-protection] OFF for the ${label} window ` +
+ "(OPENSCREEN_DISABLE_CONTENT_PROTECTION=1) — it will appear in screen captures, " +
+ "including recordings. Unset it for anything but automated testing.",
+ );
+ return;
+ }
+ win.setContentProtection(true);
+}
+
// Asset base URL for renderer (wallpapers, etc.). Packaged: extraResources copies
// public/wallpapers to resources/wallpapers. Unpackaged: <appRoot>/public/.
const ASSET_BASE_DIR = process.defaultApp
@@ -187,10 +209,8 @@ export function createHudOverlayWindow(): BrowserWindow {
});
win.setIgnoreMouseEvents(true, { forward: true });
- // Exclude the HUD from any screen/window capture (WGC on Windows uses the same
- // SetWindowDisplayAffinity affinity this sets) so the recording controls never
- // end up baked into the recorded video, same as the notes window below.
- win.setContentProtection(true);
+ // Keep the recording controls out of the recording (see applyContentProtection).
+ applyContentProtection(win, "HUD");
// Follow the user across macOS Spaces, else the HUD stays pinned to the Space
// it was first opened on.
@@ -201,7 +221,7 @@ export function createHudOverlayWindow(): BrowserWindow {
// Show only once painted to avoid the black rectangle flash when a transparent
// window is shown before its first paint.
win.once("ready-to-show", () => {
- win.setContentProtection(true);
+ applyContentProtection(win, "HUD");
if (!HEADLESS) win.show();
});
@@ -428,9 +448,9 @@ export function createNotesWindow(): BrowserWindow {
win.setAutoHideMenuBar(true);
}
- win.setContentProtection(true);
+ applyContentProtection(win, "Notes");
win.once("ready-to-show", () => {
- win.setContentProtection(true);
+ applyContentProtection(win, "Notes");
win.show();
});
diff --git a/poc-d3d/src/compositor.rs b/poc-d3d/src/compositor.rs
index 97bb0a936..a15d78333 100644
--- a/poc-d3d/src/compositor.rs
+++ b/poc-d3d/src/compositor.rs
@@ -1366,6 +1366,56 @@ impl Compositor {
self.draw_solid(&cb);
}
+ /// Ombre d'un écran incliné en 3D : la pénombre suit le QUADRILATÈRE projeté (mode 12), pas
+ /// son rect englobant. `corners` sont les 4 coins (TL, TR, BR, BL) en px relatifs au centre,
+ /// tels que `rotated_quad_corners_px` les rend ; `center_px` est ce centre à l'écran.
+ ///
+ /// `radius` est le rayon des coins du PLAN, réutilisé tel quel : la projection l'étire de
+ /// ±10 % selon l'endroit du bord, écart invisible sur une ombre floue, alors qu'une ombre à
+ /// coins vifs derrière un écran arrondi dépasse en pointe et se voit tout de suite.
+ pub unsafe fn draw_quad_shadow(
+ &self,
+ corners: &[(f32, f32); 4],
+ center_px: [f32; 2],
+ radius: f32,
+ spread: f32,
+ offset_px: [f32; 2],
+ opacity: f32,
+ ) {
+ let (min_x, max_x) =
+ corners.iter().fold((f32::MAX, f32::MIN), |(mn, mx), &(x, _)| (mn.min(x), mx.max(x)));
+ let (min_y, max_y) =
+ corners.iter().fold((f32::MAX, f32::MIN), |(mn, mx), &(_, y)| (mn.min(y), mx.max(y)));
+ // La boîte de rendu doit contenir la pénombre entière, sinon elle se coupe net — le
+ // quadrilatère seul ne suffit pas.
+ let box_w = (max_x - min_x) + 2.0 * spread;
+ let box_h = (max_y - min_y) + 2.0 * spread;
+ let origin_x = center_px[0] + min_x - spread + offset_px[0];
+ let origin_y = center_px[1] + min_y - spread + offset_px[1];
+ // Coins en px locaux à cette boîte, même convention que le mode 8.
+ let local = |(x, y): (f32, f32)| -> [f32; 2] { [x - min_x + spread, y - min_y + spread] };
+ let [tl0, tl1] = local(corners[0]);
+ let [tr0, tr1] = local(corners[1]);
+ let [br0, br1] = local(corners[2]);
+ let [bl0, bl1] = local(corners[3]);
+ self.draw_solid(&LayerCB {
+ dst: [
+ origin_x / self.rw(),
+ origin_y / self.rh(),
+ box_w / self.rw(),
+ box_h / self.rh(),
+ ],
+ quad_px: [box_w, box_h],
+ radius_px: radius,
+ mode: 12.0,
+ color: [0.0, 0.0, 0.0, opacity],
+ fx: [tl0, tl1, tr0, tr1],
+ src_prev: [br0, br1, bl0, bl1],
+ mb: [0.0, spread, 1.0, 0.0],
+ ..Default::default()
+ });
+ }
+
/// Compose une frame animée (§6/§8) : fond flouté + screen zoomé (padding, coins, ombre)
/// + webcam crop carré (coins, ombre), placements interpolés A↔B par la timeline.
pub unsafe fn compose_frame(
@@ -1817,20 +1867,32 @@ impl Compositor {
let [su0_p, sv0_p, su1_p, sv1_p] =
cover(screen_source_rect(u_max, v_max, active_crop, pp.zoom, p.focus));
let (hu_p, hv_p) = ((su1_p - su0_p) * 0.5, (sv1_p - sv0_p) * 0.5);
- // L'ombre est dessinée à partir du rect NON pivoté. Tant que l'écran est droit, c'est
- // exactement sa silhouette ; incliné en 3D, ce n'en est plus une — on voyait alors un
- // rectangle arrondi bien droit derrière un écran penché, détaché de lui. Une ombre fausse
- // renseigne moins que pas d'ombre : on la supprime pendant le tilt, en attendant une
- // silhouette qui suive réellement le plan projeté.
- if cfg.shadow && crate::regions::is_identity_rotation(zoom_rotation) {
- self.draw_shadow(
- s_dst,
- s_px,
- s_radius,
- SCREEN_SHADOW_SPREAD_FRAC * frame_min_px,
- [0.0, SCREEN_SHADOW_OFFSET_FRAC * frame_min_px],
- 0.45 * lp.shadow_scale,
- );
+ // Géométrie du tilt, calculée UNE fois : l'ombre et l'écran doivent porter exactement le
+ // même quadrilatère. Deux calculs séparés, c'est une ombre qui se décolle dès qu'un des
+ // deux change.
+ let tilt = (!crate::regions::is_identity_rotation(zoom_rotation))
+ .then(|| crate::regions::rotated_quad_corners_px(s_px[0], s_px[1], zoom_rotation));
+ let quad_center_px =
+ [(s_dst[0] + s_dst[2] * 0.5) * self.rw(), (s_dst[1] + s_dst[3] * 0.5) * self.rh()];
+ // L'ombre suit la silhouette réellement affichée : le rect arrondi quand l'écran est
+ // droit, le quadrilatère projeté quand il est incliné. Un rect droit derrière un écran
+ // penché ne se lisait pas comme son ombre mais comme une seconde surface.
+ if cfg.shadow {
+ let spread = SCREEN_SHADOW_SPREAD_FRAC * frame_min_px;
+ let offset = [0.0, SCREEN_SHADOW_OFFSET_FRAC * frame_min_px];
+ let opacity = 0.45 * lp.shadow_scale;
+ match tilt.as_ref() {
+ None => self.draw_shadow(s_dst, s_px, s_radius, spread, offset, opacity),
+ Some(quad) => self.draw_quad_shadow(
+ &quad.corners,
+ quad_center_px,
+ // Même rayon que le plan incliné lui-même (cf. le dessin du mode 8).
+ s_radius * quad.scale,
+ spread,
+ offset,
+ opacity,
+ ),
+ }
}
if crate::regions::is_identity_rotation(zoom_rotation) {
self.draw_video(
@@ -1851,11 +1913,20 @@ impl Compositor {
);
} else {
// Tilt 3D (zoom "rotation" iso/left/right) : warp bilinéaire inverse (mode 8, voir
- // shaders.hlsl) — pas de motion blur ni de coins arrondis dans ce chemin (le tilt
- // est un effet ponctuel bref, cette simplification ne se voit pas).
- let corners = crate::regions::rotated_quad_corners_px(s_px[0], s_px[1], zoom_rotation);
- let (cx_px, cy_px) =
- ((s_dst[0] + s_dst[2] * 0.5) * self.rw(), (s_dst[1] + s_dst[3] * 0.5) * self.rh());
+ // shaders.hlsl). Pas de motion blur dans ce chemin — le tilt est un effet bref, la
+ // simplification ne se voit pas. Les coins arrondis, eux, se voyaient : sans eux le
+ // plan a des arêtes de couteau qui tranchent le contenu en pleine phrase, et l'œil lit
+ // une découpe (« un overflow hidden qui tronque l'enregistrement ») là où il devrait
+ // lire une inclinaison. Ils sont donc rendus, dans le repère DU PLAN.
+ let quad = tilt.unwrap_or_else(|| {
+ crate::regions::rotated_quad_corners_px(s_px[0], s_px[1], zoom_rotation)
+ });
+ let corners = quad.corners;
+ // Taille du plan dans son propre repère, avant projection : c'est là que vit le rayon,
+ // pour qu'il reste un rayon constant le long du bord et non un arrondi qui s'étire avec
+ // la perspective.
+ let plane_px = [s_px[0] * quad.scale, s_px[1] * quad.scale];
+ let (cx_px, cy_px) = (quad_center_px[0], quad_center_px[1]);
let (min_x, max_x) = corners.iter().fold((f32::MAX, f32::MIN), |(mn, mx), &(x, _)| {
(mn.min(x), mx.max(x))
});
@@ -1881,9 +1952,13 @@ impl Compositor {
dst: bbox_dst,
src: [su0, sv0, su0 + 2.0 * hu, sv0 + 2.0 * hv],
quad_px: [bbox_w, bbox_h],
+ // Le rayon suit la réduction du plan : l'écran incliné est plus petit, ses
+ // coins le sont d'autant, exactement comme s'il s'éloignait.
+ radius_px: s_radius * quad.scale,
mode: 8.0,
fx: [tl0, tl1, tr0, tr1],
src_prev: [br0, br1, bl0, bl1],
+ dst_prev: [plane_px[0], plane_px[1], 0.0, 0.0],
..Default::default()
},
&sy,
@@ -2285,14 +2360,48 @@ impl Compositor {
}) else {
continue;
};
+ // Animation d'apparition. Elle est comptée en temps SOURCE (le seul dont on
+ // dispose ici) : dans une région accélérée, elle défile donc au rythme du
+ // clip. À vitesse 1 — le cas de toutes les annotations existantes — c'est
+ // exactement le timing de l'aperçu DOM.
+ let anim = crate::text_anim::text_animation_state(
+ text.animation.as_deref(),
+ (t - annotation.start_sec as f32) * 1000.0,
+ );
+ // Les décalages sont donnés à la hauteur de référence : on les ramène à la
+ // sortie, comme la taille de police, pour que l'animation ait la même
+ // amplitude visuelle quelle que soit la résolution.
+ let anim_px = self.rh() / crate::text_anim::ANIMATION_REFERENCE_HEIGHT;
+ let (mut ax, mut ay, mut aw, mut ah) = (
+ dst[0] + anim.translate_x * anim_px / self.rw(),
+ dst[1] + anim.translate_y * anim_px / self.rh(),
+ dst[2],
+ dst[3],
+ );
+ if (anim.scale - 1.0).abs() > 1e-4 {
+ // Mise à l'échelle autour du CENTRE de la boîte : un texte qui grossit par
+ // son coin haut-gauche glisserait en biais au lieu de gonfler sur place.
+ let (cx, cy) = (ax + aw * 0.5, ay + ah * 0.5);
+ aw *= anim.scale;
+ ah *= anim.scale;
+ ax = cx - aw * 0.5;
+ ay = cy - ah * 0.5;
+ }
+ // Machine à écrire : on ne rogne que la LARGEUR, source et destination
+ // ensemble, ce qui reproduit le `inset(0 X% 0 0)` de l'aperçu sans redemander
+ // une rastérisation par caractère.
+ let reveal = anim.reveal.clamp(0.0, 1.0);
+ if reveal <= 0.0 {
+ continue;
+ }
self.ctx.PSSetShaderResources(2, Some(&[Some(srv)]));
self.draw_solid(&LayerCB {
- dst,
- src: [0.0, 0.0, 1.0, 1.0],
- quad_px,
+ dst: [ax, ay, aw * reveal, ah],
+ src: [0.0, 0.0, reveal, 1.0],
+ quad_px: [aw * reveal * self.rw(), ah * self.rh()],
// mode 11 : sprite en alpha DÉJÀ prémultiplié (ce que produit D2D).
mode: 11.0,
- color: [1.0, 1.0, 1.0, 1.0],
+ color: [1.0, 1.0, 1.0, anim.opacity],
..Default::default()
});
}
@@ -2770,6 +2879,30 @@ impl Compositor {
mod tests {
use super::*;
+ /// Le HLSL est compilé au démarrage du compositeur : jusqu'ici une faute dedans ne se voyait
+ /// qu'à l'exécution, donc après un rebuild du natif ET un relancement de l'app. `D3DCompile`
+ /// ne demande aucun device — le compilateur seul suffit, et ça tient en quelques
+ /// millisecondes.
+ #[test]
+ fn every_shader_entry_point_compiles() {
+ let hlsl = include_bytes!("shaders.hlsl");
+ for (entry, target) in [
+ (&b"vs_main\0"[..], &b"vs_5_0\0"[..]),
+ (&b"ps_main\0"[..], &b"ps_5_0\0"[..]),
+ (&b"vs_fs\0"[..], &b"vs_5_0\0"[..]),
+ (&b"ps_y\0"[..], &b"ps_5_0\0"[..]),
+ (&b"ps_uv\0"[..], &b"ps_5_0\0"[..]),
+ (&b"ps_blur\0"[..], &b"ps_5_0\0"[..]),
+ (&b"ps_tex\0"[..], &b"ps_5_0\0"[..]),
+ (&b"ps_kawase_down\0"[..], &b"ps_5_0\0"[..]),
+ (&b"ps_kawase_up\0"[..], &b"ps_5_0\0"[..]),
+ ] {
+ let name = String::from_utf8_lossy(&entry[..entry.len() - 1]).to_string();
+ unsafe { compile(hlsl, entry, target) }
+ .unwrap_or_else(|e| panic!("{name} ne compile pas : {e}"));
+ }
+ }
+
fn assert_rect(actual: [f32; 4], expected: [f32; 4]) {
for (actual, expected) in actual.into_iter().zip(expected) {
assert!((actual - expected).abs() < 1e-6, "actual={actual}, expected={expected}");
diff --git a/poc-d3d/src/lib.rs b/poc-d3d/src/lib.rs
index 5e6f9d473..7946eb0ad 100644
--- a/poc-d3d/src/lib.rs
+++ b/poc-d3d/src/lib.rs
@@ -14,6 +14,7 @@ pub mod pipeline;
pub mod regions;
pub mod scene;
pub mod text;
+pub mod text_anim;
use anyhow::{Context as _, Result};
use compositor::Compositor;
diff --git a/poc-d3d/src/regions.rs b/poc-d3d/src/regions.rs
index ff21a92ea..075a25f55 100644
--- a/poc-d3d/src/regions.rs
+++ b/poc-d3d/src/regions.rs
@@ -211,11 +211,27 @@ fn ease_connected_pan(t: f32) -> f32 {
}
/// Port de `getRotation3D`/`ROTATION_3D_PRESETS` (TS, `types.ts`) — degrés (rotationX, Y, Z).
+/// Angles des présets, en degrés X/Y/Z.
+///
+/// Les valeurs d'origine (iso [-10,-16,0], left [0,-22,0], right [0,22,0]) produisaient un quad
+/// dont AU MOINS UNE ARÊTE tombait à moins de 0.1° d'un axe de l'image : les deux bords verticaux
+/// pour left/right (une rotation Y pure laisse les verticales verticales — c'est de la géométrie,
+/// pas un réglage), le bord haut pour iso, dont la remontée due au rotateX était annulée par la
+/// division perspective à cette distance-là.
+///
+/// Une arête parfaitement verticale qui traverse du texte est indiscernable d'un `overflow:
+/// hidden`. C'est ce qui a été rapporté trois fois comme « une troncature de l'enregistrement »,
+/// alors que le plan était rendu en entier — mesuré au pixel sur un export 1920×1080 : bord droit
+/// à 1539, coin calculé à 1540, arrondis présents aux quatre coins.
+///
+/// Chaque préset a donc maintenant ses trois composantes, choisies pour qu'aucune arête ne
+/// s'approche d'un axe à moins de 2° (cf. `no_preset_has_an_axis_aligned_edge`) tout en gardant
+/// l'identité du préset : left penche vers la gauche, right vers la droite, iso est le plus incliné.
fn rotation3d_for(rotation: &Option<String>) -> [f32; 3] {
match rotation.as_deref() {
- Some("iso") => [-10.0, -16.0, 0.0],
- Some("left") => [0.0, -22.0, 0.0],
- Some("right") => [0.0, 22.0, 0.0],
+ Some("iso") => [-12.0, -18.0, -2.0],
+ Some("left") => [-8.0, -16.0, -1.0],
+ Some("right") => [-8.0, 16.0, 1.0],
_ => [0.0, 0.0, 0.0],
}
}
@@ -503,12 +519,26 @@ fn projected_extents(corners: &[(f32, f32); 4]) -> (f32, f32) {
corners.iter().fold((0.0f32, 0.0f32), |(mx, my), &(x, y)| (mx.max(x.abs()), my.max(y.abs())))
}
+/// Un écran incliné : ses 4 coins projetés, et la réduction qu'il a fallu pour qu'ils tiennent.
+pub struct TiltedQuad {
+ /// Coins TL, TR, BR, BL en px relatifs au CENTRE du rect d'origine.
+ pub corners: [(f32, f32); 4],
+ /// Facteur de containment. Le plan mesure donc `taille_du_rect × scale` dans son PROPRE repère,
+ /// avant projection — ce qu'il faut connaître pour y poser un rayon de coin à la bonne échelle.
+ pub scale: f32,
+}
+
/// Les 4 coins (TL, TR, BR, BL) du quad tilté en 3D, en px relatifs au CENTRE du rect d'origine
/// (0,0 = centre — l'appelant les recentre sur le centre réel à l'écran). `width`/`height` en
/// px = la taille du rect d'origine, aussi utilisée comme référence de perspective (comme le
/// web : la perspective/le containScale sont calculés sur la taille de l'élément lui-même).
-pub fn rotated_quad_corners_px(width: f32, height: f32, rot: [f32; 3]) -> [(f32, f32); 4] {
- const PERSPECTIVE_FACTOR: f32 = 2.6; // ROTATION_3D_PERSPECTIVE_FACTOR (TS)
+pub fn rotated_quad_corners_px(width: f32, height: f32, rot: [f32; 3]) -> TiltedQuad {
+ // ROTATION_3D_PERSPECTIVE_FACTOR (TS) — à garder synchronisé avec `types.ts`, que la passe 3D
+ // de l'exporteur canvas lit encore. Distance de fuite = facteur × min(w,h) : plus le facteur
+ // est grand, plus la caméra est loin et plus la convergence des arêtes s'aplatit. À 2.6 elle
+ // était si faible que l'inclinaison ne se lisait plus (le bord haut d'iso ressortait à 0.08° de
+ // l'horizontale).
+ const PERSPECTIVE_FACTOR: f32 = 1.6;
let perspective = width.min(height) * PERSPECTIVE_FACTOR;
let (half_w, half_h) = (width * 0.5, height * 0.5);
@@ -526,7 +556,17 @@ pub fn rotated_quad_corners_px(width: f32, height: f32, rot: [f32; 3]) -> [(f32,
Some(c) => c,
// Un coin derrière le plan de fuite : on rend le quad non tourné plutôt qu'une projection
// absurde (même repli qu'avant).
- None => return [(-half_w, -half_h), (half_w, -half_h), (half_w, half_h), (-half_w, half_h)],
+ None => {
+ return TiltedQuad {
+ corners: [
+ (-half_w, -half_h),
+ (half_w, -half_h),
+ (half_w, half_h),
+ (-half_w, half_h),
+ ],
+ scale: 1.0,
+ };
+ }
};
for _ in 0..8 {
let (max_x, max_y) = projected_extents(&corners);
@@ -545,7 +585,7 @@ pub fn rotated_quad_corners_px(width: f32, height: f32, rot: [f32; 3]) -> [(f32,
None => break,
}
}
- corners
+ TiltedQuad { corners, scale }
}
#[cfg(test)]
@@ -744,7 +784,7 @@ mod tilt_tests {
] {
// Plusieurs formes de boîte : le débordement dépend du ratio.
for (w, h) in [(1920.0f32, 1080.0f32), (1080.0, 1920.0), (800.0, 800.0)] {
- let corners = rotated_quad_corners_px(w, h, rot);
+ let corners = rotated_quad_corners_px(w, h, rot).corners;
let (max_x, max_y) = projected_extents(&corners);
// Tolérance d'un demi-pixel : l'itération s'arrête à 0.1 % près.
assert!(
@@ -757,10 +797,39 @@ mod tilt_tests {
}
}
+ /// Aucune arête d'un préset ne doit longer un axe de l'image. C'est LE critère qui distingue
+ /// « un écran incliné » d'« un enregistrement tronqué » : un bord parfaitement vertical qui
+ /// coupe une phrase se lit comme un `overflow: hidden`, quelle que soit la justesse du reste.
+ #[test]
+ fn no_preset_has_an_axis_aligned_edge() {
+ for (name, rot) in [
+ ("iso", rotation3d_for(&Some("iso".into()))),
+ ("left", rotation3d_for(&Some("left".into()))),
+ ("right", rotation3d_for(&Some("right".into()))),
+ ] {
+ let c = rotated_quad_corners_px(1920.0, 1080.0, rot).corners;
+ // haut, bas (contre l'horizontale) ; gauche, droite (contre la verticale)
+ let h_angle = |p: (f32, f32), q: (f32, f32)| (q.1 - p.1).atan2(q.0 - p.0).to_degrees();
+ let v_angle = |p: (f32, f32), q: (f32, f32)| (q.0 - p.0).atan2(q.1 - p.1).to_degrees();
+ let edges = [
+ ("haut", h_angle(c[0], c[1])),
+ ("bas", h_angle(c[3], c[2])),
+ ("gauche", v_angle(c[0], c[3])),
+ ("droite", v_angle(c[1], c[2])),
+ ];
+ for (edge, angle) in edges {
+ assert!(
+ angle.abs() >= 2.0,
+ "{name} : arête {edge} à {angle:.2}° de son axe — ça se lit comme une découpe"
+ );
+ }
+ }
+ }
+
#[test]
fn a_flat_quad_is_left_alone() {
// Sans rotation, aucun containment ne doit s'appliquer : les coins sont ceux du rect.
- let corners = rotated_quad_corners_px(1000.0, 600.0, [0.0, 0.0, 0.0]);
+ let corners = rotated_quad_corners_px(1000.0, 600.0, [0.0, 0.0, 0.0]).corners;
let (max_x, max_y) = projected_extents(&corners);
assert!((max_x - 500.0).abs() < 0.5 && (max_y - 300.0).abs() < 0.5);
}
@@ -769,8 +838,121 @@ mod tilt_tests {
fn the_tilt_actually_tilts() {
// Garde-fou contre un containment trop zélé qui aplatirait l'effet : les quatre coins
// d'un quad incliné ne peuvent pas rester alignés deux à deux comme un rectangle droit.
- let corners = rotated_quad_corners_px(1920.0, 1080.0, rotation3d_for(&Some("iso".into())));
+ let corners = rotated_quad_corners_px(1920.0, 1080.0, rotation3d_for(&Some("iso".into()))).corners;
let top_edge_slope = (corners[1].1 - corners[0].1).abs();
assert!(top_edge_slope > 1.0, "arête supérieure horizontale : le tilt a disparu");
}
+
+ // ---- Mapping inverse du mode 8, reproduit à l'identique -------------------------------
+ // Le pixel shader retrouve (s,t) dans le quad projeté en résolvant un système quadratique.
+ // Le miroir ci-dessous est une COPIE de `shaders.hlsl` (mode 8) : même algèbre, même choix
+ // de racine, mêmes tolérances. Il sert à interroger ce mapping sans GPU — un bord droit qui
+ // tranche un écran penché ne peut venir que de trois endroits (les coins, ce mapping, le
+ // rect source), et c'est le seul des trois qu'on ne pouvait pas encore examiner.
+
+ fn cross2(a: (f32, f32), b: (f32, f32)) -> f32 {
+ a.0 * b.1 - a.1 * b.0
+ }
+
+ fn sub(a: (f32, f32), b: (f32, f32)) -> (f32, f32) {
+ (a.0 - b.0, a.1 - b.1)
+ }
+
+ /// Point du quad pour un couple (s,t) — la direction que le shader inverse.
+ fn forward_bilinear(corners: &[(f32, f32); 4], s: f32, t: f32) -> (f32, f32) {
+ let (c00, c10, c11, c01) = (corners[0], corners[1], corners[2], corners[3]);
+ let e = sub(c10, c00);
+ let f = sub(c01, c00);
+ let g = (c00.0 - c10.0 - c01.0 + c11.0, c00.1 - c10.1 - c01.1 + c11.1);
+ (c00.0 + e.0 * s + f.0 * t + g.0 * s * t, c00.1 + e.1 * s + f.1 * t + g.1 * s * t)
+ }
+
+ /// `None` = le shader rend ce pixel TRANSPARENT (donc un trou dans l'écran incliné).
+ fn shader_inverse_bilinear(corners: &[(f32, f32); 4], p: (f32, f32)) -> Option<(f32, f32)> {
+ let (c00, c10, c11, c01) = (corners[0], corners[1], corners[2], corners[3]);
+ let e = sub(c10, c00);
+ let f = sub(c01, c00);
+ let g = (c00.0 - c10.0 - c01.0 + c11.0, c00.1 - c10.1 - c01.1 + c11.1);
+ let h = sub(p, c00);
+ let k2 = cross2(g, f);
+ let k1 = cross2(e, f) + cross2(h, g);
+ let k0 = cross2(h, e);
+ // Pour une racine `t` candidate, le `s` correspondant — et si le couple tombe dans le quad.
+ let st_for_root = |t: f32| -> Option<(f32, f32)> {
+ let denom_x = e.0 + g.0 * t;
+ let denom_y = e.1 + g.1 * t;
+ let s = if denom_x.abs() > denom_y.abs() {
+ (h.0 - f.0 * t) / denom_x
+ } else {
+ (h.1 - f.1 * t) / denom_y
+ };
+ ((-0.02..=1.02).contains(&s) && (-0.02..=1.02).contains(&t)).then_some((s, t))
+ };
+ // Seuil RELATIF. Un prését « left »/« right » est une rotation Y pure : le quad projeté
+ // est un trapèze symétrique dont `f` et `g` sont tous deux verticaux, donc k2 = 0
+ // exactement — au bruit d'arrondi près, et ce bruit vaut quelques centièmes sur des
+ // produits en 10^6. Un seuil absolu de 0.001 le manquait, l'équation partait dans la
+ // branche quadratique avec un k2 ≈ 0, et `(-k1 + sqrt(k1²)) / 2k2` y perd toute
+ // précision : soustraire deux nombres presque égaux ne laisse que du bruit, divisé
+ // ensuite par un k2 minuscule. C'est ça qui amputait l'écran incliné.
+ if k2.abs() < 1e-5 * k1.abs() {
+ let t = if k1.abs() < 1e-6 { 0.0 } else { -k0 / k1 };
+ return st_for_root(t);
+ }
+ let disc = k1 * k1 - 4.0 * k2 * k0;
+ if disc < 0.0 {
+ return None;
+ }
+ // Forme stable : `q` évite la soustraction catastrophique, et les deux racines s'en
+ // déduisent sans jamais retrancher deux quantités voisines. Le signe s'écrit en ternaire
+ // et non via `signum`, pour coller au shader — où `sign()` vaut 0 en 0 et annulerait `q`.
+ let sign_k1 = if k1 >= 0.0 { 1.0 } else { -1.0 };
+ let q = -0.5 * (k1 + sign_k1 * disc.sqrt());
+ let roots = [q / k2, if q.abs() > 0.0 { k0 / q } else { q / k2 }];
+ // Les DEUX racines sont essayées : trancher sur `t` seul retenait parfois celle dont le
+ // `s` tombe hors du quad, et le pixel était alors déclaré dehors alors que l'autre racine
+ // le plaçait dedans.
+ st_for_root(roots[0]).or_else(|| st_for_root(roots[1]))
+ }
+
+ #[test]
+ fn the_shader_mapping_covers_the_whole_tilted_quad() {
+ // Le bug rapporté : « une sorte d'overflow hidden qui tronque le screen recording ». Si le
+ // mapping inverse perd des pixels pourtant intérieurs au quad, le trou a exactement cette
+ // allure — un bord net, sans rapport avec la géométrie visible.
+ for (name, rot) in [
+ ("iso", rotation3d_for(&Some("iso".into()))),
+ ("left", rotation3d_for(&Some("left".into()))),
+ ("right", rotation3d_for(&Some("right".into()))),
+ ] {
+ let corners = rotated_quad_corners_px(1920.0, 1080.0, rot).corners;
+ let mut dropped = Vec::new();
+ let n = 64;
+ for i in 0..=n {
+ for j in 0..=n {
+ // On reste à un cheveu des arêtes : le contour exact est une frontière où le
+ // rejet est légitime.
+ let s = 0.002 + (i as f32 / n as f32) * 0.996;
+ let t = 0.002 + (j as f32 / n as f32) * 0.996;
+ let p = forward_bilinear(&corners, s, t);
+ match shader_inverse_bilinear(&corners, p) {
+ None => dropped.push((s, t)),
+ Some((s2, t2)) => {
+ // Retrouver le mauvais (s,t) est aussi grave : l'écran afficherait
+ // alors un morceau de lui-même au mauvais endroit.
+ if (s2 - s).abs() > 0.01 || (t2 - t).abs() > 0.01 {
+ dropped.push((s, t));
+ }
+ }
+ }
+ }
+ }
+ assert!(
+ dropped.is_empty(),
+ "{name} : {} points intérieurs perdus par le mapping, p.ex. {:?}",
+ dropped.len(),
+ &dropped[..dropped.len().min(5)]
+ );
+ }
+ }
}
diff --git a/poc-d3d/src/shaders.hlsl b/poc-d3d/src/shaders.hlsl
index 061ff41c9..47e3a0636 100644
--- a/poc-d3d/src/shaders.hlsl
+++ b/poc-d3d/src/shaders.hlsl
@@ -78,6 +78,46 @@ float sd_round_rect(float2 p, float2 halfsz, float r)
return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r;
}
+// Intersection de deux droites données par (normale, offset) : n·x = d. Cramer.
+float2 line_cross(float2 n1, float d1, float2 n2, float d2)
+{
+ float det = n1.x * n2.y - n1.y * n2.x;
+ if (abs(det) < 1e-6) return float2(0.0, 0.0); // arêtes parallèles : quad dégénéré
+ return float2(d1 * n2.y - d2 * n1.y, d2 * n1.x - d1 * n2.x) / det;
+}
+
+// Distance signée EXACTE à un quadrilatère convexe (<0 dedans). Le max des demi-plans suffit près
+// des arêtes mais donne un coin en pointe ; ici on veut aussi la distance juste au coin, puisque
+// c'est elle qui devient l'arrondi une fois le rayon retranché.
+float sd_convex_quad(float2 p, float2 v0, float2 v1, float2 v2, float2 v3)
+{
+ float2 v[5] = { v0, v1, v2, v3, v0 };
+ float inside = -1e9;
+ float border = 1e9;
+ [unroll] for (int k = 0; k < 4; k++)
+ {
+ float2 a = v[k];
+ float2 e = v[k + 1] - a;
+ float2 n = float2(e.y, -e.x) / max(length(e), 1e-6);
+ inside = max(inside, dot(p - a, n));
+ border = min(border, sd_segment(p, a, v[k + 1]));
+ }
+ return (inside < 0.0) ? -border : border;
+}
+
+// (s, t, ok) du warp inverse du mode 8 pour une racine `t` donnée : `ok` = 1 quand le couple
+// tombe dans le quad projeté (même marge 0.02 qu'ailleurs). Les deux racines doivent être
+// essayées — trancher sur `t` seul retient parfois celle dont le `s` sort du quad, et le pixel
+// est alors déclaré dehors alors que l'autre racine le plaçait dedans.
+float3 quad_st_for_root(float t, float2 e, float2 f, float2 g, float2 h)
+{
+ float denomX = e.x + g.x * t;
+ float denomY = e.y + g.y * t;
+ float s = (abs(denomX) > abs(denomY)) ? (h.x - f.x * t) / denomX : (h.y - f.y * t) / denomY;
+ float ok = (s >= -0.02 && s <= 1.02 && t >= -0.02 && t <= 1.02) ? 1.0 : 0.0;
+ return float3(s, t, ok);
+}
+
float4 ps_main(VSOut i) : SV_Target
{
// mode 8 : écran tilté en 3D (zoom regions "rotation" : iso/left/right). `dst`/`quad_px`
@@ -91,6 +131,39 @@ float4 ps_main(VSOut i) : SV_Target
// droit) il ne faut SURTOUT pas re-multiplier ici : les bords adoucis des glyphes
// deviendraient deux fois trop transparents et le texte paraîtrait délavé.
// `color.a` reste l'opacité globale (fondu d'animation).
+ //
+ // mode 12 : ombre du quad PROJETÉ. Même pénombre que le mode 2, mais portée par le
+ // quadrilatère incliné au lieu d'un rect droit — une ombre droite derrière un écran penché ne
+ // se lit pas comme son ombre, mais comme une seconde surface posée derrière. Les coins
+ // arrivent dans la même convention que le mode 8 (fx = TL/TR, src_prev = BR/BL, px locaux) ;
+ // mb.y = étalement de la pénombre en px.
+ if (mode > 11.5)
+ {
+ float2 quad[5] = { fx.xy, fx.zw, src_prev.xy, src_prev.zw, fx.xy };
+ // Coins arrondis du même rayon que le plan (`radius_px`). Une ombre à coins vifs derrière
+ // un écran aux coins arrondis dépasse en pointe à chaque coin — visible, et d'autant plus
+ // que le rayon monte. On rentre donc chaque arête de `r`, et retrancher `r` à la distance
+ // du quadrilatère ainsi obtenu redonne un arrondi exactement tangent aux deux arêtes.
+ float r = max(radius_px, 0.0);
+ float2 v[4];
+ [unroll] for (int k = 0; k < 4; k++)
+ {
+ // TL→TR→BR→BL tourne dans le sens horaire en y-bas, donc (e.y, -e.x) sort du quad.
+ // Division par la longueur plutôt que `normalize` : une arête dégénérée donnerait un
+ // NaN qui effacerait l'ombre entière.
+ float2 ep = quad[k] - quad[(k + 3) & 3]; // arête précédente
+ float2 ec = quad[k + 1] - quad[k]; // arête courante
+ float2 np = float2(ep.y, -ep.x) / max(length(ep), 1e-6);
+ float2 nc = float2(ec.y, -ec.x) / max(length(ec), 1e-6);
+ // Chaque arête rentrée de r : n·x = n·a - r. Leur intersection est le coin rentré.
+ v[k] = line_cross(np, dot(quad[(k + 3) & 3], np) - r, nc, dot(quad[k], nc) - r);
+ }
+ float d = sd_convex_quad(i.local, v[0], v[1], v[2], v[3]) - r;
+ float spread = max(mb.y, 1e-3);
+ float a = color.a * (1.0 - smoothstep(0.0, spread, d));
+ return float4(color.rgb * a, a);
+ }
+
if (mode > 10.5)
{
float4 s = texImg.Sample(samp, i.uv);
@@ -183,29 +256,50 @@ float4 ps_main(VSOut i) : SV_Target
float k2 = g.x * f.y - g.y * f.x;
float k1 = e.x * f.y - e.y * f.x + h.x * g.y - h.y * g.x;
float k0 = h.x * e.y - h.y * e.x;
- float t;
- if (abs(k2) < 0.001)
+ float3 r;
+ // Seuil RELATIF. Les présets « left »/« right » sont une rotation Y pure : le quad
+ // projeté est un trapèze symétrique dont `f` et `g` sont tous deux verticaux, donc
+ // k2 = 0 EXACTEMENT — au bruit d'arrondi près, et ce bruit vaut quelques centièmes sur
+ // des produits en 10^6. Un seuil absolu de 0.001 le manquait : l'équation passait dans la
+ // branche quadratique avec k2 ≈ 0, où `(-k1 + sqrt(k1²)) / 2k2` ne renvoie que du bruit —
+ // soustraire deux nombres presque égaux, puis diviser par presque rien. La quasi-totalité
+ // du quad était rejetée, ce qui se voyait comme un écran incliné tranché net.
+ if (abs(k2) < 1e-5 * abs(k1))
{
- t = (abs(k1) < 0.0001) ? 0.0 : -k0 / k1;
+ float t = (abs(k1) < 1e-6) ? 0.0 : -k0 / k1;
+ r = quad_st_for_root(t, e, f, g, h);
}
else
{
float disc = k1 * k1 - 4.0 * k2 * k0;
if (disc < 0.0) return float4(0.0, 0.0, 0.0, 0.0);
- float sq = sqrt(disc);
- float t1 = (-k1 + sq) / (2.0 * k2);
- float t2 = (-k1 - sq) / (2.0 * k2);
- t = (t1 >= -0.02 && t1 <= 1.02) ? t1 : t2;
+ // Forme stable : `q` n'oppose jamais deux quantités voisines, et les deux racines
+ // s'en déduisent exactement. `sign()` est évité parce qu'il vaut 0 en 0, ce qui
+ // annulerait `q` là où la formule reste parfaitement définie.
+ float q = -0.5 * (k1 + (k1 >= 0.0 ? 1.0 : -1.0) * sqrt(disc));
+ float3 r0 = quad_st_for_root(q / k2, e, f, g, h);
+ float3 r1 = quad_st_for_root(abs(q) > 0.0 ? k0 / q : q / k2, e, f, g, h);
+ r = (r0.z > 0.5) ? r0 : r1;
}
- float denomX = e.x + g.x * t;
- float denomY = e.y + g.y * t;
- float s = (abs(denomX) > abs(denomY)) ? (h.x - f.x * t) / denomX : (h.y - f.y * t) / denomY;
- if (s < -0.02 || s > 1.02 || t < -0.02 || t > 1.02)
+ if (r.z < 0.5)
{
return float4(0.0, 0.0, 0.0, 0.0); // hors du quad projeté
}
- float2 uv = float2(lerp(src.x, src.z, saturate(s)), lerp(src.y, src.w, saturate(t)));
- return float4(sample_yuv(uv), 1.0);
+ float2 uv = float2(lerp(src.x, src.z, saturate(r.x)), lerp(src.y, src.w, saturate(r.y)));
+ float tilt_a = 1.0;
+ if (radius_px > 0.0)
+ {
+ // Coins arrondis DANS LE REPÈRE DU PLAN (`dst_prev.xy` = sa taille avant projection) :
+ // le rayon reste constant le long du bord, alors qu'un arrondi calculé dans la bbox
+ // s'étirerait avec la perspective. Sans cet arrondi, un écran penché a des arêtes de
+ // couteau qui coupent le contenu en pleine phrase, et ça se lit comme une troncature
+ // plutôt que comme une inclinaison.
+ float2 plane_px = dst_prev.xy;
+ float2 p = float2(r.x, r.y) * plane_px - plane_px * 0.5;
+ float d = sd_round_rect(p, plane_px * 0.5, radius_px);
+ tilt_a = 1.0 - smoothstep(0.0, 1.5, d);
+ }
+ return float4(sample_yuv(uv) * tilt_a, tilt_a); // prémultiplié, comme les autres modes
}
// mode 7 : sprite curseur thème (PNG alpha droite, arrow.png etc.). Prémultiplie ici
diff --git a/poc-d3d/src/text_anim.rs b/poc-d3d/src/text_anim.rs
new file mode 100644
index 000000000..6a30bd0a0
--- /dev/null
+++ b/poc-d3d/src/text_anim.rs
@@ -0,0 +1,164 @@
+//! Animations d'apparition du texte d'annotation.
+//!
+//! Port VERBATIM de `src/lib/annotationTextAnimation.ts` : même durée, mêmes easings, mêmes
+//! amplitudes. Les sept animations étaient déjà nommées dans le schéma, traduites dans les treize
+//! langues et transportées jusqu'ici par la scène — mais rien ne les jouait. Reprendre les
+//! constantes du TS plutôt que d'en réinventer garantit qu'un projet fait à l'époque de l'aperçu
+//! DOM s'anime toujours pareil.
+
+/// Les décalages ci-dessous sont exprimés en px À CETTE HAUTEUR : l'appelant les met à l'échelle
+/// de la sortie, exactement comme la taille de police (cf. `annotationScale.ts`). En pixels
+/// absolus, la même animation sauterait de deux fois plus haut dans un rendu 4K que dans l'aperçu.
+pub const ANIMATION_REFERENCE_HEIGHT: f32 = 1080.0;
+
+pub const TEXT_ANIMATION_DURATION_MS: f32 = 700.0;
+
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct TextAnimationState {
+ pub opacity: f32,
+ pub scale: f32,
+ pub translate_x: f32,
+ pub translate_y: f32,
+ /// Fraction du bloc révélée depuis la gauche (machine à écrire). 1 = tout visible.
+ pub reveal: f32,
+}
+
+impl TextAnimationState {
+ /// L'état « rien à animer » — aussi celui d'une animation inconnue ou absente.
+ pub const IDLE: TextAnimationState =
+ TextAnimationState { opacity: 1.0, scale: 1.0, translate_x: 0.0, translate_y: 0.0, reveal: 1.0 };
+}
+
+fn clamp01(v: f32) -> f32 {
+ v.clamp(0.0, 1.0)
+}
+
+fn ease_out_cubic(v: f32) -> f32 {
+ let t = clamp01(v);
+ 1.0 - (1.0 - t).powi(3)
+}
+
+fn ease_out_back(v: f32) -> f32 {
+ let t = clamp01(v);
+ const C1: f32 = 1.70158;
+ const C3: f32 = C1 + 1.0;
+ 1.0 + C3 * (t - 1.0).powi(3) + C1 * (t - 1.0).powi(2)
+}
+
+/// État de l'animation `animation` après `elapsed_ms` depuis le début de l'annotation.
+pub fn text_animation_state(animation: Option<&str>, elapsed_ms: f32) -> TextAnimationState {
+ let name = animation.unwrap_or("none");
+ if name == "none" {
+ return TextAnimationState::IDLE;
+ }
+ let progress = clamp01(elapsed_ms.max(0.0) / TEXT_ANIMATION_DURATION_MS);
+ let eased = ease_out_cubic(progress);
+ match name {
+ "fade" => TextAnimationState { opacity: eased, ..TextAnimationState::IDLE },
+ "rise" => TextAnimationState {
+ opacity: eased,
+ translate_y: (1.0 - eased) * 18.0,
+ ..TextAnimationState::IDLE
+ },
+ "pop" => TextAnimationState {
+ opacity: eased,
+ scale: ease_out_back(progress).max(0.72),
+ ..TextAnimationState::IDLE
+ },
+ "slide-left" => TextAnimationState {
+ opacity: eased,
+ translate_x: (1.0 - eased) * -28.0,
+ ..TextAnimationState::IDLE
+ },
+ "typewriter" => TextAnimationState { reveal: progress, ..TextAnimationState::IDLE },
+ "pulse" => TextAnimationState {
+ scale: 1.0 + (progress * std::f32::consts::PI).sin() * 0.06,
+ ..TextAnimationState::IDLE
+ },
+ // Un nom inconnu (projet plus récent que ce binaire) montre le texte tel quel plutôt que
+ // de le faire disparaître.
+ _ => TextAnimationState::IDLE,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn no_animation_shows_the_text_as_is() {
+ for at in [0.0, 350.0, 5000.0] {
+ assert_eq!(text_animation_state(None, at), TextAnimationState::IDLE);
+ assert_eq!(text_animation_state(Some("none"), at), TextAnimationState::IDLE);
+ }
+ }
+
+ #[test]
+ fn an_unknown_name_shows_the_text_rather_than_hiding_it() {
+ // Le pire comportement serait une opacité 0 : l'annotation disparaîtrait sans explication.
+ assert_eq!(text_animation_state(Some("kenburns"), 0.0), TextAnimationState::IDLE);
+ }
+
+ #[test]
+ fn every_animation_settles_on_the_plain_text() {
+ // Propriété qui compte le plus : passée la durée, aucune animation ne laisse de trace.
+ for name in ["fade", "rise", "pop", "slide-left", "typewriter", "pulse"] {
+ let end = text_animation_state(Some(name), TEXT_ANIMATION_DURATION_MS + 1.0);
+ assert!((end.opacity - 1.0).abs() < 1e-3, "{name} : opacité {}", end.opacity);
+ assert!((end.scale - 1.0).abs() < 1e-3, "{name} : échelle {}", end.scale);
+ assert!(end.translate_x.abs() < 1e-3 && end.translate_y.abs() < 1e-3, "{name} : décalé");
+ assert!((end.reveal - 1.0).abs() < 1e-3, "{name} : révélation {}", end.reveal);
+ }
+ }
+
+ #[test]
+ fn fade_and_rise_start_invisible_and_below() {
+ let fade = text_animation_state(Some("fade"), 0.0);
+ assert_eq!(fade.opacity, 0.0);
+ let rise = text_animation_state(Some("rise"), 0.0);
+ assert_eq!(rise.opacity, 0.0);
+ assert!((rise.translate_y - 18.0).abs() < 1e-3, "part de 18px plus bas");
+ }
+
+ #[test]
+ fn slide_left_enters_from_the_right() {
+ // Signe négatif = le texte commence décalé vers la gauche et revient, comme le TS.
+ let s = text_animation_state(Some("slide-left"), 0.0);
+ assert!((s.translate_x + 28.0).abs() < 1e-3, "translate_x = {}", s.translate_x);
+ }
+
+ #[test]
+ fn pop_overshoots_then_comes_back() {
+ // easeOutBack dépasse 1 avant de retomber : c'est ce qui donne le « pop ».
+ let mid = (0..=100)
+ .map(|i| text_animation_state(Some("pop"), i as f32 * 7.0).scale)
+ .fold(0.0f32, f32::max);
+ assert!(mid > 1.0, "aucun dépassement : échelle max {mid}");
+ assert!(text_animation_state(Some("pop"), 0.0).scale >= 0.72, "plancher du TS respecté");
+ }
+
+ #[test]
+ fn pulse_swells_in_the_middle_and_never_moves() {
+ let mid = text_animation_state(Some("pulse"), TEXT_ANIMATION_DURATION_MS * 0.5);
+ assert!((mid.scale - 1.06).abs() < 1e-3, "échelle {}", mid.scale);
+ assert_eq!(mid.opacity, 1.0);
+ assert_eq!(mid.translate_x, 0.0);
+ }
+
+ #[test]
+ fn typewriter_reveals_linearly_and_only_from_the_left() {
+ for (at, expected) in [(0.0, 0.0), (175.0, 0.25), (350.0, 0.5), (700.0, 1.0)] {
+ let s = text_animation_state(Some("typewriter"), at);
+ assert!((s.reveal - expected).abs() < 1e-3, "à {at}ms : {}", s.reveal);
+ // Le texte reste opaque : c'est la largeur qui se dévoile, pas l'alpha (l'aperçu DOM
+ // faisait exactement ça avec un `inset()`).
+ assert_eq!(s.opacity, 1.0);
+ }
+ }
+
+ #[test]
+ fn a_negative_elapsed_time_is_the_start_not_the_end() {
+ // Peut arriver d'une frame calculée juste avant le début de l'annotation.
+ assert_eq!(text_animation_state(Some("fade"), -50.0).opacity, 0.0);
+ }
+}
diff --git a/src/components/ai-edition/AnnotationLayer.tsx b/src/components/ai-edition/AnnotationLayer.tsx
index 94b688171..c79ed460b 100644
--- a/src/components/ai-edition/AnnotationLayer.tsx
+++ b/src/components/ai-edition/AnnotationLayer.tsx
@@ -8,19 +8,15 @@
import type { AxcutAnnotationRegion } from "@/lib/ai-edition/schema";
import { AnnotationOverlay } from "./AnnotationOverlay";
-type BlurData = NonNullable<AxcutAnnotationRegion["blurData"]>;
-
interface AnnotationLayerProps {
annotations: AxcutAnnotationRegion[];
selectedAnnotationId: string | null;
currentTimeSec: number;
containerWidth: number;
containerHeight: number;
- videoElement?: HTMLVideoElement | null;
onSelectAnnotation: (id: string) => void;
onPositionChange: (id: string, position: { x: number; y: number }) => void;
onSizeChange: (id: string, size: { width: number; height: number }) => void;
- onBlurDataChange: (id: string, blurData: BlurData) => void;
onCommit: () => void;
}
@@ -30,11 +26,9 @@ export function AnnotationLayer({
currentTimeSec,
containerWidth,
containerHeight,
- videoElement,
onSelectAnnotation,
onPositionChange,
onSizeChange,
- onBlurDataChange,
onCommit,
}: AnnotationLayerProps) {
const currentTimeMs = Math.round(currentTimeSec * 1000);
@@ -65,25 +59,20 @@ export function AnnotationLayer({
<div className="absolute inset-0" style={{ pointerEvents: "none" }}>
{visible.map((annotation) => (
<AnnotationOverlay
- key={
- annotation.type === "blur"
- ? `${annotation.id}-${containerWidth}-${containerHeight}-${annotation.blurData?.shape ?? "rectangle"}-${annotation.blurData?.color ?? "white"}-${Math.round(annotation.blurData?.blockSize ?? 0)}-${(annotation.blurData?.freehandPoints ?? []).map((p) => `${Math.round(p.x)}_${Math.round(p.y)}`).join("-")}`
- : `${annotation.id}-${containerWidth}-${containerHeight}`
- }
+ // La clé ne porte plus les champs de `blurData` : ils forçaient un remontage à
+ // chaque réglage du flou, pour resynchroniser un canvas de mosaïque qui n'existe
+ // plus. La taille du conteneur y reste, elle, parce qu'elle change le rect en px.
+ key={`${annotation.id}-${containerWidth}-${containerHeight}`}
annotation={annotation}
isSelected={annotation.id === selectedAnnotationId}
containerWidth={containerWidth}
containerHeight={containerHeight}
onPositionChange={onPositionChange}
onSizeChange={onSizeChange}
- onBlurDataChange={annotation.type === "blur" ? onBlurDataChange : undefined}
- onBlurDataCommit={annotation.type === "blur" ? onCommit : undefined}
onCommit={onCommit}
onClick={handleClick}
zIndex={annotation.zIndex}
isSelectedBoost={annotation.id === selectedAnnotationId}
- videoElement={videoElement}
- currentTimeMs={currentTimeMs}
/>
))}
</div>
diff --git a/src/components/ai-edition/AnnotationOverlay.tsx b/src/components/ai-edition/AnnotationOverlay.tsx
index 9901a2020..81f8c2592 100644
--- a/src/components/ai-edition/AnnotationOverlay.tsx
+++ b/src/components/ai-edition/AnnotationOverlay.tsx
@@ -1,49 +1,18 @@
-// Port of `src/components/video-editor/AnnotationOverlay.tsx`, adapted for
-// the new editor's CSS-only preview (no Pixi stage to `extract` a frame
-// from): the mosaic blur effect samples pixels directly from the active
-// <video> element via `drawImage` instead of a Pixi-rendered snapshot
-// canvas. Everything else — Rnd drag/resize math, per-type rendering,
-// freehand blur drawing, text animation — is ported verbatim so the preview
-// behaves identically to the legacy editor.
-
-import { type CSSProperties, type PointerEvent, useEffect, useRef, useState } from "react";
+// Chrome d'édition d'une annotation : cadre de sélection, glissement, poignées de
+// redimensionnement. Les PIXELS de l'annotation — texte, image, flèche, flou — sont peints par le
+// compositeur natif, aperçu compris.
+//
+// Ce fichier était le port du `AnnotationOverlay` de l'éditeur v2 : il rendait les quatre types en
+// DOM et portait la saisie du tracé libre, soit ~400 lignes qui ne s'exécutaient plus depuis que
+// le natif peint l'aperçu. Les garder ne coûtait pas seulement de la lecture : elles décrivaient un
+// rendu concurrent, sur une autre horloge, ce qui avait déjà produit le bug des annotations
+// affichées en double (une copie collée au curseur, un fantôme resté en place jusqu'au
+// relâchement). Le détail reste dans `git log`.
+
+import { useEffect, useRef, useState } from "react";
import { Rnd } from "react-rnd";
-import { useScopedT } from "@/contexts/I18nContext";
-import { annotationFontSizePx } from "@/lib/ai-edition/annotationScale";
-import {
- getBlurOverlayColor,
- getMosaicGridOverlayColor,
- getNormalizedMosaicBlockSize,
-} from "@/lib/ai-edition/annotations/blurEffects";
-import { DEFAULT_BLUR_BLOCK_SIZE, DEFAULT_BLUR_DATA } from "@/lib/ai-edition/annotations/constants";
-import { getTextAnimationState } from "@/lib/ai-edition/annotations/textAnimation";
import type { AxcutAnnotationRegion } from "@/lib/ai-edition/schema";
import { cn } from "@/lib/utils";
-import { getArrowComponent } from "./ArrowSvgs";
-
-type BlurData = NonNullable<AxcutAnnotationRegion["blurData"]>;
-
-const FREEHAND_POINT_THRESHOLD = 1;
-
-function buildBlurPolygonClipPath(points: Array<{ x: number; y: number }>) {
- if (points.length < 3) return undefined;
- const polygon = points.map((point) => `${point.x}% ${point.y}%`).join(", ");
- return `polygon(${polygon})`;
-}
-
-function buildBlurFreehandPath(points: Array<{ x: number; y: number }>, closed = true) {
- if (closed ? points.length < 3 : points.length < 2) return null;
- const [firstPoint, ...rest] = points;
- const path = `M ${firstPoint.x} ${firstPoint.y} ${rest.map((point) => `L ${point.x} ${point.y}`).join(" ")}`;
- return closed ? `${path} Z` : path;
-}
-
-/**
- * Le compositeur natif est-il responsable des pixels d'annotation ? Constante plutôt que valeur
- * en dur, pour que le point de bascule soit nommé et qu'on retrouve d'un coup tout ce qui en
- * dépend le jour où l'on nettoiera le code de peinture devenu inatteignable.
- */
-const NATIVE_PAINTS_ANNOTATIONS = true;
interface AnnotationOverlayProps {
annotation: AxcutAnnotationRegion;
@@ -52,15 +21,11 @@ interface AnnotationOverlayProps {
containerHeight: number;
onPositionChange: (id: string, position: { x: number; y: number }) => void;
onSizeChange: (id: string, size: { width: number; height: number }) => void;
- onBlurDataChange?: (id: string, blurData: BlurData) => void;
- onBlurDataCommit?: () => void;
/** Écriture disque, appelée une fois en fin de geste — le drag/resize ne fait que du live. */
onCommit?: () => void;
onClick: (id: string) => void;
zIndex: number;
isSelectedBoost: boolean;
- videoElement?: HTMLVideoElement | null;
- currentTimeMs: number;
}
export function AnnotationOverlay({
@@ -70,35 +35,17 @@ export function AnnotationOverlay({
containerHeight,
onPositionChange,
onSizeChange,
- onBlurDataChange,
- onBlurDataCommit,
onCommit,
onClick,
zIndex,
isSelectedBoost,
- videoElement,
- currentTimeMs,
}: AnnotationOverlayProps) {
- const te = useScopedT("editor");
const committedX = (annotation.position.x / 100) * containerWidth;
const committedY = (annotation.position.y / 100) * containerHeight;
const committedWidth = (annotation.size.width / 100) * containerWidth;
const committedHeight = (annotation.size.height / 100) * containerHeight;
const blurShape = annotation.type === "blur" ? (annotation.blurData?.shape ?? "rectangle") : null;
- const isSelectedFreehandBlur = isSelected && blurShape === "freehand";
const isDraggingRef = useRef(false);
- const isDrawingFreehandRef = useRef(false);
- const freehandPointsRef = useRef<Array<{ x: number; y: number }>>([]);
- const [isFreehandDrawing, setIsFreehandDrawing] = useState(false);
- const [draftFreehandPoints, setDraftFreehandPoints] = useState<Array<{ x: number; y: number }>>(
- [],
- );
- const [livePointerPoint, setLivePointerPoint] = useState<{ x: number; y: number } | null>(null);
- const mosaicCanvasRef = useRef<HTMLCanvasElement | null>(null);
- const blurOverlayColor =
- annotation.type === "blur" ? getBlurOverlayColor(annotation.blurData) : "";
- const mosaicGridOverlayColor =
- annotation.type === "blur" ? getMosaicGridOverlayColor(annotation.blurData) : "";
const [liveRect, setLiveRect] = useState({
x: committedX,
y: committedY,
@@ -117,393 +64,6 @@ export function AnnotationOverlay({
const { x, y, width, height } = liveRect;
- // ponytail: legacy sampled from `app.renderer.extract.canvas(app.stage)` —
- // a Pixi-composited frame. The new preview has no Pixi stage for the main
- // video, so this samples the <video> element directly. Visually
- // equivalent as long as nothing else (zoom, cursor) sits between the
- // video and this overlay in z-order, which matches today's stacking.
- useEffect(() => {
- if (annotation.type !== "blur") return;
- void currentTimeMs;
-
- const canvas = mosaicCanvasRef.current;
- const video = videoElement;
- if (!canvas || !video || video.readyState < 2) return;
-
- const sourceWidth = video.videoWidth;
- const sourceHeight = video.videoHeight;
- const sourceClientWidth = video.clientWidth || containerWidth || sourceWidth;
- const sourceClientHeight = video.clientHeight || containerHeight || sourceHeight;
- if (
- sourceWidth <= 0 ||
- sourceHeight <= 0 ||
- sourceClientWidth <= 0 ||
- sourceClientHeight <= 0
- ) {
- return;
- }
-
- const drawWidth = Math.max(1, Math.round(width));
- const drawHeight = Math.max(1, Math.round(height));
- if (drawWidth <= 0 || drawHeight <= 0) return;
-
- const context = canvas.getContext("2d", { willReadFrequently: true });
- if (!context) return;
-
- const scaleX = sourceWidth / sourceClientWidth;
- const scaleY = sourceHeight / sourceClientHeight;
- const sourceX = Math.max(0, Math.floor(x * scaleX));
- const sourceY = Math.max(0, Math.floor(y * scaleY));
- const sourceSampleWidth = Math.max(1, Math.ceil(drawWidth * scaleX));
- const sourceSampleHeight = Math.max(1, Math.ceil(drawHeight * scaleY));
- const clampedSampleWidth = Math.max(1, Math.min(sourceSampleWidth, sourceWidth - sourceX));
- const clampedSampleHeight = Math.max(1, Math.min(sourceSampleHeight, sourceHeight - sourceY));
- const blockSize = getNormalizedMosaicBlockSize(annotation.blurData);
- const downscaledWidth = Math.max(1, Math.round(drawWidth / blockSize));
- const downscaledHeight = Math.max(1, Math.round(drawHeight / blockSize));
- canvas.width = downscaledWidth;
- canvas.height = downscaledHeight;
-
- context.clearRect(0, 0, downscaledWidth, downscaledHeight);
- context.imageSmoothingEnabled = true;
- context.drawImage(
- video,
- sourceX,
- sourceY,
- clampedSampleWidth,
- clampedSampleHeight,
- 0,
- 0,
- downscaledWidth,
- downscaledHeight,
- );
- }, [
- annotation,
- containerHeight,
- containerWidth,
- height,
- videoElement,
- currentTimeMs,
- width,
- x,
- y,
- ]);
-
- const renderArrow = () => {
- const direction = annotation.figureData?.arrowDirection || "right";
- const color = annotation.figureData?.color || "#34B27B";
- const strokeWidth = annotation.figureData?.strokeWidth || 4;
- const ArrowComponent = getArrowComponent(direction);
- return <ArrowComponent color={color} strokeWidth={strokeWidth} />;
- };
-
- const normalizePoint = (event: PointerEvent<HTMLDivElement>) => {
- const rect = event.currentTarget.getBoundingClientRect();
- const px = ((event.clientX - rect.left) / rect.width) * 100;
- const py = ((event.clientY - rect.top) / rect.height) * 100;
- return { x: Math.max(0, Math.min(100, px)), y: Math.max(0, Math.min(100, py)) };
- };
-
- const appendFreehandPoint = (point: { x: number; y: number }) => {
- const points = freehandPointsRef.current;
- const lastPoint = points[points.length - 1];
- if (!lastPoint) {
- points.push(point);
- return;
- }
- const dx = point.x - lastPoint.x;
- const dy = point.y - lastPoint.y;
- if (Math.hypot(dx, dy) >= FREEHAND_POINT_THRESHOLD) {
- points.push(point);
- }
- };
-
- const handleFreehandPointerDown = (event: PointerEvent<HTMLDivElement>) => {
- if (
- !isSelected ||
- annotation.type !== "blur" ||
- annotation.blurData?.shape !== "freehand" ||
- !onBlurDataChange
- ) {
- return;
- }
- event.preventDefault();
- event.stopPropagation();
- event.currentTarget.setPointerCapture(event.pointerId);
- isDrawingFreehandRef.current = true;
- setIsFreehandDrawing(true);
- const point = normalizePoint(event);
- freehandPointsRef.current = [point];
- setDraftFreehandPoints([point]);
- setLivePointerPoint(point);
- };
-
- const handleFreehandPointerMove = (event: PointerEvent<HTMLDivElement>) => {
- if (!isDrawingFreehandRef.current) return;
- event.preventDefault();
- event.stopPropagation();
- const point = normalizePoint(event);
- setLivePointerPoint(point);
- appendFreehandPoint(point);
- setDraftFreehandPoints([...freehandPointsRef.current]);
- };
-
- const finishFreehandPointer = (event: PointerEvent<HTMLDivElement>) => {
- if (!isDrawingFreehandRef.current || !onBlurDataChange) return;
- isDrawingFreehandRef.current = false;
- setIsFreehandDrawing(false);
- try {
- event.currentTarget.releasePointerCapture(event.pointerId);
- } catch {
- // no-op if already released
- }
- const points = [...freehandPointsRef.current];
- if (livePointerPoint) {
- const last = points[points.length - 1];
- if (!last || Math.hypot(last.x - livePointerPoint.x, last.y - livePointerPoint.y) > 0.001) {
- points.push(livePointerPoint);
- }
- }
- if (points.length >= 3) {
- const closedPoints = [...points];
- const first = closedPoints[0];
- const last = closedPoints[closedPoints.length - 1];
- if (Math.hypot(last.x - first.x, last.y - first.y) > 0.001) {
- closedPoints.push({ ...first });
- }
- onBlurDataChange(annotation.id, {
- ...(annotation.blurData || { ...DEFAULT_BLUR_DATA, shape: "freehand" }),
- shape: "freehand",
- freehandPoints: closedPoints,
- });
- setDraftFreehandPoints(closedPoints);
- onBlurDataCommit?.();
- }
- setLivePointerPoint(null);
- };
-
- const renderContent = () => {
- // Le compositeur natif dessine désormais les quatre types d'annotation, PREVIEW COMPRISE.
- // Les peindre aussi ici donnait deux copies superposées ; et comme les deux ne suivent pas
- // la même horloge, celle du DOM collait au curseur pendant qu'un fantôme restait en place
- // jusqu'au relâchement, avant de se recaler avec un écart de taille. Ce composant ne garde
- // donc que le chrome d'édition — cadre de sélection et poignées — qui n'a rien à faire
- // dans le rendu final.
- //
- // Le code de peinture ci-dessous est laissé en place, inatteignable : le supprimer touche
- // à ~400 lignes et à la saisie du tracé libre, qui est de toute façon en cours de retrait.
- // À nettoyer dans un passage dédié plutôt qu'au milieu d'un correctif.
- if (NATIVE_PAINTS_ANNOTATIONS) return null;
- switch (annotation.type) {
- case "text": {
- const animationState = getTextAnimationState(annotation, currentTimeMs);
- const typewriterClip =
- animationState.revealProgress < 1
- ? `inset(0 ${100 - animationState.revealProgress * 100}% 0 0)`
- : undefined;
- return (
- <div
- className="w-full h-full flex items-center p-2 overflow-hidden"
- style={{
- justifyContent:
- annotation.style.textAlign === "left"
- ? "flex-start"
- : annotation.style.textAlign === "right"
- ? "flex-end"
- : "center",
- alignItems: "center",
- }}
- >
- <span
- style={{
- color: annotation.style.color,
- backgroundColor: annotation.style.backgroundColor,
- fontSize: `${annotationFontSizePx(annotation.style.fontSize, containerHeight)}px`,
- fontFamily: annotation.style.fontFamily,
- fontWeight: annotation.style.fontWeight,
- fontStyle: annotation.style.fontStyle,
- textDecoration: annotation.style.textDecoration,
- textAlign: annotation.style.textAlign,
- opacity: animationState.opacity,
- transform: `translate(${animationState.translateX}px, ${animationState.translateY}px) scale(${animationState.scale})`,
- transformOrigin: "center",
- clipPath: typewriterClip,
- WebkitClipPath: typewriterClip,
- wordBreak: "break-word",
- whiteSpace: "pre-wrap",
- boxDecorationBreak: "clone",
- WebkitBoxDecorationBreak: "clone",
- padding: "0.1em 0.2em",
- borderRadius: "4px",
- lineHeight: "1.4",
- }}
- >
- {annotation.content}
- </span>
- </div>
- );
- }
-
- case "image":
- if (annotation.content?.startsWith("data:image")) {
- return (
- <img
- src={annotation.content}
- alt={te("annotationOverlay.imageAlt")}
- className="w-full h-full object-contain"
- draggable={false}
- />
- );
- }
- return (
- <div className="w-full h-full flex items-center justify-center text-slate-400 text-sm">
- {te("annotationOverlay.noImage")}
- </div>
- );
-
- case "figure":
- if (!annotation.figureData) {
- return (
- <div className="w-full h-full flex items-center justify-center text-slate-400 text-sm">
- {te("annotationOverlay.noArrowData")}
- </div>
- );
- }
- return (
- <div className="w-full h-full flex items-center justify-center p-2">{renderArrow()}</div>
- );
-
- case "blur": {
- const shape = annotation.blurData?.shape ?? "rectangle";
- const blockSize = Math.max(
- 1,
- Math.round(annotation.blurData?.blockSize ?? DEFAULT_BLUR_BLOCK_SIZE),
- );
- const activeFreehandPoints =
- shape === "freehand"
- ? isFreehandDrawing
- ? draftFreehandPoints
- : (annotation.blurData?.freehandPoints ?? [])
- : [];
- const drawingPoints =
- isFreehandDrawing && livePointerPoint
- ? (() => {
- const last = activeFreehandPoints[activeFreehandPoints.length - 1];
- if (!last) return [livePointerPoint];
- const dx = livePointerPoint.x - last.x;
- const dy = livePointerPoint.y - last.y;
- return Math.hypot(dx, dy) > 0.01
- ? [...activeFreehandPoints, livePointerPoint]
- : activeFreehandPoints;
- })()
- : activeFreehandPoints;
- const clipPath =
- shape === "freehand" ? buildBlurPolygonClipPath(activeFreehandPoints) : undefined;
- const freehandPath =
- shape === "freehand"
- ? buildBlurFreehandPath(
- isFreehandDrawing ? drawingPoints : activeFreehandPoints,
- !isFreehandDrawing,
- )
- : null;
- const currentPointerPoint = isFreehandDrawing
- ? livePointerPoint || drawingPoints[drawingPoints.length - 1] || null
- : null;
- const shapeBorderRadius = shape === "oval" ? "50%" : shape === "rectangle" ? "8px" : "0";
- const shouldShowFreehandBlurFill =
- shape !== "freehand" || (!!clipPath && !isFreehandDrawing);
- const shapeMaskStyle: CSSProperties = {
- borderRadius: shapeBorderRadius,
- clipPath: isFreehandDrawing ? undefined : clipPath,
- WebkitClipPath: isFreehandDrawing ? undefined : clipPath,
- };
- const isFreehandSelected = isSelectedFreehandBlur;
- return (
- <div className="w-full h-full relative">
- <div
- className="absolute inset-0 overflow-hidden"
- style={{ ...shapeMaskStyle, isolation: "isolate" }}
- >
- <div
- className="absolute inset-0"
- style={{
- ...shapeMaskStyle,
- backgroundColor: blurOverlayColor,
- opacity: shouldShowFreehandBlurFill ? 1 : 0,
- }}
- />
- {shouldShowFreehandBlurFill && (
- <canvas
- ref={mosaicCanvasRef}
- className="absolute inset-0 w-full h-full"
- style={{ ...shapeMaskStyle, imageRendering: "pixelated" }}
- />
- )}
- {shouldShowFreehandBlurFill && (
- <div
- className="absolute inset-0 pointer-events-none"
- style={{ ...shapeMaskStyle, backgroundColor: blurOverlayColor }}
- />
- )}
- <div
- className="absolute inset-0 pointer-events-none"
- style={{
- ...shapeMaskStyle,
- backgroundImage: `linear-gradient(${mosaicGridOverlayColor} 1px, transparent 1px), linear-gradient(90deg, ${mosaicGridOverlayColor} 1px, transparent 1px)`,
- backgroundSize: `${blockSize}px ${blockSize}px`,
- mixBlendMode: "screen",
- opacity: 0.35,
- }}
- />
- {isSelected && shape !== "freehand" && (
- <div
- className="absolute inset-0 pointer-events-none border-2 border-[#34B27B]/80"
- style={{ borderRadius: shapeBorderRadius }}
- />
- )}
- </div>
- {isSelected && shape === "freehand" && freehandPath && (
- <svg
- viewBox="0 0 100 100"
- preserveAspectRatio="none"
- className="absolute inset-0 pointer-events-none"
- >
- <path
- d={freehandPath}
- fill="none"
- stroke="#34B27B"
- strokeWidth="0.55"
- strokeLinecap="round"
- strokeLinejoin="round"
- />
- {currentPointerPoint && (
- <circle
- cx={currentPointerPoint.x}
- cy={currentPointerPoint.y}
- r="0.6"
- fill="#34B27B"
- />
- )}
- </svg>
- )}
- {isFreehandSelected && (
- <div
- className="absolute inset-0 cursor-crosshair"
- onPointerDown={handleFreehandPointerDown}
- onPointerMove={handleFreehandPointerMove}
- onPointerUp={finishFreehandPointer}
- onPointerCancel={finishFreehandPointer}
- />
- )}
- </div>
- );
- }
-
- default:
- return null;
- }
- };
-
return (
<Rnd
position={{ x, y }}
@@ -584,8 +144,11 @@ export function AnnotationOverlay({
boxShadow:
isSelected && annotation.type !== "blur" ? "0 0 0 1px rgba(52, 178, 123, 0.35)" : "none",
}}
- enableResizing={isSelected && !isSelectedFreehandBlur}
- disableDragging={!isSelected || isSelectedFreehandBlur}
+ // Un flou en tracé libre se déplace et se redimensionne comme les autres : ce qui le
+ // bloquait, c'était la zone de saisie du tracé qui capturait le pointeur — et elle est
+ // partie avec l'outil.
+ enableResizing={isSelected}
+ disableDragging={!isSelected}
resizeHandleStyles={{
topLeft: {
width: "12px",
@@ -631,12 +194,20 @@ export function AnnotationOverlay({
>
<div
className={cn(
- "w-full h-full",
+ "w-full h-full relative",
annotation.type !== "blur" && "rounded-lg",
isSelected && annotation.type !== "blur" && "shadow-lg",
)}
>
- {renderContent()}
+ {/* Le cadre d'un flou sélectionné, à la forme du masque. Les autres types portent le
+ leur sur le `Rnd` lui-même ; un flou n'en a pas, pour ne pas encadrer la zone qu'il
+ est censé cacher — sans ce liseré il n'aurait AUCUN retour de sélection. */}
+ {isSelected && annotation.type === "blur" ? (
+ <div
+ className="absolute inset-0 pointer-events-none border-2 border-[#34B27B]/80"
+ style={{ borderRadius: blurShape === "oval" ? "50%" : "8px" }}
+ />
+ ) : null}
</div>
</Rnd>
);
diff --git a/src/components/ai-edition/ColorField.test.tsx b/src/components/ai-edition/ColorField.test.tsx
index 18e8113c8..84e6f771e 100644
--- a/src/components/ai-edition/ColorField.test.tsx
+++ b/src/components/ai-edition/ColorField.test.tsx
@@ -16,9 +16,9 @@ beforeAll(() => {
vi.stubGlobal(
"ResizeObserver",
class {
- observe() {}
- unobserve() {}
- disconnect() {}
+ observe = () => undefined;
+ unobserve = () => undefined;
+ disconnect = () => undefined;
},
);
});
diff --git a/src/components/ai-edition/PreviewCanvas.tsx b/src/components/ai-edition/PreviewCanvas.tsx
index b2985ec41..8a32b1fe7 100644
--- a/src/components/ai-edition/PreviewCanvas.tsx
+++ b/src/components/ai-edition/PreviewCanvas.tsx
@@ -300,12 +300,12 @@ export function PreviewCanvas(props: PreviewCanvasProps) {
layout?.webcamRect && activeCameraTrack?.visible && activeCameraTrack.sourcePath,
);
const [isPlaying, setIsPlaying] = useState(false);
- const [videoEl, setVideoEl] = useState<HTMLVideoElement | null>(null);
const handleVideoElement = useMemo(() => props.onVideoElement, [props.onVideoElement]);
+ // L'élément `<video>` lui-même n'est plus retenu : il ne servait qu'à échantillonner des pixels
+ // pour la mosaïque dessinée en DOM, que le compositeur natif rend désormais.
const relayIsPlaying = (el: HTMLVideoElement | null) => {
handleVideoElement(el);
setIsPlaying(!el?.paused);
- setVideoEl(el);
};
const relayLoadedMetadata = (
durationSec: number,
@@ -423,7 +423,6 @@ export function PreviewCanvas(props: PreviewCanvasProps) {
props.onSelectAnnotation &&
props.onAnnotationPositionChange &&
props.onAnnotationSizeChange &&
- props.onAnnotationBlurDataChange &&
props.onAnnotationCommit ? (
<AnnotationLayer
annotations={props.annotationRegions}
@@ -431,11 +430,9 @@ export function PreviewCanvas(props: PreviewCanvasProps) {
currentTimeSec={props.currentTimeSec}
containerWidth={layout.screenRect.width}
containerHeight={layout.screenRect.height}
- videoElement={videoEl}
onSelectAnnotation={props.onSelectAnnotation}
onPositionChange={props.onAnnotationPositionChange}
onSizeChange={props.onAnnotationSizeChange}
- onBlurDataChange={props.onAnnotationBlurDataChange}
onCommit={props.onAnnotationCommit}
/>
) : null}
diff --git a/src/components/ai-edition/v4/FloatingInspector.tsx b/src/components/ai-edition/v4/FloatingInspector.tsx
index 9a7c02228..93f491e8d 100644
--- a/src/components/ai-edition/v4/FloatingInspector.tsx
+++ b/src/components/ai-edition/v4/FloatingInspector.tsx
@@ -17,7 +17,11 @@ import type { ComponentProps } from "react";
import { useMemo, useRef, useState } from "react";
import { toast } from "sonner";
import { parseCustomPlaybackSpeedInput } from "@/components/video-editor/customPlaybackSpeed";
-import { MAX_PLAYBACK_SPEED, SPEED_OPTIONS } from "@/components/video-editor/types";
+import {
+ MAX_PLAYBACK_SPEED,
+ SPEED_OPTIONS,
+ ZOOM_DEPTH_SCALES,
+} from "@/components/video-editor/types";
import { useScopedT } from "@/contexts/I18nContext";
import {
hasTextBackground,
@@ -25,6 +29,10 @@ import {
textBackgroundColor,
toggleTextBackground,
} from "@/lib/ai-edition/annotations/background";
+import {
+ type AnnotationTextAnimation,
+ TEXT_ANIMATION_VALUES,
+} from "@/lib/ai-edition/annotations/textAnimation";
import type { AxcutAnnotationRegion, AxcutClip } from "@/lib/ai-edition/schema";
import { rafCoalesce } from "@/lib/ai-edition/store/rafCoalesce";
import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";
@@ -514,7 +522,9 @@ function SelectionPane({ tl, onClose }: { tl: TimelineApi; onClose: () => void }
>
{ZOOM_DEPTHS.map((d) => (
<option key={d} value={d}>
- {(d / 2 + 0.5).toFixed(1)}×
+ {/* La table, pas une formule : ce libellé annonçait « 2.0× » là où la pastille de la
+ timeline affiche « 1.80× » et où le rendu applique 1.8. */}
+ {ZOOM_DEPTH_SCALES[d]}×
</option>
))}
</select>,
@@ -885,6 +895,34 @@ function SelectionPane({ tl, onClose }: { tl: TimelineApi; onClose: () => void }
</div>,
)
: null}
+ {region.type === "text"
+ ? paneRow(
+ ts("textAnimation.title"),
+ // Les sept animations existaient : nommées dans le schéma, traduites dans les
+ // treize langues, transportées jusqu'au compositeur — et injouables, faute de
+ // ce sélecteur.
+ <select
+ aria-label={ts("textAnimation.selectAnimation")}
+ value={region.style?.textAnimation ?? "none"}
+ onChange={(e) => {
+ tl.updateAnnotationLive(region.id, {
+ style: {
+ ...region.style,
+ textAnimation: e.target.value as AnnotationTextAnimation,
+ },
+ });
+ void tl.commitAnnotationChange();
+ }}
+ style={selectStyle}
+ >
+ {TEXT_ANIMATION_VALUES.map((value) => (
+ <option key={value} value={value}>
+ {ts(`textAnimation.${value === "slide-left" ? "slideLeft" : value}`)}
+ </option>
+ ))}
+ </select>,
+ )
+ : null}
{region.type === "text"
? paneRow(
ts("annotation.color"),
diff --git a/src/components/video-editor/types.ts b/src/components/video-editor/types.ts
index 00666a8c6..cabf28800 100644
--- a/src/components/video-editor/types.ts
+++ b/src/components/video-editor/types.ts
@@ -45,17 +45,25 @@ export const DEFAULT_ROTATION_3D: Rotation3D = {
export type Rotation3DPreset = "iso" | "left" | "right";
+// Every preset carries all three components on purpose. With a single-axis rotation the projected
+// quad keeps an edge exactly parallel to the frame — both vertical edges for a pure Y rotation,
+// which is geometry rather than a setting — and a perfectly vertical edge cutting through text is
+// indistinguishable from `overflow: hidden`. That is what got reported three times as "the
+// recording is truncated" while the plane was in fact drawn whole. `regions.rs` holds the same
+// numbers and a test asserting no edge comes within 2° of an axis.
export const ROTATION_3D_PRESETS: Record<Rotation3DPreset, Rotation3D> = {
- iso: { rotationX: -10, rotationY: -16, rotationZ: 0 },
- left: { rotationX: 0, rotationY: -22, rotationZ: 0 },
- right: { rotationX: 0, rotationY: 22, rotationZ: 0 },
+ iso: { rotationX: -12, rotationY: -18, rotationZ: -2 },
+ left: { rotationX: -8, rotationY: -16, rotationZ: -1 },
+ right: { rotationX: -8, rotationY: 16, rotationZ: 1 },
};
export const ROTATION_3D_PRESET_ORDER: Rotation3DPreset[] = ["iso", "left", "right"];
/** Perspective distance in CSS px is this factor times min(viewport w, h). Same
- * factor in preview and export so the look matches at any canvas resolution. */
-export const ROTATION_3D_PERSPECTIVE_FACTOR = 2.6;
+ * factor in preview and export so the look matches at any canvas resolution.
+ * Lower = camera closer = edges converge more visibly. At 2.6 the convergence was so flat that
+ * iso's top edge came out 0.08° off horizontal and the tilt stopped reading as a tilt. */
+export const ROTATION_3D_PERSPECTIVE_FACTOR = 1.6;
export function rotation3DPerspective(width: number, height: number): number {
return Math.min(width, height) * ROTATION_3D_PERSPECTIVE_FACTOR;
diff --git a/src/lib/ai-edition/annotations/textAnimation.ts b/src/lib/ai-edition/annotations/textAnimation.ts
index 0f3826aed..61399d440 100644
--- a/src/lib/ai-edition/annotations/textAnimation.ts
+++ b/src/lib/ai-edition/annotations/textAnimation.ts
@@ -21,7 +21,8 @@ export interface TextAnimationState {
revealProgress: number;
}
-const TEXT_ANIMATION_VALUES: AnnotationTextAnimation[] = [
+/** Les sept animations, dans l'ordre où le sélecteur les propose. */
+export const TEXT_ANIMATION_VALUES: AnnotationTextAnimation[] = [
"none",
"fade",
"rise",
diff --git a/src/native/sceneDescription.test.ts b/src/native/sceneDescription.test.ts
index 8249c5d5f..f4d79537f 100644
--- a/src/native/sceneDescription.test.ts
+++ b/src/native/sceneDescription.test.ts
@@ -6,7 +6,12 @@
// crop / settings mapping / output dims).
import { describe, expect, it } from "vitest";
-import { DEFAULT_CROP_REGION } from "@/components/video-editor/types";
+import {
+ DEFAULT_CROP_REGION,
+ getZoomScale,
+ ZOOM_DEPTH_SCALES,
+} from "@/components/video-editor/types";
+import { getFocusBoundsForScale } from "@/components/video-editor/videoPlayback/focusUtils";
import type {
AxcutAsset,
AxcutClip,
@@ -350,18 +355,48 @@ describe("buildSceneDescription.clips", () => {
// --- zoomRegions -----------------------------------------------------------
describe("buildSceneDescription.zoomRegions", () => {
- it("depth 1 → scale 1.0", () => {
+ // Ces deux tests attendaient `depth / 2 + 0.5` — la formule qui vivait dans
+ // `sceneDescription`, à côté de la table que le reste de l'app utilise. Ils verrouillaient donc
+ // le bug : le focus était borné avec la table et la fenêtre source découpée avec la formule.
+ it("depth 1 → the table's scale, not a formula", () => {
const z = makeZoom({ id: "z", startMs: 0, endMs: 1000, depth: 1, focus: { cx: 0.5, cy: 0.5 } });
const doc = makeDoc({ zoomRanges: [z] });
const { zoomRegions } = buildSceneDescription(doc);
- expect(zoomRegions[0].scale).toBe(1.0);
+ expect(zoomRegions[0].scale).toBe(ZOOM_DEPTH_SCALES[1]);
+ expect(zoomRegions[0].scale).toBe(1.25);
});
- it("depth 6 → scale 3.5", () => {
+ it("depth 6 → the table's scale", () => {
const z = makeZoom({ id: "z", startMs: 0, endMs: 1000, depth: 6, focus: { cx: 0.5, cy: 0.5 } });
const doc = makeDoc({ zoomRanges: [z] });
const { zoomRegions } = buildSceneDescription(doc);
- expect(zoomRegions[0].scale).toBe(3.5);
+ expect(zoomRegions[0].scale).toBe(ZOOM_DEPTH_SCALES[6]);
+ expect(zoomRegions[0].scale).toBe(5.0);
+ });
+
+ // L'invariant qui compte, et que personne ne vérifiait : le compositeur doit recevoir
+ // EXACTEMENT l'échelle avec laquelle l'interface borne le point de focus. Sinon la fenêtre
+ // source ne peut plus atteindre le bord de l'enregistrement — gimbal poussé à fond dans le
+ // coin, 53 px sur 1920 restaient hors d'atteinte à la profondeur 3.
+ it("sends the very scale the focus bounds are computed from, at every depth", () => {
+ for (const depth of [1, 2, 3, 4, 5, 6] as const) {
+ const z = makeZoom({
+ id: "z",
+ startMs: 0,
+ endMs: 1000,
+ depth,
+ focus: { cx: 0.5, cy: 0.5 },
+ });
+ const { zoomRegions } = buildSceneDescription(makeDoc({ zoomRanges: [z] }));
+ const uiScale = getZoomScale({ depth });
+ expect(zoomRegions[0].scale).toBe(uiScale);
+ // Et la conséquence géométrique : au bord du domaine de focus, la fenêtre source touche
+ // bien le bord de la source (à la précision flottante près).
+ const bounds = getFocusBoundsForScale(uiScale);
+ const halfWindow = 1 / (2 * zoomRegions[0].scale);
+ expect(bounds.minX - halfWindow).toBeCloseTo(0, 10);
+ expect(bounds.minY - halfWindow).toBeCloseTo(0, 10);
+ }
});
it("customScale overrides the depth-derived value", () => {
@@ -472,7 +507,9 @@ describe("buildSceneDescription.zoomRegions with an earlier trim", () => {
id: "z",
startSec: 6,
endSec: 8,
- scale: 2,
+ // profondeur 3 = 1.8 dans `ZOOM_DEPTH_SCALES` ; ce test portait sur la ventilation
+ // du zoom après un trim, pas sur l'échelle, mais il en fixait la valeur au passage.
+ scale: ZOOM_DEPTH_SCALES[3],
focusX: 0.5,
focusY: 0.5,
focusMode: null,
diff --git a/src/native/sceneDescription.ts b/src/native/sceneDescription.ts
index 868722229..59000e4c7 100644
--- a/src/native/sceneDescription.ts
+++ b/src/native/sceneDescription.ts
@@ -16,7 +16,7 @@
*/
import type { CameraFullscreenRegion, SpeedRegion } from "@/components/video-editor/types";
-import { DEFAULT_CROP_REGION } from "@/components/video-editor/types";
+import { DEFAULT_CROP_REGION, ZOOM_DEPTH_SCALES } from "@/components/video-editor/types";
import { annotationFontSizeFraction } from "@/lib/ai-edition/annotationScale";
import { createId } from "@/lib/ai-edition/document/ids";
import { pickOutputDims } from "@/lib/ai-edition/document/outputFormat";
@@ -675,7 +675,15 @@ export function buildSceneDescription(
id: region.id,
startSec: region.startMs / 1000,
endSec: region.endMs / 1000,
- scale: region.customScale ?? region.depth / 2 + 0.5,
+ // `ZOOM_DEPTH_SCALES` et rien d'autre. Cette ligne portait sa propre formule,
+ // `depth / 2 + 0.5`, qui ne coïncide avec la table qu'à la profondeur 2 — et le focus,
+ // lui, est borné avec la table (`getFocusBoundsForScale`, via `getZoomScale`). Les deux
+ // échelles se contredisaient donc : à la profondeur 3 le gimbal butait à 1/(2×1.8) =
+ // 0.2778 pendant que le compositeur découpait une demi-fenêtre de 1/(2×2.0) = 0.25, si
+ // bien que la fenêtre source s'arrêtait 2.78 % avant le bord — 53 px sur 1920
+ // définitivement hors d'atteinte, gimbal à fond dans le coin. Le symptôme rapporté :
+ // « le zoom coupe les bords extérieurs ».
+ scale: region.customScale ?? ZOOM_DEPTH_SCALES[region.depth],
focusX: region.focus.cx,
focusY: region.focus.cy,
// The global Auto-Focus toggle OVERRIDES each region's own mode rather than merely