Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
fix(cursor): pivot custom cursors on their hotspot, and give the native path a sprite per OS state
Etienne Lescote6b96d3b9daa
diff --git a/electron/native-bridge/services/compositorViewService.test.ts b/electron/native-bridge/services/compositorViewService.test.tsindex c0b05038e..84c731d81 100644--- a/electron/native-bridge/services/compositorViewService.test.ts+++ b/electron/native-bridge/services/compositorViewService.test.ts@@ -2,7 +2,7 @@ import fs from "node:fs";import os from "node:os";import path from "node:path";import { afterEach, beforeEach, describe, expect, it } from "vitest";-import { CURSOR_THEMES } from "../../../src/lib/cursor/cursorThemes";+import { CURSOR_THEMES, DEFAULT_CURSOR_SPRITES } from "../../../src/lib/cursor/cursorThemes";import {CompositorViewService,ffmpegSharedBinCandidates,@@ -191,10 +191,14 @@ describe("resolveSceneAssetPaths", () => {resources = fs.mkdtempSync(path.join(os.tmpdir(), "openscreen-scene-assets-"));fs.mkdirSync(path.join(resources, "wallpapers"), { recursive: true });fs.writeFileSync(path.join(resources, "wallpapers", "wallpaper1.jpg"), "jpg");- if (themed?.assets.arrow) {- const arrow = path.join(resources, themed.assets.arrow.assetPath);- fs.mkdirSync(path.dirname(arrow), { recursive: true });- fs.writeFileSync(arrow, "png");+ const assetPaths = [+ ...Object.values(themed?.assets ?? {}).map((a) => a.assetPath),+ ...Object.values(DEFAULT_CURSOR_SPRITES).map((s) => s.assetPath),+ ];+ for (const assetPath of assetPaths) {+ const file = path.join(resources, assetPath);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, "png");}originalResourcesPath = Object.getOwnPropertyDescriptor(process, "resourcesPath");Object.defineProperty(process, "resourcesPath", { value: resources, configurable: true });@@ -230,10 +234,38 @@ describe("resolveSceneAssetPaths", () => {it("resolves a cursor theme's arrow sprite to a path that exists on disk", () => {if (!themed) return; // no bundled theme ships an arrow override- const out = resolved({ cursor: { theme: themed.id } });+ const arrow = resolved({ cursor: { theme: themed.id } }).cursor.cursorSprites.arrow;- expect(out.cursor.cursorSpritePath).toBe(path.join(resources, themed.assets.arrow!.assetPath));- expect(fs.existsSync(out.cursor.cursorSpritePath)).toBe(true);+ expect(arrow.path).toBe(path.join(resources, themed.assets.arrow!.assetPath));+ expect(fs.existsSync(arrow.path)).toBe(true);+ });++ it("fills the states a theme doesn't ship with the built-in art", () => {+ if (!themed) return;+ const sprites = resolved({ cursor: { theme: themed.id } }).cursor.cursorSprites;++ // The sweezy packs only carry an arrow and a pointer, but a recording walks through+ // far more states than that — each one still has to get its own sprite.+ expect(sprites.text.path).toBe(path.join(resources, "cursors", "default", "text.png"));+ expect(sprites["resize-ew"].path).toContain(path.join("cursors", "default"));+ expect(Object.keys(sprites).sort()).toEqual(Object.keys(DEFAULT_CURSOR_SPRITES).sort());+ });++ it("carries each sprite's hotspot as a fraction of its own image", () => {+ const sprites = resolved({ cursor: { theme: "default" } }).cursor.cursorSprites;++ // The whole point of the fraction: it survives the size slider. A hotspot in source+ // pixels would have to be rescaled at draw time, and drifted when it wasn't.+ for (const [type, sprite] of Object.entries(sprites)) {+ expect(sprite.hotspotX, type).toBeGreaterThanOrEqual(0);+ expect(sprite.hotspotX, type).toBeLessThanOrEqual(1);+ expect(sprite.hotspotY, type).toBeGreaterThanOrEqual(0);+ expect(sprite.hotspotY, type).toBeLessThanOrEqual(1);+ }+ // The arrow's tip is near its top-left corner, nowhere near the centre it used to+ // be drawn from.+ expect(sprites.arrow.hotspotX).toBeLessThan(0.25);+ expect(sprites.arrow.hotspotY).toBeLessThan(0.25);});it("leaves a custom upload's data: URL untouched — the addon decodes it in memory", () => {@@ -243,8 +275,13 @@ describe("resolveSceneAssetPaths", () => {expect(out.background.path).toBe(dataUrl);});- it("nulls the sprite for the default theme so the built-in art is used", () => {- expect(resolved({ cursor: { theme: "default" } }).cursor.cursorSpritePath).toBeNull();+ it("gives the default theme the built-in arrow, not a placeholder", () => {+ // Regression: "default" used to resolve to no sprite at all, and the compositor drew+ // its dot-and-ring fallback — a dot in a circle where the standard arrow belongs.+ const sprites = resolved({ cursor: { theme: "default" } }).cursor.cursorSprites;++ expect(sprites.arrow.path).toBe(path.join(resources, "cursors", "default", "arrow.png"));+ expect(fs.existsSync(sprites.arrow.path)).toBe(true);});it("leaves the scene alone when no base dir holds the asset", () => {diff --git a/electron/native-bridge/services/compositorViewService.ts b/electron/native-bridge/services/compositorViewService.tsindex ab114e775..de2edff11 100644--- a/electron/native-bridge/services/compositorViewService.ts+++ b/electron/native-bridge/services/compositorViewService.ts@@ -3,7 +3,7 @@ import { createRequire } from "node:module";import path from "node:path";import { fileURLToPath } from "node:url";import { app } from "electron";-import { CURSOR_THEMES, DEFAULT_CURSOR_THEME_ID } from "../../../src/lib/cursor/cursorThemes";+import { resolveCursorSprites } from "../../../src/lib/cursor/cursorThemes";import type {ClipInput,CompositorParamValue,@@ -86,21 +86,38 @@ export function resolveSceneAssetPath(relativePath: string): string | null {return null;}-/** Absolute path of a theme's "arrow" sprite, or null (unknown theme / default / theme ships no- * arrow override / asset missing — same fallback to built-in art the web renderer applies). */-function resolveCursorThemeArrowPath(themeId: string): string | null {- if (!themeId || themeId === DEFAULT_CURSOR_THEME_ID) {- return null;+/**+ * The theme's sprite set with every `assetPath` turned into an absolute on-disk path.+ *+ * Entries whose file doesn't resolve are dropped rather than passed through: the addon+ * would fail to decode them and fall back to its placeholder anyway, and a missing entry+ * lets it fall back to the arrow instead, which is closer to right.+ */+function resolveCursorSpritePaths(+ themeId: string,+): Record<string, { path: string; hotspotX: number; hotspotY: number }> {+ const resolved: Record<string, { path: string; hotspotX: number; hotspotY: number }> = {};+ for (const [type, sprite] of Object.entries(resolveCursorSprites(themeId))) {+ const absolute = resolveSceneAssetPath(sprite.assetPath);+ if (absolute) {+ resolved[type] = {+ path: absolute,+ hotspotX: sprite.hotspotX,+ hotspotY: sprite.hotspotY,+ };+ }}- const arrow = CURSOR_THEMES.find((t) => t.id === themeId)?.assets.arrow;- return arrow ? resolveSceneAssetPath(arrow.assetPath) : null;+ return resolved;}export function resolveSceneAssetPaths(sceneJson: string): string {try {const scene = JSON.parse(sceneJson) as {background?: { kind?: string; path?: string };- cursor?: { theme?: string; cursorSpritePath?: string | null };+ cursor?: {+ theme?: string;+ cursorSprites?: Record<string, { path: string; hotspotX: number; hotspotY: number }>;+ };};let changed = false;const bg = scene.background;@@ -113,7 +130,7 @@ export function resolveSceneAssetPaths(sceneJson: string): string {}}if (scene.cursor && typeof scene.cursor.theme === "string") {- scene.cursor.cursorSpritePath = resolveCursorThemeArrowPath(scene.cursor.theme);+ scene.cursor.cursorSprites = resolveCursorSpritePaths(scene.cursor.theme);changed = true;}return changed ? JSON.stringify(scene) : sceneJson;diff --git a/poc-d3d/src/compositor.rs b/poc-d3d/src/compositor.rsindex a15d78333..b6199c140 100644--- a/poc-d3d/src/compositor.rs+++ b/poc-d3d/src/compositor.rs@@ -3,7 +3,7 @@use crate::config::Cfg;use crate::cursor::CursorTrack;-use crate::scene::{Scene, SceneBackground, SceneCrop};+use crate::scene::{Scene, SceneBackground, SceneCrop, SceneCursorSprite};use crate::d3d::Gpu;use crate::ffi::AVFrame;use anyhow::{bail, Result};@@ -423,6 +423,17 @@ const WEBCAM_SHADOW_OPACITY: f32 = 0.35;/// Taille de base du curseur, même convention (34 px réglés contre un cadre 1080).const CURSOR_BASE_SIZE_FRAC: f32 = 34.0 / SHADOW_TUNING_REF_PX;+/// Rect [x,y,w,h] normalisé d'un sprite de curseur de taille `w`×`h` dont le pivot `hotspot`+/// (fraction 0..1 de l'image) doit tomber exactement sur `center`.+///+/// L'invariant est que `center` reste sur le pixel désigné QUELLE QUE SOIT la taille : le+/// décalage grandit avec le sprite, donc il doit être une fraction de `w`/`h` et pas une+/// constante. Un pivot centré en dur (0.5) laissait la pointe dériver de plus en plus loin de+/// la zone visée à mesure qu'on agrandissait le curseur.+fn cursor_sprite_dst(center: [f32; 2], w: f32, h: f32, hotspot: [f32; 2]) -> [f32; 4] {+ [center[0] - w * hotspot[0], center[1] - h * hotspot[1], w, h]+}+fn ease_in_out_cubic(x: f32) -> f32 {let x = x.clamp(0.0, 1.0);if x < 0.5 {@@ -1273,17 +1284,18 @@ impl Compositor {});}- /// Curseur thème (sprite PNG, ex. arrow.png) centré en `center`, taille de référence- /// `size_px` (ancré centre — l'ajustement fin du hotspot par thème est un raffinement- /// futur). `Err` → l'appelant retombe sur `draw_cursor` (math dot+ring).+ /// Curseur thème (sprite PNG, ex. arrow.png) dont le PIVOT `hotspot` (fraction 0..1 de+ /// l'image) tombe sur `center`, à la taille de référence `size_px`. `Err` → l'appelant+ /// retombe sur `draw_cursor` (math dot+ring).unsafe fn draw_cursor_sprite(&self,center: [f32; 2],size_px: f32,a: f32,- path: &str,+ sprite: &SceneCursorSprite,clip: [f32; 4],) -> Result<()> {+ let path = sprite.path.as_str();let cached = self.img_cache.borrow().get(path).cloned();let (srv, iw, ih) = match cached {Some(v) => v,@@ -1297,7 +1309,7 @@ impl Compositor {let (pw, ph) = if ar >= 1.0 { (size_px, size_px / ar) } else { (size_px * ar, size_px) };let w = pw / self.rw();let h = ph / self.rh();- let dst = [center[0] - w * 0.5, center[1] - h * 0.5, w, h];+ let dst = cursor_sprite_dst(center, w, h, [sprite.hotspot_x, sprite.hotspot_y]);self.upload_cb(&LayerCB {dst,src: [0.0, 0.0, 1.0, 1.0],@@ -1311,17 +1323,24 @@ impl Compositor {Ok(())}- /// Sprite du thème si résolu et chargeable, sinon le curseur math (dot+ring).+ /// Sprite de l'état courant (`cursor_type`, ex. `"text"`), à défaut celui de la flèche,+ /// à défaut le curseur math (dot+ring).+ ///+ /// Le repli sur la flèche compte : un thème n'apporte que sa flèche et son pointeur, les+ /// autres états venant de l'art intégrée — mais si un état inconnu apparaît, mieux vaut+ /// une flèche qu'un point dans un cercle.unsafe fn draw_cur_themed(&self,- sprite: &Option<String>,+ sprites: &HashMap<String, SceneCursorSprite>,+ cursor_type: Option<&str>,center: [f32; 2],size_px: f32,a: f32,clip: [f32; 4],) {- if let Some(path) = sprite {- if self.draw_cursor_sprite(center, size_px, a, path, clip).is_ok() {+ let sprite = cursor_type.and_then(|t| sprites.get(t)).or_else(|| sprites.get("arrow"));+ if let Some(sprite) = sprite {+ if self.draw_cursor_sprite(center, size_px, a, sprite, clip).is_ok() {return;}}@@ -1968,10 +1987,14 @@ impl Compositor {// --- curseur custom : suit le mapping src/dst (zoom+layout), click bounce,// et flou de mouvement par fantômes le long de sa vélocité (frame-1 -> frame) ---- // Thème (sprite) si résolu par l'app, sinon math dot+ring (défaut / fallback si le- // sprite ne charge pas).- let cursor_sprite: Option<String> =- self.scene.borrow().as_ref().and_then(|s| s.cursor.cursor_sprite_path.clone());+ // Jeu de sprites résolu par l'app (art du thème + art intégrée pour les états qu'il ne+ // fournit pas), sinon math dot+ring — fixture/bench sans scène uniquement.+ let cursor_sprites: HashMap<String, SceneCursorSprite> = self+ .scene+ .borrow()+ .as_ref()+ .map(|s| s.cursor.cursor_sprites.clone())+ .unwrap_or_default();// « Clip to canvas » : tronque le curseur aux bords de l'écran (utile quand le padding// crée une marge et que la pointe, près du bord de la vidéo, dépasserait dedans).// Rect englobant tout par défaut = pas d'effet (le mode 4/7 du shader clippe sur `fx`).@@ -2034,8 +2057,20 @@ impl Compositor {} else {cfg.mblur_n // fixture/bench : comportement historique inchangé};+ // L'état est celui de l'instant rendu : la traînée de flou reprend le même+ // sprite pour toutes ses copies, un changement d'état en plein mouvement+ // n'a pas à laisser une traînée hybride.+ let cursor_type = track.type_at(t).map(str::to_string);+ let cursor_type = cursor_type.as_deref();if taps <= 1 {- self.draw_cur_themed(&cursor_sprite, cur, sz, 1.0, cursor_clip_rect);+ self.draw_cur_themed(+ &cursor_sprites,+ cursor_type,+ cur,+ sz,+ 1.0,+ cursor_clip_rect,+ );} else {let tp = t - trail_frames / FPS;let prev = map(track.at(tp), [su0_p, sv0_p], [hu_p, hv_p], s_dst_prev)@@ -2057,7 +2092,14 @@ impl Compositor {for k in 0..taps {let f = k as f32 / (taps - 1) as f32;let c = [prev[0] + (cur[0] - prev[0]) * f, prev[1] + (cur[1] - prev[1]) * f];- self.draw_cur_themed(&cursor_sprite, c, sz, 1.0, cursor_clip_rect);+ self.draw_cur_themed(+ &cursor_sprites,+ cursor_type,+ c,+ sz,+ 1.0,+ cursor_clip_rect,+ );}// composite le buffer accumulé sur la scène (blend "over" normal, prémultiplié).self.ctx.OMSetRenderTargets(Some(&[Some(self.rtv.clone())]), None);@@ -2879,6 +2921,28 @@ impl Compositor {mod tests {use super::*;+ /// Le pivot doit rester collé à `center` quand le sprite grandit — c'est exactement ce qui+ /// était cassé (ancrage centré en dur : la pointe s'éloignait proportionnellement à la+ /// taille). On dessine la même flèche à deux tailles et on vérifie que le point désigné+ /// ne bouge pas.+ #[test]+ fn sprite_hotspot_stays_on_target_at_any_size() {+ let center = [0.4, 0.6];+ let hotspot = [0.119, 0.0874]; // flèche intégrée : la pointe, près du coin haut-gauche++ for (w, h) in [(0.02, 0.04), (0.08, 0.16)] {+ let dst = cursor_sprite_dst(center, w, h, hotspot);+ let pivot = [dst[0] + dst[2] * hotspot[0], dst[1] + dst[3] * hotspot[1]];+ assert!((pivot[0] - center[0]).abs() < 1e-6, "x drifted at {w}x{h}: {pivot:?}");+ assert!((pivot[1] - center[1]).abs() < 1e-6, "y drifted at {w}x{h}: {pivot:?}");+ assert_eq!([dst[2], dst[3]], [w, h], "taille altérée");+ }++ // Et un pivot centré reste bien l'ancien comportement, pour les sprites qui le veulent+ // (viseur, I-beam, poignées de redimensionnement).+ assert_eq!(cursor_sprite_dst([0.5, 0.5], 0.2, 0.2, [0.5, 0.5]), [0.4, 0.4, 0.2, 0.2]);+ }+/// 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 quelquesdiff --git a/poc-d3d/src/cursor.rs b/poc-d3d/src/cursor.rsindex 0319b80f8..8d518c6e1 100644--- a/poc-d3d/src/cursor.rs+++ b/poc-d3d/src/cursor.rs@@ -22,6 +22,11 @@ pub struct CursorTrack {follow_samples: Vec<(f32, f32, f32)>,/// instants de clic (secondes) dans la fenêtre.clicks: Vec<f32>,+ /// CHANGEMENTS d'état du curseur : (instant, `"arrow"` / `"text"` / `"pointer"` / …), triés.+ /// Une fonction en escalier, pas une valeur par échantillon : l'état tient sur des secondes+ /// entières alors que la position est échantillonnée à ~120 Hz, donc n'enregistrer que les+ /// transitions garde cette liste minuscule et rend `type_at` trivial.+ types: Vec<(f32, String)>,}/// Interpolation linéaire dans une liste `(t, x, y)` triée ; saturation aux bornes.@@ -87,9 +92,16 @@ impl CursorTrack {/// Seul point de construction : garantit que `follow_samples` est toujours dérivé des/// échantillons courants. Une piste re-lissée (`smoothed`) recalcule donc aussi son suivi,/// pour que la caméra suive la trajectoire que l'utilisateur voit réellement.- fn new(samples: Vec<(f32, f32, f32)>, clicks: Vec<f32>) -> CursorTrack {+ fn new(samples: Vec<(f32, f32, f32)>, clicks: Vec<f32>, types: Vec<(f32, String)>) -> CursorTrack {let follow_samples = smooth_follow_samples(&samples);- CursorTrack { samples, follow_samples, clicks }+ CursorTrack { samples, follow_samples, clicks, types }+ }++ /// État du curseur au temps `t` : la dernière transition à `t` ou avant. `None` avant la+ /// première (enregistrement sans état tagué → l'appelant retombe sur la flèche).+ pub fn type_at(&self, t: f32) -> Option<&str> {+ let i = self.types.partition_point(|(tc, _)| *tc <= t);+ (i > 0).then(|| self.types[i - 1].1.as_str())}/// Nombre d'échantillons de la piste (utile au diag de chargement).@@ -104,6 +116,7 @@ impl CursorTrack {let arr = v["samples"].as_array().context("samples[]")?;let mut samples = Vec::new();let mut clicks = Vec::new();+ let mut types: Vec<(f32, String)> = Vec::new();let end = offset_ms + dur_s * 1000.0;for s in arr {let tm = s["timeMs"].as_f64().unwrap_or(-1.0);@@ -117,10 +130,19 @@ impl CursorTrack {if s["interactionType"].as_str() == Some("click") {clicks.push(t);}+ // Seules les TRANSITIONS sont retenues — voir `types`. Les échantillons sans+ // `cursorType` (macOS ne le tague pas toujours) n'interrompent pas l'état courant :+ // c'est une absence d'information, pas un retour à la flèche.+ if let Some(ct) = s["cursorType"].as_str() {+ if types.last().map(|(_, prev)| prev.as_str()) != Some(ct) {+ types.push((t, ct.to_string()));+ }+ }}samples.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());clicks.sort_by(|a, b| a.partial_cmp(b).unwrap());- Ok(CursorTrack::new(samples, clicks))+ types.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());+ Ok(CursorTrack::new(samples, clicks, types))}/// Position lissée au temps `t`, pour le suivi auto du zoom. La télémétrie brute est@@ -172,7 +194,7 @@ impl CursorTrack {/// bruts (le bounce est temporel, pas positionnel — ne doit pas suivre le lissage).pub fn smoothed(&self, factor: f32) -> CursorTrack {if self.samples.len() < 2 || factor <= 0.0 {- return CursorTrack::new(self.samples.clone(), self.clicks.clone());+ return CursorTrack::new(self.samples.clone(), self.clicks.clone(), self.types.clone());}const STEP_S: f32 = 1.0 / 240.0;let start = self.samples[0].0;@@ -193,7 +215,9 @@ impl CursorTrack {let xs = spring_smooth(&raw_x, stiffness, damping, mass, STEP_S);let ys = spring_smooth(&raw_y, stiffness, damping, mass, STEP_S);let samples = times.into_iter().zip(xs).zip(ys).map(|((t, x), y)| (t, x, y)).collect();- CursorTrack::new(samples, self.clicks.clone())+ // Comme les clics, les changements d'état gardent leurs instants bruts : le lissage+ // déplace la trajectoire, pas la chronologie de ce que faisait l'utilisateur.+ CursorTrack::new(samples, self.clicks.clone(), self.types.clone())}}@@ -231,3 +255,40 @@ fn cursor_spring_config(smoothing_factor: f32) -> (f32, f32, f32) {let n = ((clamped - LEGACY_MAX) / (2.0 - LEGACY_MAX)).clamp(0.0, 1.0);(340.0 - n * 180.0, 58.0 + n * 22.0, 1.0 + n * 0.35)}++#[cfg(test)]+mod tests {+ use super::*;++ /// L'état du curseur est une fonction en escalier : il tient jusqu'à la transition+ /// suivante, il n'est pas interpolé, et avant la première il n'y en a pas.+ #[test]+ fn cursor_type_holds_until_the_next_transition() {+ let track = CursorTrack::new(+ vec![(0.0, 0.0, 0.0), (2.0, 1.0, 1.0)],+ vec![],+ vec![(0.5, "arrow".into()), (1.0, "text".into()), (1.5, "pointer".into())],+ );++ assert_eq!(track.type_at(0.0), None, "avant la première transition");+ assert_eq!(track.type_at(0.5), Some("arrow"), "à l'instant même de la transition");+ assert_eq!(track.type_at(0.9), Some("arrow"), "tient jusqu'à la suivante");+ assert_eq!(track.type_at(1.2), Some("text"));+ assert_eq!(track.type_at(99.0), Some("pointer"), "la dernière tient jusqu'à la fin");+ }++ /// Le lissage déplace la trajectoire, pas la chronologie : les états doivent survivre+ /// intacts à `smoothed()`, comme les clics.+ #[test]+ fn smoothing_preserves_cursor_types() {+ let track = CursorTrack::new(+ vec![(0.0, 0.0, 0.0), (0.5, 0.4, 0.4), (1.0, 1.0, 1.0)],+ vec![0.25],+ vec![(0.0, "arrow".into()), (0.6, "text".into())],+ );++ let smoothed = track.smoothed(0.4);+ assert_eq!(smoothed.type_at(0.1), Some("arrow"));+ assert_eq!(smoothed.type_at(0.7), Some("text"));+ }+}diff --git a/poc-d3d/src/scene.rs b/poc-d3d/src/scene.rsindex aadf885cd..2de569510 100644--- a/poc-d3d/src/scene.rs+++ b/poc-d3d/src/scene.rs@@ -323,13 +323,33 @@ pub struct SceneCursor {pub motion_blur: f32,pub click_bounce: f32,pub clip_to_bounds: bool,- /// id du thème (jeu de sprites) — "default" = pas d'override, curseur math dot+ring.+ /// id du thème (jeu de sprites) — informatif ici : le natif consomme `cursor_sprites`.pub theme: String,- /// Chemin absolu du sprite "arrow" du thème, résolu côté app (compositorViewService,- /// même mécanisme que le wallpaper image). Absent/`None` → curseur math par défaut.+ /// Sprites par état de curseur (`"arrow"`, `"text"`, `"pointer"`, `"resize-ew"`, …), chemins+ /// absolus résolus côté app (compositorViewService, même mécanisme que le wallpaper image).+ /// Le thème choisi n'y fournit que les états qu'il possède ; l'app complète le reste avec+ /// l'art intégrée, si bien qu'ici la table est TOUJOURS complète ou vide.+ ///+ /// Vide → curseur math dot+ring, qui n'est qu'un filet de sécurité : ce n'est PAS à quoi+ /// ressemble un pointeur système, et l'afficher en temps normal était le bug « le curseur+ /// par défaut est un point dans un cercle »./// `#[serde(default)]` : champ ajouté après coup, absent des JSON de test existants.#[serde(default)]- pub cursor_sprite_path: Option<String>,+ pub cursor_sprites: std::collections::HashMap<String, SceneCursorSprite>,+}++/// Un sprite de curseur : image + point de pivot.+#[derive(Debug, Clone, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SceneCursorSprite {+ /// Chemin absolu d'un PNG/JPEG déchiffrable par le crate `image`.+ pub path: String,+ /// Pivot en FRACTION de l'image (0..1), pas en pixels : le sprite est redimensionné au+ /// réglage « taille du curseur », et seule une fraction survit à cette mise à l'échelle.+ /// Un pivot centré (0.5, 0.5) imposé à tous les sprites décalait la pointe d'autant plus+ /// que le curseur était agrandi — le bug que ce champ corrige.+ pub hotspot_x: f32,+ pub hotspot_y: f32,}#[derive(Debug, Clone, Copy, Deserialize)]diff --git a/public/cursors/default/app-starting.png b/public/cursors/default/app-starting.pngnew file mode 100644index 000000000..9a1649eeaBinary files /dev/null and b/public/cursors/default/app-starting.png differdiff --git a/public/cursors/default/arrow.png b/public/cursors/default/arrow.pngnew file mode 100644index 000000000..85998081eBinary files /dev/null and b/public/cursors/default/arrow.png differdiff --git a/public/cursors/default/closed-hand.png b/public/cursors/default/closed-hand.pngnew file mode 100644index 000000000..621fba8a2Binary files /dev/null and b/public/cursors/default/closed-hand.png differdiff --git a/public/cursors/default/crosshair.png b/public/cursors/default/crosshair.pngnew file mode 100644index 000000000..09d40cd95Binary files /dev/null and b/public/cursors/default/crosshair.png differdiff --git a/public/cursors/default/help.png b/public/cursors/default/help.pngnew file mode 100644index 000000000..6746db84dBinary files /dev/null and b/public/cursors/default/help.png differdiff --git a/public/cursors/default/move.png b/public/cursors/default/move.pngnew file mode 100644index 000000000..69a819fcfBinary files /dev/null and b/public/cursors/default/move.png differdiff --git a/public/cursors/default/not-allowed.png b/public/cursors/default/not-allowed.pngnew file mode 100644index 000000000..f7f35d12eBinary files /dev/null and b/public/cursors/default/not-allowed.png differdiff --git a/public/cursors/default/open-hand.png b/public/cursors/default/open-hand.pngnew file mode 100644index 000000000..147ebdabfBinary files /dev/null and b/public/cursors/default/open-hand.png differdiff --git a/public/cursors/default/pointer.png b/public/cursors/default/pointer.pngnew file mode 100644index 000000000..a89d388bfBinary files /dev/null and b/public/cursors/default/pointer.png differdiff --git a/public/cursors/default/resize-ew.png b/public/cursors/default/resize-ew.pngnew file mode 100644index 000000000..b15a4fe5fBinary files /dev/null and b/public/cursors/default/resize-ew.png differdiff --git a/public/cursors/default/resize-nesw.png b/public/cursors/default/resize-nesw.pngnew file mode 100644index 000000000..0f9746865Binary files /dev/null and b/public/cursors/default/resize-nesw.png differdiff --git a/public/cursors/default/resize-ns.png b/public/cursors/default/resize-ns.pngnew file mode 100644index 000000000..229ddfaabBinary files /dev/null and b/public/cursors/default/resize-ns.png differdiff --git a/public/cursors/default/resize-nwse.png b/public/cursors/default/resize-nwse.pngnew file mode 100644index 000000000..eac720eb6Binary files /dev/null and b/public/cursors/default/resize-nwse.png differdiff --git a/public/cursors/default/text.png b/public/cursors/default/text.pngnew file mode 100644index 000000000..27a5e5ef9Binary files /dev/null and b/public/cursors/default/text.png differdiff --git a/public/cursors/default/up-arrow.png b/public/cursors/default/up-arrow.pngnew file mode 100644index 000000000..a32665e50Binary files /dev/null and b/public/cursors/default/up-arrow.png differdiff --git a/public/cursors/default/wait.png b/public/cursors/default/wait.pngnew file mode 100644index 000000000..e8ba48724Binary files /dev/null and b/public/cursors/default/wait.png differdiff --git a/scripts/generate-default-cursor-sprites.mjs b/scripts/generate-default-cursor-sprites.mjsnew file mode 100644index 000000000..94db9237c--- /dev/null+++ b/scripts/generate-default-cursor-sprites.mjs@@ -0,0 +1,147 @@+// Rasterizes the built-in cursor SVG set (src/assets/cursors/) into+// public/cursors/default/<type>.png.+//+// Why files at all: the native compositor decodes with the `image` crate (png/jpeg+// only) from a real path outside app.asar — it cannot read the SVGs, which exist only+// as Vite-bundled URLs in the renderer. Without a PNG set the native path has no+// default art and falls back to a math dot+ring, which is not what the OS cursor+// looks like.+//+// The PNGs are cropped to the art's alpha bounds. The sweezy theme packs fill their+// 128x128 box edge to edge, while the built-in SVGs sit in the middle of a 32-unit+// canvas using only ~55% of it — uncropped, every built-in cursor would render about+// half the size of a themed one at the same size slider. Cropping puts both on the+// same footing, and the hotspot is recomputed into the cropped image as a 0..1+// fraction, which is what the scene contract carries.+//+// Run: node scripts/generate-default-cursor-sprites.mjs+// Then paste the printed table into DEFAULT_CURSOR_SPRITES in src/lib/cursor/cursorThemes.ts.++import { mkdir, readFile, writeFile } from "node:fs/promises";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { chromium } from "playwright";++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");+const SRC_DIR = path.join(ROOT, "src", "assets", "cursors");+const OUT_DIR = path.join(ROOT, "public", "cursors", "default");+const OUT_SIZE = 128;++/**+ * cursorType -> { file, hotspotX, hotspotY } in the 32-logical reference.+ * Hotspots are copied from PRETTY_NATIVE_CURSOR_ASSETS in src/lib/cursor/nativeCursor.ts,+ * which is the live web renderer's table and stays the source of truth; this generator+ * only re-expresses them for the native path.+ */+const SPRITES = {+ arrow: { file: "Cursor=Default.svg", hotspotX: 16.25, hotspotY: 15.03 },+ text: { file: "Cursor=Text-Cursor.svg", hotspotX: 16, hotspotY: 16 },+ pointer: { file: "Cursor=Hand-(Pointing).svg", hotspotX: 16.65, hotspotY: 14.24 },+ crosshair: { file: "Cursor=Cross.svg", hotspotX: 16, hotspotY: 16 },+ "open-hand": { file: "Cursor=Hand-(Open).svg", hotspotX: 16, hotspotY: 9 },+ // The grabbing fist is drawn lower and shorter than the open hand: y=9 (what the table+ // carried, copied from open-hand) lands above the art entirely. Centred on the fist.+ "closed-hand": { file: "Cursor=Hand-(Grabbing).svg", hotspotX: 16, hotspotY: 17 },+ "resize-ew": { file: "Cursor=Resize-West-East.svg", hotspotX: 16, hotspotY: 16 },+ "resize-ns": { file: "Cursor=Resize-North-South.svg", hotspotX: 16, hotspotY: 16 },+ "resize-nesw": { file: "Cursor=Resize-North-East-South-West.svg", hotspotX: 16, hotspotY: 16 },+ "resize-nwse": { file: "Cursor=Resize-North-West-South-East.svg", hotspotX: 16, hotspotY: 16 },+ move: { file: "Cursor=Move.svg", hotspotX: 16, hotspotY: 16 },+ "not-allowed": { file: "Cursor=Not-Allowed.svg", hotspotX: 16, hotspotY: 16 },+ wait: { file: "Cursor=Wait.svg", hotspotX: 16, hotspotY: 16 },+ "app-starting": { file: "Cursor=App-Starting.svg", hotspotX: 7.25, hotspotY: 4.03 },+ help: { file: "Cursor=Help.svg", hotspotX: 7.25, hotspotY: 4.03 },+ "up-arrow": { file: "Cursor=Up-Arrow.svg", hotspotX: 16, hotspotY: 3 },+};++/**+ * Renders an SVG into an OUT_SIZE square, crops to the art's alpha bounds, and maps the+ * 32-reference hotspot into the cropped image as a 0..1 fraction.+ */+async function rasterize(page, svgText, hotspot) {+ return page.evaluate(+ async ([svg, size, hs]) => {+ const url = `data:image/svg+xml;utf8,${encodeURIComponent(svg)}`;+ const img = new Image();+ await new Promise((resolve, reject) => {+ img.onload = resolve;+ img.onerror = () => reject(new Error("svg decode failed"));+ img.src = url;+ });+ const canvas = document.createElement("canvas");+ canvas.width = size;+ canvas.height = size;+ const ctx = canvas.getContext("2d");+ // The viewBox may not be square (the pointing hand is 32x33): fit its longest+ // side to the box so `scale` maps the whole SVG user space uniformly.+ const scale = size / Math.max(img.naturalWidth, img.naturalHeight);+ ctx.drawImage(img, 0, 0, img.naturalWidth * scale, img.naturalHeight * scale);++ const { data } = ctx.getImageData(0, 0, size, size);+ let minX = size;+ let minY = size;+ let maxX = -1;+ let maxY = -1;+ for (let y = 0; y < size; y += 1) {+ for (let x = 0; x < size; x += 1) {+ if (data[(y * size + x) * 4 + 3] > 8) {+ if (x < minX) minX = x;+ if (y < minY) minY = y;+ if (x > maxX) maxX = x;+ if (y > maxY) maxY = y;+ }+ }+ }+ const bbox = { x: minX, y: minY, width: maxX - minX + 1, height: maxY - minY + 1 };++ const cropped = document.createElement("canvas");+ cropped.width = bbox.width;+ cropped.height = bbox.height;+ cropped+ .getContext("2d")+ .drawImage(canvas, bbox.x, bbox.y, bbox.width, bbox.height, 0, 0, bbox.width, bbox.height);++ return {+ dataUrl: cropped.toDataURL("image/png"),+ bbox,+ // SVG user units -> rendered px -> cropped px -> fraction of the cropped image.+ hotspot: {+ x: (hs[0] * scale - bbox.x) / bbox.width,+ y: (hs[1] * scale - bbox.y) / bbox.height,+ },+ };+ },+ [svgText, OUT_SIZE, hotspot],+ );+}++const browser = await chromium.launch();+const page = await browser.newPage();+await page.goto("about:blank");+await mkdir(OUT_DIR, { recursive: true });++const rows = [];+for (const [type, spec] of Object.entries(SPRITES)) {+ const svg = await readFile(path.join(SRC_DIR, spec.file), "utf8");+ const { dataUrl, bbox, hotspot } = await rasterize(page, svg, [spec.hotspotX, spec.hotspotY]);+ await writeFile(+ path.join(OUT_DIR, `${type}.png`),+ Buffer.from(dataUrl.slice(dataUrl.indexOf(",") + 1), "base64"),+ );+ if (hotspot.x < 0 || hotspot.x > 1 || hotspot.y < 0 || hotspot.y > 1) {+ console.warn(` !! ${type}: hotspot falls outside the art (${hotspot.x}, ${hotspot.y})`);+ }+ rows.push({ type, bbox, hotspot });+}++await browser.close();++console.log(`Wrote ${rows.length} sprites to ${path.relative(ROOT, OUT_DIR)}\n`);+console.log("// generated by scripts/generate-default-cursor-sprites.mjs");+for (const { type, bbox, hotspot } of rows) {+ const key = /^[a-z]+$/.test(type) ? type : `"${type}"`;+ console.log(+ `\t${key}: { assetPath: "cursors/default/${type}.png", ` ++ `hotspotX: ${hotspot.x.toFixed(4)}, hotspotY: ${hotspot.y.toFixed(4)} }, // ${bbox.width}x${bbox.height}`,+ );+}diff --git a/src/lib/cursor/cursorThemes.ts b/src/lib/cursor/cursorThemes.tsindex dd6fa7cc0..e4674845f 100644--- a/src/lib/cursor/cursorThemes.ts+++ b/src/lib/cursor/cursorThemes.ts@@ -33,6 +33,58 @@ export interface CursorTheme {/** Sentinel id for the built-in cursor art (no theme override). */export const DEFAULT_CURSOR_THEME_ID = "default";+/**+ * One sprite as the native compositor consumes it: a path under the public asset root,+ * plus the hotspot as a 0..1 fraction OF THAT IMAGE.+ *+ * The fraction is the whole point of the contract. The compositor scales the sprite to+ * the cursor-size setting, so an offset expressed in the source image's pixels would have+ * to be rescaled at draw time; a fraction survives any scale untouched. Getting this wrong+ * is what made an enlarged cursor drift further and further from what it points at.+ */+export interface CursorSprite {+ /** Path relative to the public asset root, e.g. "cursors/default/arrow.png". */+ assetPath: string;+ /** Hotspot as a fraction of the image width / height. */+ hotspotX: number;+ hotspotY: number;+}++/**+ * The built-in cursor art, rasterized from src/assets/cursors/*.svg — the native+ * compositor decodes png/jpeg from disk and cannot read those SVGs (they only exist as+ * bundler URLs in the renderer).+ *+ * Generated by scripts/generate-default-cursor-sprites.mjs; regenerate it rather than+ * hand-editing, so the PNGs and these hotspots can't drift apart.+ */+export const DEFAULT_CURSOR_SPRITES: Record<NativeCursorType, CursorSprite> = {+ arrow: { assetPath: "cursors/default/arrow.png", hotspotX: 0.119, hotspotY: 0.0874 },+ text: { assetPath: "cursors/default/text.png", hotspotX: 0.4375, hotspotY: 0.5333 },+ pointer: { assetPath: "cursors/default/pointer.png", hotspotX: 0.3893, hotspotY: 0.0032 },+ crosshair: { assetPath: "cursors/default/crosshair.png", hotspotX: 0.4667, hotspotY: 0.4667 },+ "open-hand": { assetPath: "cursors/default/open-hand.png", hotspotX: 0.4375, hotspotY: 0.1781 },+ "closed-hand": {+ assetPath: "cursors/default/closed-hand.png",+ hotspotX: 0.3889,+ hotspotY: 0.451,+ },+ "resize-ew": { assetPath: "cursors/default/resize-ew.png", hotspotX: 0.4881, hotspotY: 0.4706 },+ "resize-ns": { assetPath: "cursors/default/resize-ns.png", hotspotX: 0.5, hotspotY: 0.5 },+ "resize-nesw": { assetPath: "cursors/default/resize-nesw.png", hotspotX: 0.5, hotspotY: 0.5 },+ "resize-nwse": { assetPath: "cursors/default/resize-nwse.png", hotspotX: 0.5, hotspotY: 0.5 },+ move: { assetPath: "cursors/default/move.png", hotspotX: 0.4444, hotspotY: 0.4444 },+ "not-allowed": { assetPath: "cursors/default/not-allowed.png", hotspotX: 0.5, hotspotY: 0.5 },+ wait: { assetPath: "cursors/default/wait.png", hotspotX: 0.5, hotspotY: 0.5 },+ "app-starting": {+ assetPath: "cursors/default/app-starting.png",+ hotspotX: 0.05,+ hotspotY: 0.0537,+ },+ help: { assetPath: "cursors/default/help.png", hotspotX: 0.0515, hotspotY: 0.0572 },+ "up-arrow": { assetPath: "cursors/default/up-arrow.png", hotspotX: 0.5, hotspotY: 0.069 },+};+/*** Bundled cursor themes. To add a pack: drop arrow.png/pointer.png into* public/cursors/<id>/ and add an entry here with hotspots normalized to the@@ -69,8 +121,12 @@ export const CURSOR_THEMES: readonly CursorTheme[] = [assetPath: "cursors/among-us-sus-knife-and-red-animated/arrow.png",width: 32,height: 32,- hotspotX: 1.6,- hotspotY: 0.96,+ // Measured off the artwork, not copied from the packs that draw their arrow+ // into the image's corner: this blade starts 18px in and 13px down in the+ // 128px source, so the (1.6, 0.96) it used to carry sat in empty space+ // diagonally up-left of the point — a visible miss at any decent cursor size.+ hotspotX: 4.9,+ hotspotY: 3.25,},pointer: {assetPath: "cursors/among-us-sus-knife-and-red-animated/pointer.png",@@ -419,3 +475,37 @@ export function getCursorTheme(id: string | null | undefined): CursorTheme | nulexport function normalizeCursorThemeId(id: unknown): string {return typeof id === "string" && CURSOR_THEME_IDS.has(id) ? id : DEFAULT_CURSOR_THEME_ID;}++/**+ * The full sprite set for a theme: its own art where it has any, the built-in art for+ * every other cursor state.+ *+ * The packs only ship an arrow and a pointer, but a recording moves through a dozen OS+ * states — text, resize, wait, grab. Serving the theme's arrow for all of them (what the+ * native path used to do) shows a resize handle as an arrow; serving nothing shows a+ * placeholder. Mixing in the built-in art per state keeps the pointer honest about what+ * the user was doing, and a pack that later adds a text.png slots straight in.+ */+export function resolveCursorSprites(+ themeId: string | null | undefined,+): Record<NativeCursorType, CursorSprite> {+ const theme = getCursorTheme(themeId);+ if (!theme) {+ return DEFAULT_CURSOR_SPRITES;+ }++ const sprites = { ...DEFAULT_CURSOR_SPRITES };+ for (const [type, asset] of Object.entries(theme.assets)) {+ if (asset.width <= 0 || asset.height <= 0) {+ continue;+ }+ sprites[type as NativeCursorType] = {+ assetPath: asset.assetPath,+ // Theme hotspots are authored against the asset's own 32-logical reference;+ // the contract is a fraction of the image. See CursorSprite.+ hotspotX: asset.hotspotX / asset.width,+ hotspotY: asset.hotspotY / asset.height,+ };+ }+ return sprites;+}diff --git a/src/lib/cursor/nativeCursor.ts b/src/lib/cursor/nativeCursor.tsindex 746492932..353f6be5a 100644--- a/src/lib/cursor/nativeCursor.ts+++ b/src/lib/cursor/nativeCursor.ts@@ -138,7 +138,9 @@ const PRETTY_NATIVE_CURSOR_ASSETS: Partial<Record<NativeCursorType, PrettyNativewidth: 32,height: 32,hotspotX: 16,- hotspotY: 9,+ // Not 9 — that was open-hand's value, and the grabbing fist is drawn lower and+ // shorter, so it put the hotspot above the artwork entirely. Centred on the fist.+ hotspotY: 17,},"resize-ew": {imageDataUrl: resizeEwUrl,diff --git a/technical-documentation/architecture/cursor.md b/technical-documentation/architecture/cursor.mdindex 7b9d96737..55c5e577e 100644--- a/technical-documentation/architecture/cursor.md+++ b/technical-documentation/architecture/cursor.md@@ -33,6 +33,14 @@ Cursor telemetry also drives camera focus for auto-follow zooms. `src/componentsThe themed cursor packs are stored under `public/cursors/<id>/` and contain arrow and pointer PNGs registered in `src/lib/cursor/cursorThemes.ts`. The built-in native replacement SVG set is under `src/assets/cursors/` and is selected by `src/lib/cursor/nativeCursor.ts`, which maps captured cursor types to render assets and hotspots.+The same built-in art also exists as PNGs under `public/cursors/default/`, generated from those SVGs by `scripts/generate-default-cursor-sprites.mjs`. The native compositor decodes png/jpeg from a real path and cannot read the SVGs, which exist only as bundler URLs in the renderer — so without the PNG set it had no default art and drew a placeholder dot-and-ring instead of a pointer. Regenerate rather than hand-editing: the script also emits the `DEFAULT_CURSOR_SPRITES` hotspot table, which would otherwise drift from the images.++## Sprite selection and the hotspot++`resolveCursorSprites` (`cursorThemes.ts`) resolves one sprite per `NativeCursorType`: the selected theme's art where it has any, the built-in art everywhere else. The packs only ship an arrow and a pointer while a recording walks through a dozen OS states, so this fallback is what keeps a text caret from rendering as an arrow. `resolveSceneAssetPaths` (`compositorViewService.ts`) turns that table into absolute on-disk paths and puts it in the scene as `cursor.cursorSprites`; the compositor picks by the state in the track and falls back to the arrow.++Each sprite carries its hotspot as a **fraction of its own image**, not in pixels. The compositor scales the sprite to the cursor-size setting, so a pixel offset would need rescaling at draw time; a fraction survives any scale. Both renderers anchor on it (`cursor_sprite_dst` in `compositor.rs`, and `renderAsset.hotspot* × scale` in the web paths) — drawing from the sprite's centre instead made an enlarged cursor point further and further from its target.+## Known gapsmacOS single-window capture can report a cursor offset relative to the captured surface. This remains an open platform-specific alignment issue; display capture does not exhibit the same verified gap.diff --git a/technical-documentation/architecture/native-compositor.md b/technical-documentation/architecture/native-compositor.mdindex 5c1bc05e8..2a5499868 100644--- a/technical-documentation/architecture/native-compositor.md+++ b/technical-documentation/architecture/native-compositor.md@@ -74,9 +74,12 @@ what `shaders.hlsl` actually implements:[`compositor.rs:1950`](../../poc-d3d/src/compositor.rs)). Motion bluruses the previous frame's UV delta as a per-pixel velocity vector and samplesalong it (the "blur by velocity" optimisation — early-outs on still frames).-4. **Cursor.** Math dot+ring by default; sprite (loaded from- `cursor.cursorSpritePath`) when the app hands the native side a theme- path. Motion blur is its own accumulation buffer (additive blend into an+4. **Cursor.** A sprite picked from `cursor.cursorSprites` by the OS cursor state+ recorded in the `.cursor.json` track (`arrow`, `text`, `pointer`, the resize+ handles…), anchored so the sprite's hotspot — a 0..1 fraction of its own image,+ so it survives the size slider — lands on the recorded position. Falls back to+ the arrow for an unknown state, then to a math dot+ring if the app supplied no+ sprites at all. Motion blur is its own accumulation buffer (additive blend into anisolated RT, then "over"-composited onto the scene), independent of thescene's `effects.motionBlur`([`compositor.rs:2038`](../../poc-d3d/src/compositor.rs) /