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(compositor): render every gradient stop at its offset, not just the ends

EtienneLescotba62acd5bcad
diff --git a/crates/compositor/src/compositor_linux.rs b/crates/compositor/src/compositor_linux.rs
index fc0ed6c27..903f9015a 100644
--- a/crates/compositor/src/compositor_linux.rs
+++ b/crates/compositor/src/compositor_linux.rs
@@ -1493,22 +1493,17 @@ impl Compositor {
flat(solid(parse_hex(color).unwrap_or(BLACK)))
}
// Le mouvement ne vaut que pour le fond d'ecran : la bulle garde son degrade immobile.
- Some(SceneBackground::Gradient { angle_deg, stops, .. }) => {
- let c0 = stops.first().and_then(|s| parse_hex(s)).unwrap_or(BLACK);
- let c1 = stops.last().and_then(|s| parse_hex(s)).unwrap_or(c0);
+ Some(SceneBackground::Gradient { angle_deg, stops, offsets, .. }) => {
// angle CSS -> direction unitaire, meme convention que le fond
// d'ecran (dont la direction se lit en espace SORTIE : le degrade
// traverse le cadre, la bulle n'en montre que sa tranche).
let a = angle_deg.to_radians();
flat(LayerCB {
dst,
- src: [c1[0], c1[1], c1[2], c1[3]],
quad_px,
radius_px,
- mode: 5.0,
- color: c0,
fx: [a.sin(), -a.cos(), 0.0, 0.0],
- ..Default::default()
+ ..crate::frame_geometry::gradient_layer(stops, offsets, BLACK)
})
}
Some(SceneBackground::Image { path }) => {
@@ -2048,21 +2043,16 @@ impl Compositor {
Some(SceneBackground::Color { color }) => {
(parse_hex(&color).unwrap_or(lp.bg_color), None)
}
- Some(SceneBackground::Gradient { angle_deg, stops, motion }) => {
- let c0 = stops.first().and_then(|s| parse_hex(s)).unwrap_or(lp.bg_color);
- let c1 = stops.last().and_then(|s| parse_hex(s)).unwrap_or(c0);
+ Some(SceneBackground::Gradient { angle_deg, stops, offsets, motion }) => {
let a = angle_deg.to_radians();
let (anim, mb) =
crate::frame_geometry::gradient_motion_slots(motion, g.programme_t, rw / rh);
let cb = LayerCB {
dst: [0.0, 0.0, 1.0, 1.0],
- src: [c1[0], c1[1], c1[2], c1[3]],
quad_px: [rw, rh],
- mode: 5.0,
- color: c0,
fx: [a.sin(), -a.cos(), anim[0], anim[1]],
mb,
- ..Default::default()
+ ..crate::frame_geometry::gradient_layer(&stops, &offsets, lp.bg_color)
};
([0.0, 0.0, 0.0, 1.0], Some(BgLayer::Gradient(cb)))
}
diff --git a/crates/compositor/src/compositor_macos.rs b/crates/compositor/src/compositor_macos.rs
index 48c17e34b..36ed92db7 100644
--- a/crates/compositor/src/compositor_macos.rs
+++ b/crates/compositor/src/compositor_macos.rs
@@ -1077,22 +1077,17 @@ impl Compositor {
self.draw_solid(enc, &solid(parse_hex(color).unwrap_or(BLACK)));
}
// Le mouvement ne vaut que pour le fond d'écran : la bulle garde son dégradé immobile.
- Some(SceneBackground::Gradient { angle_deg, stops, .. }) => {
- let c0 = stops.first().and_then(|s| parse_hex(s)).unwrap_or(BLACK);
- let c1 = stops.last().and_then(|s| parse_hex(s)).unwrap_or(c0);
+ Some(SceneBackground::Gradient { angle_deg, stops, offsets, .. }) => {
// angle CSS → direction unitaire, même convention que le fond d'écran.
let a = angle_deg.to_radians();
self.draw_solid(
enc,
&LayerCB {
dst,
- src: [c1[0], c1[1], c1[2], c1[3]],
quad_px,
radius_px,
- mode: 5.0,
- color: c0,
fx: [a.sin(), -a.cos(), 0.0, 0.0],
- ..Default::default()
+ ..crate::frame_geometry::gradient_layer(stops, offsets, BLACK)
},
);
}
@@ -2145,9 +2140,7 @@ impl Compositor {
&LayerCB { dst: [0.0, 0.0, 1.0, 1.0], mode: 1.0, color: c, ..Default::default() },
);
}
- Some(SceneBackground::Gradient { angle_deg, stops, motion }) => {
- let c0 = stops.first().and_then(|s| parse_hex(s)).unwrap_or(lp.bg_color);
- let c1 = stops.last().and_then(|s| parse_hex(s)).unwrap_or(c0);
+ Some(SceneBackground::Gradient { angle_deg, stops, offsets, motion }) => {
let a = angle_deg.to_radians();
let (anim, mb) =
crate::frame_geometry::gradient_motion_slots(motion, g.programme_t, rw / rh);
@@ -2155,12 +2148,9 @@ impl Compositor {
enc,
&LayerCB {
dst: [0.0, 0.0, 1.0, 1.0],
- src: [c1[0], c1[1], c1[2], c1[3]],
- mode: 5.0,
- color: c0,
fx: [a.sin(), -a.cos(), anim[0], anim[1]],
mb,
- ..Default::default()
+ ..crate::frame_geometry::gradient_layer(&stops, &offsets, lp.bg_color)
},
);
}
diff --git a/crates/compositor/src/compositor_windows.rs b/crates/compositor/src/compositor_windows.rs
index 26882df3a..721ea309b 100644
--- a/crates/compositor/src/compositor_windows.rs
+++ b/crates/compositor/src/compositor_windows.rs
@@ -1020,9 +1020,7 @@ impl Compositor {
self.draw_solid(&solid(parse_hex(color).unwrap_or(BLACK)));
}
// Le mouvement ne vaut que pour le fond d'écran : la bulle garde son dégradé immobile.
- Some(SceneBackground::Gradient { angle_deg, stops, .. }) => {
- let c0 = stops.first().and_then(|s| parse_hex(s)).unwrap_or(BLACK);
- let c1 = stops.last().and_then(|s| parse_hex(s)).unwrap_or(c0);
+ Some(SceneBackground::Gradient { angle_deg, stops, offsets, .. }) => {
// angle CSS → direction unitaire, même convention que le fond d'écran.
let a = angle_deg.to_radians();
let dir = [a.sin(), -a.cos()];
@@ -1030,11 +1028,8 @@ impl Compositor {
dst,
quad_px,
radius_px,
- src: [c1[0], c1[1], c1[2], c1[3]],
- mode: 5.0,
- color: c0,
fx: [dir[0], dir[1], 0.0, 0.0],
- ..Default::default()
+ ..crate::frame_geometry::gradient_layer(stops, offsets, BLACK)
});
}
Some(SceneBackground::Image { path }) => {
@@ -1787,9 +1782,7 @@ impl Compositor {
..Default::default()
});
}
- SceneBackground::Gradient { angle_deg, stops, motion } => {
- let c0 = stops.first().and_then(|s| parse_hex(s)).unwrap_or(lp.bg_color);
- let c1 = stops.last().and_then(|s| parse_hex(s)).unwrap_or(c0);
+ SceneBackground::Gradient { angle_deg, stops, offsets, motion } => {
// angle CSS → direction unitaire (espace sortie, y vers le bas) :
// 0° = vers le haut, 90° = vers la droite.
let a = angle_deg.to_radians();
@@ -1801,12 +1794,9 @@ impl Compositor {
);
self.draw_solid(&LayerCB {
dst: [0.0, 0.0, 1.0, 1.0],
- src: [c1[0], c1[1], c1[2], c1[3]],
- mode: 5.0,
- color: c0,
fx: [dir[0], dir[1], anim[0], anim[1]],
mb,
- ..Default::default()
+ ..crate::frame_geometry::gradient_layer(&stops, &offsets, lp.bg_color)
});
}
SceneBackground::Image { path } => {
diff --git a/crates/compositor/src/frame_geometry.rs b/crates/compositor/src/frame_geometry.rs
index 00c889f50..7b70fa6a0 100644
--- a/crates/compositor/src/frame_geometry.rs
+++ b/crates/compositor/src/frame_geometry.rs
@@ -1561,6 +1561,66 @@ pub fn gradient_motion_slots(
)
}
+/// Un dégradé linéaire en calque du mode 5, stops compris : quatre nœuds `[r, g, b, position]`
+/// dans `color`, `src_prev`, `dst_prev` puis `src`, dans l'ordre du dégradé. Le shader va de nœud
+/// en nœud comme CSS, donc un stop du milieu est peint là où la vignette le montre. Avant, seuls
+/// le premier et le dernier stop arrivaient au shader, et le milieu d'un dégradé à trois stops
+/// (celui de l'ancien éditeur) disparaissait du rendu.
+///
+/// Positions : celles de l'app quand il y en a une par stop, sinon réparties à égale distance
+/// (scène plus ancienne). Bornées à 0..1 et jamais en recul sur la précédente, comme en CSS. Un
+/// stop illisible est sauté ; sans aucun stop lisible, `fallback` remplit tout. Moins de quatre
+/// stops : le dernier se répète, en segments de longueur nulle qui ne peignent rien. Deux stops
+/// à 0 et 1 rendent donc exactement l'ancien `lerp(c0, c1, t)`.
+pub fn gradient_layer(stops: &[String], offsets: &[f32], fallback: [f32; 4]) -> LayerCB {
+ let mut knots: Vec<[f32; 4]> = Vec::with_capacity(stops.len().max(4));
+ let mut floor = 0.0f32;
+ for (i, stop) in stops.iter().enumerate() {
+ let Some(c) = parse_hex(stop) else { continue };
+ let raw = if offsets.len() == stops.len() {
+ offsets[i]
+ } else if stops.len() > 1 {
+ i as f32 / (stops.len() - 1) as f32
+ } else {
+ 0.0
+ };
+ let at = if raw.is_finite() { raw.clamp(0.0, 1.0) } else { floor }.max(floor);
+ floor = at;
+ knots.push([c[0], c[1], c[2], at]);
+ }
+ if knots.is_empty() {
+ knots.push([fallback[0], fallback[1], fallback[2], 0.0]);
+ }
+ // ponytail: quatre nœuds, les emplacements libres du mode 5. Au-delà (les presets v1.5 en
+ // avaient jusqu'à sept), on retire tour à tour le stop intérieur que ses voisins reproduisent
+ // le mieux. Une rampe en texture lèverait la limite si un dégradé plus riche devenait courant.
+ while knots.len() > 4 {
+ let miss = |i: usize| {
+ let (p, k, n) = (knots[i - 1], knots[i], knots[i + 1]);
+ let span = n[3] - p[3];
+ if span <= 1e-6 {
+ return 0.0; // stop de largeur nulle : il ne peint rien
+ }
+ let f = (k[3] - p[3]) / span;
+ (0..3).map(|c| (k[c] - (p[c] + (n[c] - p[c]) * f)).abs()).sum::<f32>()
+ };
+ let drop = (1..knots.len() - 1).min_by(|&a, &b| miss(a).total_cmp(&miss(b))).unwrap_or(1);
+ knots.remove(drop);
+ }
+ while knots.len() < 4 {
+ let last = knots[knots.len() - 1];
+ knots.push(last);
+ }
+ LayerCB {
+ mode: 5.0,
+ color: knots[0],
+ src_prev: knots[1],
+ dst_prev: knots[2],
+ src: knots[3],
+ ..Default::default()
+ }
+}
+
/// True when this clip really has a camera to draw.
///
/// TWO ways the app says "no camera", and both must be caught here, because the
@@ -6177,6 +6237,67 @@ mod tests {
}
}
+ const BLACK_TEST: [f32; 4] = [0.0, 0.0, 0.0, 1.0];
+
+ fn knots(cb: &LayerCB) -> [[f32; 4]; 4] {
+ [cb.color, cb.src_prev, cb.dst_prev, cb.src]
+ }
+
+ #[test]
+ fn gradient_layer_keeps_the_middle_stop_where_css_puts_it() {
+ // Le dégradé de l'ancien éditeur : trois stops rgb(), le milieu à 50 %.
+ let stops = ["rgb(255, 0, 0)", "rgb(0, 255, 0)", "rgb(0, 0, 255)"].map(String::from);
+ let cb = gradient_layer(&stops, &[0.0, 0.5, 1.0], BLACK_TEST);
+ assert_eq!(cb.mode, 5.0);
+ let k = knots(&cb);
+ assert_eq!(k[0], [1.0, 0.0, 0.0, 0.0]);
+ assert_eq!(k[1], [0.0, 1.0, 0.0, 0.5]);
+ assert_eq!(k[2], [0.0, 0.0, 1.0, 1.0]);
+ assert_eq!(k[3], [0.0, 0.0, 1.0, 1.0]);
+ }
+
+ #[test]
+ fn gradient_layer_two_stops_render_the_old_ramp() {
+ // Scène d'avant les offsets : les stops se répartissent à 0 et 1, le reste répète la fin.
+ let cb = gradient_layer(&["#000000".into(), "#ffffff".into()], &[], BLACK_TEST);
+ let k = knots(&cb);
+ assert_eq!(k[0], [0.0, 0.0, 0.0, 0.0]);
+ for knot in &k[1..] {
+ assert_eq!(*knot, [1.0, 1.0, 1.0, 1.0]);
+ }
+ }
+
+ #[test]
+ fn gradient_layer_bounds_and_orders_offsets_and_skips_bad_stops() {
+ let stops = ["#ff0000", "nope", "#00ff00", "#0000ff"].map(String::from);
+ let cb = gradient_layer(&stops, &[-0.2, 0.3, 0.6, 0.4], BLACK_TEST);
+ let at: Vec<f32> = knots(&cb).iter().map(|k| k[3]).collect();
+ // -0.2 borné à 0 ; 0.4 derrière 0.6 ramené à 0.6 ; "nope" sauté.
+ assert_eq!(at, vec![0.0, 0.6, 0.6, 0.6]);
+ assert_eq!(knots(&cb)[1][1], 1.0, "le vert suit le rouge, le stop illisible est sauté");
+ let empty = gradient_layer(&[], &[], [0.2, 0.3, 0.4, 1.0]);
+ assert!(knots(&empty).iter().all(|k| *k == [0.2, 0.3, 0.4, 0.0]));
+ }
+
+ #[test]
+ fn gradient_layer_folds_a_long_preset_into_four_knots() {
+ // Un preset v1.5 à sept stops : les extrémités restent, les positions restent en ordre,
+ // et le stop retiré est celui que ses voisins reproduisaient déjà.
+ let stops = ["#fcc5e4", "#fda34b", "#ff7882", "#c8699e", "#7046aa", "#0c1db8", "#020f75"]
+ .map(String::from);
+ let offsets = [0.0, 0.15, 0.35, 0.52, 0.71, 0.87, 1.0];
+ let k = knots(&gradient_layer(&stops, &offsets, BLACK_TEST));
+ assert_eq!(k[0][3], 0.0);
+ assert_eq!(k[3][3], 1.0);
+ assert_eq!(&k[0][..3], &parse_hex("#fcc5e4").unwrap()[..3]);
+ assert_eq!(&k[3][..3], &parse_hex("#020f75").unwrap()[..3]);
+ assert!(k.windows(2).all(|w| w[0][3] <= w[1][3]));
+ // Un stop parfaitement sur la droite de ses voisins part en premier.
+ let straight = ["#000000", "#404040", "#808080", "#ff0000", "#ffffff"].map(String::from);
+ let k = knots(&gradient_layer(&straight, &[0.0, 0.25, 0.5, 0.75, 1.0], BLACK_TEST));
+ assert_eq!(k.iter().map(|k| k[3]).collect::<Vec<_>>(), vec![0.0, 0.5, 0.75, 1.0]);
+ }
+
/// Le contrat cross-backend, verrouillé octet par octet. Un shader qui lit un champ
/// décalé ne lève rien : il rend faux, en silence.
#[test]
diff --git a/crates/compositor/src/scene.rs b/crates/compositor/src/scene.rs
index 40713319a..4e2f46c0e 100644
--- a/crates/compositor/src/scene.rs
+++ b/crates/compositor/src/scene.rs
@@ -258,6 +258,10 @@ pub enum SceneBackground {
#[serde(rename = "angleDeg")]
angle_deg: f32,
stops: Vec<String>,
+ /// Position 0..1 de chaque stop le long du dégradé, telle que CSS la résout. Absente d'une
+ /// scène plus ancienne : les stops se répartissent alors à égale distance, comme en CSS.
+ #[serde(default)]
+ offsets: Vec<f32>,
/// Absent pour un fond immobile : l'app n'émet la clé que si un mouvement est choisi,
/// donc la scène d'un projet sans animation ne bouge pas d'un octet.
#[serde(default)]
@@ -785,9 +789,10 @@ mod tests {
assert!(scene.layout.webcam_mirror);
assert!((scene.effects.roundness_frac - 0.0222).abs() < 1e-6);
match scene.background {
- SceneBackground::Gradient { angle_deg, ref stops, motion } => {
+ SceneBackground::Gradient { angle_deg, ref stops, ref offsets, motion } => {
assert_eq!(angle_deg, 135.0);
assert_eq!(stops.len(), 2);
+ assert!(offsets.is_empty(), "une scène sans offsets reste lisible");
assert_eq!(motion, GradientMotion::None);
}
_ => panic!("expected gradient"),
diff --git a/crates/compositor/src/shaders.hlsl b/crates/compositor/src/shaders.hlsl
index 052acbfc5..ef6a08e62 100644
--- a/crates/compositor/src/shaders.hlsl
+++ b/crates/compositor/src/shaders.hlsl
@@ -301,12 +301,25 @@ float value_noise(float2 q)
return lerp(lerp(a, b, u.x), lerp(c, d, u.x), u.y);
}
-// Mouvements 2 (aurore) et 3 (vagues) du mode 5, dans les deux couleurs des stops seulement.
+// Rampe du mode 5 : quatre nœuds `rgb + position (w)`, dans l'ordre du dégradé, interpolés de
+// nœud en nœud comme CSS (avant le premier : sa couleur ; après le dernier : la sienne). Un
+// segment de longueur nulle est une marche nette. Deux stops à 0 et 1 suivis de deux copies du
+// dernier rendent exactement `lerp(c0, c1, t)`. `frame_geometry::gradient_layer` les remplit.
+float3 ramp4(float t, float4 k0, float4 k1, float4 k2, float4 k3)
+{
+ float3 c = k0.rgb;
+ c = lerp(c, k1.rgb, saturate((t - k0.w) / max(k1.w - k0.w, 1e-5)));
+ c = lerp(c, k2.rgb, saturate((t - k1.w) / max(k2.w - k1.w, 1e-5)));
+ c = lerp(c, k3.rgb, saturate((t - k2.w) / max(k3.w - k2.w, 1e-5)));
+ return c;
+}
+
+// Mouvements 2 (aurore) et 3 (vagues) du mode 5, sur la rampe de ses stops.
// `gp` 0..1 sur le quad, `dir`/`denom` ceux du dégradé, `time` = temps programme replié sur
// 120 s (toutes les périodes ci-dessous le divisent), `aspect` = w/h de la sortie. Périodes
// longues et contraste bas : le fond ne doit jamais prendre l'attention.
-float3 gradient_motion(float2 gp, float2 dir, float denom, float3 c0, float3 c1, float time,
- float motion, float aspect)
+float3 gradient_motion(float2 gp, float2 dir, float denom, float4 k0, float4 k1, float4 k2,
+ float4 k3, float time, float motion, float aspect)
{
const float TAU = 6.2831853;
float u = dot(gp - 0.5, dir) / denom; // position le long de l'axe, -0.5..0.5
@@ -318,20 +331,20 @@ float3 gradient_motion(float2 gp, float2 dir, float denom, float3 c0, float3 c1,
float2 p = float2((gp.x - 0.5) * aspect, gp.y - 0.5);
float ph = TAU * time / 120.0;
float n = value_noise(p * 2.5 + 1.5 * float2(cos(ph), sin(ph)));
- float3 g = lerp(c0, c1, saturate(0.5 + u + 0.3 * (n - 0.5)));
+ float3 g = ramp4(saturate(0.5 + u + 0.3 * (n - 0.5)), k0, k1, k2, k3);
float2 b0 = float2(0.35 * aspect * sin(TAU * time / 20.0), 0.25 * sin(TAU * time / 30.0 + 1.0));
float2 b1 = float2(0.30 * aspect * sin(TAU * time / 24.0 + 2.0), 0.22 * cos(TAU * time / 40.0));
float2 b2 = float2(0.25 * aspect * cos(TAU * time / 30.0 + 4.0), 0.28 * sin(TAU * time / 24.0 + 3.0));
- g = lerp(g, c1, 0.45 * exp(-dot(p - b0, p - b0) / 0.08));
- g = lerp(g, c0, 0.45 * exp(-dot(p - b1, p - b1) / 0.06));
- g = lerp(g, c1, 0.35 * exp(-dot(p - b2, p - b2) / 0.05));
+ g = lerp(g, k3.rgb, 0.45 * exp(-dot(p - b0, p - b0) / 0.08));
+ g = lerp(g, k0.rgb, 0.45 * exp(-dot(p - b1, p - b1) / 0.06));
+ g = lerp(g, k3.rgb, 0.35 * exp(-dot(p - b2, p - b2) / 0.05));
return g;
}
// Vagues : trois bandes sinus perpendiculaires à l'axe, qui avancent d'une bande en 12 s,
// légèrement ondulées le long des bandes (20 s). Elles décalent la rampe, rien d'autre.
float v = dot(gp - 0.5, float2(-dir.y, dir.x)) / denom;
float w = sin(TAU * (3.0 * u + 0.04 * sin(TAU * (1.5 * v + time / 20.0)) - time / 12.0));
- return lerp(c0, c1, saturate(0.5 + u + 0.07 * w));
+ return ramp4(saturate(0.5 + u + 0.07 * w), k0, k1, k2, k3);
}
// Couverture d'une pastille (disque) adoucie sur ~1.5 px, pour la barre de titre du mode 14.
@@ -1691,8 +1704,8 @@ float4 ps_main(VSOut i) : SV_Target
return float4(texImg.Sample(samp, i.uv).rgb * a, a); // prémultiplié
}
- // mode 5 : gradient linéaire 2 stops (parité web wallpaper dégradé). color = stop0,
- // src.xyz = stop1, fx.xy = direction unitaire (espace sortie, y vers le bas). t est
+ // mode 5 : gradient linéaire jusqu'à 4 stops (parité web wallpaper dégradé). Nœuds
+ // `rgb + position` dans color, src_prev, dst_prev, src (cf. `ramp4`), fx.xy = direction unitaire (espace sortie, y vers le bas). t est
// normalisé coin-à-coin (dénominateur = |dx|+|dy|) pour couvrir toute la diagonale.
// Fond animé : fx.z = temps programme (s, replié sur 120), fx.w = mouvement (0 immobile,
// 1 dérive, 2 aurore, 3 vagues), mb.x = aspect w/h. 0 rend le dégradé d'avant à l'octet.
@@ -1714,10 +1727,10 @@ float4 ps_main(VSOut i) : SV_Target
// le sélecteur affiche.
float2 gp = (quad_px.x > 0.0 && quad_px.y > 0.0) ? (i.local / quad_px) : i.pout;
float t = saturate(0.5 + dot(gp - 0.5, dir) / denom);
- float3 g = lerp(color.rgb, src.xyz, t);
+ float3 g = ramp4(t, color, src_prev, dst_prev, src);
if (fx.w > 1.5)
{
- g = gradient_motion(gp, dir, denom, color.rgb, src.xyz, fx.z, fx.w, mb.x);
+ g = gradient_motion(gp, dir, denom, color, src_prev, dst_prev, src, fx.z, fx.w, mb.x);
}
float a = quad_round_alpha(i.local, quad_px, radius_px);
return float4(g * a, a); // prémultiplié
diff --git a/crates/compositor/src/shaders.metal b/crates/compositor/src/shaders.metal
index fb53b114a..1d89caa3f 100644
--- a/crates/compositor/src/shaders.metal
+++ b/crates/compositor/src/shaders.metal
@@ -420,10 +420,20 @@ inline float value_noise(float2 q)
return mix(mix(a, b, u.x), mix(c, d, u.x), u.y);
}
+// Rampe du mode 5 à quatre nœuds. Miroir de `ramp4` côté HLSL (commentaires complets là-bas).
+inline float3 ramp4(float t, float4 k0, float4 k1, float4 k2, float4 k3)
+{
+ float3 c = k0.rgb;
+ c = mix(c, k1.rgb, clamp((t - k0.w) / max(k1.w - k0.w, 1e-5), 0.0, 1.0));
+ c = mix(c, k2.rgb, clamp((t - k1.w) / max(k2.w - k1.w, 1e-5), 0.0, 1.0));
+ c = mix(c, k3.rgb, clamp((t - k2.w) / max(k3.w - k2.w, 1e-5), 0.0, 1.0));
+ return c;
+}
+
// Mouvements 2 (aurore) et 3 (vagues) du mode 5. Miroir ligne pour ligne de
// `gradient_motion` côté HLSL (commentaires complets là-bas).
-inline float3 gradient_motion(float2 gp, float2 dir, float denom, float3 c0, float3 c1,
- float time, float motion, float aspect)
+inline float3 gradient_motion(float2 gp, float2 dir, float denom, float4 k0, float4 k1,
+ float4 k2, float4 k3, float time, float motion, float aspect)
{
const float TAU = 6.2831853;
float u = dot(gp - 0.5, dir) / denom; // position le long de l'axe, -0.5..0.5
@@ -433,19 +443,19 @@ inline float3 gradient_motion(float2 gp, float2 dir, float denom, float3 c0, flo
float2 p = float2((gp.x - 0.5) * aspect, gp.y - 0.5);
float ph = TAU * time / 120.0;
float n = value_noise(p * 2.5 + 1.5 * float2(cos(ph), sin(ph)));
- float3 g = mix(c0, c1, clamp(0.5 + u + 0.3 * (n - 0.5), 0.0, 1.0));
+ float3 g = ramp4(clamp(0.5 + u + 0.3 * (n - 0.5), 0.0, 1.0), k0, k1, k2, k3);
float2 b0 = float2(0.35 * aspect * sin(TAU * time / 20.0), 0.25 * sin(TAU * time / 30.0 + 1.0));
float2 b1 = float2(0.30 * aspect * sin(TAU * time / 24.0 + 2.0), 0.22 * cos(TAU * time / 40.0));
float2 b2 = float2(0.25 * aspect * cos(TAU * time / 30.0 + 4.0), 0.28 * sin(TAU * time / 24.0 + 3.0));
- g = mix(g, c1, 0.45 * exp(-dot(p - b0, p - b0) / 0.08));
- g = mix(g, c0, 0.45 * exp(-dot(p - b1, p - b1) / 0.06));
- g = mix(g, c1, 0.35 * exp(-dot(p - b2, p - b2) / 0.05));
+ g = mix(g, k3.rgb, 0.45 * exp(-dot(p - b0, p - b0) / 0.08));
+ g = mix(g, k0.rgb, 0.45 * exp(-dot(p - b1, p - b1) / 0.06));
+ g = mix(g, k3.rgb, 0.35 * exp(-dot(p - b2, p - b2) / 0.05));
return g;
}
// Vagues : trois bandes sinus perpendiculaires à l'axe (12 s), ondulées (20 s).
float v = dot(gp - 0.5, float2(-dir.y, dir.x)) / denom;
float w = sin(TAU * (3.0 * u + 0.04 * sin(TAU * (1.5 * v + time / 20.0)) - time / 12.0));
- return mix(c0, c1, clamp(0.5 + u + 0.07 * w, 0.0, 1.0));
+ return ramp4(clamp(0.5 + u + 0.07 * w, 0.0, 1.0), k0, k1, k2, k3);
}
// ============ Curseur MODÉLISÉ (mode 15) ============
@@ -1566,8 +1576,8 @@ fragment float4 ps_main(VSOut i [[stage_in]],
return float4(texImg.sample(samp, i.uv).rgb * a, a); // prémultiplié
}
- // mode 5 : gradient linéaire 2 stops (parité web wallpaper dégradé). color = stop0,
- // src.xyz = stop1, fx.xy = direction unitaire (espace sortie, y vers le bas). t est
+ // mode 5 : gradient linéaire jusqu'à 4 stops (parité web wallpaper dégradé). Nœuds
+ // `rgb + position` dans color, src_prev, dst_prev, src (cf. `ramp4`), fx.xy = direction unitaire (espace sortie, y vers le bas). t est
// normalisé coin-à-coin (dénominateur = |dx|+|dy|) pour couvrir toute la diagonale.
//
// Le port avait remplacé tout ce calcul par une couleur plate : un dégradé s'affichait
@@ -1595,11 +1605,11 @@ fragment float4 ps_main(VSOut i [[stage_in]],
? (i.local / layer.quad_px)
: i.pout;
float t = clamp(0.5 + dot(gp - 0.5, dir) / denom, 0.0, 1.0);
- float3 g = mix(layer.color.rgb, layer.src.xyz, t);
+ float3 g = ramp4(t, layer.color, layer.src_prev, layer.dst_prev, layer.src);
if (layer.fx.w > 1.5)
{
- g = gradient_motion(gp, dir, denom, layer.color.rgb, layer.src.xyz, layer.fx.z,
- layer.fx.w, layer.mb.x);
+ g = gradient_motion(gp, dir, denom, layer.color, layer.src_prev, layer.dst_prev,
+ layer.src, layer.fx.z, layer.fx.w, layer.mb.x);
}
float a = quad_round_alpha(i.local, layer.quad_px, layer.radius_px);
return float4(g * a, a); // prémultiplié
diff --git a/crates/compositor/src/vk_shaders/layer.wgsl b/crates/compositor/src/vk_shaders/layer.wgsl
index cdf12c322..78303b87f 100644
--- a/crates/compositor/src/vk_shaders/layer.wgsl
+++ b/crates/compositor/src/vk_shaders/layer.wgsl
@@ -375,10 +375,19 @@ fn value_noise(q: vec2<f32>) -> f32 {
return mix(mix(a, b, u.x), mix(c, d, u.x), u.y);
}
+// Rampe du mode 5 a quatre noeuds. Miroir de `ramp4` cote HLSL (commentaires complets la-bas).
+fn ramp4(t: f32, k0: vec4<f32>, k1: vec4<f32>, k2: vec4<f32>, k3: vec4<f32>) -> vec3<f32> {
+ var c = k0.rgb;
+ c = mix(c, k1.rgb, clamp((t - k0.w) / max(k1.w - k0.w, 1e-5), 0.0, 1.0));
+ c = mix(c, k2.rgb, clamp((t - k1.w) / max(k2.w - k1.w, 1e-5), 0.0, 1.0));
+ c = mix(c, k3.rgb, clamp((t - k2.w) / max(k3.w - k2.w, 1e-5), 0.0, 1.0));
+ return c;
+}
+
// Mouvements 2 (aurore) et 3 (vagues) du mode 5. Miroir ligne pour ligne de
// `gradient_motion` cote HLSL (commentaires complets la-bas).
-fn gradient_motion(gp: vec2<f32>, dir: vec2<f32>, denom: f32, c0: vec3<f32>, c1: vec3<f32>,
- time: f32, motion: f32, aspect: f32) -> vec3<f32> {
+fn gradient_motion(gp: vec2<f32>, dir: vec2<f32>, denom: f32, k0: vec4<f32>, k1: vec4<f32>,
+ k2: vec4<f32>, k3: vec4<f32>, time: f32, motion: f32, aspect: f32) -> vec3<f32> {
let TAU = 6.2831853;
let u = dot(gp - vec2<f32>(0.5), dir) / denom; // position le long de l'axe, -0.5..0.5
if motion < 2.5 {
@@ -386,19 +395,19 @@ fn gradient_motion(gp: vec2<f32>, dir: vec2<f32>, denom: f32, c0: vec3<f32>, c1:
let p = vec2<f32>((gp.x - 0.5) * aspect, gp.y - 0.5);
let ph = TAU * time / 120.0;
let n = value_noise(p * 2.5 + 1.5 * vec2<f32>(cos(ph), sin(ph)));
- var g = mix(c0, c1, clamp(0.5 + u + 0.3 * (n - 0.5), 0.0, 1.0));
+ var g = ramp4(clamp(0.5 + u + 0.3 * (n - 0.5), 0.0, 1.0), k0, k1, k2, k3);
let b0 = vec2<f32>(0.35 * aspect * sin(TAU * time / 20.0), 0.25 * sin(TAU * time / 30.0 + 1.0));
let b1 = vec2<f32>(0.30 * aspect * sin(TAU * time / 24.0 + 2.0), 0.22 * cos(TAU * time / 40.0));
let b2 = vec2<f32>(0.25 * aspect * cos(TAU * time / 30.0 + 4.0), 0.28 * sin(TAU * time / 24.0 + 3.0));
- g = mix(g, c1, 0.45 * exp(-dot(p - b0, p - b0) / 0.08));
- g = mix(g, c0, 0.45 * exp(-dot(p - b1, p - b1) / 0.06));
- g = mix(g, c1, 0.35 * exp(-dot(p - b2, p - b2) / 0.05));
+ g = mix(g, k3.rgb, 0.45 * exp(-dot(p - b0, p - b0) / 0.08));
+ g = mix(g, k0.rgb, 0.45 * exp(-dot(p - b1, p - b1) / 0.06));
+ g = mix(g, k3.rgb, 0.35 * exp(-dot(p - b2, p - b2) / 0.05));
return g;
}
// Vagues : trois bandes sinus perpendiculaires a l'axe (12 s), ondulees (20 s).
let v = dot(gp - vec2<f32>(0.5), vec2<f32>(-dir.y, dir.x)) / denom;
let w = sin(TAU * (3.0 * u + 0.04 * sin(TAU * (1.5 * v + time / 20.0)) - time / 12.0));
- return mix(c0, c1, clamp(0.5 + u + 0.07 * w, 0.0, 1.0));
+ return ramp4(clamp(0.5 + u + 0.07 * w, 0.0, 1.0), k0, k1, k2, k3);
}
// Couverture d'une pastille (disque) adoucie sur ~1.5 px, pour la barre de titre du mode 14.
@@ -1248,8 +1257,9 @@ fn fs_main(i: VsOut) -> @location(0) vec4<f32> {
// Mode 1 — couleur pleine.
rgb = layer.color.rgb;
} else if layer.mode > 4.5 && layer.mode < 5.5 {
- // Mode 5 -- gradient lineaire : color (c0) -> src.rgb (c1) le long de
- // la direction fx.xy (sin, -cos de l'angle). Parite avec le HLSL/MSL.
+ // Mode 5 -- gradient lineaire jusqu'a 4 stops : noeuds `rgb + position` dans color,
+ // src_prev, dst_prev, src (cf. `ramp4`), le long de la direction fx.xy (sin, -cos de
+ // l'angle). Parite avec le HLSL/MSL.
// `denom` : HLSL et MSL normalisent coin-a-coin (|dx|+|dy|) pour couvrir toute la
// diagonale. Il manquait ici, donc le meme degrade ne rendait pas pareil sur Linux.
// Fond anime : fx.z = temps programme (s, replie sur 120), fx.w = mouvement (0 immobile,
@@ -1271,10 +1281,10 @@ fn fs_main(i: VsOut) -> @location(0) vec4<f32> {
gp = i.local / layer.quad_px;
}
let t = clamp(0.5 + dot(gp - vec2<f32>(0.5), dir) / denom, 0.0, 1.0);
- rgb = mix(layer.color.rgb, layer.src.rgb, t);
+ rgb = ramp4(t, layer.color, layer.src_prev, layer.dst_prev, layer.src);
if layer.fx.w > 1.5 {
- rgb = gradient_motion(gp, dir, denom, layer.color.rgb, layer.src.rgb, layer.fx.z,
- layer.fx.w, layer.mb.x);
+ rgb = gradient_motion(gp, dir, denom, layer.color, layer.src_prev, layer.dst_prev,
+ layer.src, layer.fx.z, layer.fx.w, layer.mb.x);
}
} else if layer.mode > 10.5 && layer.mode < 11.5 {
// Mode 11 : texte. texY est l'atlas R8 (couverture alpha au canal .r,
diff --git a/src/components/ui/gradient-editor.test.tsx b/src/components/ui/gradient-editor.test.tsx
deleted file mode 100644
index 81be1c3eb..000000000
--- a/src/components/ui/gradient-editor.test.tsx
+++ /dev/null
@@ -1,70 +0,0 @@
-// @vitest-environment jsdom
-import "@testing-library/jest-dom";
-import { fireEvent, render, screen, waitFor } from "@testing-library/react";
-import { describe, expect, it, vi } from "vitest";
-import type { GradientEditorState } from "./gradient-editor";
-import GradientEditor from "./gradient-editor";
-
-const getLastState = (onChange: ReturnType<typeof vi.fn>): GradientEditorState => {
- const calls = onChange.mock.calls;
- expect(calls.length).toBeGreaterThan(0);
- return calls[calls.length - 1][0] as GradientEditorState;
-};
-
-describe("GradientEditor", () => {
- it("emits unique point IDs after an interaction", async () => {
- const onChange = vi.fn();
- render(<GradientEditor onChange={onChange} />);
-
- const removeButton = screen.getByRole("button", { name: "Remove color" });
- fireEvent.click(removeButton);
- await waitFor(() => expect(onChange).toHaveBeenCalled());
-
- const state = getLastState(onChange);
- const ids = state.points.map((p) => p.id);
- expect(new Set(ids).size).toBe(ids.length);
- expect(ids).toContain("main");
- expect(ids).toHaveLength(2);
- });
-
- it("generates a fresh ID after remove→add instead of reusing an existing one", async () => {
- const onChange = vi.fn();
- render(<GradientEditor onChange={onChange} />);
-
- fireEvent.click(screen.getByRole("button", { name: "Remove color" }));
- await waitFor(() => expect(getLastState(onChange).points).toHaveLength(2));
- expect(getLastState(onChange).points.map((p) => p.id)).toEqual(["main", "o1"]);
-
- fireEvent.click(screen.getByRole("button", { name: "Add color" }));
- await waitFor(() => expect(getLastState(onChange).points).toHaveLength(3));
- const finalIds = getLastState(onChange).points.map((p) => p.id);
- expect(new Set(finalIds).size).toBe(finalIds.length);
- expect(finalIds).toContain("o3");
- });
-
- it("disables add at MAX_COLORS and remove at one color", async () => {
- render(<GradientEditor onChange={vi.fn()} />);
-
- const addButton = screen.getByRole("button", { name: "Add color" });
- const removeButton = screen.getByRole("button", { name: "Remove color" });
-
- expect(addButton).toBeDisabled();
- expect(removeButton).not.toBeDisabled();
-
- fireEvent.click(removeButton);
- await waitFor(() => expect(addButton).not.toBeDisabled());
-
- fireEvent.click(removeButton);
- await waitFor(() => expect(removeButton).toBeDisabled());
- expect(addButton).not.toBeDisabled();
- });
-
- it("cycles harmony when eligible", async () => {
- const onChange = vi.fn();
- render(<GradientEditor onChange={onChange} />);
-
- fireEvent.click(screen.getByRole("button", { name: "Cycle harmony" }));
- await waitFor(() => expect(onChange).toHaveBeenCalled());
- expect(getLastState(onChange).harmonyType).not.toBe("splitComplementary");
- });
-});
diff --git a/src/components/ui/gradient-editor.tsx b/src/components/ui/gradient-editor.tsx
deleted file mode 100644
index c9e2525dc..000000000
--- a/src/components/ui/gradient-editor.tsx
+++ /dev/null
@@ -1,587 +0,0 @@
-import type { PointerEvent as ReactPointerEvent } from "react";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { clamp } from "@/utils/math";
-
-/* ---------- icons ---------- */
-const PlusIcon = () => (
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
- <path d="M12 5v14M5 12h14" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
- </svg>
-);
-
-const MinusIcon = () => (
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
- <path d="M5 12h14" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
- </svg>
-);
-
-const RingsIcon = () => (
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
- <circle cx="8" cy="9" r="5" stroke="currentColor" strokeWidth="1.6" />
- <circle cx="16" cy="9" r="5" stroke="currentColor" strokeWidth="1.6" />
- <circle cx="12" cy="16" r="5" stroke="currentColor" strokeWidth="1.6" />
- </svg>
-);
-
-const MAX_COLORS = 3;
-const MAIN_ID = "main";
-const MAIN_MAX_RADIUS = 40;
-
-/* ---------- color-wheel harmony math ---------- */
-type ColorHarmony = {
- type: HarmonyType;
- count: number;
- angles: number[];
-};
-
-type HarmonyType = "complementary" | "analogous" | "splitComplementary" | "triadic" | "square";
-
-const colorHarmonies: ColorHarmony[] = [
- { type: "complementary", count: 1, angles: [180] },
- { type: "analogous", count: 1, angles: [35] },
- { type: "splitComplementary", count: 2, angles: [150, 210] },
- { type: "triadic", count: 2, angles: [120, 240] },
- { type: "square", count: 2, angles: [90, 270] },
-];
-
-function getEligibleHarmonies(secondaryCount: number): ColorHarmony[] {
- return colorHarmonies.filter((h) => h.count === secondaryCount);
-}
-
-function getHarmonyAngles(secondaryCount: number, harmonyType: HarmonyType): number[] {
- const eligible = getEligibleHarmonies(secondaryCount);
- if (eligible.length === 0) return [];
- return (eligible.find((h) => h.type === harmonyType) || eligible[0]).angles;
-}
-
-function computeSecondaryPositions(
- mainAngle: number,
- mainRadius: number,
- secondaries: { id: string }[],
- harmonyType: HarmonyType,
-): { id: string; x: number; y: number; color: string }[] {
- const angles = getHarmonyAngles(secondaries.length, harmonyType);
- return secondaries.map((p, i) => {
- const angle = mainAngle + (angles[i] ?? 0);
- const rad = (angle * Math.PI) / 180;
- const x = clamp(50 + mainRadius * Math.cos(rad), 5, 95);
- const y = clamp(50 + mainRadius * Math.sin(rad), 5, 95);
- return { id: p.id, x, y, color: colorFromPolar(angle, mainRadius) };
- });
-}
-
-/* ---------- position -> color ---------- */
-function hueToRgb(p: number, q: number, t: number): number {
- let tt = t;
- if (tt < 0) tt += 1;
- if (tt > 1) tt -= 1;
- if (tt < 1 / 6) return p + (q - p) * 6 * tt;
- if (tt < 1 / 2) return q;
- if (tt < 2 / 3) return p + (q - p) * (2 / 3 - tt) * 6;
- return p;
-}
-
-function hslToRgb(h: number, s: number, l: number): [number, number, number] {
- let r: number;
- let g: number;
- let b: number;
- if (s === 0) {
- r = g = b = l;
- } else {
- const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
- const p = 2 * l - q;
- r = hueToRgb(p, q, h + 1 / 3);
- g = hueToRgb(p, q, h);
- b = hueToRgb(p, q, h - 1 / 3);
- }
- return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
-}
-
-function colorFromPolar(angleDeg: number, radiusPct: number): string {
- const hue = ((angleDeg % 360) + 360) % 360;
- const saturation = clamp(radiusPct / MAIN_MAX_RADIUS, 0, 1);
- const [r, g, b] = hslToRgb(hue / 360, saturation, 0.5);
- return `rgb(${r}, ${g}, ${b})`;
-}
-
-/* ---------- wavy-slider path ---------- */
-const LINE_PATH = `M 51.373 27.395 L 367.037 27.395`;
-const SINE_PATH = `M 51.373 27.395 C 60.14 -8.503 68.906 -8.503 77.671 27.395 C 86.438 63.293 95.205 63.293 103.971 27.395 C 112.738 -8.503 121.504 -8.503 130.271 27.395 C 139.037 63.293 147.803 63.293 156.57 27.395 C 165.335 -8.503 174.101 -8.503 182.868 27.395 C 191.634 63.293 200.4 63.293 209.167 27.395 C 217.933 -8.503 226.7 -8.503 235.467 27.395 C 244.233 63.293 252.999 63.293 261.765 27.395 C 270.531 -8.503 279.297 -8.503 288.064 27.395 C 296.83 63.293 305.596 63.293 314.363 27.395 C 323.13 -8.503 331.896 -8.503 340.662 27.395 M 314.438 27.395 C 323.204 -8.503 331.97 -8.503 340.737 27.395 C 349.503 63.293 358.27 63.293 367.037 27.395`;
-
-type PathPoint =
- | { type: "M"; x: number; y: number }
- | { type: "L"; x: number; y: number }
- | { type: "C"; x1: number; y1: number; x2: number; y2: number; x: number; y: number };
-
-function parseSinePath(pathStr: string): PathPoint[] {
- const points: PathPoint[] = [];
- const commands = pathStr.match(/[MCL]\s*[\d\s.\-,]+/g);
- if (!commands) return points;
-
- for (const command of commands) {
- const type = command.charAt(0);
- const coords = command
- .slice(1)
- .trim()
- .split(/[\s,]+/)
- .map(Number);
-
- if (type === "M") {
- points.push({ type: "M", x: coords[0], y: coords[1] });
- } else if (type === "C") {
- if (coords.length >= 6 && coords.length % 6 === 0) {
- for (let i = 0; i < coords.length; i += 6) {
- points.push({
- x1: coords[i],
- y1: coords[i + 1],
- x2: coords[i + 2],
- y2: coords[i + 3],
- x: coords[i + 4],
- y: coords[i + 5],
- type: "C",
- });
- }
- }
- } else if (type === "L") {
- points.push({ type: "L", x: coords[0], y: coords[1] });
- }
- }
- return points;
-}
-
-const SINE_POINTS = parseSinePath(SINE_PATH);
-
-function getInterpolatedWavePath(progress: number): string {
- const referenceY = 27.395;
- if (SINE_POINTS.length === 0) return progress < 0.5 ? LINE_PATH : SINE_PATH;
- if (progress <= 0.001) return LINE_PATH;
- if (progress >= 0.999) return SINE_PATH;
-
- const t = progress;
- let d = "";
- for (const p of SINE_POINTS) {
- if (p.type === "M") {
- d += `M ${p.x} ${referenceY + (p.y - referenceY) * t} `;
- } else if (p.type === "C") {
- const y1 = referenceY + (p.y1 - referenceY) * t;
- const y2 = referenceY + (p.y2 - referenceY) * t;
- const y = referenceY + (p.y - referenceY) * t;
- d += `C ${p.x1} ${y1} ${p.x2} ${y2} ${p.x} ${y} `;
- } else if (p.type === "L") {
- d += `L ${p.x} ${p.y} `;
- }
- }
- return d.trim();
-}
-
-/* ---------- exported state ---------- */
-export type GradientEditorState = {
- points: { id: string; x: number; y: number; color: string }[];
- mainX: number;
- mainY: number;
- mainColor: string;
- brightness: number;
- angle: number;
- harmonyType: HarmonyType;
-};
-
-type GradientEditorProps = {
- onChange?: (state: GradientEditorState) => void;
-};
-
-export default function GradientEditor({ onChange }: GradientEditorProps) {
- const [mainAngle, setMainAngle] = useState(-35);
- const [mainRadius, setMainRadius] = useState(20);
- const idCounter = useRef(1);
- const [orbitPoints, setOrbitPoints] = useState<{ id: string }[]>(() => [
- { id: `o${idCounter.current++}` },
- { id: `o${idCounter.current++}` },
- ]);
- const [harmonyType, setHarmonyType] = useState<HarmonyType>("splitComplementary");
- const [brightness, setBrightness] = useState(55);
- const [angle, setAngle] = useState(135);
-
- const canvasRef = useRef<HTMLDivElement>(null);
- const trackRef = useRef<HTMLDivElement>(null);
- const draggingMain = useRef(false);
- const mountedRef = useRef(false);
- const dragCleanup = useRef<(() => void) | null>(null);
-
- useEffect(() => {
- return () => {
- dragCleanup.current?.();
- dragCleanup.current = null;
- };
- }, []);
-
- const totalColors = 1 + orbitPoints.length;
-
- /* ---------- derived visuals ---------- */
- const mainX = 50 + mainRadius * Math.cos((mainAngle * Math.PI) / 180);
- const mainY = 50 + mainRadius * Math.sin((mainAngle * Math.PI) / 180);
- const mainColor = colorFromPolar(mainAngle, mainRadius);
-
- const allPoints = useMemo(() => {
- const secondaries = computeSecondaryPositions(
- mainAngle,
- mainRadius,
- orbitPoints,
- harmonyType,
- ).map((p) => ({ ...p, size: 20 }));
-
- return [{ id: MAIN_ID, x: mainX, y: mainY, color: mainColor, size: 64 }, ...secondaries];
- }, [mainX, mainY, mainColor, orbitPoints, mainAngle, mainRadius, harmonyType]);
-
- /* ---------- emit state ---------- */
- const onChangeRef = useRef(onChange);
- useEffect(() => {
- onChangeRef.current = onChange;
- }, [onChange]);
-
- useEffect(() => {
- const cb = onChangeRef.current;
- if (!cb) return;
- if (!mountedRef.current) {
- mountedRef.current = true;
- return;
- }
-
- cb({
- points: allPoints.map((p) => ({ id: p.id, x: p.x, y: p.y, color: p.color })),
- mainX,
- mainY,
- mainColor,
- brightness,
- harmonyType,
- angle,
- });
- }, [allPoints, mainX, mainY, mainColor, brightness, harmonyType, angle]);
-
- /* ---------- main point drag ---------- */
- const updateMainFromPointer = useCallback((clientX: number, clientY: number) => {
- const el = canvasRef.current;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- const cx = rect.left + rect.width / 2;
- const cy = rect.top + rect.height / 2;
- const dx = clientX - cx;
- const dy = clientY - cy;
- const angle = (Math.atan2(dy, dx) * 180) / Math.PI;
- const radius = clamp((Math.hypot(dx, dy) / (rect.width / 2)) * 50, 0, MAIN_MAX_RADIUS);
-
- setMainAngle(angle);
- setMainRadius(radius);
- }, []);
-
- const onMainPointerDown = (e: ReactPointerEvent) => {
- e.stopPropagation();
- draggingMain.current = true;
- dragCleanup.current?.();
- const onUp = () => {
- draggingMain.current = false;
- window.removeEventListener("pointermove", onMainPointerMove);
- window.removeEventListener("pointerup", onUp);
- window.removeEventListener("pointercancel", onUp);
- dragCleanup.current = null;
- };
- dragCleanup.current = onUp;
- window.addEventListener("pointermove", onMainPointerMove);
- window.addEventListener("pointerup", onUp);
- window.addEventListener("pointercancel", onUp);
- };
-
- const onMainPointerMove = useCallback(
- (e: PointerEvent) => {
- if (!draggingMain.current) return;
- updateMainFromPointer(e.clientX, e.clientY);
- },
- [updateMainFromPointer],
- );
-
- /* ---------- add / remove / harmony ---------- */
- const addPoint = () => {
- if (totalColors >= MAX_COLORS) return;
- const id = `o${idCounter.current++}`;
- setOrbitPoints((prev) => [...prev, { id }]);
- };
-
- const removePoint = () => {
- if (totalColors <= 1) return;
- setOrbitPoints((prev) => prev.slice(0, -1));
- };
-
- const eligibleHarmonies = getEligibleHarmonies(orbitPoints.length);
-
- const cycleHarmony = () => {
- if (eligibleHarmonies.length <= 1) return;
- const idx = eligibleHarmonies.findIndex((h) => h.type === harmonyType);
- const next = eligibleHarmonies[(idx + 1) % eligibleHarmonies.length];
- setHarmonyType(next.type);
- };
-
- /* ---------- brightness slider ---------- */
- const setBrightnessFromClientX = (clientX: number) => {
- const el = trackRef.current;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- const pct = clamp(((clientX - rect.left) / rect.width) * 100, 0, 100);
- setBrightness(pct);
- };
-
- /* visual clamp so thumb stays on the visible wave path */
- const WAVE_START_PCT = (51.373 / 420) * 100;
- const WAVE_END_PCT = (367.037 / 420) * 100;
- const clampedBrightness = clamp(brightness, WAVE_START_PCT, WAVE_END_PCT);
-
- const onSliderPointerDown = (e: ReactPointerEvent) => {
- setBrightnessFromClientX(e.clientX);
- dragCleanup.current?.();
- const move = (ev: PointerEvent) => setBrightnessFromClientX(ev.clientX);
- const onUp = () => {
- window.removeEventListener("pointermove", move);
- window.removeEventListener("pointerup", onUp);
- window.removeEventListener("pointercancel", onUp);
- dragCleanup.current = null;
- };
- dragCleanup.current = onUp;
- window.addEventListener("pointermove", move);
- window.addEventListener("pointerup", onUp);
- window.addEventListener("pointercancel", onUp);
- };
-
- /* ---------- angle knob ---------- */
- // Angle knob
- const angleKnobRef = useRef<HTMLDivElement>(null);
- const angleKnobAngle = ((angle % 360) / 360) * 360;
- const setAngleFromClientPos = (clientX: number, clientY: number) => {
- const el = angleKnobRef.current;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- const cx = rect.left + rect.width / 2;
- const cy = rect.top + rect.height / 2;
- let a = (Math.atan2(-(clientY - cy), clientX - cx) * 180) / Math.PI;
- if (a < 0) a += 360;
- setAngle(Math.round(a));
- };
- const onAngleKnobPointerDown = (e: ReactPointerEvent) => {
- e.stopPropagation();
- setAngleFromClientPos(e.clientX, e.clientY);
- dragCleanup.current?.();
- const move = (ev: PointerEvent) => setAngleFromClientPos(ev.clientX, ev.clientY);
- const onUp = () => {
- window.removeEventListener("pointermove", move);
- window.removeEventListener("pointerup", onUp);
- window.removeEventListener("pointercancel", onUp);
- dragCleanup.current = null;
- };
- dragCleanup.current = onUp;
- window.addEventListener("pointermove", move);
- window.addEventListener("pointerup", onUp);
- window.addEventListener("pointercancel", onUp);
- };
-
- // Preview brightness must match the per-channel multiplier in
- // applyBrightness so the wheel is WYSIWYG.
- const brightnessFilter = `brightness(${brightness / 100})`;
-
- const wavePath = useMemo(() => getInterpolatedWavePath(brightness / 100), [brightness]);
-
- /* ---------- keyboard handlers ---------- */
- const onMainKeyDown = useCallback((e: React.KeyboardEvent) => {
- const step = e.shiftKey ? 10 : 5;
- if (e.key === "ArrowLeft" || e.key === "ArrowDown") {
- e.preventDefault();
- setMainAngle((a) => a - step);
- } else if (e.key === "ArrowRight" || e.key === "ArrowUp") {
- e.preventDefault();
- setMainAngle((a) => a + step);
- }
- }, []);
-
- const onSliderKeyDown = useCallback((e: React.KeyboardEvent) => {
- const step = e.shiftKey ? 10 : 2;
- if (e.key === "ArrowLeft" || e.key === "ArrowDown") {
- e.preventDefault();
- setBrightness((b) => clamp(b - step, 0, 100));
- } else if (e.key === "ArrowRight" || e.key === "ArrowUp") {
- e.preventDefault();
- setBrightness((b) => clamp(b + step, 0, 100));
- }
- }, []);
-
- const onAngleKeyDown = useCallback((e: React.KeyboardEvent) => {
- const step = e.shiftKey ? 15 : 5;
- if (e.key === "ArrowLeft" || e.key === "ArrowDown") {
- e.preventDefault();
- setAngle((a) => (a - step + 360) % 360);
- } else if (e.key === "ArrowRight" || e.key === "ArrowUp") {
- e.preventDefault();
- setAngle((a) => (a + step) % 360);
- }
- }, []);
-
- return (
- <div className="w-[240px] max-w-full mx-auto rounded-[18px] p-[10px] box-border font-sans text-[#f2f2f2] select-none">
- {/* Color Wheel Canvas */}
- <div
- ref={canvasRef}
- className="relative w-full aspect-square rounded-[18px] overflow-hidden bg-[#141414]
- [background-image:radial-gradient(#ffffff0c_1px,transparent_1px)] bg-[16px_16px]"
- >
- {/* Center marker */}
- <div className="absolute left-1/2 top-1/2 w-1 h-1 rounded-full bg-white/25 -translate-x-1/2 -translate-y-1/2 pointer-events-none" />
-
- {/* Points container with brightness filter */}
- <div
- className="absolute inset-0 transition-[filter] duration-75"
- style={{ filter: brightnessFilter }}
- >
- {/* Secondary points */}
- {allPoints
- .filter((p) => p.id !== MAIN_ID)
- .map((p) => (
- <div
- key={p.id}
- className="absolute w-5 h-5 rounded-full shadow-[0_3px_10px_rgba(0,0,0,0.35)] transition-all z-[2]"
- style={{
- left: `${p.x}%`,
- top: `${p.y}%`,
- transform: "translate(-50%, -50%)",
- background: p.color,
- }}
- />
- ))}
-
- {/* Main draggable point */}
- <div
- onPointerDown={onMainPointerDown}
- onKeyDown={onMainKeyDown}
- tabIndex={0}
- role="slider"
- aria-label="Color hue"
- aria-valuemin={0}
- aria-valuemax={360}
- aria-valuenow={Math.round(((mainAngle % 360) + 360) % 360)}
- className="absolute w-11 h-11 rounded-full cursor-grab shadow-[0_0_0_4px_#f5f5f5,0_4px_14px_rgba(0,0,0,0.35)] transition-shadow z-10 active:cursor-grabbing focus:outline-none focus:ring-2 focus:ring-[var(--brand)]"
- style={{
- left: `${mainX}%`,
- top: `${mainY}%`,
- transform: "translate(-50%, -50%)",
- background: mainColor,
- }}
- />
- </div>
-
- {/* Controls on canvas */}
- <div className="absolute left-3.5 bottom-3 flex gap-3">
- <button
- type="button"
- onClick={addPoint}
- disabled={totalColors >= MAX_COLORS}
- className={`w-6 h-6 rounded-full flex items-center justify-center border-none bg-transparent transition-all text-white/80 hover:text-white ${
- totalColors >= MAX_COLORS
- ? "opacity-40 cursor-not-allowed"
- : "hover:bg-white/10 cursor-pointer"
- }`}
- title="Add color"
- >
- <PlusIcon />
- </button>
-
- <button
- type="button"
- onClick={removePoint}
- disabled={totalColors <= 1}
- className={`w-6 h-6 rounded-full flex items-center justify-center border-none bg-transparent transition-all text-white/80 hover:text-white ${
- totalColors <= 1
- ? "opacity-40 cursor-not-allowed"
- : "hover:bg-white/10 cursor-pointer"
- }`}
- title="Remove color"
- >
- <MinusIcon />
- </button>
-
- <button
- type="button"
- onClick={cycleHarmony}
- disabled={eligibleHarmonies.length <= 1}
- className={`w-6 h-6 rounded-full flex items-center justify-center border-none bg-transparent transition-all text-white/80 hover:text-white ${
- eligibleHarmonies.length <= 1
- ? "opacity-40 cursor-not-allowed"
- : "hover:bg-white/10 cursor-pointer"
- }`}
- title="Cycle harmony"
- >
- <RingsIcon />
- </button>
- </div>
- </div>
-
- {/* Bottom controls: Brightness + Angle */}
- <div className="flex items-center gap-3.5 mt-3.5">
- {/* Brightness wavy slider. Its thumb/track are colored for the dark
- canvas above, so it needs its own dark backing here too — this row
- otherwise sits directly on the (theme-dependent) popover background,
- where the light thumb disappears in light mode. */}
- <div
- ref={trackRef}
- onPointerDown={onSliderPointerDown}
- onKeyDown={onSliderKeyDown}
- tabIndex={0}
- role="slider"
- aria-label="Brightness"
- aria-valuemin={0}
- aria-valuemax={100}
- aria-valuenow={Math.round(brightness)}
- className="relative flex-1 h-10 flex items-center cursor-pointer bg-[#141414] rounded-full focus:outline-none focus:ring-2 focus:ring-[var(--brand)]"
- >
- <svg
- width="100%"
- height="30"
- viewBox="0 -15 420 80"
- preserveAspectRatio="none"
- className="absolute left-0 right-0"
- >
- <path
- d={wavePath}
- fill="none"
- stroke="rgba(255,255,255,0.22)"
- strokeWidth="6"
- strokeLinecap="round"
- strokeLinejoin="round"
- />
- </svg>
-
- <div
- className="absolute w-3 h-[30px] rounded-[7px] bg-[#f5f5f5] shadow-[0_2px_8px_rgba(0,0,0,0.3)] transition-all"
- style={{
- left: `${clampedBrightness}%`,
- top: "50%",
- transform: "translate(-50%, -50%)",
- }}
- />
- </div>
-
- {/* Angle knob */}
- <div
- ref={angleKnobRef}
- onPointerDown={onAngleKnobPointerDown}
- onKeyDown={onAngleKeyDown}
- tabIndex={0}
- role="slider"
- aria-label="Gradient angle"
- aria-valuemin={0}
- aria-valuemax={360}
- aria-valuenow={angle}
- className="relative w-[42px] h-[42px] rounded-full bg-[radial-gradient(circle_at_35%_30%,#2b2b2b,#0c0c0c)] shadow-[0_3px_10px_rgba(0,0,0,0.4)] cursor-grab flex-shrink-0 active:cursor-grabbing focus:outline-none focus:ring-2 focus:ring-[var(--brand)]"
- title="Gradient angle"
- >
- <div className="absolute inset-0" style={{ transform: `rotate(${angleKnobAngle}deg)` }}>
- <div className="absolute top-[5px] left-1/2 w-[2px] h-[9px] bg-[#e8e8e8] translate-x-[-50%] rounded" />
- </div>
- </div>
- </div>
- </div>
- );
-}
diff --git a/src/native/sceneDescription.test.ts b/src/native/sceneDescription.test.ts
index 7ea4fe9b6..8500e89e5 100644
--- a/src/native/sceneDescription.test.ts
+++ b/src/native/sceneDescription.test.ts
@@ -114,6 +114,7 @@ describe("buildSceneDescription.background", () => {
kind: "gradient",
angleDeg: 135,
stops: ["#eaebed", "#bcc0c6"],
+ offsets: [0, 1],
});
});
@@ -123,6 +124,7 @@ describe("buildSceneDescription.background", () => {
kind: "gradient",
angleDeg: 180,
stops: ["#a1b2c3", "#d4e5f6"],
+ offsets: [0, 1],
});
});
@@ -139,6 +141,7 @@ describe("buildSceneDescription.background", () => {
kind: "gradient",
angleDeg: 90,
stops: ["rgba(1,2,3,0.5)", "#fff"],
+ offsets: [0, 1],
});
});
@@ -150,6 +153,7 @@ describe("buildSceneDescription.background", () => {
kind: "gradient",
angleDeg: 135,
stops: ["#a1b2c3", "#d4e5f6"],
+ offsets: [0, 1],
});
});
@@ -160,6 +164,24 @@ describe("buildSceneDescription.background", () => {
kind: "gradient",
angleDeg: 180,
stops: [],
+ offsets: [],
+ });
+ });
+
+ // The gradient editor wrote 3-stop gradients and older presets up to 7: the compositor
+ // draws each stop at its offset, so the offsets travel with the colours.
+ it("sends every stop with its offset", () => {
+ const doc = makeDoc({
+ legacyEditor: {
+ wallpaper:
+ "linear-gradient(135deg, rgb(255, 0, 0) 0%, rgb(0, 255, 0) 50%, rgb(0, 0, 255) 100%)",
+ },
+ });
+ expect(buildSceneDescription(doc).background).toEqual({
+ kind: "gradient",
+ angleDeg: 135,
+ stops: ["rgb(255, 0, 0)", "rgb(0, 255, 0)", "rgb(0, 0, 255)"],
+ offsets: [0, 0.5, 1],
});
});
@@ -189,6 +211,7 @@ describe("buildSceneDescription.background motion", () => {
kind: "gradient",
angleDeg: 135,
stops: ["#eaebed", "#bcc0c6"],
+ offsets: [0, 1],
motion: "aurora",
});
});
diff --git a/src/native/sceneDescription.ts b/src/native/sceneDescription.ts
index 2d3ff0df1..62722544a 100644
--- a/src/native/sceneDescription.ts
+++ b/src/native/sceneDescription.ts
@@ -69,11 +69,14 @@ import { ROUNDNESS_REFERENCE_PX } from "./paramUnits";
export type SceneBackground =
| { kind: "color"; color: string } // "#rrggbb"
// linear-gradient(deg, c1, c2, …). `motion` is omitted when still, so a project without
- // animation sends the same payload as before the setting existed.
+ // animation sends the same payload as before the setting existed. `offsets` (0..1, one per
+ // stop) place the stops where CSS puts them: the thumbnail draws a middle stop at its
+ // offset, and so must the compositor.
| {
kind: "gradient";
angleDeg: number;
stops: string[];
+ offsets: number[];
motion?: Exclude<WallpaperMotion, "none">;
}
| { kind: "image"; path: string }; // "/wallpapers/…" or a data: URL
@@ -561,6 +564,7 @@ function parseWallpaper(wallpaper: string) {
kind: "gradient",
angleDeg: resolveLinearGradientAngle(parsed?.descriptor ?? null),
stops: parsed?.stops.map((stop) => stop.color) ?? [],
+ offsets: parsed?.stops.map((stop) => stop.offset) ?? [],
} as const;
}
return { kind: "image", path: wallpaper } as const;