From 3619b5dd25149814756d1cfb3e63fc0918a31e7c Mon Sep 17 00:00:00 2001 From: clover caruso Date: Mon, 30 Nov 2026 20:42:35 -0800 Subject: [PATCH] Split flow, viewer, keyframes, and engine media into focused submodules Assisted-by: claude-sonnet-5.5 --- crates/app/src/keyframes.rs | 381 +----------- crates/app/src/keyframes/paint.rs | 384 ++++++++++++ crates/engine/src/media.rs | 798 +------------------------ crates/engine/src/media/exr.rs | 280 +++++++++ crates/engine/src/media/raster.rs | 238 ++++++++ crates/engine/src/media/video.rs | 268 +++++++++ crates/flow/src/hit.rs | 228 ++++++++ crates/flow/src/lib.rs | 728 +---------------------- crates/flow/src/paint.rs | 503 ++++++++++++++++ crates/viewer/src/clock.rs | 440 ++++++++++++++ crates/viewer/src/lib.rs | 935 +----------------------------- crates/viewer/src/paint.rs | 499 ++++++++++++++++ 12 files changed, 2863 insertions(+), 2819 deletions(-) create mode 100644 crates/app/src/keyframes/paint.rs create mode 100644 crates/engine/src/media/exr.rs create mode 100644 crates/engine/src/media/raster.rs create mode 100644 crates/engine/src/media/video.rs create mode 100644 crates/flow/src/hit.rs create mode 100644 crates/flow/src/paint.rs create mode 100644 crates/viewer/src/clock.rs create mode 100644 crates/viewer/src/paint.rs diff --git a/crates/app/src/keyframes.rs b/crates/app/src/keyframes.rs index 25bd3a5dfa9c17827f81a407189f8d3090e9eeed..38bfe6a0697514c2364c2ad50d36ad3ff8e84d8d 100644 --- a/crates/app/src/keyframes.rs +++ b/crates/app/src/keyframes.rs @@ -1,6 +1,8 @@ //! Docked Keyframes dope-sheet pane: animated node/channel tracks, audio waveform track, //! green RAM cache bar, and interactive drag-to-retime keyframes with `CompHistory` undo. +mod paint; + use draw::{Glyphs, Primitive}; use model::{Comp, CompHistory, Keyframe, NodeId}; use std::collections::{HashMap, HashSet}; @@ -507,377 +509,6 @@ impl KeyframesView { _ => {} } } - - pub fn prepare_labels(&mut self) { - if self.text_cache.len() > TEXT_CACHE_CAP { - self.text_cache.clear(); - } - let font_sm = text::Font { - families: Arc::from([text::Family::Mono]), - size: 10.0, - weight: 500, - italic: false, - }; - let font_row = text::Font { - families: Arc::from([text::Family::Sans]), - size: 11.0, - weight: 500, - italic: false, - }; - let font_hdr = text::Font { - families: Arc::from([text::Family::Sans]), - size: 11.0, - weight: 600, - italic: false, - }; - let make = |s: &str, font: &text::Font| { - let styles = [text::Style::new(font.clone())]; - text::Paragraph { - text: s, - styles: &styles, - spans: &[], - replacements: &[], - width: None, - indent: 0.0, - line_height: 1.2, - align: text::Align::Left, - tab: 32.0, - } - .layout() - }; - - for (k, txt, f) in [ - ("hdr:title", "Keyframes", &font_hdr), - ("hdr:all", "All", &font_sm), - ("hdr:sel", "Sel", &font_sm), - ("hdr:audio", "Audio", &font_row), - ("footer", "Drag keys/spans to retime · Ruler: Scrub · Wheel: Zoom · Del: Remove · F: Fit", &font_sm), - ] { - self.text_cache.entry(k.to_owned()).or_insert_with(|| make(txt, f)); - } - - for row in &self.rows { - match row { - TrackRow::NodeHeader { node_id, label, .. } => { - let glyph = if self.collapsed_nodes.contains(node_id) { "▸" } else { "▾" }; - let text = format!("{glyph} {label}"); - self.text_cache.entry(format!("nh:{text}")).or_insert_with(|| make(&text, &font_hdr)); - } - TrackRow::Channel { label, .. } => { - self.text_cache.entry(format!("ch:{label}")).or_insert_with(|| make(label, &font_row)); - } - } - } - - let plot = self.plot_rect(); - let max_ticks = f64::from(((plot[2] - plot[0]) / 56.0).max(2.0)); - let t_step = nice_step((self.t_range[1] - self.t_range[0]) / max_ticks); - let t_start = (self.t_range[0] / t_step).floor() as i64; - let t_end = (self.t_range[1] / t_step).ceil() as i64; - for ti in t_start..=t_end { - let key = format!("t:{}", (ti as f64 * t_step).round() as i64); - self.text_cache.entry(key.clone()).or_insert_with(|| make(&key[2..], &font_sm)); - } - } - - pub fn paint<'a>(&'a self, comp: &'a Comp, current_frame: f64) -> Vec> { - let mut out = Vec::with_capacity(512); - let [w, h] = self.size; - let plot = self.plot_rect(); - let top = self.tracks_top(); - - // Sidebar + Ruler chrome - out.push(Primitive::Rect { rect: [0.0, 0.0, SIDEBAR_W, h], color: self.palette.sidebar }); - out.push(Primitive::Rect { rect: [SIDEBAR_W, 0.0, w, RULER_H], color: self.palette.ruler }); - out.push(Primitive::Segment { from: [SIDEBAR_W, 0.0], to: [SIDEBAR_W, h], width: 1.0, color: self.palette.rule }); - out.push(Primitive::Segment { from: [0.0, RULER_H], to: [w, RULER_H], width: 1.0, color: self.palette.rule }); - - if let Some(tl) = self.text_cache.get("hdr:title") { - out.push(Primitive::Text { - text: tl as &dyn Glyphs, - origin: [10.0, 6.0], - clip: Some([8.0, 0.0, SIDEBAR_W - 52.0, RULER_H]), - ink: self.palette.text, - }); - } - // "All / Sel" filter pill - let pill_rect = [SIDEBAR_W - 46.0, 4.0, SIDEBAR_W - 8.0, RULER_H - 4.0]; - out.push(Primitive::RoundedRect { - rect: pill_rect, - radius: 4.0, - stroke: None, - color: if self.selected_only { - [self.palette.accent[0], self.palette.accent[1], self.palette.accent[2], 0.28] - } else { - [self.palette.bg[0], self.palette.bg[1], self.palette.bg[2], 0.7] - }, - }); - out.push(Primitive::RoundedRect { - rect: pill_rect, - radius: 4.0, - stroke: Some(1.0), - color: if self.selected_only { self.palette.accent } else { self.palette.rule }, - }); - let mode_key = if self.selected_only { "hdr:sel" } else { "hdr:all" }; - if let Some(ml) = self.text_cache.get(mode_key) { - out.push(Primitive::Text { - text: ml as &dyn Glyphs, - origin: [pill_rect[0] + 9.0, 7.0], - clip: Some(pill_rect), - ink: if self.selected_only { self.palette.text } else { self.palette.text_dim }, - }); - } - - // Ruler frame ticks - let max_ticks = f64::from(((plot[2] - plot[0]) / 56.0).max(2.0)); - let t_step = nice_step((self.t_range[1] - self.t_range[0]) / max_ticks); - let t_start = (self.t_range[0] / t_step).floor() as i64; - let t_end = (self.t_range[1] / t_step).ceil() as i64; - for ti in t_start..=t_end { - let t = ti as f64 * t_step; - let x = self.time_to_x(t); - if x < plot[0] || x > plot[2] { - continue; - } - out.push(Primitive::Segment { from: [x, RULER_H], to: [x, plot[3]], width: 1.0, color: self.palette.grid }); - let key = format!("t:{}", t.round() as i64); - if let Some(tl) = self.text_cache.get(&key) { - out.push(Primitive::Text { - text: tl as &dyn Glyphs, - origin: [x + 3.0, 5.0], - clip: Some([plot[0], 0.0, plot[2], RULER_H]), - ink: self.palette.text_dim, - }); - } - } - - // Green RAM cache bar along bottom edge of ruler - for &(c0, c1) in &self.cached_ranges { - let x0 = self.time_to_x(c0 as f64).max(plot[0]); - let x1 = self.time_to_x((c1 + 1) as f64).min(plot[2]); - if x1 > x0 { - out.push(Primitive::Rect { - rect: [x0, RULER_H - 3.5, x1.max(x0 + 2.0), RULER_H - 0.5], - color: [0.22, 0.86, 0.48, 0.92], - }); - } - } - - // Dedicated Audio Waveform row when audio is present - if !self.audio_peaks.is_empty() { - let ay0 = RULER_H; - let ay1 = RULER_H + AUDIO_ROW_H; - out.push(Primitive::Rect { rect: [0.0, ay0, w, ay1], color: self.palette.row_alt }); - out.push(Primitive::Segment { from: [0.0, ay1], to: [w, ay1], width: 1.0, color: self.palette.rule }); - if let Some(al) = self.text_cache.get("hdr:audio") { - out.push(Primitive::Text { - text: al as &dyn Glyphs, - origin: [12.0, ay0 + 5.0], - clip: Some([8.0, ay0, SIDEBAR_W - 8.0, ay1]), - ink: [0.54, 0.80, 1.0, 0.95], - }); - } - out.push(Primitive::PushClip { rect: [plot[0], ay0, plot[2], ay1], radius: 0.0 }); - let mid_y = 0.5 * (ay0 + ay1); - let max_half = AUDIO_ROW_H * 0.42; - let a0 = self.audio_range[0]; - let n = self.audio_peaks.len() as i64; - let f_vis0 = (self.t_range[0].floor() as i64).max(a0); - let f_vis1 = (self.t_range[1].ceil() as i64).min(a0 + n - 1); - let bar_step = ((plot[2] - plot[0]) / ((self.t_range[1] - self.t_range[0]).max(1.0) as f32)).max(1.5); - let stride = ((1.8 / bar_step).ceil() as i64).max(1); - let mut f = f_vis0; - while f <= f_vis1 { - let mut peak = 0.0_f32; - for off in 0..stride { - let idx = (f + off - a0) as usize; - if let Some(&v) = self.audio_peaks.get(idx) { - if v > peak { peak = v; } - } - } - if peak > 0.01 { - let x = self.time_to_x(f as f64); - let hh = (peak * max_half).max(1.0); - let bw = (bar_step * stride as f32 - 0.6).max(1.2); - out.push(Primitive::Rect { - rect: [x, mid_y - hh, x + bw, mid_y + hh], - color: [0.46, 0.74, 0.98, 0.55], - }); - } - f += stride; - } - out.push(Primitive::PopClip); - } - - // Render range subtle shading - let rx0 = self.time_to_x(comp.render_range[0] as f64); - let rx1 = self.time_to_x(comp.render_range[1] as f64); - out.push(Primitive::PushClip { rect: [plot[0], top, plot[2], plot[3]], radius: 0.0 }); - if rx0 > plot[0] { - out.push(Primitive::Rect { rect: [plot[0], top, rx0.min(plot[2]), plot[3]], color: [0.0, 0.0, 0.0, 0.16] }); - } - if rx1 < plot[2] { - out.push(Primitive::Rect { rect: [rx1.max(plot[0]), top, plot[2], plot[3]], color: [0.0, 0.0, 0.0, 0.16] }); - } - out.push(Primitive::PopClip); - - // Track rows (clipped to track area) - out.push(Primitive::PushClip { rect: [0.0, top, w, plot[3]], radius: 0.0 }); - for (ri, row) in self.rows.iter().enumerate() { - let y0 = self.row_y(ri); - let y1 = y0 + ROW_H; - if y1 < top || y0 > plot[3] { - continue; - } - if ri % 2 == 1 { - out.push(Primitive::Rect { rect: [0.0, y0, w, y1], color: self.palette.row_alt }); - } - out.push(Primitive::Segment { from: [0.0, y1], to: [w, y1], width: 1.0, color: self.palette.grid }); - - match row { - TrackRow::NodeHeader { node_id, label, splines } => { - let glyph = if self.collapsed_nodes.contains(node_id) { "▸" } else { "▾" }; - let key = format!("nh:{glyph} {label}"); - if let Some(tl) = self.text_cache.get(&key) { - out.push(Primitive::Text { - text: tl as &dyn Glyphs, - origin: [10.0, y0 + 4.0], - clip: Some([6.0, y0, SIDEBAR_W - 6.0, y1]), - ink: self.palette.text, - }); - } - // Summary span + tick dots on node header row - let mut t_min = f64::INFINITY; - let mut t_max = f64::NEG_INFINITY; - for sname in splines { - if let Some(sp) = comp.splines.get(sname) { - for kf in &sp.keyframes { - t_min = t_min.min(kf.time); - t_max = t_max.max(kf.time); - } - } - } - if t_min.is_finite() { - let sx0 = self.time_to_x(t_min).max(plot[0]); - let sx1 = self.time_to_x(t_max).min(plot[2]); - if sx1 >= sx0 { - out.push(Primitive::RoundedRect { - rect: [sx0, y0 + 6.0, sx1.max(sx0 + 4.0), y1 - 6.0], - radius: 3.0, - stroke: None, - color: [self.palette.accent[0], self.palette.accent[1], self.palette.accent[2], 0.22], - }); - } - } - } - TrackRow::Channel { label, spline, color, .. } => { - out.push(Primitive::RoundedRect { - rect: [20.0, y0 + 7.0, 28.0, y0 + 15.0], - radius: 2.0, - stroke: None, - color: *color, - }); - if let Some(tl) = self.text_cache.get(&format!("ch:{label}")) { - out.push(Primitive::Text { - text: tl as &dyn Glyphs, - origin: [34.0, y0 + 4.0], - clip: Some([32.0, y0, SIDEBAR_W - 6.0, y1]), - ink: self.palette.text_dim, - }); - } - - if let Some(sp) = comp.splines.get(spline) { - if sp.keyframes.len() >= 2 { - let sx0 = self.time_to_x(sp.keyframes.first().unwrap().time).max(plot[0]); - let sx1 = self.time_to_x(sp.keyframes.last().unwrap().time).min(plot[2]); - if sx1 > sx0 { - out.push(Primitive::RoundedRect { - rect: [sx0, y0 + 8.0, sx1, y1 - 8.0], - radius: 2.0, - stroke: None, - color: [color[0], color[1], color[2], 0.28], - }); - } - } - let cy = y0 + ROW_H * 0.5; - for (ki, kf) in sp.keyframes.iter().enumerate() { - let kx = self.time_to_x(kf.time); - if kx < plot[0] - 8.0 || kx > plot[2] + 8.0 { - continue; - } - let kref = DopeKeyRef { spline: spline.clone(), key_idx: ki }; - let sel = self.selected_keys.contains(&kref); - let hov = self.hovered_key.as_ref() == Some(&kref); - let r = if sel || hov { 5.0 } else { 4.0 }; - out.push(Primitive::RoundedRect { - rect: [kx - r, cy - r, kx + r, cy + r], - radius: 1.5, - stroke: None, - color: if sel { - [1.0, 0.84, 0.24, 1.0] - } else if hov { - [1.0, 1.0, 1.0, 1.0] - } else { - *color - }, - }); - out.push(Primitive::RoundedRect { - rect: [kx - r, cy - r, kx + r, cy + r], - radius: 1.5, - stroke: Some(1.0), - color: [0.04, 0.04, 0.06, 0.9], - }); - } - } - } - } - } - - // Box select overlay - if let Some((a, b)) = self.box_select { - let x0 = a[0].min(b[0]); - let x1 = a[0].max(b[0]); - let y0 = a[1].min(b[1]); - let y1 = a[1].max(b[1]); - out.push(Primitive::RoundedRect { - rect: [x0, y0, x1, y1], - radius: 2.0, - stroke: None, - color: [self.palette.accent[0], self.palette.accent[1], self.palette.accent[2], 0.16], - }); - out.push(Primitive::RoundedRect { - rect: [x0, y0, x1, y1], - radius: 2.0, - stroke: Some(1.2), - color: self.palette.accent, - }); - } - out.push(Primitive::PopClip); - - // Playhead vertical line - let px = self.time_to_x(current_frame); - if px >= plot[0] && px <= plot[2] { - out.push(Primitive::Segment { - from: [px, 0.0], - to: [px, plot[3]], - width: 1.6, - color: [0.96, 0.36, 0.34, 0.92], - }); - } - - // Footer bar - out.push(Primitive::Rect { rect: [SIDEBAR_W, h - FOOTER_H, w, h], color: self.palette.ruler }); - if let Some(fl) = self.text_cache.get("footer") { - out.push(Primitive::Text { - text: fl as &dyn Glyphs, - origin: [SIDEBAR_W + 10.0, h - FOOTER_H + 5.0], - clip: Some([SIDEBAR_W + 6.0, h - FOOTER_H, w - 6.0, h]), - ink: self.palette.text_dim, - }); - } - - out - } } pub fn build_tracks( @@ -986,14 +617,6 @@ pub fn retime_selected_keys( .collect() } -fn nice_step(raw: f64) -> f64 { - let raw = raw.max(1.0); - let pow = 10.0_f64.powf(raw.log10().floor()); - let frac = raw / pow; - let nice = if frac < 1.5 { 1.0 } else if frac < 3.5 { 2.0 } else if frac < 7.5 { 5.0 } else { 10.0 }; - (nice * pow).max(1.0) -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/app/src/keyframes/paint.rs b/crates/app/src/keyframes/paint.rs new file mode 100644 index 0000000000000000000000000000000000000000..0b39cad219f0131d3211ad319ddaef9bbe93df1a --- /dev/null +++ b/crates/app/src/keyframes/paint.rs @@ -0,0 +1,384 @@ +//! Label layout and primitive painting for [`KeyframesView`]. + +use super::*; + +impl KeyframesView { + pub fn prepare_labels(&mut self) { + if self.text_cache.len() > TEXT_CACHE_CAP { + self.text_cache.clear(); + } + let font_sm = text::Font { + families: Arc::from([text::Family::Mono]), + size: 10.0, + weight: 500, + italic: false, + }; + let font_row = text::Font { + families: Arc::from([text::Family::Sans]), + size: 11.0, + weight: 500, + italic: false, + }; + let font_hdr = text::Font { + families: Arc::from([text::Family::Sans]), + size: 11.0, + weight: 600, + italic: false, + }; + let make = |s: &str, font: &text::Font| { + let styles = [text::Style::new(font.clone())]; + text::Paragraph { + text: s, + styles: &styles, + spans: &[], + replacements: &[], + width: None, + indent: 0.0, + line_height: 1.2, + align: text::Align::Left, + tab: 32.0, + } + .layout() + }; + + for (k, txt, f) in [ + ("hdr:title", "Keyframes", &font_hdr), + ("hdr:all", "All", &font_sm), + ("hdr:sel", "Sel", &font_sm), + ("hdr:audio", "Audio", &font_row), + ("footer", "Drag keys/spans to retime · Ruler: Scrub · Wheel: Zoom · Del: Remove · F: Fit", &font_sm), + ] { + self.text_cache.entry(k.to_owned()).or_insert_with(|| make(txt, f)); + } + + for row in &self.rows { + match row { + TrackRow::NodeHeader { node_id, label, .. } => { + let glyph = if self.collapsed_nodes.contains(node_id) { "▸" } else { "▾" }; + let text = format!("{glyph} {label}"); + self.text_cache.entry(format!("nh:{text}")).or_insert_with(|| make(&text, &font_hdr)); + } + TrackRow::Channel { label, .. } => { + self.text_cache.entry(format!("ch:{label}")).or_insert_with(|| make(label, &font_row)); + } + } + } + + let plot = self.plot_rect(); + let max_ticks = f64::from(((plot[2] - plot[0]) / 56.0).max(2.0)); + let t_step = nice_step((self.t_range[1] - self.t_range[0]) / max_ticks); + let t_start = (self.t_range[0] / t_step).floor() as i64; + let t_end = (self.t_range[1] / t_step).ceil() as i64; + for ti in t_start..=t_end { + let key = format!("t:{}", (ti as f64 * t_step).round() as i64); + self.text_cache.entry(key.clone()).or_insert_with(|| make(&key[2..], &font_sm)); + } + } + + pub fn paint<'a>(&'a self, comp: &'a Comp, current_frame: f64) -> Vec> { + let mut out = Vec::with_capacity(512); + let [w, h] = self.size; + let plot = self.plot_rect(); + let top = self.tracks_top(); + + // Sidebar + Ruler chrome + out.push(Primitive::Rect { rect: [0.0, 0.0, SIDEBAR_W, h], color: self.palette.sidebar }); + out.push(Primitive::Rect { rect: [SIDEBAR_W, 0.0, w, RULER_H], color: self.palette.ruler }); + out.push(Primitive::Segment { from: [SIDEBAR_W, 0.0], to: [SIDEBAR_W, h], width: 1.0, color: self.palette.rule }); + out.push(Primitive::Segment { from: [0.0, RULER_H], to: [w, RULER_H], width: 1.0, color: self.palette.rule }); + + if let Some(tl) = self.text_cache.get("hdr:title") { + out.push(Primitive::Text { + text: tl as &dyn Glyphs, + origin: [10.0, 6.0], + clip: Some([8.0, 0.0, SIDEBAR_W - 52.0, RULER_H]), + ink: self.palette.text, + }); + } + // "All / Sel" filter pill + let pill_rect = [SIDEBAR_W - 46.0, 4.0, SIDEBAR_W - 8.0, RULER_H - 4.0]; + out.push(Primitive::RoundedRect { + rect: pill_rect, + radius: 4.0, + stroke: None, + color: if self.selected_only { + [self.palette.accent[0], self.palette.accent[1], self.palette.accent[2], 0.28] + } else { + [self.palette.bg[0], self.palette.bg[1], self.palette.bg[2], 0.7] + }, + }); + out.push(Primitive::RoundedRect { + rect: pill_rect, + radius: 4.0, + stroke: Some(1.0), + color: if self.selected_only { self.palette.accent } else { self.palette.rule }, + }); + let mode_key = if self.selected_only { "hdr:sel" } else { "hdr:all" }; + if let Some(ml) = self.text_cache.get(mode_key) { + out.push(Primitive::Text { + text: ml as &dyn Glyphs, + origin: [pill_rect[0] + 9.0, 7.0], + clip: Some(pill_rect), + ink: if self.selected_only { self.palette.text } else { self.palette.text_dim }, + }); + } + + // Ruler frame ticks + let max_ticks = f64::from(((plot[2] - plot[0]) / 56.0).max(2.0)); + let t_step = nice_step((self.t_range[1] - self.t_range[0]) / max_ticks); + let t_start = (self.t_range[0] / t_step).floor() as i64; + let t_end = (self.t_range[1] / t_step).ceil() as i64; + for ti in t_start..=t_end { + let t = ti as f64 * t_step; + let x = self.time_to_x(t); + if x < plot[0] || x > plot[2] { + continue; + } + out.push(Primitive::Segment { from: [x, RULER_H], to: [x, plot[3]], width: 1.0, color: self.palette.grid }); + let key = format!("t:{}", t.round() as i64); + if let Some(tl) = self.text_cache.get(&key) { + out.push(Primitive::Text { + text: tl as &dyn Glyphs, + origin: [x + 3.0, 5.0], + clip: Some([plot[0], 0.0, plot[2], RULER_H]), + ink: self.palette.text_dim, + }); + } + } + + // Green RAM cache bar along bottom edge of ruler + for &(c0, c1) in &self.cached_ranges { + let x0 = self.time_to_x(c0 as f64).max(plot[0]); + let x1 = self.time_to_x((c1 + 1) as f64).min(plot[2]); + if x1 > x0 { + out.push(Primitive::Rect { + rect: [x0, RULER_H - 3.5, x1.max(x0 + 2.0), RULER_H - 0.5], + color: [0.22, 0.86, 0.48, 0.92], + }); + } + } + + // Dedicated Audio Waveform row when audio is present + if !self.audio_peaks.is_empty() { + let ay0 = RULER_H; + let ay1 = RULER_H + AUDIO_ROW_H; + out.push(Primitive::Rect { rect: [0.0, ay0, w, ay1], color: self.palette.row_alt }); + out.push(Primitive::Segment { from: [0.0, ay1], to: [w, ay1], width: 1.0, color: self.palette.rule }); + if let Some(al) = self.text_cache.get("hdr:audio") { + out.push(Primitive::Text { + text: al as &dyn Glyphs, + origin: [12.0, ay0 + 5.0], + clip: Some([8.0, ay0, SIDEBAR_W - 8.0, ay1]), + ink: [0.54, 0.80, 1.0, 0.95], + }); + } + out.push(Primitive::PushClip { rect: [plot[0], ay0, plot[2], ay1], radius: 0.0 }); + let mid_y = 0.5 * (ay0 + ay1); + let max_half = AUDIO_ROW_H * 0.42; + let a0 = self.audio_range[0]; + let n = self.audio_peaks.len() as i64; + let f_vis0 = (self.t_range[0].floor() as i64).max(a0); + let f_vis1 = (self.t_range[1].ceil() as i64).min(a0 + n - 1); + let bar_step = ((plot[2] - plot[0]) / ((self.t_range[1] - self.t_range[0]).max(1.0) as f32)).max(1.5); + let stride = ((1.8 / bar_step).ceil() as i64).max(1); + let mut f = f_vis0; + while f <= f_vis1 { + let mut peak = 0.0_f32; + for off in 0..stride { + let idx = (f + off - a0) as usize; + if let Some(&v) = self.audio_peaks.get(idx) { + if v > peak { peak = v; } + } + } + if peak > 0.01 { + let x = self.time_to_x(f as f64); + let hh = (peak * max_half).max(1.0); + let bw = (bar_step * stride as f32 - 0.6).max(1.2); + out.push(Primitive::Rect { + rect: [x, mid_y - hh, x + bw, mid_y + hh], + color: [0.46, 0.74, 0.98, 0.55], + }); + } + f += stride; + } + out.push(Primitive::PopClip); + } + + // Render range subtle shading + let rx0 = self.time_to_x(comp.render_range[0] as f64); + let rx1 = self.time_to_x(comp.render_range[1] as f64); + out.push(Primitive::PushClip { rect: [plot[0], top, plot[2], plot[3]], radius: 0.0 }); + if rx0 > plot[0] { + out.push(Primitive::Rect { rect: [plot[0], top, rx0.min(plot[2]), plot[3]], color: [0.0, 0.0, 0.0, 0.16] }); + } + if rx1 < plot[2] { + out.push(Primitive::Rect { rect: [rx1.max(plot[0]), top, plot[2], plot[3]], color: [0.0, 0.0, 0.0, 0.16] }); + } + out.push(Primitive::PopClip); + + // Track rows (clipped to track area) + out.push(Primitive::PushClip { rect: [0.0, top, w, plot[3]], radius: 0.0 }); + for (ri, row) in self.rows.iter().enumerate() { + let y0 = self.row_y(ri); + let y1 = y0 + ROW_H; + if y1 < top || y0 > plot[3] { + continue; + } + if ri % 2 == 1 { + out.push(Primitive::Rect { rect: [0.0, y0, w, y1], color: self.palette.row_alt }); + } + out.push(Primitive::Segment { from: [0.0, y1], to: [w, y1], width: 1.0, color: self.palette.grid }); + + match row { + TrackRow::NodeHeader { node_id, label, splines } => { + let glyph = if self.collapsed_nodes.contains(node_id) { "▸" } else { "▾" }; + let key = format!("nh:{glyph} {label}"); + if let Some(tl) = self.text_cache.get(&key) { + out.push(Primitive::Text { + text: tl as &dyn Glyphs, + origin: [10.0, y0 + 4.0], + clip: Some([6.0, y0, SIDEBAR_W - 6.0, y1]), + ink: self.palette.text, + }); + } + // Summary span + tick dots on node header row + let mut t_min = f64::INFINITY; + let mut t_max = f64::NEG_INFINITY; + for sname in splines { + if let Some(sp) = comp.splines.get(sname) { + for kf in &sp.keyframes { + t_min = t_min.min(kf.time); + t_max = t_max.max(kf.time); + } + } + } + if t_min.is_finite() { + let sx0 = self.time_to_x(t_min).max(plot[0]); + let sx1 = self.time_to_x(t_max).min(plot[2]); + if sx1 >= sx0 { + out.push(Primitive::RoundedRect { + rect: [sx0, y0 + 6.0, sx1.max(sx0 + 4.0), y1 - 6.0], + radius: 3.0, + stroke: None, + color: [self.palette.accent[0], self.palette.accent[1], self.palette.accent[2], 0.22], + }); + } + } + } + TrackRow::Channel { label, spline, color, .. } => { + out.push(Primitive::RoundedRect { + rect: [20.0, y0 + 7.0, 28.0, y0 + 15.0], + radius: 2.0, + stroke: None, + color: *color, + }); + if let Some(tl) = self.text_cache.get(&format!("ch:{label}")) { + out.push(Primitive::Text { + text: tl as &dyn Glyphs, + origin: [34.0, y0 + 4.0], + clip: Some([32.0, y0, SIDEBAR_W - 6.0, y1]), + ink: self.palette.text_dim, + }); + } + + if let Some(sp) = comp.splines.get(spline) { + if sp.keyframes.len() >= 2 { + let sx0 = self.time_to_x(sp.keyframes.first().unwrap().time).max(plot[0]); + let sx1 = self.time_to_x(sp.keyframes.last().unwrap().time).min(plot[2]); + if sx1 > sx0 { + out.push(Primitive::RoundedRect { + rect: [sx0, y0 + 8.0, sx1, y1 - 8.0], + radius: 2.0, + stroke: None, + color: [color[0], color[1], color[2], 0.28], + }); + } + } + let cy = y0 + ROW_H * 0.5; + for (ki, kf) in sp.keyframes.iter().enumerate() { + let kx = self.time_to_x(kf.time); + if kx < plot[0] - 8.0 || kx > plot[2] + 8.0 { + continue; + } + let kref = DopeKeyRef { spline: spline.clone(), key_idx: ki }; + let sel = self.selected_keys.contains(&kref); + let hov = self.hovered_key.as_ref() == Some(&kref); + let r = if sel || hov { 5.0 } else { 4.0 }; + out.push(Primitive::RoundedRect { + rect: [kx - r, cy - r, kx + r, cy + r], + radius: 1.5, + stroke: None, + color: if sel { + [1.0, 0.84, 0.24, 1.0] + } else if hov { + [1.0, 1.0, 1.0, 1.0] + } else { + *color + }, + }); + out.push(Primitive::RoundedRect { + rect: [kx - r, cy - r, kx + r, cy + r], + radius: 1.5, + stroke: Some(1.0), + color: [0.04, 0.04, 0.06, 0.9], + }); + } + } + } + } + } + + // Box select overlay + if let Some((a, b)) = self.box_select { + let x0 = a[0].min(b[0]); + let x1 = a[0].max(b[0]); + let y0 = a[1].min(b[1]); + let y1 = a[1].max(b[1]); + out.push(Primitive::RoundedRect { + rect: [x0, y0, x1, y1], + radius: 2.0, + stroke: None, + color: [self.palette.accent[0], self.palette.accent[1], self.palette.accent[2], 0.16], + }); + out.push(Primitive::RoundedRect { + rect: [x0, y0, x1, y1], + radius: 2.0, + stroke: Some(1.2), + color: self.palette.accent, + }); + } + out.push(Primitive::PopClip); + + // Playhead vertical line + let px = self.time_to_x(current_frame); + if px >= plot[0] && px <= plot[2] { + out.push(Primitive::Segment { + from: [px, 0.0], + to: [px, plot[3]], + width: 1.6, + color: [0.96, 0.36, 0.34, 0.92], + }); + } + + // Footer bar + out.push(Primitive::Rect { rect: [SIDEBAR_W, h - FOOTER_H, w, h], color: self.palette.ruler }); + if let Some(fl) = self.text_cache.get("footer") { + out.push(Primitive::Text { + text: fl as &dyn Glyphs, + origin: [SIDEBAR_W + 10.0, h - FOOTER_H + 5.0], + clip: Some([SIDEBAR_W + 6.0, h - FOOTER_H, w - 6.0, h]), + ink: self.palette.text_dim, + }); + } + + out + } +} + +fn nice_step(raw: f64) -> f64 { + let raw = raw.max(1.0); + let pow = 10.0_f64.powf(raw.log10().floor()); + let frac = raw / pow; + let nice = if frac < 1.5 { 1.0 } else if frac < 3.5 { 2.0 } else if frac < 7.5 { 5.0 } else { 10.0 }; + (nice * pow).max(1.0) +} diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index f907fe33594af6b154f55b51f509bcb19886a7f8..bc057b1b6f07b8b3cc5cd2640b4f4ee70c095513 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -1,6 +1,18 @@ //! Media loading (PNG/JPG/EXR/TIFF stills & numbered image sequences) and //! CPU rasterizers (`TextPlus` via `text_engine`, `PolylineMask` via `zeno`). +mod exr; +mod raster; +mod video; + +pub use exr::f32_to_f16_bits; +pub use raster::{TextPlusParams, rasterize_polyline_mask, rasterize_text_plus}; +#[cfg(target_os = "macos")] +pub use video::AvFoundationDecoder; +pub use video::{FfmpegDecoder, VideoDecoder, VideoInfo, open_video_decoder}; +use exr::{apply_post_multiply_rgba8, decode_exr_rgba, is_exr_path, normalize_channel_opt}; +use video::is_video_path; + use crate::text_engine; use model::{ClipSpec, ClsEntry, PolyPoint}; use std::collections::HashMap; @@ -36,552 +48,6 @@ impl DecodedImage { } } -/// Converts IEEE-754 `f32` to IEEE-754 binary16 (`f16`) bits for direct `Rgba16Float` GPU upload. -#[inline] -pub fn f32_to_f16_bits(val: f32) -> u16 { - let bits = val.to_bits(); - let sign = ((bits >> 16) & 0x8000) as u16; - let exp = ((bits >> 23) & 0xFF) as i32; - let frac = bits & 0x007F_FFFF; - - if exp == 0xFF { - return if frac != 0 { 0 } else { sign | 0x7C00 }; - } - let new_exp = exp - 127 + 15; - if new_exp >= 31 { - return sign | 0x7BFF; - } - if new_exp <= 0 { - if new_exp < -10 { - return sign; - } - let m = (frac | 0x0080_0000) >> (1 - new_exp + 13); - return sign | (m as u16); - } - let rounded = frac + 0x1000; - if rounded >= 0x0080_0000 { - let e = new_exp + 1; - return if e >= 31 { sign | 0x7BFF } else { sign | ((e as u16) << 10) }; - } - sign | ((new_exp as u16) << 10) | ((rounded >> 13) as u16) -} - -#[derive(Clone, Copy, Debug)] -pub struct VideoInfo { - pub width: u32, - pub height: u32, - pub fps: f64, - pub nb_frames: i64, -} - -pub trait VideoDecoder: Send { - fn info(&self) -> VideoInfo; - fn decode_frame(&mut self, frame_idx: i64) -> Option>; - fn backend_name(&self) -> &'static str; -} - -#[cfg(target_os = "macos")] -mod av_ffi { - use std::ffi::c_char; - - #[repr(C)] - pub struct AvVideoDecoder { - _private: [u8; 0], - } - - unsafe extern "C" { - pub fn av_video_open( - path: *const c_char, - out_w: *mut u32, - out_h: *mut u32, - out_fps: *mut f64, - out_nb_frames: *mut i64, - ) -> *mut AvVideoDecoder; - - pub fn av_video_decode_frame( - dec: *mut AvVideoDecoder, - frame_idx: i64, - out_rgba: *mut u8, - out_len: usize, - ) -> i32; - - pub fn av_video_close(dec: *mut AvVideoDecoder); - } -} - -#[cfg(target_os = "macos")] -pub struct AvFoundationDecoder { - ptr: *mut av_ffi::AvVideoDecoder, - info: VideoInfo, -} - -#[cfg(target_os = "macos")] -unsafe impl Send for AvFoundationDecoder {} - -#[cfg(target_os = "macos")] -impl Drop for AvFoundationDecoder { - fn drop(&mut self) { - if !self.ptr.is_null() { - unsafe { av_ffi::av_video_close(self.ptr) }; - self.ptr = std::ptr::null_mut(); - } - } -} - -#[cfg(target_os = "macos")] -impl AvFoundationDecoder { - pub fn open(path: &Path) -> Option { - use std::ffi::CString; - let path_str = path.to_str()?; - let c_path = CString::new(path_str).ok()?; - let mut width = 0u32; - let mut height = 0u32; - let mut fps = 0.0f64; - let mut nb_frames = 0i64; - let ptr = unsafe { - av_ffi::av_video_open( - c_path.as_ptr(), - &mut width, - &mut height, - &mut fps, - &mut nb_frames, - ) - }; - if ptr.is_null() || width == 0 || height == 0 { - if !ptr.is_null() { - unsafe { av_ffi::av_video_close(ptr) }; - } - return None; - } - Some(Self { - ptr, - info: VideoInfo { - width, - height, - fps: if fps > 0.0 { fps } else { 30.0 }, - nb_frames, - }, - }) - } -} - -#[cfg(target_os = "macos")] -impl VideoDecoder for AvFoundationDecoder { - fn info(&self) -> VideoInfo { - self.info - } - - fn decode_frame(&mut self, frame_idx: i64) -> Option> { - let len = (self.info.width as usize) - .checked_mul(self.info.height as usize)? - .checked_mul(4)?; - let mut buf = vec![0u8; len]; - let ok = unsafe { - av_ffi::av_video_decode_frame(self.ptr, frame_idx.max(0), buf.as_mut_ptr(), len) - }; - if ok != 0 { - Some(buf) - } else { - None - } - } - - fn backend_name(&self) -> &'static str { - "AVFoundation/VideoToolbox" - } -} - -pub struct FfmpegDecoder { - path: PathBuf, - info: VideoInfo, -} - -impl FfmpegDecoder { - pub fn open(path: &Path) -> Option { - let info = probe_video(path)?; - Some(Self { - path: path.to_path_buf(), - info, - }) - } -} - -impl VideoDecoder for FfmpegDecoder { - fn info(&self) -> VideoInfo { - self.info - } - - fn decode_frame(&mut self, frame_idx: i64) -> Option> { - decode_video_frame(&self.path, self.info, frame_idx) - } - - fn backend_name(&self) -> &'static str { - "ffmpeg" - } -} - -/// Opens a hardware-accelerated video decoder (`AVFoundation`/`VideoToolbox` on macOS), -/// falling back to `ffmpeg` for unsupported containers or codecs. -pub fn open_video_decoder(path: &Path) -> Option> { - #[cfg(target_os = "macos")] - { - if let Some(av) = AvFoundationDecoder::open(path) { - return Some(Box::new(av)); - } - } - FfmpegDecoder::open(path).map(|ff| Box::new(ff) as Box) -} - -fn is_video_path(path: &Path) -> bool { - let Some(ext) = path.extension().and_then(|e| e.to_str()) else { - return false; - }; - matches!( - ext.to_ascii_lowercase().as_str(), - "mov" | "mp4" | "m4v" | "mkv" | "avi" | "webm" | "mxf" - ) -} - -fn probe_video(path: &Path) -> Option { - let out = Command::new("ffprobe") - .args([ - "-v", - "error", - "-select_streams", - "v:0", - "-show_entries", - "stream=width,height,r_frame_rate,nb_frames", - "-of", - "default=noprint_wrappers=1", - ]) - .arg(path) - .output() - .ok()?; - if !out.status.success() { - return None; - } - let text = String::from_utf8_lossy(&out.stdout); - let mut width = 0u32; - let mut height = 0u32; - let mut fps = 30.0_f64; - let mut nb_frames = 0i64; - for line in text.lines() { - if let Some((k, v)) = line.split_once('=') { - match k.trim() { - "width" => width = v.trim().parse().unwrap_or(0), - "height" => height = v.trim().parse().unwrap_or(0), - "nb_frames" => nb_frames = v.trim().parse().unwrap_or(0), - "r_frame_rate" => { - if let Some((n, d)) = v.trim().split_once('/') { - let num: f64 = n.parse().unwrap_or(30.0); - let den: f64 = d.parse().unwrap_or(1.0); - if den > 0.0 && num > 0.0 { - fps = num / den; - } - } else if let Ok(r) = v.trim().parse::() { - if r > 0.0 { - fps = r; - } - } - } - _ => {} - } - } - } - if width == 0 || height == 0 { - return None; - } - Some(VideoInfo { width, height, fps, nb_frames }) -} - -fn decode_video_frame(path: &Path, info: VideoInfo, frame_idx: i64) -> Option> { - let idx = frame_idx.max(0); - let ts = if idx == 0 { - 0.0 - } else { - ((idx as f64) - 0.005) / info.fps.max(1.0) - }; - let out = Command::new("ffmpeg") - .args([ - "-v", - "error", - "-ss", - &format!("{ts:.6}"), - "-i", - ]) - .arg(path) - .args([ - "-frames:v", - "1", - "-f", - "rawvideo", - "-pix_fmt", - "rgba", - "-", - ]) - .output() - .ok()?; - if !out.status.success() { - return None; - } - let expected = (info.width as usize) * (info.height as usize) * 4; - if out.stdout.len() < expected { - return None; - } - let mut buf = out.stdout; - buf.truncate(expected); - Some(buf) -} - -fn is_exr_path(path: &Path) -> bool { - path.extension() - .and_then(|e| e.to_str()) - .is_some_and(|e| e.eq_ignore_ascii_case("exr")) -} - -fn full_exr_channel_name(layer_name: Option<&str>, ch_name: &str) -> String { - match layer_name { - Some(ln) if !ln.is_empty() && !ch_name.starts_with(&format!("{ln}.")) => { - format!("{ln}.{ch_name}") - } - _ => ch_name.to_owned(), - } -} - -fn normalize_channel_opt(opt: Option<&str>) -> Option { - opt.map(str::trim) - .filter(|s| !s.is_empty()) - .map(str::to_owned) -} - -fn apply_post_multiply_rgba8(raw: &mut [u8]) { - for px in raw.chunks_exact_mut(4) { - let a = u16::from(px[3]); - if a < 255 { - px[0] = ((u16::from(px[0]) * a + 127) / 255) as u8; - px[1] = ((u16::from(px[1]) * a + 127) / 255) as u8; - px[2] = ((u16::from(px[2]) * a + 127) / 255) as u8; - } - } -} - -fn find_exr_channel_loc( - headers: &[exr::meta::header::Header], - w: usize, - h: usize, - preferred: Option<&str>, - beauty_upper: &str, - beauty_lower: &str, -) -> Option<(usize, usize)> { - let valid_layer = |header: &exr::meta::header::Header| { - !header.deep && header.layer_size.width() == w && header.layer_size.height() == h - }; - - if let Some(pref) = preferred.map(str::trim).filter(|s| !s.is_empty()) { - for (li, header) in headers.iter().enumerate() { - if !valid_layer(header) { - continue; - } - let lname = header.own_attributes.layer_name.as_ref().map(|t| t.to_string()); - for (ci, ch) in header.channels.list.iter().enumerate() { - if ch.sampling != exr::math::Vec2(1, 1) { - continue; - } - let full = full_exr_channel_name(lname.as_deref(), &ch.name.to_string()); - if full == pref { - return Some((li, ci)); - } - } - } - let suffix = format!(".{pref}"); - for (li, header) in headers.iter().enumerate() { - if !valid_layer(header) { - continue; - } - let lname = header.own_attributes.layer_name.as_ref().map(|t| t.to_string()); - for (ci, ch) in header.channels.list.iter().enumerate() { - if ch.sampling != exr::math::Vec2(1, 1) { - continue; - } - let full = full_exr_channel_name(lname.as_deref(), &ch.name.to_string()); - if full.ends_with(&suffix) { - return Some((li, ci)); - } - } - } - return None; - } - - // Beauty pass fallback: check ViewLayer.Combined., Combined., *.Combined., - // then exact bare /. Never match non-beauty layers such as CryptoObject00.R! - let view_combined = format!("ViewLayer.Combined.{beauty_upper}"); - let combined = format!("Combined.{beauty_upper}"); - let any_combined = format!(".Combined.{beauty_upper}"); - let matcher_passes: [&dyn Fn(&str) -> bool; 4] = [ - &|full: &str| full == view_combined, - &|full: &str| full == combined || full.ends_with(&any_combined), - &|full: &str| full == beauty_upper, - &|full: &str| full == beauty_lower, - ]; - for pred in matcher_passes { - for (li, header) in headers.iter().enumerate() { - if !valid_layer(header) { - continue; - } - let lname = header.own_attributes.layer_name.as_ref().map(|t| t.to_string()); - for (ci, ch) in header.channels.list.iter().enumerate() { - if ch.sampling != exr::math::Vec2(1, 1) { - continue; - } - let full = full_exr_channel_name(lname.as_deref(), &ch.name.to_string()); - if pred(&full) { - return Some((li, ci)); - } - } - } - } - None -} - -/// Decodes a single-layer or multi-layer (Blender `ViewLayer.Combined.R/G/B/A`) OpenEXR -/// selectively for only the matched RGBA channels, producing clamped RGBA8 and linear HDR -/// RGBA16F/RGBA32F buffers without decoding unrelated AOV/Cryptomatte layers. -fn decode_exr_rgba( - path: &Path, - red_name: Option<&str>, - green_name: Option<&str>, - blue_name: Option<&str>, - alpha_name: Option<&str>, - post_multiply: bool, -) -> Option { - use exr::block::reader::ChunksReader; - use exr::meta::attribute::SampleType; - use exr::prelude::*; - - let file = std::fs::File::open(path).ok()?; - let chunks_reader = exr::block::read(std::io::BufReader::new(file), false).ok()?; - let first_header = chunks_reader.headers().first()?; - let w = first_header.layer_size.width(); - let h = first_header.layer_size.height(); - if w == 0 || h == 0 { - return None; - } - - let r_loc = find_exr_channel_loc(chunks_reader.headers(), w, h, red_name, "R", "r")?; - let g_loc = find_exr_channel_loc(chunks_reader.headers(), w, h, green_name, "G", "g"); - let b_loc = find_exr_channel_loc(chunks_reader.headers(), w, h, blue_name, "B", "b"); - let a_loc = find_exr_channel_loc(chunks_reader.headers(), w, h, alpha_name, "A", "a"); - - let target_locs = [Some(r_loc), g_loc, b_loc, a_loc]; - let mut needed_layers: Vec = target_locs.iter().flatten().map(|(l, _)| *l).collect(); - needed_layers.sort_unstable(); - needed_layers.dedup(); - - let mut raw_f32 = vec![0.0_f32; w * h * 4]; - let mut line_f32 = Vec::::new(); - let mut line_f16 = Vec::::new(); - let mut line_u32 = Vec::::new(); - - chunks_reader - .filter_chunks(false, |_, tile, block| { - tile.is_largest_resolution_level() && needed_layers.contains(&block.layer) - }) - .ok()? - .decompress_parallel(false, |meta, block| { - let header = &meta.headers[block.index.layer]; - for line in block.lines(&header.channels) { - let loc = (line.location.layer, line.location.channel); - let mut comp_mask = [false; 4]; - for (c, t) in target_locs.iter().enumerate() { - if *t == Some(loc) { - comp_mask[c] = true; - } - } - if !comp_mask.iter().any(|&m| m) { - continue; - } - let y = line.location.position.y(); - let x0 = line.location.position.x(); - let len = line.location.sample_count; - if y >= h || x0 + len > w { - continue; - } - - line_f32.clear(); - match header.channels.list[line.location.channel].sample_type { - SampleType::F32 => { - line_f32.resize(len, 0.0); - line.read_samples_into_slice(&mut line_f32)?; - } - SampleType::F16 => { - line_f16.resize(len, f16::ZERO); - line.read_samples_into_slice(&mut line_f16)?; - line_f32.extend(line_f16.iter().map(|v| v.to_f32())); - } - SampleType::U32 => { - line_u32.resize(len, 0); - line.read_samples_into_slice(&mut line_u32)?; - line_f32.extend(line_u32.iter().map(|&v| v as f32)); - } - } - - let row_base = (y * w + x0) * 4; - for (dx, &sample) in line_f32.iter().enumerate() { - let val = if sample.is_nan() { 0.0 } else { sample }; - let px_off = row_base + dx * 4; - for (c, &enabled) in comp_mask.iter().enumerate() { - if enabled { - raw_f32[px_off + c] = val; - } - } - } - } - Ok(()) - }) - .ok()?; - - let mut raw = vec![0u8; w * h * 4]; - let mut raw_f16 = vec![0u16; w * h * 4]; - for i in 0..(w * h) { - let off = i * 4; - let mut r_raw = raw_f32[off]; - let mut g_raw = if g_loc.is_some() { raw_f32[off + 1] } else { r_raw }; - let mut b_raw = if b_loc.is_some() { raw_f32[off + 2] } else { r_raw }; - let a_raw = if a_loc.is_some() { raw_f32[off + 3] } else { 1.0 }; - - if post_multiply && a_raw < 1.0 { - let a_mul = a_raw.clamp(0.0, 1.0); - r_raw *= a_mul; - g_raw *= a_mul; - b_raw *= a_mul; - } - raw_f32[off] = r_raw; - raw_f32[off + 1] = g_raw; - raw_f32[off + 2] = b_raw; - raw_f32[off + 3] = a_raw; - - raw_f16[off] = f32_to_f16_bits(r_raw); - raw_f16[off + 1] = f32_to_f16_bits(g_raw); - raw_f16[off + 2] = f32_to_f16_bits(b_raw); - raw_f16[off + 3] = f32_to_f16_bits(a_raw); - - let a = a_raw.clamp(0.0, 1.0); - let r = r_raw.clamp(0.0, 1.0); - let g = g_raw.clamp(0.0, 1.0); - let b = b_raw.clamp(0.0, 1.0); - raw[off] = (r * 255.0 + 0.5) as u8; - raw[off + 1] = (g * 255.0 + 0.5) as u8; - raw[off + 2] = (b * 255.0 + 0.5) as u8; - raw[off + 3] = (a * 255.0 + 0.5) as u8; - } - Some(DecodedImage { - size: [w as u32, h as u32], - rgba: Arc::new(raw), - rgba_f16: Some(Arc::new(raw_f16)), - rgba_f32: Some(Arc::new(raw_f32)), - }) -} - const MAX_VIDEO_DECODERS: usize = 12; #[derive(Clone, Debug, PartialEq, Eq, Hash)] @@ -865,244 +331,6 @@ pub fn resolve_clip_path(clip: &ClipSpec, frame: i64) -> Option { let candidate = base.with_file_name(new_name); candidate.exists().then_some(candidate) } - -/// Parameters for rasterizing a Fusion `TextPlus` node with [`crate::text_engine`]. -pub struct TextPlusParams<'a> { - pub text: &'a str, - pub font_family: &'a str, - pub font_style: &'a str, - pub size_norm: f32, // Fusion Size (fraction of canvas width, ~0.08 default) - pub tracking: f32, // Fusion CharacterSpacing (1.0 = normal) - pub line_spacing: f32, // Fusion LineSpacing (1.0 = normal) - pub center: [f32; 2], // Fusion normalized Y-up (0.5, 0.5) - pub h_lcr: f32, // Fusion HorizontalLeftCenterRight: -1=Left, 0=Center, +1=Right - pub v_tcb: f32, // Fusion VerticalTopCenterBottom: -1=Top, 0=Center, +1=Bottom - pub fill_rgba: [f32; 4], - pub write_on_start: f32, - pub write_on_end: f32, - pub shear_x: f32, // Fusion CharacterShearX - pub cls: &'a [ClsEntry], // Optional StyledTextCLS per-character overrides - pub outline_rgba: [f32; 4], // Fusion Element 2 color, already scaled by Opacity2 - pub outline_width_px: f32, // Fusion Thickness2 as a full stroke width; 0 disables the outline -} - -/// Rasterizes a `TextPlus` layer (outline under fill) into premultiplied RGBA8 with automatic -/// Domain-of-Definition (DoD) expansion so off-screen glyphs (e.g. text shifted into frame by a -/// downstream `Transform`) are never clipped; `dod_pad` adds margin for decoration drawn from -/// the result. Returns `(tex_size, dod_origin_px, rgba)`. -pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, dod_pad: i32) -> ([u32; 2], [i32; 2], Vec) { - let [w, h] = dims; - let empty = || (dims, [0, 0], vec![0u8; (w as usize) * (h as usize) * 4]); - if params.text.is_empty() || params.size_norm <= 1e-4 { - return empty(); - } - - // Compute WriteOn character range on the FULL string so glyph layout never shifts as letters type on! - let total_chars = params.text.chars().count(); - let c_start = ((params.write_on_start.clamp(0.0, 1.0)) * total_chars as f32).floor() as usize; - let c_end = ((params.write_on_end.clamp(0.0, 1.0)) * total_chars as f32).ceil() as usize; - if c_start >= c_end || c_start >= total_chars { - return empty(); - } - let Some(font) = text_engine::Font::find(params.font_family, params.font_style) else { - return empty(); - }; - let face = font.face(); - - // Build per-character CLS X/Y offsets (Fusion prop 1350 = X, 1351 = Y in normalized width units). - let mut cls_dx = vec![0.0_f32; total_chars]; - let mut cls_dy = vec![0.0_f32; total_chars]; - for e in params.cls { - let s = e.start.min(total_chars); - let end = (e.end + 1).min(total_chars); - for i in s..end { - if e.prop_id == 1350 { - cls_dx[i] = e.value; - } else if e.prop_id == 1351 { - cls_dy[i] = e.value; - } - } - } - - // Fusion Text+ `Size` defines the line box (ascent + descent) as `0.8 * Size * W` - // (calibrated across Open Sans, Liberation Sans, DejaVu Sans, and AT Name Sans Text - // on 16:9, square, and vertical frames). - let line_box_px = params.size_norm * w as f32 * 0.8; - let (ascent_em, descent_em) = text_engine::vertical_metrics(&face); - let font_px = (line_box_px / (ascent_em + descent_em).max(0.5)).clamp(6.0, 1024.0); - let descent = descent_em * font_px; - - // Fusion `CharacterSpacing = 1.0` adds nothing; each +1.0 adds `Size * W` between characters, - // independent of the font (probed on Fusion 21.1 with Liberation Sans, 8 gaps, 1.3 and 2.0). - let extra_track = (params.tracking - 1.0) * params.size_norm * w as f32; - - let lines: Vec<&str> = params.text.split('\n').collect(); - let line_height = (line_box_px * params.line_spacing.max(0.05)).max(1.0); - - // Fusion Center is Y-up; convert to top-down pixel coordinates. - let cx = params.center[0] * w as f32; - let cy = (1.0 - params.center[1]) * h as f32; - - // VerticalTopCenterBottom: -1=Top (baseline_0 = cy + font_px - descent), 0=Center, +1=Bottom (last baseline = cy). - let v_frac = params.v_tcb.clamp(-1.0, 1.0) * 0.5 + 0.5; - let top_anchor = (font_px - descent).max(0.0); - let block_h = (lines.len().saturating_sub(1) as f32) * line_height + top_anchor; - let baseline_0 = cy + top_anchor - v_frac * block_h; - let h_frac = params.h_lcr.clamp(-1.0, 1.0) * 0.5 + 0.5; - - let outlined = params.outline_width_px > 1e-3 && params.outline_rgba[3] > 0.0; - - // Pass 1: vector-rasterize every visible glyph and collect exact bounds to expand the DoD. - let mut placed = Vec::new(); - let (mut min_x, mut min_y, mut max_x, mut max_y) = (0i32, 0i32, w as i32, h as i32); - let mut grow = |c: &text_engine::Coverage, pad: i32| { - min_x = min_x.min(c.left - pad); - min_y = min_y.min(c.top - pad); - max_x = max_x.max(c.left + c.width as i32 + pad); - max_y = max_y.max(c.top + c.height as i32 + pad); - }; - - let mut char_cursor = 0usize; - for (li, line_str) in lines.iter().enumerate() { - let shaped = text_engine::shape_line(&face, line_str, font_px, extra_track); - let start_x = cx - shaped.width * h_frac; - let baseline_y = baseline_0 + (li as f32) * line_height; - for g in &shaped.glyphs { - let idx = char_cursor + g.char_index; - if idx < c_start || idx >= c_end { - continue; - } - let origin = [ - start_x + g.x + cls_dx[idx] * w as f32, - baseline_y - g.y - cls_dy[idx] * w as f32, - ]; - let path = text_engine::glyph_path(&font, &face, g.id, font_px, origin, -params.shear_x); - let fill = text_engine::fill(&path); - let line = if outlined { text_engine::stroke(&path, params.outline_width_px) } else { None }; - if let Some(c) = &fill { - grow(c, dod_pad); - } - if let Some(c) = &line { - grow(c, dod_pad); - } - placed.push((fill, line)); - } - char_cursor += line_str.chars().count() + 1; // + '\n' separator - } - - // Clamp DoD expansion safely to at most +/- 1 canvas width/height so GPU textures stay bounded. - let origin_x = min_x.max(-(w as i32)); - let origin_y = min_y.max(-(h as i32)); - let end_x = max_x.min((w as i32) * 2); - let end_y = max_y.min((h as i32) * 2); - let tw = (end_x - origin_x).max(1) as usize; - let th = (end_y - origin_y).max(1) as usize; - - let mut fill_plane = vec![0u8; tw * th]; - let mut line_plane = vec![0.0_f32; if outlined { tw * th } else { 0 }]; - for (fill, line) in &placed { - if let Some(c) = fill { - blit_max(c, [origin_x, origin_y], [tw, th], |i, a| fill_plane[i] = fill_plane[i].max(a)); - } - if let Some(c) = line { - blit_max(c, [origin_x, origin_y], [tw, th], |i, a| line_plane[i] = line_plane[i].max(a as f32 / 255.0)); - } - } - - let (fc, oc) = (params.fill_rgba, params.outline_rgba); - let mut out = vec![0u8; tw * th * 4]; - for (i, px) in out.chunks_exact_mut(4).enumerate() { - let fa = fill_plane[i] as f32 / 255.0 * fc[3]; - let oa = if outlined { line_plane[i] * oc[3] } else { 0.0 }; - if fa <= 0.0 && oa <= 0.0 { - continue; - } - let under = 1.0 - fa; - for k in 0..3 { - let v = fc[k] * fa + oc[k] * oa * under; - px[k] = (v * 255.0 + 0.5).clamp(0.0, 255.0) as u8; - } - px[3] = ((fa + oa * under) * 255.0 + 0.5).clamp(0.0, 255.0) as u8; - } - - ([tw as u32, th as u32], [origin_x, origin_y], out) -} - -/// Calls `f(plane_index, coverage)` for every non-zero coverage pixel that lands inside the plane. -fn blit_max(c: &text_engine::Coverage, origin: [i32; 2], plane: [usize; 2], mut f: impl FnMut(usize, u8)) { - for y in 0..c.height as i32 { - let py = c.top + y - origin[1]; - if py < 0 || py >= plane[1] as i32 { - continue; - } - for x in 0..c.width as i32 { - let px = c.left + x - origin[0]; - let a = c.data[(y as u32 * c.width + x as u32) as usize]; - if a > 0 && px >= 0 && px < plane[0] as i32 { - f(py as usize * plane[0] + px as usize, a); - } - } - } -} - -/// Rasterizes a closed Fusion `PolylineMask` into RGBA8 `[w, h]` via `zeno`. -pub fn rasterize_polyline_mask( - dims: [u32; 2], - points: &[PolyPoint], - center: [f32; 2], - invert: bool, - level: f32, -) -> Vec { - let [w, h] = dims; - let mut out = vec![0u8; (w as usize) * (h as usize) * 4]; - if points.len() < 2 { - return out; - } - let to_px = |x: f64, y: f64| -> [f32; 2] { - let fx = (center[0] + x as f32) * w as f32; - let fy = (1.0 - (center[1] + y as f32)) * h as f32; - [fx, fy] - }; - let mut cmds = Vec::new(); - let p0 = to_px(points[0].x, points[0].y); - cmds.push(zeno::Command::MoveTo(zeno::Vector::new(p0[0], p0[1]))); - for i in 0..points.len() { - let a = &points[i]; - let b = &points[(i + 1) % points.len()]; - let c1 = to_px(a.x + a.rx, a.y + a.ry); - let c2 = to_px(b.x + b.lx, b.y + b.ly); - let p = to_px(b.x, b.y); - if a.linear && b.linear { - cmds.push(zeno::Command::LineTo(zeno::Vector::new(p[0], p[1]))); - } else { - cmds.push(zeno::Command::CurveTo( - zeno::Vector::new(c1[0], c1[1]), - zeno::Vector::new(c2[0], c2[1]), - zeno::Vector::new(p[0], p[1]), - )); - } - } - cmds.push(zeno::Command::Close); - - let mut mask = vec![0u8; (w as usize) * (h as usize)]; - let mut scratch = zeno::Scratch::new(); - let placement = zeno::Mask::with_scratch(&cmds, &mut scratch) - .size(w, h) - .origin(zeno::Origin::TopLeft) - .render_into(&mut mask, None); - let _ = placement; - for (i, &cov) in mask.iter().enumerate() { - let mut a = cov as f32 / 255.0; - if invert { a = 1.0 - a; } - let b = (a * level * 255.0).clamp(0.0, 255.0) as u8; - out[i * 4] = b; - out[i * 4 + 1] = b; - out[i * 4 + 2] = b; - out[i * 4 + 3] = b; - } - out -} - #[cfg(test)] mod tests { use super::*; @@ -1344,7 +572,7 @@ mod tests { #[test] fn exr_channel_cache_isolation_and_non_beauty_guard() { - use exr::prelude::*; + use ::exr::prelude::*; let dir = std::env::temp_dir().join(format!("fission_exr_chan_test_{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); diff --git a/crates/engine/src/media/exr.rs b/crates/engine/src/media/exr.rs new file mode 100644 index 0000000000000000000000000000000000000000..25b82642237d7fd5cb60630d18f5452672ce4b15 --- /dev/null +++ b/crates/engine/src/media/exr.rs @@ -0,0 +1,280 @@ +use super::*; + +/// Converts IEEE-754 `f32` to IEEE-754 binary16 (`f16`) bits for direct `Rgba16Float` GPU upload. +#[inline] +pub fn f32_to_f16_bits(val: f32) -> u16 { + let bits = val.to_bits(); + let sign = ((bits >> 16) & 0x8000) as u16; + let exp = ((bits >> 23) & 0xFF) as i32; + let frac = bits & 0x007F_FFFF; + + if exp == 0xFF { + return if frac != 0 { 0 } else { sign | 0x7C00 }; + } + let new_exp = exp - 127 + 15; + if new_exp >= 31 { + return sign | 0x7BFF; + } + if new_exp <= 0 { + if new_exp < -10 { + return sign; + } + let m = (frac | 0x0080_0000) >> (1 - new_exp + 13); + return sign | (m as u16); + } + let rounded = frac + 0x1000; + if rounded >= 0x0080_0000 { + let e = new_exp + 1; + return if e >= 31 { sign | 0x7BFF } else { sign | ((e as u16) << 10) }; + } + sign | ((new_exp as u16) << 10) | ((rounded >> 13) as u16) +} + +pub(super) fn is_exr_path(path: &Path) -> bool { + path.extension() + .and_then(|e| e.to_str()) + .is_some_and(|e| e.eq_ignore_ascii_case("exr")) +} + +pub(super) fn full_exr_channel_name(layer_name: Option<&str>, ch_name: &str) -> String { + match layer_name { + Some(ln) if !ln.is_empty() && !ch_name.starts_with(&format!("{ln}.")) => { + format!("{ln}.{ch_name}") + } + _ => ch_name.to_owned(), + } +} + +pub(super) fn normalize_channel_opt(opt: Option<&str>) -> Option { + opt.map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_owned) +} + +pub(super) fn apply_post_multiply_rgba8(raw: &mut [u8]) { + for px in raw.chunks_exact_mut(4) { + let a = u16::from(px[3]); + if a < 255 { + px[0] = ((u16::from(px[0]) * a + 127) / 255) as u8; + px[1] = ((u16::from(px[1]) * a + 127) / 255) as u8; + px[2] = ((u16::from(px[2]) * a + 127) / 255) as u8; + } + } +} + +pub(super) fn find_exr_channel_loc( + headers: &[::exr::meta::header::Header], + w: usize, + h: usize, + preferred: Option<&str>, + beauty_upper: &str, + beauty_lower: &str, +) -> Option<(usize, usize)> { + let valid_layer = |header: &::exr::meta::header::Header| { + !header.deep && header.layer_size.width() == w && header.layer_size.height() == h + }; + + if let Some(pref) = preferred.map(str::trim).filter(|s| !s.is_empty()) { + for (li, header) in headers.iter().enumerate() { + if !valid_layer(header) { + continue; + } + let lname = header.own_attributes.layer_name.as_ref().map(|t| t.to_string()); + for (ci, ch) in header.channels.list.iter().enumerate() { + if ch.sampling != ::exr::math::Vec2(1, 1) { + continue; + } + let full = full_exr_channel_name(lname.as_deref(), &ch.name.to_string()); + if full == pref { + return Some((li, ci)); + } + } + } + let suffix = format!(".{pref}"); + for (li, header) in headers.iter().enumerate() { + if !valid_layer(header) { + continue; + } + let lname = header.own_attributes.layer_name.as_ref().map(|t| t.to_string()); + for (ci, ch) in header.channels.list.iter().enumerate() { + if ch.sampling != ::exr::math::Vec2(1, 1) { + continue; + } + let full = full_exr_channel_name(lname.as_deref(), &ch.name.to_string()); + if full.ends_with(&suffix) { + return Some((li, ci)); + } + } + } + return None; + } + + // Beauty pass fallback: check ViewLayer.Combined., Combined., *.Combined., + // then exact bare /. Never match non-beauty layers such as CryptoObject00.R! + let view_combined = format!("ViewLayer.Combined.{beauty_upper}"); + let combined = format!("Combined.{beauty_upper}"); + let any_combined = format!(".Combined.{beauty_upper}"); + let matcher_passes: [&dyn Fn(&str) -> bool; 4] = [ + &|full: &str| full == view_combined, + &|full: &str| full == combined || full.ends_with(&any_combined), + &|full: &str| full == beauty_upper, + &|full: &str| full == beauty_lower, + ]; + for pred in matcher_passes { + for (li, header) in headers.iter().enumerate() { + if !valid_layer(header) { + continue; + } + let lname = header.own_attributes.layer_name.as_ref().map(|t| t.to_string()); + for (ci, ch) in header.channels.list.iter().enumerate() { + if ch.sampling != ::exr::math::Vec2(1, 1) { + continue; + } + let full = full_exr_channel_name(lname.as_deref(), &ch.name.to_string()); + if pred(&full) { + return Some((li, ci)); + } + } + } + } + None +} + +/// Decodes a single-layer or multi-layer (Blender `ViewLayer.Combined.R/G/B/A`) OpenEXR +/// selectively for only the matched RGBA channels, producing clamped RGBA8 and linear HDR +/// RGBA16F/RGBA32F buffers without decoding unrelated AOV/Cryptomatte layers. +pub(super) fn decode_exr_rgba( + path: &Path, + red_name: Option<&str>, + green_name: Option<&str>, + blue_name: Option<&str>, + alpha_name: Option<&str>, + post_multiply: bool, +) -> Option { + use ::exr::block::reader::ChunksReader; + use ::exr::meta::attribute::SampleType; + use ::exr::prelude::*; + + let file = std::fs::File::open(path).ok()?; + let chunks_reader = ::exr::block::read(std::io::BufReader::new(file), false).ok()?; + let first_header = chunks_reader.headers().first()?; + let w = first_header.layer_size.width(); + let h = first_header.layer_size.height(); + if w == 0 || h == 0 { + return None; + } + + let r_loc = find_exr_channel_loc(chunks_reader.headers(), w, h, red_name, "R", "r")?; + let g_loc = find_exr_channel_loc(chunks_reader.headers(), w, h, green_name, "G", "g"); + let b_loc = find_exr_channel_loc(chunks_reader.headers(), w, h, blue_name, "B", "b"); + let a_loc = find_exr_channel_loc(chunks_reader.headers(), w, h, alpha_name, "A", "a"); + + let target_locs = [Some(r_loc), g_loc, b_loc, a_loc]; + let mut needed_layers: Vec = target_locs.iter().flatten().map(|(l, _)| *l).collect(); + needed_layers.sort_unstable(); + needed_layers.dedup(); + + let mut raw_f32 = vec![0.0_f32; w * h * 4]; + let mut line_f32 = Vec::::new(); + let mut line_f16 = Vec::::new(); + let mut line_u32 = Vec::::new(); + + chunks_reader + .filter_chunks(false, |_, tile, block| { + tile.is_largest_resolution_level() && needed_layers.contains(&block.layer) + }) + .ok()? + .decompress_parallel(false, |meta, block| { + let header = &meta.headers[block.index.layer]; + for line in block.lines(&header.channels) { + let loc = (line.location.layer, line.location.channel); + let mut comp_mask = [false; 4]; + for (c, t) in target_locs.iter().enumerate() { + if *t == Some(loc) { + comp_mask[c] = true; + } + } + if !comp_mask.iter().any(|&m| m) { + continue; + } + let y = line.location.position.y(); + let x0 = line.location.position.x(); + let len = line.location.sample_count; + if y >= h || x0 + len > w { + continue; + } + + line_f32.clear(); + match header.channels.list[line.location.channel].sample_type { + SampleType::F32 => { + line_f32.resize(len, 0.0); + line.read_samples_into_slice(&mut line_f32)?; + } + SampleType::F16 => { + line_f16.resize(len, f16::ZERO); + line.read_samples_into_slice(&mut line_f16)?; + line_f32.extend(line_f16.iter().map(|v| v.to_f32())); + } + SampleType::U32 => { + line_u32.resize(len, 0); + line.read_samples_into_slice(&mut line_u32)?; + line_f32.extend(line_u32.iter().map(|&v| v as f32)); + } + } + + let row_base = (y * w + x0) * 4; + for (dx, &sample) in line_f32.iter().enumerate() { + let val = if sample.is_nan() { 0.0 } else { sample }; + let px_off = row_base + dx * 4; + for (c, &enabled) in comp_mask.iter().enumerate() { + if enabled { + raw_f32[px_off + c] = val; + } + } + } + } + Ok(()) + }) + .ok()?; + + let mut raw = vec![0u8; w * h * 4]; + let mut raw_f16 = vec![0u16; w * h * 4]; + for i in 0..(w * h) { + let off = i * 4; + let mut r_raw = raw_f32[off]; + let mut g_raw = if g_loc.is_some() { raw_f32[off + 1] } else { r_raw }; + let mut b_raw = if b_loc.is_some() { raw_f32[off + 2] } else { r_raw }; + let a_raw = if a_loc.is_some() { raw_f32[off + 3] } else { 1.0 }; + + if post_multiply && a_raw < 1.0 { + let a_mul = a_raw.clamp(0.0, 1.0); + r_raw *= a_mul; + g_raw *= a_mul; + b_raw *= a_mul; + } + raw_f32[off] = r_raw; + raw_f32[off + 1] = g_raw; + raw_f32[off + 2] = b_raw; + raw_f32[off + 3] = a_raw; + + raw_f16[off] = f32_to_f16_bits(r_raw); + raw_f16[off + 1] = f32_to_f16_bits(g_raw); + raw_f16[off + 2] = f32_to_f16_bits(b_raw); + raw_f16[off + 3] = f32_to_f16_bits(a_raw); + + let a = a_raw.clamp(0.0, 1.0); + let r = r_raw.clamp(0.0, 1.0); + let g = g_raw.clamp(0.0, 1.0); + let b = b_raw.clamp(0.0, 1.0); + raw[off] = (r * 255.0 + 0.5) as u8; + raw[off + 1] = (g * 255.0 + 0.5) as u8; + raw[off + 2] = (b * 255.0 + 0.5) as u8; + raw[off + 3] = (a * 255.0 + 0.5) as u8; + } + Some(DecodedImage { + size: [w as u32, h as u32], + rgba: Arc::new(raw), + rgba_f16: Some(Arc::new(raw_f16)), + rgba_f32: Some(Arc::new(raw_f32)), + }) +} diff --git a/crates/engine/src/media/raster.rs b/crates/engine/src/media/raster.rs new file mode 100644 index 0000000000000000000000000000000000000000..5a623c36c164fdf67f6a646c098c7828141f273c --- /dev/null +++ b/crates/engine/src/media/raster.rs @@ -0,0 +1,238 @@ +use super::*; + +/// Parameters for rasterizing a Fusion `TextPlus` node with [`crate::text_engine`]. +pub struct TextPlusParams<'a> { + pub text: &'a str, + pub font_family: &'a str, + pub font_style: &'a str, + pub size_norm: f32, // Fusion Size (fraction of canvas width, ~0.08 default) + pub tracking: f32, // Fusion CharacterSpacing (1.0 = normal) + pub line_spacing: f32, // Fusion LineSpacing (1.0 = normal) + pub center: [f32; 2], // Fusion normalized Y-up (0.5, 0.5) + pub h_lcr: f32, // Fusion HorizontalLeftCenterRight: -1=Left, 0=Center, +1=Right + pub v_tcb: f32, // Fusion VerticalTopCenterBottom: -1=Top, 0=Center, +1=Bottom + pub fill_rgba: [f32; 4], + pub write_on_start: f32, + pub write_on_end: f32, + pub shear_x: f32, // Fusion CharacterShearX + pub cls: &'a [ClsEntry], // Optional StyledTextCLS per-character overrides + pub outline_rgba: [f32; 4], // Fusion Element 2 color, already scaled by Opacity2 + pub outline_width_px: f32, // Fusion Thickness2 as a full stroke width; 0 disables the outline +} + +/// Rasterizes a `TextPlus` layer (outline under fill) into premultiplied RGBA8 with automatic +/// Domain-of-Definition (DoD) expansion so off-screen glyphs (e.g. text shifted into frame by a +/// downstream `Transform`) are never clipped; `dod_pad` adds margin for decoration drawn from +/// the result. Returns `(tex_size, dod_origin_px, rgba)`. +pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, dod_pad: i32) -> ([u32; 2], [i32; 2], Vec) { + let [w, h] = dims; + let empty = || (dims, [0, 0], vec![0u8; (w as usize) * (h as usize) * 4]); + if params.text.is_empty() || params.size_norm <= 1e-4 { + return empty(); + } + + // Compute WriteOn character range on the FULL string so glyph layout never shifts as letters type on! + let total_chars = params.text.chars().count(); + let c_start = ((params.write_on_start.clamp(0.0, 1.0)) * total_chars as f32).floor() as usize; + let c_end = ((params.write_on_end.clamp(0.0, 1.0)) * total_chars as f32).ceil() as usize; + if c_start >= c_end || c_start >= total_chars { + return empty(); + } + let Some(font) = text_engine::Font::find(params.font_family, params.font_style) else { + return empty(); + }; + let face = font.face(); + + // Build per-character CLS X/Y offsets (Fusion prop 1350 = X, 1351 = Y in normalized width units). + let mut cls_dx = vec![0.0_f32; total_chars]; + let mut cls_dy = vec![0.0_f32; total_chars]; + for e in params.cls { + let s = e.start.min(total_chars); + let end = (e.end + 1).min(total_chars); + for i in s..end { + if e.prop_id == 1350 { + cls_dx[i] = e.value; + } else if e.prop_id == 1351 { + cls_dy[i] = e.value; + } + } + } + + // Fusion Text+ `Size` defines the line box (ascent + descent) as `0.8 * Size * W` + // (calibrated across Open Sans, Liberation Sans, DejaVu Sans, and AT Name Sans Text + // on 16:9, square, and vertical frames). + let line_box_px = params.size_norm * w as f32 * 0.8; + let (ascent_em, descent_em) = text_engine::vertical_metrics(&face); + let font_px = (line_box_px / (ascent_em + descent_em).max(0.5)).clamp(6.0, 1024.0); + let descent = descent_em * font_px; + + // Fusion `CharacterSpacing = 1.0` adds nothing; each +1.0 adds `Size * W` between characters, + // independent of the font (probed on Fusion 21.1 with Liberation Sans, 8 gaps, 1.3 and 2.0). + let extra_track = (params.tracking - 1.0) * params.size_norm * w as f32; + + let lines: Vec<&str> = params.text.split('\n').collect(); + let line_height = (line_box_px * params.line_spacing.max(0.05)).max(1.0); + + // Fusion Center is Y-up; convert to top-down pixel coordinates. + let cx = params.center[0] * w as f32; + let cy = (1.0 - params.center[1]) * h as f32; + + // VerticalTopCenterBottom: -1=Top (baseline_0 = cy + font_px - descent), 0=Center, +1=Bottom (last baseline = cy). + let v_frac = params.v_tcb.clamp(-1.0, 1.0) * 0.5 + 0.5; + let top_anchor = (font_px - descent).max(0.0); + let block_h = (lines.len().saturating_sub(1) as f32) * line_height + top_anchor; + let baseline_0 = cy + top_anchor - v_frac * block_h; + let h_frac = params.h_lcr.clamp(-1.0, 1.0) * 0.5 + 0.5; + + let outlined = params.outline_width_px > 1e-3 && params.outline_rgba[3] > 0.0; + + // Pass 1: vector-rasterize every visible glyph and collect exact bounds to expand the DoD. + let mut placed = Vec::new(); + let (mut min_x, mut min_y, mut max_x, mut max_y) = (0i32, 0i32, w as i32, h as i32); + let mut grow = |c: &text_engine::Coverage, pad: i32| { + min_x = min_x.min(c.left - pad); + min_y = min_y.min(c.top - pad); + max_x = max_x.max(c.left + c.width as i32 + pad); + max_y = max_y.max(c.top + c.height as i32 + pad); + }; + + let mut char_cursor = 0usize; + for (li, line_str) in lines.iter().enumerate() { + let shaped = text_engine::shape_line(&face, line_str, font_px, extra_track); + let start_x = cx - shaped.width * h_frac; + let baseline_y = baseline_0 + (li as f32) * line_height; + for g in &shaped.glyphs { + let idx = char_cursor + g.char_index; + if idx < c_start || idx >= c_end { + continue; + } + let origin = [ + start_x + g.x + cls_dx[idx] * w as f32, + baseline_y - g.y - cls_dy[idx] * w as f32, + ]; + let path = text_engine::glyph_path(&font, &face, g.id, font_px, origin, -params.shear_x); + let fill = text_engine::fill(&path); + let line = if outlined { text_engine::stroke(&path, params.outline_width_px) } else { None }; + if let Some(c) = &fill { + grow(c, dod_pad); + } + if let Some(c) = &line { + grow(c, dod_pad); + } + placed.push((fill, line)); + } + char_cursor += line_str.chars().count() + 1; // + '\n' separator + } + + // Clamp DoD expansion safely to at most +/- 1 canvas width/height so GPU textures stay bounded. + let origin_x = min_x.max(-(w as i32)); + let origin_y = min_y.max(-(h as i32)); + let end_x = max_x.min((w as i32) * 2); + let end_y = max_y.min((h as i32) * 2); + let tw = (end_x - origin_x).max(1) as usize; + let th = (end_y - origin_y).max(1) as usize; + + let mut fill_plane = vec![0u8; tw * th]; + let mut line_plane = vec![0.0_f32; if outlined { tw * th } else { 0 }]; + for (fill, line) in &placed { + if let Some(c) = fill { + blit_max(c, [origin_x, origin_y], [tw, th], |i, a| fill_plane[i] = fill_plane[i].max(a)); + } + if let Some(c) = line { + blit_max(c, [origin_x, origin_y], [tw, th], |i, a| line_plane[i] = line_plane[i].max(a as f32 / 255.0)); + } + } + + let (fc, oc) = (params.fill_rgba, params.outline_rgba); + let mut out = vec![0u8; tw * th * 4]; + for (i, px) in out.chunks_exact_mut(4).enumerate() { + let fa = fill_plane[i] as f32 / 255.0 * fc[3]; + let oa = if outlined { line_plane[i] * oc[3] } else { 0.0 }; + if fa <= 0.0 && oa <= 0.0 { + continue; + } + let under = 1.0 - fa; + for k in 0..3 { + let v = fc[k] * fa + oc[k] * oa * under; + px[k] = (v * 255.0 + 0.5).clamp(0.0, 255.0) as u8; + } + px[3] = ((fa + oa * under) * 255.0 + 0.5).clamp(0.0, 255.0) as u8; + } + + ([tw as u32, th as u32], [origin_x, origin_y], out) +} + +/// Calls `f(plane_index, coverage)` for every non-zero coverage pixel that lands inside the plane. +fn blit_max(c: &text_engine::Coverage, origin: [i32; 2], plane: [usize; 2], mut f: impl FnMut(usize, u8)) { + for y in 0..c.height as i32 { + let py = c.top + y - origin[1]; + if py < 0 || py >= plane[1] as i32 { + continue; + } + for x in 0..c.width as i32 { + let px = c.left + x - origin[0]; + let a = c.data[(y as u32 * c.width + x as u32) as usize]; + if a > 0 && px >= 0 && px < plane[0] as i32 { + f(py as usize * plane[0] + px as usize, a); + } + } + } +} + +/// Rasterizes a closed Fusion `PolylineMask` into RGBA8 `[w, h]` via `zeno`. +pub fn rasterize_polyline_mask( + dims: [u32; 2], + points: &[PolyPoint], + center: [f32; 2], + invert: bool, + level: f32, +) -> Vec { + let [w, h] = dims; + let mut out = vec![0u8; (w as usize) * (h as usize) * 4]; + if points.len() < 2 { + return out; + } + let to_px = |x: f64, y: f64| -> [f32; 2] { + let fx = (center[0] + x as f32) * w as f32; + let fy = (1.0 - (center[1] + y as f32)) * h as f32; + [fx, fy] + }; + let mut cmds = Vec::new(); + let p0 = to_px(points[0].x, points[0].y); + cmds.push(zeno::Command::MoveTo(zeno::Vector::new(p0[0], p0[1]))); + for i in 0..points.len() { + let a = &points[i]; + let b = &points[(i + 1) % points.len()]; + let c1 = to_px(a.x + a.rx, a.y + a.ry); + let c2 = to_px(b.x + b.lx, b.y + b.ly); + let p = to_px(b.x, b.y); + if a.linear && b.linear { + cmds.push(zeno::Command::LineTo(zeno::Vector::new(p[0], p[1]))); + } else { + cmds.push(zeno::Command::CurveTo( + zeno::Vector::new(c1[0], c1[1]), + zeno::Vector::new(c2[0], c2[1]), + zeno::Vector::new(p[0], p[1]), + )); + } + } + cmds.push(zeno::Command::Close); + + let mut mask = vec![0u8; (w as usize) * (h as usize)]; + let mut scratch = zeno::Scratch::new(); + let placement = zeno::Mask::with_scratch(&cmds, &mut scratch) + .size(w, h) + .origin(zeno::Origin::TopLeft) + .render_into(&mut mask, None); + let _ = placement; + for (i, &cov) in mask.iter().enumerate() { + let mut a = cov as f32 / 255.0; + if invert { a = 1.0 - a; } + let b = (a * level * 255.0).clamp(0.0, 255.0) as u8; + out[i * 4] = b; + out[i * 4 + 1] = b; + out[i * 4 + 2] = b; + out[i * 4 + 3] = b; + } + out +} diff --git a/crates/engine/src/media/video.rs b/crates/engine/src/media/video.rs new file mode 100644 index 0000000000000000000000000000000000000000..cd15064e2836c6567743db3d30aa400538b5d2c1 --- /dev/null +++ b/crates/engine/src/media/video.rs @@ -0,0 +1,268 @@ +use super::*; + +#[derive(Clone, Copy, Debug)] +pub struct VideoInfo { + pub width: u32, + pub height: u32, + pub fps: f64, + pub nb_frames: i64, +} + +pub trait VideoDecoder: Send { + fn info(&self) -> VideoInfo; + fn decode_frame(&mut self, frame_idx: i64) -> Option>; + fn backend_name(&self) -> &'static str; +} + +#[cfg(target_os = "macos")] +mod av_ffi { + use std::ffi::c_char; + + #[repr(C)] + pub struct AvVideoDecoder { + _private: [u8; 0], + } + + unsafe extern "C" { + pub fn av_video_open( + path: *const c_char, + out_w: *mut u32, + out_h: *mut u32, + out_fps: *mut f64, + out_nb_frames: *mut i64, + ) -> *mut AvVideoDecoder; + + pub fn av_video_decode_frame( + dec: *mut AvVideoDecoder, + frame_idx: i64, + out_rgba: *mut u8, + out_len: usize, + ) -> i32; + + pub fn av_video_close(dec: *mut AvVideoDecoder); + } +} + +#[cfg(target_os = "macos")] +pub struct AvFoundationDecoder { + ptr: *mut av_ffi::AvVideoDecoder, + info: VideoInfo, +} + +#[cfg(target_os = "macos")] +unsafe impl Send for AvFoundationDecoder {} + +#[cfg(target_os = "macos")] +impl Drop for AvFoundationDecoder { + fn drop(&mut self) { + if !self.ptr.is_null() { + unsafe { av_ffi::av_video_close(self.ptr) }; + self.ptr = std::ptr::null_mut(); + } + } +} + +#[cfg(target_os = "macos")] +impl AvFoundationDecoder { + pub fn open(path: &Path) -> Option { + use std::ffi::CString; + let path_str = path.to_str()?; + let c_path = CString::new(path_str).ok()?; + let mut width = 0u32; + let mut height = 0u32; + let mut fps = 0.0f64; + let mut nb_frames = 0i64; + let ptr = unsafe { + av_ffi::av_video_open( + c_path.as_ptr(), + &mut width, + &mut height, + &mut fps, + &mut nb_frames, + ) + }; + if ptr.is_null() || width == 0 || height == 0 { + if !ptr.is_null() { + unsafe { av_ffi::av_video_close(ptr) }; + } + return None; + } + Some(Self { + ptr, + info: VideoInfo { + width, + height, + fps: if fps > 0.0 { fps } else { 30.0 }, + nb_frames, + }, + }) + } +} + +#[cfg(target_os = "macos")] +impl VideoDecoder for AvFoundationDecoder { + fn info(&self) -> VideoInfo { + self.info + } + + fn decode_frame(&mut self, frame_idx: i64) -> Option> { + let len = (self.info.width as usize) + .checked_mul(self.info.height as usize)? + .checked_mul(4)?; + let mut buf = vec![0u8; len]; + let ok = unsafe { + av_ffi::av_video_decode_frame(self.ptr, frame_idx.max(0), buf.as_mut_ptr(), len) + }; + if ok != 0 { + Some(buf) + } else { + None + } + } + + fn backend_name(&self) -> &'static str { + "AVFoundation/VideoToolbox" + } +} + +pub struct FfmpegDecoder { + path: PathBuf, + info: VideoInfo, +} + +impl FfmpegDecoder { + pub fn open(path: &Path) -> Option { + let info = probe_video(path)?; + Some(Self { + path: path.to_path_buf(), + info, + }) + } +} + +impl VideoDecoder for FfmpegDecoder { + fn info(&self) -> VideoInfo { + self.info + } + + fn decode_frame(&mut self, frame_idx: i64) -> Option> { + decode_video_frame(&self.path, self.info, frame_idx) + } + + fn backend_name(&self) -> &'static str { + "ffmpeg" + } +} + +/// Opens a hardware-accelerated video decoder (`AVFoundation`/`VideoToolbox` on macOS), +/// falling back to `ffmpeg` for unsupported containers or codecs. +pub fn open_video_decoder(path: &Path) -> Option> { + #[cfg(target_os = "macos")] + { + if let Some(av) = AvFoundationDecoder::open(path) { + return Some(Box::new(av)); + } + } + FfmpegDecoder::open(path).map(|ff| Box::new(ff) as Box) +} + +pub(super) fn is_video_path(path: &Path) -> bool { + let Some(ext) = path.extension().and_then(|e| e.to_str()) else { + return false; + }; + matches!( + ext.to_ascii_lowercase().as_str(), + "mov" | "mp4" | "m4v" | "mkv" | "avi" | "webm" | "mxf" + ) +} + +pub(super) fn probe_video(path: &Path) -> Option { + let out = Command::new("ffprobe") + .args([ + "-v", + "error", + "-select_streams", + "v:0", + "-show_entries", + "stream=width,height,r_frame_rate,nb_frames", + "-of", + "default=noprint_wrappers=1", + ]) + .arg(path) + .output() + .ok()?; + if !out.status.success() { + return None; + } + let text = String::from_utf8_lossy(&out.stdout); + let mut width = 0u32; + let mut height = 0u32; + let mut fps = 30.0_f64; + let mut nb_frames = 0i64; + for line in text.lines() { + if let Some((k, v)) = line.split_once('=') { + match k.trim() { + "width" => width = v.trim().parse().unwrap_or(0), + "height" => height = v.trim().parse().unwrap_or(0), + "nb_frames" => nb_frames = v.trim().parse().unwrap_or(0), + "r_frame_rate" => { + if let Some((n, d)) = v.trim().split_once('/') { + let num: f64 = n.parse().unwrap_or(30.0); + let den: f64 = d.parse().unwrap_or(1.0); + if den > 0.0 && num > 0.0 { + fps = num / den; + } + } else if let Ok(r) = v.trim().parse::() { + if r > 0.0 { + fps = r; + } + } + } + _ => {} + } + } + } + if width == 0 || height == 0 { + return None; + } + Some(VideoInfo { width, height, fps, nb_frames }) +} + +pub(super) fn decode_video_frame(path: &Path, info: VideoInfo, frame_idx: i64) -> Option> { + let idx = frame_idx.max(0); + let ts = if idx == 0 { + 0.0 + } else { + ((idx as f64) - 0.005) / info.fps.max(1.0) + }; + let out = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-ss", + &format!("{ts:.6}"), + "-i", + ]) + .arg(path) + .args([ + "-frames:v", + "1", + "-f", + "rawvideo", + "-pix_fmt", + "rgba", + "-", + ]) + .output() + .ok()?; + if !out.status.success() { + return None; + } + let expected = (info.width as usize) * (info.height as usize) * 4; + if out.stdout.len() < expected { + return None; + } + let mut buf = out.stdout; + buf.truncate(expected); + Some(buf) +} diff --git a/crates/flow/src/hit.rs b/crates/flow/src/hit.rs new file mode 100644 index 0000000000000000000000000000000000000000..fa9438bed82dec4e7a4bb8edebf5bff6172626f8 --- /dev/null +++ b/crates/flow/src/hit.rs @@ -0,0 +1,228 @@ +use super::*; + +impl FlowView { + pub(crate) fn world_to_local(&self, w: [f32; 2]) -> [f32; 2] { + [ + (w[0] - self.pan[0]) * self.zoom + self.size[0] * 0.5, + (w[1] - self.pan[1]) * self.zoom + self.size[1] * 0.5, + ] + } + + pub(crate) fn local_to_world(&self, l: [f32; 2]) -> [f32; 2] { + [ + (l[0] - self.size[0] * 0.5) / self.zoom + self.pan[0], + (l[1] - self.size[1] * 0.5) / self.zoom + self.pan[1], + ] + } + + pub(crate) fn node_rect_local(&self, pos: [f32; 2]) -> [f32; 4] { + let c = self.world_to_local(pos); + let hw = NODE_W * 0.5 * self.zoom; + let hh = NODE_H * 0.5 * self.zoom; + [c[0] - hw, c[1] - hh, c[0] + hw, c[1] + hh] + } + + /// Computes auto-wrapped port geometry for a wire `src -> dst` so ports snap to the + /// closest facing sides of each node (Fusion's signature clean multi-directional routing!). + pub(crate) fn wire_endpoints(&self, comp: &Comp, src: NodeId, dst: NodeId, role: PortRole) -> ([f32; 2], Edge, [f32; 2], Edge) { + let sp = comp.node(src).pos; + let dp = comp.node(dst).pos; + let sr = self.node_rect_local(sp); + let dr = self.node_rect_local(dp); + + let dx = dp[0] - sp[0]; + let dy = dp[1] - sp[1]; + // Weight Y slightly more because nodes are wider than tall (~5:1 aspect)! + let out_edge = closest_edge(dx, dy); + let in_edge = closest_edge_for_input(-dx, -dy, role); + + let a = out_edge.point_on_rect(sr, 0.5); + let b = in_edge.point_on_rect(dr, 0.5); + (a, out_edge, b, in_edge) + } + + /// Computes a node's resting output port edge (average direction of its consumers, defaulting to Right). + pub(crate) fn node_output_edge(&self, comp: &Comp, id: NodeId) -> Edge { + let name = &comp.node(id).name; + let sp = comp.node(id).pos; + let mut sx = 0.0_f32; + let mut sy = 0.0_f32; + let mut count = 0; + for other in comp.nodes.iter().filter(|n| self.scope.shows(n)) { + for binding in other.inputs.values() { + if binding.source_op.as_deref() == Some(name.as_str()) { + let dx = other.pos[0] - sp[0]; + let dy = other.pos[1] - sp[1]; + let len = (dx * dx + dy * dy).sqrt().max(1.0); + sx += dx / len; + sy += dy / len; + count += 1; + } + } + } + if count == 0 { + Edge::Right + } else { + closest_edge(sx, sy) + } + } + + pub(crate) fn hit_node(&self, comp: &Comp, local: [f32; 2]) -> Option { + for n in comp.nodes.iter().rev() { + if !self.scope.shows(n) { continue; } + let r = self.node_rect_local(n.pos); + if local[0] >= r[0] && local[0] <= r[2] && local[1] >= r[1] && local[1] <= r[3] { + return Some(n.id); + } + } + None + } + + pub(crate) fn hit_output_port(&self, comp: &Comp, local: [f32; 2]) -> Option { + for n in comp.nodes.iter().rev() { + if !self.scope.shows(n) { continue; } + let r = self.node_rect_local(n.pos); + let edge = self.node_output_edge(comp, n.id); + let nrm = edge.normal(); + let p0 = edge.point_on_rect(r, 0.5); + let p = [p0[0] + nrm[0] * 5.0, p0[1] + nrm[1] * 5.0]; + let dx = local[0] - p[0]; + let dy = local[1] - p[1]; + if dx * dx + dy * dy <= 10.0 * 10.0 { + return Some(n.id); + } + } + None + } + + pub(crate) fn hit_input_port(&self, comp: &Comp, local: [f32; 2]) -> Option<(NodeId, &'static str)> { + for n in comp.nodes.iter().rev() { + if !self.scope.shows(n) { continue; } + let r = self.node_rect_local(n.pos); + if local[0] >= r[0] - 10.0 && local[0] <= r[2] + 10.0 && local[1] >= r[1] - 10.0 && local[1] <= r[3] + 10.0 { + // Pick Background/Foreground/Mask cleanly based on approach edge for Merge/Displace! + if n.kind == "Merge" || n.kind == "Displace" || n.kind == "Dissolve" { + if local[1] < r[1] + 2.0 { + return Some((n.id, "Foreground")); + } + if local[1] > r[3] - 2.0 { + return Some((n.id, "EffectMask")); + } + return Some((n.id, "Background")); + } + if n.kind == "Merge3D" || n.kind == "Renderer3D" { + return Some((n.id, "SceneInput1")); + } + if local[1] > r[3] - 1.5 && n.kind != "PipeRouter" { + return Some((n.id, "EffectMask")); + } + return Some((n.id, default_main_input_port(&n.kind))); + } + } + None + } + + /// Hit-tests already-connected input port triangles so the user can drag an input off to disconnect/rewire. + pub(crate) fn hit_connected_input_port(&self, comp: &Comp, local: [f32; 2]) -> Option<(NodeId, String, NodeId)> { + let hit_r2 = 10.5_f32 * 10.5_f32; + for dst in comp.nodes.iter().rev() { + if !self.scope.shows(dst) { continue; } + for (port, binding) in &dst.inputs { + let Some(src_name) = &binding.source_op else { continue }; + let Some(src_id) = self.scope.resolve(comp, src_name) else { continue }; + let role = PortRole::from_input_name(port); + let (_a, _ae, b, be) = self.wire_endpoints(comp, src_id, dst.id, role); + let bn = be.normal(); + let center = [b[0] + bn[0] * 4.0, b[1] + bn[1] * 4.0]; + let dx = local[0] - center[0]; + let dy = local[1] - center[1]; + if dx * dx + dy * dy <= hit_r2 { + return Some((dst.id, port.clone(), src_id)); + } + } + } + None + } + + pub(crate) fn hit_wire(&self, comp: &Comp, local: [f32; 2], ignore_node: Option) -> Option { + let mut best: Option<(f32, WireRef)> = None; + for dst in comp.nodes.iter().filter(|n| self.scope.shows(n)) { + if Some(dst.id) == ignore_node { + continue; + } + for (port, binding) in &dst.inputs { + let Some(src_name) = &binding.source_op else { continue }; + let Some(src_id) = self.scope.resolve(comp, src_name) else { continue }; + if Some(src_id) == ignore_node { + continue; + } + let role = PortRole::from_input_name(port); + let (a, ae, b, be) = self.wire_endpoints(comp, src_id, dst.id, role); + let d = dist_to_straight_wire(local, a, ae, b, be, self.zoom); + if d < 10.0 && best.as_ref().is_none_or(|(bd, _)| d < *bd) { + best = Some(( + d, + WireRef { + src: src_id, + dst: dst.id, + port: port.clone(), + }, + )); + } + } + } + best.map(|(_, w)| w) + } +} + +/// Picks the closest node edge facing vector `(dx, dy)` accounting for thin rectangular bar aspect. +fn closest_edge(dx: f32, dy: f32) -> Edge { + // Nodes are 84x21 (4:1 aspect), so require a balanced X bias so horizontal rows snap Left/Right + // while vertical stacks naturally snap Top/Bottom! + if dx.abs() * 0.58 >= dy.abs() { + if dx >= 0.0 { Edge::Right } else { Edge::Left } + } else if dy >= 0.0 { + Edge::Bottom + } else { + Edge::Top + } +} + +/// Auto-wraps input port to the closest side facing the producer, gently nudging Mask/FG when needed. +fn closest_edge_for_input(dx_to_src: f32, dy_to_src: f32, role: PortRole) -> Edge { + let primary = closest_edge(dx_to_src, dy_to_src); + match role { + PortRole::Mask => { + // Masks prefer Top/Bottom unless directly horizontal + if dy_to_src.abs() >= dx_to_src.abs() * 0.35 { + if dy_to_src >= 0.0 { Edge::Bottom } else { Edge::Top } + } else { + primary + } + } + _ => primary, + } +} + +fn dist_to_straight_wire(pt: [f32; 2], a: [f32; 2], ae: Edge, b: [f32; 2], be: Edge, zoom: f32) -> f32 { + let stub = (8.0 * zoom).clamp(4.0, 11.0); + let an = ae.normal(); + let bn = be.normal(); + let a_out = [a[0] + an[0] * stub, a[1] + an[1] * stub]; + let b_out = [b[0] + bn[0] * stub, b[1] + bn[1] * stub]; + dist_to_seg(pt, a, a_out) + .min(dist_to_seg(pt, a_out, b_out)) + .min(dist_to_seg(pt, b_out, b)) +} + +pub(crate) fn dist_to_seg(p: [f32; 2], a: [f32; 2], b: [f32; 2]) -> f32 { + let ab = [b[0] - a[0], b[1] - a[1]]; + let len2 = ab[0] * ab[0] + ab[1] * ab[1]; + let t = if len2 < 1e-6 { + 0.0 + } else { + (((p[0] - a[0]) * ab[0] + (p[1] - a[1]) * ab[1]) / len2).clamp(0.0, 1.0) + }; + let q = [a[0] + ab[0] * t, a[1] + ab[1] * t]; + ((p[0] - q[0]).powi(2) + (p[1] - q[1]).powi(2)).sqrt() +} diff --git a/crates/flow/src/lib.rs b/crates/flow/src/lib.rs index bc94cb99d396882f821bb32dc77cf7742a0e62a3..0667f409ef3f7aba7ed95eb700d57e891cd9c2d7 100644 --- a/crates/flow/src/lib.rs +++ b/crates/flow/src/lib.rs @@ -6,6 +6,8 @@ //! - `1`/`2` multi-viewer routing, `Cmd+F` / Numpad `.` fit-to-view, `P` bypass, drag-onto-wire insert. //! - `Cmd+C` / `Cmd+V` node clipboard requests, double-click into Macro/Group subgraphs, `Esc` back out. +mod hit; +mod paint; mod scope; use draw::{Glyphs, PathStyle, Primitive}; @@ -362,179 +364,6 @@ impl FlowView { } } - fn world_to_local(&self, w: [f32; 2]) -> [f32; 2] { - [ - (w[0] - self.pan[0]) * self.zoom + self.size[0] * 0.5, - (w[1] - self.pan[1]) * self.zoom + self.size[1] * 0.5, - ] - } - - fn local_to_world(&self, l: [f32; 2]) -> [f32; 2] { - [ - (l[0] - self.size[0] * 0.5) / self.zoom + self.pan[0], - (l[1] - self.size[1] * 0.5) / self.zoom + self.pan[1], - ] - } - - fn node_rect_local(&self, pos: [f32; 2]) -> [f32; 4] { - let c = self.world_to_local(pos); - let hw = NODE_W * 0.5 * self.zoom; - let hh = NODE_H * 0.5 * self.zoom; - [c[0] - hw, c[1] - hh, c[0] + hw, c[1] + hh] - } - - /// Computes auto-wrapped port geometry for a wire `src -> dst` so ports snap to the - /// closest facing sides of each node (Fusion's signature clean multi-directional routing!). - fn wire_endpoints(&self, comp: &Comp, src: NodeId, dst: NodeId, role: PortRole) -> ([f32; 2], Edge, [f32; 2], Edge) { - let sp = comp.node(src).pos; - let dp = comp.node(dst).pos; - let sr = self.node_rect_local(sp); - let dr = self.node_rect_local(dp); - - let dx = dp[0] - sp[0]; - let dy = dp[1] - sp[1]; - // Weight Y slightly more because nodes are wider than tall (~5:1 aspect)! - let out_edge = closest_edge(dx, dy); - let in_edge = closest_edge_for_input(-dx, -dy, role); - - let a = out_edge.point_on_rect(sr, 0.5); - let b = in_edge.point_on_rect(dr, 0.5); - (a, out_edge, b, in_edge) - } - - /// Computes a node's resting output port edge (average direction of its consumers, defaulting to Right). - fn node_output_edge(&self, comp: &Comp, id: NodeId) -> Edge { - let name = &comp.node(id).name; - let sp = comp.node(id).pos; - let mut sx = 0.0_f32; - let mut sy = 0.0_f32; - let mut count = 0; - for other in comp.nodes.iter().filter(|n| self.scope.shows(n)) { - for binding in other.inputs.values() { - if binding.source_op.as_deref() == Some(name.as_str()) { - let dx = other.pos[0] - sp[0]; - let dy = other.pos[1] - sp[1]; - let len = (dx * dx + dy * dy).sqrt().max(1.0); - sx += dx / len; - sy += dy / len; - count += 1; - } - } - } - if count == 0 { - Edge::Right - } else { - closest_edge(sx, sy) - } - } - - fn hit_node(&self, comp: &Comp, local: [f32; 2]) -> Option { - for n in comp.nodes.iter().rev() { - if !self.scope.shows(n) { continue; } - let r = self.node_rect_local(n.pos); - if local[0] >= r[0] && local[0] <= r[2] && local[1] >= r[1] && local[1] <= r[3] { - return Some(n.id); - } - } - None - } - - fn hit_output_port(&self, comp: &Comp, local: [f32; 2]) -> Option { - for n in comp.nodes.iter().rev() { - if !self.scope.shows(n) { continue; } - let r = self.node_rect_local(n.pos); - let edge = self.node_output_edge(comp, n.id); - let nrm = edge.normal(); - let p0 = edge.point_on_rect(r, 0.5); - let p = [p0[0] + nrm[0] * 5.0, p0[1] + nrm[1] * 5.0]; - let dx = local[0] - p[0]; - let dy = local[1] - p[1]; - if dx * dx + dy * dy <= 10.0 * 10.0 { - return Some(n.id); - } - } - None - } - - fn hit_input_port(&self, comp: &Comp, local: [f32; 2]) -> Option<(NodeId, &'static str)> { - for n in comp.nodes.iter().rev() { - if !self.scope.shows(n) { continue; } - let r = self.node_rect_local(n.pos); - if local[0] >= r[0] - 10.0 && local[0] <= r[2] + 10.0 && local[1] >= r[1] - 10.0 && local[1] <= r[3] + 10.0 { - // Pick Background/Foreground/Mask cleanly based on approach edge for Merge/Displace! - if n.kind == "Merge" || n.kind == "Displace" || n.kind == "Dissolve" { - if local[1] < r[1] + 2.0 { - return Some((n.id, "Foreground")); - } - if local[1] > r[3] - 2.0 { - return Some((n.id, "EffectMask")); - } - return Some((n.id, "Background")); - } - if n.kind == "Merge3D" || n.kind == "Renderer3D" { - return Some((n.id, "SceneInput1")); - } - if local[1] > r[3] - 1.5 && n.kind != "PipeRouter" { - return Some((n.id, "EffectMask")); - } - return Some((n.id, default_main_input_port(&n.kind))); - } - } - None - } - - /// Hit-tests already-connected input port triangles so the user can drag an input off to disconnect/rewire. - fn hit_connected_input_port(&self, comp: &Comp, local: [f32; 2]) -> Option<(NodeId, String, NodeId)> { - let hit_r2 = 10.5_f32 * 10.5_f32; - for dst in comp.nodes.iter().rev() { - if !self.scope.shows(dst) { continue; } - for (port, binding) in &dst.inputs { - let Some(src_name) = &binding.source_op else { continue }; - let Some(src_id) = self.scope.resolve(comp, src_name) else { continue }; - let role = PortRole::from_input_name(port); - let (_a, _ae, b, be) = self.wire_endpoints(comp, src_id, dst.id, role); - let bn = be.normal(); - let center = [b[0] + bn[0] * 4.0, b[1] + bn[1] * 4.0]; - let dx = local[0] - center[0]; - let dy = local[1] - center[1]; - if dx * dx + dy * dy <= hit_r2 { - return Some((dst.id, port.clone(), src_id)); - } - } - } - None - } - - fn hit_wire(&self, comp: &Comp, local: [f32; 2], ignore_node: Option) -> Option { - let mut best: Option<(f32, WireRef)> = None; - for dst in comp.nodes.iter().filter(|n| self.scope.shows(n)) { - if Some(dst.id) == ignore_node { - continue; - } - for (port, binding) in &dst.inputs { - let Some(src_name) = &binding.source_op else { continue }; - let Some(src_id) = self.scope.resolve(comp, src_name) else { continue }; - if Some(src_id) == ignore_node { - continue; - } - let role = PortRole::from_input_name(port); - let (a, ae, b, be) = self.wire_endpoints(comp, src_id, dst.id, role); - let d = dist_to_straight_wire(local, a, ae, b, be, self.zoom); - if d < 10.0 && best.as_ref().is_none_or(|(bd, _)| d < *bd) { - best = Some(( - d, - WireRef { - src: src_id, - dst: dst.id, - port: port.clone(), - }, - )); - } - } - } - best.map(|(_, w)| w) - } - fn begin_modal(&mut self, comp: &Comp, history: &mut CompHistory, mode: TransformMode) { if self.selected.is_empty() { return; @@ -1082,564 +911,12 @@ impl FlowView { self.pan[0] += before[0] - after[0]; self.pan[1] += before[1] - after[1]; } - - pub fn prepare_labels(&mut self, comp: &Comp) { - let label_font = text::Font { - families: Arc::from([text::Family::Sans]), - size: 9.5, - weight: 500, - italic: false, - }; - let badge_font = text::Font { - families: Arc::from([text::Family::Mono]), - size: 10.0, - weight: 500, - italic: false, - }; - let tiny_font = text::Font { - families: Arc::from([text::Family::Mono]), - size: 7.5, - weight: 600, - italic: false, - }; - let make_layout = |s: &str, font: &text::Font| { - let styles = [text::Style::new(font.clone())]; - text::Paragraph { - text: s, - styles: &styles, - spans: &[], - replacements: &[], - width: None, - indent: 0.0, - line_height: 1.2, - align: text::Align::Left, - tab: 32.0, - } - .layout() - }; - if self.label_cache.len() > comp.nodes.len() + LABEL_CACHE_SLACK { - self.label_cache.clear(); - } - for n in &comp.nodes { - self.label_cache.entry(n.name.clone()).or_insert_with(|| make_layout(&n.name, &label_font)); - } - self.badge_cache - .entry("preserved".to_owned()) - .or_insert_with(|| make_layout("preserved", &tiny_font)); - self.badge_cache - .entry("cycle!".to_owned()) - .or_insert_with(|| make_layout("cycle!", &tiny_font)); - for key in [ - HUD_ROOT, - HUD_GROUP, - "GRAB [LMB/Enter confirm, RMB/Esc cancel, X/Y axis, Shift: Splice]", - "ROTATE [LMB/Enter confirm, RMB/Esc cancel]", - "SCALE [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]", - ] { - self.badge_cache.entry(key.to_owned()).or_insert_with(|| make_layout(key, &badge_font)); - } - } - - pub fn paint<'a>(&'a self, comp: &'a Comp) -> Vec> { - let mut out = Vec::with_capacity(comp.nodes.len() * 10 + 128); - let [w, h] = self.size; - - // 1. Subtle architectural grid aligned to Fusion's 110×33 flow cells - let mult = if self.zoom < 0.35 { 4.0 } else if self.zoom < 0.70 { 2.0 } else { 1.0 }; - let step_x = 110.0 * mult; - let step_y = 33.0 * mult * 2.0; - let tl = self.local_to_world([0.0, 0.0]); - let br = self.local_to_world([w, h]); - let gx0 = (tl[0] / step_x).floor() as i32; - let gx1 = (br[0] / step_x).ceil() as i32; - let gy0 = (tl[1] / step_y).floor() as i32; - let gy1 = (br[1] / step_y).ceil() as i32; - for gx in gx0..=gx1 { - let x = self.world_to_local([gx as f32 * step_x, 0.0])[0]; - let col = if gx % 4 == 0 { self.palette.grid_major } else { self.palette.grid_minor }; - out.push(Primitive::Segment { from: [x, 0.0], to: [x, h], width: 1.0, color: col }); - } - for gy in gy0..=gy1 { - let y = self.world_to_local([0.0, gy as f32 * step_y])[1]; - let col = if gy % 4 == 0 { self.palette.grid_major } else { self.palette.grid_minor }; - out.push(Primitive::Segment { from: [0.0, y], to: [w, y], width: 1.0, color: col }); - } - - // 2. Modal Blender axis-lock guide lines - if let Some(m) = &self.modal { - let piv = self.world_to_local(m.pivot_world); - match m.axis { - AxisLock::X => out.push(Primitive::Segment { - from: [0.0, piv[1]], - to: [w, piv[1]], - width: 1.5, - color: [0.95, 0.28, 0.34, 0.85], - }), - AxisLock::Y => out.push(Primitive::Segment { - from: [piv[0], 0.0], - to: [piv[0], h], - width: 1.5, - color: [0.28, 0.90, 0.42, 0.85], - }), - AxisLock::None => {} - } - } - - // 3. Straight Fusion wires + crisp white output squares (□) + inward-pointing colored input arrows (▶)! - let large_ports = self.zoom >= 0.72; - let tri_len = if large_ports { 6.5 } else { 4.5 }; - let out_half = if large_ports { 2.8 } else { 2.0 }; - let out_gap = if large_ports { 2.2 } else { 1.5 }; - let port_outline = [0.04, 0.04, 0.06, 0.92]; - - for dst in comp.nodes.iter().filter(|n| self.scope.shows(n)) { - // Track used edges on `dst` so multiple inputs on the same edge spread cleanly instead of overlapping - let mut used_edges: HashMap = HashMap::new(); - let mut sorted_ports: Vec<(&String, &model::InputBinding)> = dst.inputs.iter().collect(); - sorted_ports.sort_by_key(|(p, _)| match PortRole::from_input_name(p) { - PortRole::Background => 0u8, - PortRole::Foreground => 1, - PortRole::Mask => 2, - PortRole::Scene3D => 3, - PortRole::Aux => 4, - }); - for (port, binding) in sorted_ports { - let Some(src_name) = &binding.source_op else { continue }; - let Some(src_id) = self.scope.resolve(comp, src_name) else { continue }; - let role = PortRole::from_input_name(port); - let (a, ae, mut b, mut be) = self.wire_endpoints(comp, src_id, dst.id, role); - let ekey = |e: Edge| match e { Edge::Left => 0u8, Edge::Right => 1, Edge::Top => 2, Edge::Bottom => 3 }; - let count = used_edges.entry(ekey(be)).or_insert(0); - if *count > 0 { - // Spread horizontal top/bottom ports (e.g. FG + Mask) like Fusion's ColorCorrector / Merge - let dr = self.node_rect_local(dst.pos); - if matches!(be, Edge::Top | Edge::Bottom) { - let t = if *count == 1 { 0.25 } else { 0.75 }; - b = be.point_on_rect(dr, t); - } else if role == PortRole::Mask { - be = Edge::Bottom; - b = be.point_on_rect(dr, 0.5); - } else { - let t = if *count == 1 { 0.30 } else { 0.70 }; - b = be.point_on_rect(dr, t); - } - } - *count += 1; - - let is_hot = self.hovered_wire.as_ref().is_some_and(|hw| hw.src == src_id && hw.dst == dst.id && hw.port == *port); - let is_sel = self.selected.contains(&src_id) || self.selected.contains(&dst.id); - - let wire_col = if is_hot { - [0.98, 0.82, 0.24, 1.0] - } else if is_sel { - [0.92, 0.94, 0.98, 0.96] - } else { - [0.64, 0.66, 0.72, 0.76] - }; - let width = if is_hot { 2.4 } else if is_sel { 1.6 } else { 1.1 }; - let an = ae.normal(); - let bn = be.normal(); - let op = [a[0] + an[0] * (out_gap + out_half), a[1] + an[1] * (out_gap + out_half)]; - let ip_base = [b[0] + bn[0] * tri_len, b[1] + bn[1] * tri_len]; - - // Straight wire directly from output square center to input triangle base (exact Fusion look!) - out.push(Primitive::Segment { from: op, to: ip_base, width, color: wire_col }); - - if self.zoom >= 0.36 { - // Output port: crisp Fusion white square `□` with thin dark outline - out.push(Primitive::RoundedRect { - rect: [op[0] - out_half, op[1] - out_half, op[0] + out_half, op[1] + out_half], - radius: 0.6, - stroke: None, - color: [0.94, 0.95, 0.98, 0.98], - }); - out.push(Primitive::RoundedRect { - rect: [op[0] - out_half, op[1] - out_half, op[0] + out_half, op[1] + out_half], - radius: 0.6, - stroke: Some(0.9), - color: port_outline, - }); - - // Input port: crisp Fusion colored triangle pointing INTO `dst`! - let pcol = port_color(role); - let tri = input_arrow_svg(be, large_ports); - out.push(Primitive::Path { - data: tri, - origin: b, - style: PathStyle::Fill, - color: pcol, - }); - out.push(Primitive::Path { - data: tri, - origin: b, - style: PathStyle::Stroke(0.9), - color: port_outline, - }); - } - } - } - - // Active wire drag preview (smooth cubic bezier + cycle rejection feedback) - if let Some(wd) = &self.wire_drag { - if wd.src.0 < comp.nodes.len() { - let sr = self.node_rect_local(comp.node(wd.src).pos); - let edge = self.node_output_edge(comp, wd.src); - let a = edge.point_on_rect(sr, 0.5); - let (end, is_cycle, target_role) = match wd.target { - Some((dst, port, cycle)) if dst.0 < comp.nodes.len() => { - let role = PortRole::from_input_name(port); - let (_, _, b, _) = self.wire_endpoints(comp, wd.src, dst, role); - (b, cycle, Some(role)) - } - _ => (wd.cursor_local, false, None), - }; - let wire_col = if is_cycle { - [0.96, 0.30, 0.34, 1.0] - } else if let Some(role) = target_role { - port_color(role) - } else { - [0.98, 0.84, 0.30, 1.0] - }; - let pts = sample_preview_bezier(a, edge.normal(), end, 16); - for seg in pts.windows(2) { - out.push(Primitive::Segment { - from: seg[0], - to: seg[1], - width: if is_cycle { 2.4 } else { 2.0 }, - color: wire_col, - }); - } - if is_cycle { - if let Some(badge) = self.badge_cache.get("cycle!") { - let bx = end[0] + 8.0; - let by = end[1] - 14.0; - out.push(Primitive::RoundedRect { - rect: [bx, by, bx + 36.0, by + 13.0], - radius: 3.0, - stroke: None, - color: [0.30, 0.06, 0.08, 0.94], - }); - out.push(Primitive::RoundedRect { - rect: [bx, by, bx + 36.0, by + 13.0], - radius: 3.0, - stroke: Some(1.0), - color: [0.96, 0.30, 0.34, 0.95], - }); - out.push(Primitive::Text { - text: badge as &dyn Glyphs, - origin: [bx + 5.0, by + 2.0], - clip: Some([bx, by, bx + 36.0, by + 13.0]), - ink: [1.0, 0.65, 0.65, 1.0], - }); - } - } - } - } - - // 4. Sleek Thin Fusion-Style Node Bars (color line along BOTTOM!) - for n in comp.nodes.iter().filter(|n| self.scope.shows(n)) { - let r = self.node_rect_local(n.pos); - if r[2] < -20.0 || r[0] > w + 20.0 || r[3] < -20.0 || r[1] > h + 20.0 { - continue; - } - let sel = self.selected.contains(&n.id); - let primary = self.primary == Some(n.id); - let hovered = self.hovered_node == Some(n.id); - let v1 = self.viewed_nodes[0] == Some(n.id); - let v2 = self.viewed_nodes[1] == Some(n.id); - let supported = is_supported_tool(&n.kind); - let accent = if supported { - node_accent(&n.kind) - } else { - [0.92, 0.64, 0.24, 1.0] - }; - - let bg = if n.bypassed { - [self.palette.node_fill[0] * 0.6, self.palette.node_fill[1] * 0.6, self.palette.node_fill[2] * 0.6, 0.65] - } else if sel { - self.palette.node_selected - } else if hovered { - self.palette.node_hover - } else if !supported { - [ - (self.palette.node_fill[0] + 0.035).min(1.0), - (self.palette.node_fill[1] + 0.020).min(1.0), - self.palette.node_fill[2], - 1.0, - ] - } else { - self.palette.node_fill - }; - - let radius = (3.5 * self.zoom).clamp(1.5, 5.0); - out.push(Primitive::RoundedRect { rect: r, radius, stroke: None, color: bg }); - - // Bottom category color line (exact Fusion look — thin sleek strip on bottom edge!) - let bar_h = (2.6 * self.zoom).clamp(1.4, 3.4); - out.push(Primitive::Rect { - rect: [r[0] + 1.5, (r[3] - bar_h).max(r[1]), r[2] - 1.5, r[3]], - color: if n.bypassed { [0.28, 0.28, 0.32, 0.6] } else { accent }, - }); - - // Crisp border (amber accent for preserved/passthrough unknown nodes) - let border_col = if primary { - [0.98, 0.78, 0.30, 1.0] - } else if sel { - self.palette.accent - } else if !supported { - [0.92, 0.64, 0.24, 0.85] - } else { - self.palette.node_border - }; - out.push(Primitive::RoundedRect { - rect: r, - radius, - stroke: Some(if sel || primary { 1.4 } else if !supported { 1.15 } else { 0.9 }), - color: border_col, - }); - // Subtle top dashed ticks for preserved/passthrough unknown nodes - if !supported && self.zoom >= 0.45 { - let mut tx = r[0] + 5.0; - while tx + 4.0 < r[2] - 4.0 { - out.push(Primitive::Segment { - from: [tx, r[1] + 0.8], - to: [(tx + 4.0).min(r[2] - 4.0), r[1] + 0.8], - width: 1.2, - color: [0.96, 0.72, 0.30, 0.90], - }); - tx += 8.0; - } - } - - // Node label centered cleanly inside thin bar - if self.zoom >= 0.42 { - if let Some(layout) = self.label_cache.get(&n.name) { - let ink = if n.bypassed { self.palette.text_dim } else { self.palette.text }; - let pad_x = (6.0 * self.zoom).clamp(3.0, 8.0); - let text_y = (r[1] + r[3] - bar_h) * 0.5 - 6.0; - out.push(Primitive::Text { - text: layout as &dyn Glyphs, - origin: [r[0] + pad_x, text_y], - clip: Some([r[0] + pad_x, r[1] + 1.0, r[2] - 4.0, r[3] - bar_h]), - ink, - }); - } - } - - // Preserved/passthrough pill badge underneath bottom-right for unknown/OFX nodes - if !supported && self.zoom >= 0.50 { - if let Some(badge) = self.badge_cache.get("preserved") { - let bw = 46.0; - let bh = 10.5; - let bx = (r[2] - bw).max(r[0] + 28.0); - let by = r[3] + 1.5; - out.push(Primitive::RoundedRect { - rect: [bx, by, bx + bw, by + bh], - radius: 3.0, - stroke: None, - color: [0.14, 0.10, 0.05, 0.92], - }); - out.push(Primitive::RoundedRect { - rect: [bx, by, bx + bw, by + bh], - radius: 3.0, - stroke: Some(0.8), - color: [0.92, 0.64, 0.24, 0.72], - }); - out.push(Primitive::Text { - text: badge as &dyn Glyphs, - origin: [bx + 4.0, by + 1.0], - clip: Some([bx + 2.0, by, bx + bw - 2.0, by + bh]), - ink: [0.98, 0.78, 0.40, 1.0], - }); - } - } - - // Fusion-style tiny viewer indicator pill underneath bottom-left (`● ○` for Viewer 1 / Viewer 2!) - if v1 || v2 { - let pw = 22.0; - let ph = 9.0; - let px = r[0] + 4.0; - let py = r[3] + 1.5; - out.push(Primitive::RoundedRect { - rect: [px, py, px + pw, py + ph], - radius: 3.0, - stroke: None, - color: [0.02, 0.02, 0.03, 0.92], - }); - let d1 = if v1 { [0.24, 0.90, 0.82, 1.0] } else { [0.26, 0.28, 0.34, 0.6] }; - let d2 = if v2 { [0.98, 0.68, 0.28, 1.0] } else { [0.26, 0.28, 0.34, 0.6] }; - out.push(Primitive::RoundedRect { - rect: [px + 3.5, py + 2.0, px + 8.5, py + 7.0], - radius: 2.5, - stroke: None, - color: d1, - }); - out.push(Primitive::RoundedRect { - rect: [px + 13.0, py + 2.0, px + 18.0, py + 7.0], - radius: 2.5, - stroke: None, - color: d2, - }); - } - - if n.bypassed { - let ym = (r[1] + r[3]) * 0.5; - out.push(Primitive::Segment { - from: [r[0] + 3.0, ym], - to: [r[2] - 3.0, ym], - width: 1.4, - color: [0.95, 0.35, 0.35, 0.85], - }); - } - } - - // 5. Box select marquee - if let Some(bs) = &self.box_select { - let x0 = bs.start_local[0].min(bs.cur_local[0]); - let x1 = bs.start_local[0].max(bs.cur_local[0]); - let y0 = bs.start_local[1].min(bs.cur_local[1]); - let y1 = bs.start_local[1].max(bs.cur_local[1]); - out.push(Primitive::RoundedRect { - rect: [x0, y0, x1, y1], - radius: 2.0, - stroke: None, - color: [self.palette.accent[0], self.palette.accent[1], self.palette.accent[2], 0.16], - }); - out.push(Primitive::RoundedRect { - rect: [x0, y0, x1, y1], - radius: 2.0, - stroke: Some(1.2), - color: self.palette.accent, - }); - } - - // 6. Status HUD strip - let hud_key = match self.modal.as_ref().map(|m| m.mode) { - Some(TransformMode::Grab) => "GRAB [LMB/Enter confirm, RMB/Esc cancel, X/Y axis, Shift: Splice]", - Some(TransformMode::Rotate) => "ROTATE [LMB/Enter confirm, RMB/Esc cancel]", - Some(TransformMode::Scale) => "SCALE [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]", - None if !self.scope.is_root() => HUD_GROUP, - None => HUD_ROOT, - }; - if let Some(l) = self.badge_cache.get(hud_key) { - let pill_h = 20.0; - out.push(Primitive::RoundedRect { - rect: [8.0, h - pill_h - 6.0, w - 8.0, h - 6.0], - radius: 4.0, - stroke: None, - color: [self.palette.bg[0] * 0.75, self.palette.bg[1] * 0.75, self.palette.bg[2] * 0.75, 0.86], - }); - out.push(Primitive::Text { - text: l as &dyn Glyphs, - origin: [14.0, h - pill_h - 2.5], - clip: Some([12.0, h - pill_h - 6.0, w - 12.0, h - 6.0]), - ink: if self.modal.is_some() { [0.98, 0.82, 0.30, 1.0] } else { self.palette.text_dim }, - }); - } - - out - } } fn read_only_notice(actions: &mut Vec) { actions.push(FlowAction::StatusNotice("Group contents are read-only; press Esc to leave the group".to_owned())); } -/// Static SVG triangles pointing INTO the node edge (`origin` sits flush on the node border). -fn input_arrow_svg(edge: Edge, large: bool) -> &'static str { - match (edge, large) { - (Edge::Left, true) => "M 0 0 L -6.5 -3.6 L -6.5 3.6 Z", - (Edge::Left, false) => "M 0 0 L -4.5 -2.6 L -4.5 2.6 Z", - (Edge::Right, true) => "M 0 0 L 6.5 -3.6 L 6.5 3.6 Z", - (Edge::Right, false) => "M 0 0 L 4.5 -2.6 L 4.5 2.6 Z", - (Edge::Top, true) => "M 0 0 L -3.6 -6.5 L 3.6 -6.5 Z", - (Edge::Top, false) => "M 0 0 L -2.6 -4.5 L 2.6 -4.5 Z", - (Edge::Bottom, true) => "M 0 0 L -3.6 6.5 L 3.6 6.5 Z", - (Edge::Bottom, false) => "M 0 0 L -2.6 4.5 L 2.6 4.5 Z", - } -} - -/// Picks the closest node edge facing vector `(dx, dy)` accounting for thin rectangular bar aspect. -fn closest_edge(dx: f32, dy: f32) -> Edge { - // Nodes are 84x21 (4:1 aspect), so require a balanced X bias so horizontal rows snap Left/Right - // while vertical stacks naturally snap Top/Bottom! - if dx.abs() * 0.58 >= dy.abs() { - if dx >= 0.0 { Edge::Right } else { Edge::Left } - } else if dy >= 0.0 { - Edge::Bottom - } else { - Edge::Top - } -} - -/// Auto-wraps input port to the closest side facing the producer, gently nudging Mask/FG when needed. -fn closest_edge_for_input(dx_to_src: f32, dy_to_src: f32, role: PortRole) -> Edge { - let primary = closest_edge(dx_to_src, dy_to_src); - match role { - PortRole::Mask => { - // Masks prefer Top/Bottom unless directly horizontal - if dy_to_src.abs() >= dx_to_src.abs() * 0.35 { - if dy_to_src >= 0.0 { Edge::Bottom } else { Edge::Top } - } else { - primary - } - } - _ => primary, - } -} - -fn port_color(role: PortRole) -> [f32; 4] { - match role { - PortRole::Background => [0.94, 0.76, 0.26, 1.0], // Fusion gold - PortRole::Foreground => [0.34, 0.86, 0.46, 1.0], // Fusion green - PortRole::Mask => [0.32, 0.64, 0.98, 1.0], // Fusion blue - PortRole::Scene3D => [0.30, 0.86, 0.90, 1.0], // Cyan - PortRole::Aux => [0.74, 0.58, 0.90, 1.0], // Violet - } -} - -fn node_accent(kind: &str) -> [f32; 4] { - match kind { - "Loader" | "Saver" => [0.32, 0.72, 0.92, 1.0], - "Merge" | "Switch" | "Fuse.Switch" => [0.58, 0.60, 0.66, 1.0], - "Background" | "FastNoise" => [0.36, 0.80, 0.42, 1.0], - "TextPlus" | "Text3D" => [0.34, 0.86, 0.54, 1.0], - "ColorCorrector" | "BrightnessContrast" | "ColorCurves" | "HueCurves" | "LumaKeyer" | "UltraKeyer" => { - [0.92, 0.58, 0.22, 1.0] - } - "Blur" | "DirectionalBlur" | "Glow" | "SoftGlow" | "Displace" | "ErodeDilate" => { - [0.92, 0.52, 0.24, 1.0] - } - "Transform" | "Scale" | "Crop" | "TimeStretcher" | "TimeSpeed" => [0.84, 0.66, 0.28, 1.0], - "EllipseMask" | "RectangleMask" | "PolylineMask" | "BitmapMask" => [0.32, 0.62, 0.98, 1.0], - k if k.starts_with("Fuse.") => [0.88, 0.44, 0.76, 1.0], - _ => [0.54, 0.54, 0.60, 1.0], - } -} - -fn dist_to_straight_wire(pt: [f32; 2], a: [f32; 2], ae: Edge, b: [f32; 2], be: Edge, zoom: f32) -> f32 { - let stub = (8.0 * zoom).clamp(4.0, 11.0); - let an = ae.normal(); - let bn = be.normal(); - let a_out = [a[0] + an[0] * stub, a[1] + an[1] * stub]; - let b_out = [b[0] + bn[0] * stub, b[1] + bn[1] * stub]; - dist_to_seg(pt, a, a_out) - .min(dist_to_seg(pt, a_out, b_out)) - .min(dist_to_seg(pt, b_out, b)) -} - -fn dist_to_seg(p: [f32; 2], a: [f32; 2], b: [f32; 2]) -> f32 { - let ab = [b[0] - a[0], b[1] - a[1]]; - let len2 = ab[0] * ab[0] + ab[1] * ab[1]; - let t = if len2 < 1e-6 { - 0.0 - } else { - (((p[0] - a[0]) * ab[0] + (p[1] - a[1]) * ab[1]) / len2).clamp(0.0, 1.0) - }; - let q = [a[0] + ab[0] * t, a[1] + ab[1] * t]; - ((p[0] - q[0]).powi(2) + (p[1] - q[1]).powi(2)).sqrt() -} - /// Samples a smooth cubic Bezier preview wire leaving `a` along `out_normal` and arriving at `b`. pub fn sample_preview_bezier(a: [f32; 2], out_normal: [f32; 2], b: [f32; 2], steps: usize) -> Vec<[f32; 2]> { let steps = steps.max(2); @@ -1663,6 +940,7 @@ pub fn sample_preview_bezier(a: [f32; 2], out_normal: [f32; 2], b: [f32; 2], ste #[cfg(test)] mod tests { use super::*; + use crate::hit::dist_to_seg; fn test_comp() -> Comp { let src = r#"Composition { diff --git a/crates/flow/src/paint.rs b/crates/flow/src/paint.rs new file mode 100644 index 0000000000000000000000000000000000000000..ded993039627920a6685c2ea8d21e8f96f92c7f7 --- /dev/null +++ b/crates/flow/src/paint.rs @@ -0,0 +1,503 @@ +use super::*; + +impl FlowView { + pub fn prepare_labels(&mut self, comp: &Comp) { + let label_font = text::Font { + families: Arc::from([text::Family::Sans]), + size: 9.5, + weight: 500, + italic: false, + }; + let badge_font = text::Font { + families: Arc::from([text::Family::Mono]), + size: 10.0, + weight: 500, + italic: false, + }; + let tiny_font = text::Font { + families: Arc::from([text::Family::Mono]), + size: 7.5, + weight: 600, + italic: false, + }; + let make_layout = |s: &str, font: &text::Font| { + let styles = [text::Style::new(font.clone())]; + text::Paragraph { + text: s, + styles: &styles, + spans: &[], + replacements: &[], + width: None, + indent: 0.0, + line_height: 1.2, + align: text::Align::Left, + tab: 32.0, + } + .layout() + }; + if self.label_cache.len() > comp.nodes.len() + LABEL_CACHE_SLACK { + self.label_cache.clear(); + } + for n in &comp.nodes { + self.label_cache.entry(n.name.clone()).or_insert_with(|| make_layout(&n.name, &label_font)); + } + self.badge_cache + .entry("preserved".to_owned()) + .or_insert_with(|| make_layout("preserved", &tiny_font)); + self.badge_cache + .entry("cycle!".to_owned()) + .or_insert_with(|| make_layout("cycle!", &tiny_font)); + for key in [ + HUD_ROOT, + HUD_GROUP, + "GRAB [LMB/Enter confirm, RMB/Esc cancel, X/Y axis, Shift: Splice]", + "ROTATE [LMB/Enter confirm, RMB/Esc cancel]", + "SCALE [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]", + ] { + self.badge_cache.entry(key.to_owned()).or_insert_with(|| make_layout(key, &badge_font)); + } + } + + pub fn paint<'a>(&'a self, comp: &'a Comp) -> Vec> { + let mut out = Vec::with_capacity(comp.nodes.len() * 10 + 128); + let [w, h] = self.size; + + // 1. Subtle architectural grid aligned to Fusion's 110×33 flow cells + let mult = if self.zoom < 0.35 { 4.0 } else if self.zoom < 0.70 { 2.0 } else { 1.0 }; + let step_x = 110.0 * mult; + let step_y = 33.0 * mult * 2.0; + let tl = self.local_to_world([0.0, 0.0]); + let br = self.local_to_world([w, h]); + let gx0 = (tl[0] / step_x).floor() as i32; + let gx1 = (br[0] / step_x).ceil() as i32; + let gy0 = (tl[1] / step_y).floor() as i32; + let gy1 = (br[1] / step_y).ceil() as i32; + for gx in gx0..=gx1 { + let x = self.world_to_local([gx as f32 * step_x, 0.0])[0]; + let col = if gx % 4 == 0 { self.palette.grid_major } else { self.palette.grid_minor }; + out.push(Primitive::Segment { from: [x, 0.0], to: [x, h], width: 1.0, color: col }); + } + for gy in gy0..=gy1 { + let y = self.world_to_local([0.0, gy as f32 * step_y])[1]; + let col = if gy % 4 == 0 { self.palette.grid_major } else { self.palette.grid_minor }; + out.push(Primitive::Segment { from: [0.0, y], to: [w, y], width: 1.0, color: col }); + } + + // 2. Modal Blender axis-lock guide lines + if let Some(m) = &self.modal { + let piv = self.world_to_local(m.pivot_world); + match m.axis { + AxisLock::X => out.push(Primitive::Segment { + from: [0.0, piv[1]], + to: [w, piv[1]], + width: 1.5, + color: [0.95, 0.28, 0.34, 0.85], + }), + AxisLock::Y => out.push(Primitive::Segment { + from: [piv[0], 0.0], + to: [piv[0], h], + width: 1.5, + color: [0.28, 0.90, 0.42, 0.85], + }), + AxisLock::None => {} + } + } + + // 3. Straight Fusion wires + crisp white output squares (□) + inward-pointing colored input arrows (▶)! + let large_ports = self.zoom >= 0.72; + let tri_len = if large_ports { 6.5 } else { 4.5 }; + let out_half = if large_ports { 2.8 } else { 2.0 }; + let out_gap = if large_ports { 2.2 } else { 1.5 }; + let port_outline = [0.04, 0.04, 0.06, 0.92]; + + for dst in comp.nodes.iter().filter(|n| self.scope.shows(n)) { + // Track used edges on `dst` so multiple inputs on the same edge spread cleanly instead of overlapping + let mut used_edges: HashMap = HashMap::new(); + let mut sorted_ports: Vec<(&String, &model::InputBinding)> = dst.inputs.iter().collect(); + sorted_ports.sort_by_key(|(p, _)| match PortRole::from_input_name(p) { + PortRole::Background => 0u8, + PortRole::Foreground => 1, + PortRole::Mask => 2, + PortRole::Scene3D => 3, + PortRole::Aux => 4, + }); + for (port, binding) in sorted_ports { + let Some(src_name) = &binding.source_op else { continue }; + let Some(src_id) = self.scope.resolve(comp, src_name) else { continue }; + let role = PortRole::from_input_name(port); + let (a, ae, mut b, mut be) = self.wire_endpoints(comp, src_id, dst.id, role); + let ekey = |e: Edge| match e { Edge::Left => 0u8, Edge::Right => 1, Edge::Top => 2, Edge::Bottom => 3 }; + let count = used_edges.entry(ekey(be)).or_insert(0); + if *count > 0 { + // Spread horizontal top/bottom ports (e.g. FG + Mask) like Fusion's ColorCorrector / Merge + let dr = self.node_rect_local(dst.pos); + if matches!(be, Edge::Top | Edge::Bottom) { + let t = if *count == 1 { 0.25 } else { 0.75 }; + b = be.point_on_rect(dr, t); + } else if role == PortRole::Mask { + be = Edge::Bottom; + b = be.point_on_rect(dr, 0.5); + } else { + let t = if *count == 1 { 0.30 } else { 0.70 }; + b = be.point_on_rect(dr, t); + } + } + *count += 1; + + let is_hot = self.hovered_wire.as_ref().is_some_and(|hw| hw.src == src_id && hw.dst == dst.id && hw.port == *port); + let is_sel = self.selected.contains(&src_id) || self.selected.contains(&dst.id); + + let wire_col = if is_hot { + [0.98, 0.82, 0.24, 1.0] + } else if is_sel { + [0.92, 0.94, 0.98, 0.96] + } else { + [0.64, 0.66, 0.72, 0.76] + }; + let width = if is_hot { 2.4 } else if is_sel { 1.6 } else { 1.1 }; + let an = ae.normal(); + let bn = be.normal(); + let op = [a[0] + an[0] * (out_gap + out_half), a[1] + an[1] * (out_gap + out_half)]; + let ip_base = [b[0] + bn[0] * tri_len, b[1] + bn[1] * tri_len]; + + // Straight wire directly from output square center to input triangle base (exact Fusion look!) + out.push(Primitive::Segment { from: op, to: ip_base, width, color: wire_col }); + + if self.zoom >= 0.36 { + // Output port: crisp Fusion white square `□` with thin dark outline + out.push(Primitive::RoundedRect { + rect: [op[0] - out_half, op[1] - out_half, op[0] + out_half, op[1] + out_half], + radius: 0.6, + stroke: None, + color: [0.94, 0.95, 0.98, 0.98], + }); + out.push(Primitive::RoundedRect { + rect: [op[0] - out_half, op[1] - out_half, op[0] + out_half, op[1] + out_half], + radius: 0.6, + stroke: Some(0.9), + color: port_outline, + }); + + // Input port: crisp Fusion colored triangle pointing INTO `dst`! + let pcol = port_color(role); + let tri = input_arrow_svg(be, large_ports); + out.push(Primitive::Path { + data: tri, + origin: b, + style: PathStyle::Fill, + color: pcol, + }); + out.push(Primitive::Path { + data: tri, + origin: b, + style: PathStyle::Stroke(0.9), + color: port_outline, + }); + } + } + } + + // Active wire drag preview (smooth cubic bezier + cycle rejection feedback) + if let Some(wd) = &self.wire_drag { + if wd.src.0 < comp.nodes.len() { + let sr = self.node_rect_local(comp.node(wd.src).pos); + let edge = self.node_output_edge(comp, wd.src); + let a = edge.point_on_rect(sr, 0.5); + let (end, is_cycle, target_role) = match wd.target { + Some((dst, port, cycle)) if dst.0 < comp.nodes.len() => { + let role = PortRole::from_input_name(port); + let (_, _, b, _) = self.wire_endpoints(comp, wd.src, dst, role); + (b, cycle, Some(role)) + } + _ => (wd.cursor_local, false, None), + }; + let wire_col = if is_cycle { + [0.96, 0.30, 0.34, 1.0] + } else if let Some(role) = target_role { + port_color(role) + } else { + [0.98, 0.84, 0.30, 1.0] + }; + let pts = sample_preview_bezier(a, edge.normal(), end, 16); + for seg in pts.windows(2) { + out.push(Primitive::Segment { + from: seg[0], + to: seg[1], + width: if is_cycle { 2.4 } else { 2.0 }, + color: wire_col, + }); + } + if is_cycle { + if let Some(badge) = self.badge_cache.get("cycle!") { + let bx = end[0] + 8.0; + let by = end[1] - 14.0; + out.push(Primitive::RoundedRect { + rect: [bx, by, bx + 36.0, by + 13.0], + radius: 3.0, + stroke: None, + color: [0.30, 0.06, 0.08, 0.94], + }); + out.push(Primitive::RoundedRect { + rect: [bx, by, bx + 36.0, by + 13.0], + radius: 3.0, + stroke: Some(1.0), + color: [0.96, 0.30, 0.34, 0.95], + }); + out.push(Primitive::Text { + text: badge as &dyn Glyphs, + origin: [bx + 5.0, by + 2.0], + clip: Some([bx, by, bx + 36.0, by + 13.0]), + ink: [1.0, 0.65, 0.65, 1.0], + }); + } + } + } + } + + // 4. Sleek Thin Fusion-Style Node Bars (color line along BOTTOM!) + for n in comp.nodes.iter().filter(|n| self.scope.shows(n)) { + let r = self.node_rect_local(n.pos); + if r[2] < -20.0 || r[0] > w + 20.0 || r[3] < -20.0 || r[1] > h + 20.0 { + continue; + } + let sel = self.selected.contains(&n.id); + let primary = self.primary == Some(n.id); + let hovered = self.hovered_node == Some(n.id); + let v1 = self.viewed_nodes[0] == Some(n.id); + let v2 = self.viewed_nodes[1] == Some(n.id); + let supported = is_supported_tool(&n.kind); + let accent = if supported { + node_accent(&n.kind) + } else { + [0.92, 0.64, 0.24, 1.0] + }; + + let bg = if n.bypassed { + [self.palette.node_fill[0] * 0.6, self.palette.node_fill[1] * 0.6, self.palette.node_fill[2] * 0.6, 0.65] + } else if sel { + self.palette.node_selected + } else if hovered { + self.palette.node_hover + } else if !supported { + [ + (self.palette.node_fill[0] + 0.035).min(1.0), + (self.palette.node_fill[1] + 0.020).min(1.0), + self.palette.node_fill[2], + 1.0, + ] + } else { + self.palette.node_fill + }; + + let radius = (3.5 * self.zoom).clamp(1.5, 5.0); + out.push(Primitive::RoundedRect { rect: r, radius, stroke: None, color: bg }); + + // Bottom category color line (exact Fusion look — thin sleek strip on bottom edge!) + let bar_h = (2.6 * self.zoom).clamp(1.4, 3.4); + out.push(Primitive::Rect { + rect: [r[0] + 1.5, (r[3] - bar_h).max(r[1]), r[2] - 1.5, r[3]], + color: if n.bypassed { [0.28, 0.28, 0.32, 0.6] } else { accent }, + }); + + // Crisp border (amber accent for preserved/passthrough unknown nodes) + let border_col = if primary { + [0.98, 0.78, 0.30, 1.0] + } else if sel { + self.palette.accent + } else if !supported { + [0.92, 0.64, 0.24, 0.85] + } else { + self.palette.node_border + }; + out.push(Primitive::RoundedRect { + rect: r, + radius, + stroke: Some(if sel || primary { 1.4 } else if !supported { 1.15 } else { 0.9 }), + color: border_col, + }); + // Subtle top dashed ticks for preserved/passthrough unknown nodes + if !supported && self.zoom >= 0.45 { + let mut tx = r[0] + 5.0; + while tx + 4.0 < r[2] - 4.0 { + out.push(Primitive::Segment { + from: [tx, r[1] + 0.8], + to: [(tx + 4.0).min(r[2] - 4.0), r[1] + 0.8], + width: 1.2, + color: [0.96, 0.72, 0.30, 0.90], + }); + tx += 8.0; + } + } + + // Node label centered cleanly inside thin bar + if self.zoom >= 0.42 { + if let Some(layout) = self.label_cache.get(&n.name) { + let ink = if n.bypassed { self.palette.text_dim } else { self.palette.text }; + let pad_x = (6.0 * self.zoom).clamp(3.0, 8.0); + let text_y = (r[1] + r[3] - bar_h) * 0.5 - 6.0; + out.push(Primitive::Text { + text: layout as &dyn Glyphs, + origin: [r[0] + pad_x, text_y], + clip: Some([r[0] + pad_x, r[1] + 1.0, r[2] - 4.0, r[3] - bar_h]), + ink, + }); + } + } + + // Preserved/passthrough pill badge underneath bottom-right for unknown/OFX nodes + if !supported && self.zoom >= 0.50 { + if let Some(badge) = self.badge_cache.get("preserved") { + let bw = 46.0; + let bh = 10.5; + let bx = (r[2] - bw).max(r[0] + 28.0); + let by = r[3] + 1.5; + out.push(Primitive::RoundedRect { + rect: [bx, by, bx + bw, by + bh], + radius: 3.0, + stroke: None, + color: [0.14, 0.10, 0.05, 0.92], + }); + out.push(Primitive::RoundedRect { + rect: [bx, by, bx + bw, by + bh], + radius: 3.0, + stroke: Some(0.8), + color: [0.92, 0.64, 0.24, 0.72], + }); + out.push(Primitive::Text { + text: badge as &dyn Glyphs, + origin: [bx + 4.0, by + 1.0], + clip: Some([bx + 2.0, by, bx + bw - 2.0, by + bh]), + ink: [0.98, 0.78, 0.40, 1.0], + }); + } + } + + // Fusion-style tiny viewer indicator pill underneath bottom-left (`● ○` for Viewer 1 / Viewer 2!) + if v1 || v2 { + let pw = 22.0; + let ph = 9.0; + let px = r[0] + 4.0; + let py = r[3] + 1.5; + out.push(Primitive::RoundedRect { + rect: [px, py, px + pw, py + ph], + radius: 3.0, + stroke: None, + color: [0.02, 0.02, 0.03, 0.92], + }); + let d1 = if v1 { [0.24, 0.90, 0.82, 1.0] } else { [0.26, 0.28, 0.34, 0.6] }; + let d2 = if v2 { [0.98, 0.68, 0.28, 1.0] } else { [0.26, 0.28, 0.34, 0.6] }; + out.push(Primitive::RoundedRect { + rect: [px + 3.5, py + 2.0, px + 8.5, py + 7.0], + radius: 2.5, + stroke: None, + color: d1, + }); + out.push(Primitive::RoundedRect { + rect: [px + 13.0, py + 2.0, px + 18.0, py + 7.0], + radius: 2.5, + stroke: None, + color: d2, + }); + } + + if n.bypassed { + let ym = (r[1] + r[3]) * 0.5; + out.push(Primitive::Segment { + from: [r[0] + 3.0, ym], + to: [r[2] - 3.0, ym], + width: 1.4, + color: [0.95, 0.35, 0.35, 0.85], + }); + } + } + + // 5. Box select marquee + if let Some(bs) = &self.box_select { + let x0 = bs.start_local[0].min(bs.cur_local[0]); + let x1 = bs.start_local[0].max(bs.cur_local[0]); + let y0 = bs.start_local[1].min(bs.cur_local[1]); + let y1 = bs.start_local[1].max(bs.cur_local[1]); + out.push(Primitive::RoundedRect { + rect: [x0, y0, x1, y1], + radius: 2.0, + stroke: None, + color: [self.palette.accent[0], self.palette.accent[1], self.palette.accent[2], 0.16], + }); + out.push(Primitive::RoundedRect { + rect: [x0, y0, x1, y1], + radius: 2.0, + stroke: Some(1.2), + color: self.palette.accent, + }); + } + + // 6. Status HUD strip + let hud_key = match self.modal.as_ref().map(|m| m.mode) { + Some(TransformMode::Grab) => "GRAB [LMB/Enter confirm, RMB/Esc cancel, X/Y axis, Shift: Splice]", + Some(TransformMode::Rotate) => "ROTATE [LMB/Enter confirm, RMB/Esc cancel]", + Some(TransformMode::Scale) => "SCALE [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]", + None if !self.scope.is_root() => HUD_GROUP, + None => HUD_ROOT, + }; + if let Some(l) = self.badge_cache.get(hud_key) { + let pill_h = 20.0; + out.push(Primitive::RoundedRect { + rect: [8.0, h - pill_h - 6.0, w - 8.0, h - 6.0], + radius: 4.0, + stroke: None, + color: [self.palette.bg[0] * 0.75, self.palette.bg[1] * 0.75, self.palette.bg[2] * 0.75, 0.86], + }); + out.push(Primitive::Text { + text: l as &dyn Glyphs, + origin: [14.0, h - pill_h - 2.5], + clip: Some([12.0, h - pill_h - 6.0, w - 12.0, h - 6.0]), + ink: if self.modal.is_some() { [0.98, 0.82, 0.30, 1.0] } else { self.palette.text_dim }, + }); + } + + out + } +} + +/// Static SVG triangles pointing INTO the node edge (`origin` sits flush on the node border). +fn input_arrow_svg(edge: Edge, large: bool) -> &'static str { + match (edge, large) { + (Edge::Left, true) => "M 0 0 L -6.5 -3.6 L -6.5 3.6 Z", + (Edge::Left, false) => "M 0 0 L -4.5 -2.6 L -4.5 2.6 Z", + (Edge::Right, true) => "M 0 0 L 6.5 -3.6 L 6.5 3.6 Z", + (Edge::Right, false) => "M 0 0 L 4.5 -2.6 L 4.5 2.6 Z", + (Edge::Top, true) => "M 0 0 L -3.6 -6.5 L 3.6 -6.5 Z", + (Edge::Top, false) => "M 0 0 L -2.6 -4.5 L 2.6 -4.5 Z", + (Edge::Bottom, true) => "M 0 0 L -3.6 6.5 L 3.6 6.5 Z", + (Edge::Bottom, false) => "M 0 0 L -2.6 4.5 L 2.6 4.5 Z", + } +} + +fn port_color(role: PortRole) -> [f32; 4] { + match role { + PortRole::Background => [0.94, 0.76, 0.26, 1.0], // Fusion gold + PortRole::Foreground => [0.34, 0.86, 0.46, 1.0], // Fusion green + PortRole::Mask => [0.32, 0.64, 0.98, 1.0], // Fusion blue + PortRole::Scene3D => [0.30, 0.86, 0.90, 1.0], // Cyan + PortRole::Aux => [0.74, 0.58, 0.90, 1.0], // Violet + } +} + +fn node_accent(kind: &str) -> [f32; 4] { + match kind { + "Loader" | "Saver" => [0.32, 0.72, 0.92, 1.0], + "Merge" | "Switch" | "Fuse.Switch" => [0.58, 0.60, 0.66, 1.0], + "Background" | "FastNoise" => [0.36, 0.80, 0.42, 1.0], + "TextPlus" | "Text3D" => [0.34, 0.86, 0.54, 1.0], + "ColorCorrector" | "BrightnessContrast" | "ColorCurves" | "HueCurves" | "LumaKeyer" | "UltraKeyer" => { + [0.92, 0.58, 0.22, 1.0] + } + "Blur" | "DirectionalBlur" | "Glow" | "SoftGlow" | "Displace" | "ErodeDilate" => { + [0.92, 0.52, 0.24, 1.0] + } + "Transform" | "Scale" | "Crop" | "TimeStretcher" | "TimeSpeed" => [0.84, 0.66, 0.28, 1.0], + "EllipseMask" | "RectangleMask" | "PolylineMask" | "BitmapMask" => [0.32, 0.62, 0.98, 1.0], + k if k.starts_with("Fuse.") => [0.88, 0.44, 0.76, 1.0], + _ => [0.54, 0.54, 0.60, 1.0], + } +} diff --git a/crates/viewer/src/clock.rs b/crates/viewer/src/clock.rs new file mode 100644 index 0000000000000000000000000000000000000000..35e6a493b76fecda8e359c3ddd132bf76d21d2fc --- /dev/null +++ b/crates/viewer/src/clock.rs @@ -0,0 +1,440 @@ +use model::Comp; +use std::time::{Duration, Instant}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SyncMode { + /// Wall/audio clock master: skips frames to hold real-time FPS. + RealtimeDrop, + /// Steps exactly +1 integer frame, throttled so it never runs faster than `comp.fps`. + EveryFrame, +} + +/// Outcome of advancing [`PlaybackClock::tick_synced`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct TickResult { + pub playing: bool, + pub frame_changed: bool, + pub looped: bool, +} + +/// Shared timeline & playback clock shared across all open viewers (Viewer 1, Viewer 2, Spline). +pub struct PlaybackClock { + pub current_frame: f64, + pub playing: bool, + pub sync_mode: SyncMode, + /// Optional user-defined preview/export `[in, out]` frame markers (inclusive). + pub in_out_range: [Option; 2], + anchor_time: Instant, + anchor_frame: f64, + last_every_step: Instant, +} + +impl Default for PlaybackClock { + fn default() -> Self { + Self::new() + } +} + +impl PlaybackClock { + pub fn new() -> Self { + let now = Instant::now(); + Self { + current_frame: 0.0, + playing: false, + sync_mode: SyncMode::RealtimeDrop, + in_out_range: [None, None], + anchor_time: now, + anchor_frame: 0.0, + last_every_step: now, + } + } + + pub fn init_from_comp(&mut self, comp: &Comp) { + let cur = comp.current_time.round(); + let r0 = comp.render_range[0] as f64; + let r1 = comp.render_range[1] as f64; + self.current_frame = if cur >= r0 && cur <= r1 { cur } else { r0 }; + self.in_out_range = [None, None]; + self.anchor_frame = self.current_frame; + self.anchor_time = Instant::now(); + self.last_every_step = self.anchor_time; + } + + /// Returns the active inclusive preview/export range `[in.unwrap_or(r0), out.unwrap_or(r1)]`, + /// clamped to `comp.render_range` and sorted ascending. + pub fn effective_preview_range(&self, comp: &Comp) -> [i64; 2] { + let r0 = comp.render_range[0]; + let r1 = comp.render_range[1].max(r0); + let a = self.in_out_range[0].unwrap_or(r0).clamp(r0, r1); + let b = self.in_out_range[1].unwrap_or(r1).clamp(r0, r1); + if a <= b { [a, b] } else { [b, a] } + } + + pub fn set_in_point(&mut self, comp: &Comp) { + let r0 = comp.render_range[0]; + let r1 = comp.render_range[1].max(r0); + let f = (self.current_frame.round() as i64).clamp(r0, r1); + self.in_out_range[0] = Some(f); + if self.playing { + let [p0, p1] = self.effective_preview_range(comp); + if self.current_frame < p0 as f64 || self.current_frame > p1 as f64 { + self.current_frame = p0 as f64; + } + let now = Instant::now(); + self.anchor_time = now; + self.anchor_frame = self.current_frame; + self.last_every_step = now; + } + } + + pub fn set_out_point(&mut self, comp: &Comp) { + let r0 = comp.render_range[0]; + let r1 = comp.render_range[1].max(r0); + let f = (self.current_frame.round() as i64).clamp(r0, r1); + self.in_out_range[1] = Some(f); + if self.playing { + let [p0, p1] = self.effective_preview_range(comp); + if self.current_frame < p0 as f64 || self.current_frame > p1 as f64 { + self.current_frame = p0 as f64; + } + let now = Instant::now(); + self.anchor_time = now; + self.anchor_frame = self.current_frame; + self.last_every_step = now; + } + } + + pub fn clear_in_out(&mut self) { + self.in_out_range = [None, None]; + if self.playing { + let now = Instant::now(); + self.anchor_time = now; + self.anchor_frame = self.current_frame; + self.last_every_step = now; + } + } + + /// Exact audio track timestamp (in seconds) for `frame` under `comp.fps` and `comp.audio_offset`. + pub fn audio_time_for_frame(comp: &Comp, frame: f64) -> f64 { + (frame - comp.audio_offset) / comp.fps.max(1.0) + } + + /// Exact audio track timestamp (in seconds) for the current playhead frame. + pub fn audio_target_secs(&self, comp: &Comp) -> f64 { + Self::audio_time_for_frame(comp, self.current_frame) + } + + /// Expected live audio playback timestamp (in seconds) at wall-clock `now`. + /// + /// In `RealtimeDrop`, tracks continuous wall-clock frame progress across the preview range. + /// In `EveryFrame`, bounds sub-frame progress to `[0, 1/fps]` so slow frame renders do not + /// let the audio stream drift ahead of the displayed frame. + pub fn expected_audio_secs(&self, comp: &Comp, now: Instant) -> f64 { + let fps = comp.fps.max(1.0); + if !self.playing { + return Self::audio_time_for_frame(comp, self.current_frame); + } + match self.sync_mode { + SyncMode::RealtimeDrop => { + let [p0, p1] = self.effective_preview_range(comp); + let r0 = p0 as f64; + let r1 = p1.max(p0) as f64; + let span = (r1 - r0 + 1.0).max(1.0); + if span <= 1.0 { + return Self::audio_time_for_frame(comp, r0); + } + let base = if self.anchor_frame < r0 || self.anchor_frame > r1 { + r0 + } else { + self.anchor_frame + }; + let elapsed = now.saturating_duration_since(self.anchor_time).as_secs_f64(); + let continuous = r0 + (base - r0 + elapsed * fps).rem_euclid(span); + Self::audio_time_for_frame(comp, continuous) + } + SyncMode::EveryFrame => { + let frame_dur = 1.0 / fps; + let sub = now + .saturating_duration_since(self.last_every_step) + .as_secs_f64() + .clamp(0.0, frame_dur); + Self::audio_time_for_frame(comp, self.current_frame) + sub + } + } + } + + pub fn set_frame(&mut self, comp: &Comp, frame: f64, now: Instant) -> bool { + let clamped = frame + .round() + .clamp(comp.global_range[0] as f64, comp.global_range[1] as f64); + let changed = (clamped - self.current_frame).abs() > 1e-6; + self.current_frame = clamped; + if self.playing { + self.anchor_time = now; + self.anchor_frame = self.current_frame; + self.last_every_step = now; + } + changed + } + + pub fn toggle_play(&mut self, now: Instant) { + self.playing = !self.playing; + self.anchor_time = now; + self.anchor_frame = self.current_frame; + self.last_every_step = now; + } + + /// Toggles playback and, when starting, snaps playhead into `effective_preview_range(comp)` + /// if it was outside so video and audio start locked on the same frame. + pub fn toggle_play_with_comp(&mut self, comp: &Comp, now: Instant) { + self.playing = !self.playing; + if self.playing { + let [p0, p1] = self.effective_preview_range(comp); + let r0 = p0 as f64; + let r1 = p1.max(p0) as f64; + if self.current_frame < r0 || self.current_frame > r1 { + self.current_frame = r0; + } + } + self.anchor_time = now; + self.anchor_frame = self.current_frame; + self.last_every_step = now; + } + + /// Advances the playback clock; returns `(still_playing, frame_changed)`. + /// In `EveryFrame` mode, throttles to `<= comp.fps` so it never runs faster than realtime! + pub fn tick(&mut self, comp: &Comp, now: Instant) -> (bool, bool) { + let res = self.tick_synced(comp, now); + (res.playing, res.frame_changed) + } + + /// Advances the playback clock and reports frame change plus exact loop wraparound. + pub fn tick_synced(&mut self, comp: &Comp, now: Instant) -> TickResult { + if !self.playing { + return TickResult { + playing: false, + frame_changed: false, + looped: false, + }; + } + let [p0, p1] = self.effective_preview_range(comp); + let r0 = p0 as f64; + let r1 = p1.max(p0) as f64; + let span = (r1 - r0 + 1.0).max(1.0); + let fps = comp.fps.max(1.0); + let frame_dur = Duration::from_secs_f64(1.0 / fps); + + let mut changed = false; + let mut looped = false; + match self.sync_mode { + SyncMode::RealtimeDrop => { + if span <= 1.0 { + if (self.current_frame - r0).abs() >= 1.0 { + self.current_frame = r0; + changed = true; + } + self.anchor_frame = r0; + self.anchor_time = now; + } else { + if self.anchor_frame < r0 || self.anchor_frame > r1 { + self.anchor_frame = r0; + self.anchor_time = now; + if (self.current_frame - r0).abs() >= 1.0 { + self.current_frame = r0; + changed = true; + looped = true; + } + } + let elapsed = now.saturating_duration_since(self.anchor_time).as_secs_f64(); + let adv = (elapsed * fps).floor(); + let raw = (self.anchor_frame - r0) + adv; + let wrapped = raw >= span; + let next = r0 + raw.rem_euclid(span); + if wrapped { + // Keep the sub-frame overshoot so looping never drifts behind the wall clock. + let overshoot = Duration::from_secs_f64((elapsed * fps - adv) / fps); + self.anchor_frame = next; + self.anchor_time = now.checked_sub(overshoot).unwrap_or(now); + looped = true; + } + if (next - self.current_frame).abs() >= 1.0 { + self.current_frame = next; + changed = true; + } + } + } + SyncMode::EveryFrame => { + let elapsed = now.saturating_duration_since(self.last_every_step); + if elapsed >= frame_dur { + let out_or_end = self.current_frame + 1.0 > r1 || self.current_frame < r0; + let next = if out_or_end { + if span > 1.0 { + looped = true; + } + r0 + } else { + self.current_frame + 1.0 + }; + if (next - self.current_frame).abs() >= 1.0 { + changed = true; + } + self.current_frame = next; + // Preserve exact cadence under minor timer jitter while avoiding catch-up bursts after stalls. + if elapsed < frame_dur.mul_f64(2.0) { + self.last_every_step += frame_dur; + } else { + self.last_every_step = now; + } + } + } + } + TickResult { + playing: true, + frame_changed: changed, + looped, + } + } + + pub fn next_wake(&self, comp: &Comp) -> Duration { + let fps = comp.fps.max(1.0); + Duration::from_secs_f64((0.5 / fps).min(0.016)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::test_comp; + + #[test] + fn effective_preview_range_sorts_and_clamps() { + let comp = test_comp(); + let mut clock = PlaybackClock::new(); + clock.init_from_comp(&comp); + assert_eq!(clock.effective_preview_range(&comp), [10, 50]); + + clock.in_out_range = [Some(20), None]; + assert_eq!(clock.effective_preview_range(&comp), [20, 50]); + + clock.in_out_range = [None, Some(30)]; + assert_eq!(clock.effective_preview_range(&comp), [10, 30]); + + // Reversed and out-of-bounds points get clamped and sorted cleanly + clock.in_out_range = [Some(99), Some(2)]; + assert_eq!(clock.effective_preview_range(&comp), [10, 50]); + + clock.in_out_range = [Some(35), Some(18)]; + assert_eq!(clock.effective_preview_range(&comp), [18, 35]); + } + + #[test] + fn playback_clock_in_out_wraparound_realtime_and_every_frame() { + let comp = test_comp(); // fps = 30, render_range = [10, 50] + let t0 = Instant::now(); + + // RealtimeDrop: starting outside [20, 24] snaps cleanly to 20, then wraps 24 -> 20 + let mut rt = PlaybackClock::new(); + rt.init_from_comp(&comp); + rt.in_out_range = [Some(20), Some(24)]; + rt.set_frame(&comp, 12.0, t0); // outside In/Out range + rt.toggle_play_with_comp(&comp, t0); + assert_eq!(rt.current_frame, 20.0); + + let step = Duration::from_secs_f64(1.0 / 30.0); + // Advance 4 frames -> frame 24 (last frame in [20..=24]) + let r4 = rt.tick_synced(&comp, t0 + step * 4 + Duration::from_millis(2)); + assert!(r4.playing); + assert!(r4.frame_changed); + assert!(!r4.looped); + assert_eq!(rt.current_frame, 24.0); + + // Advance 5th frame -> wraps cleanly back to 20 and reports looped = true + let r5 = rt.tick_synced(&comp, t0 + step * 5 + Duration::from_millis(2)); + assert!(r5.playing); + assert!(r5.frame_changed); + assert!(r5.looped); + assert_eq!(rt.current_frame, 20.0); + + // Next frame after wrap advances from 20 -> 21 without double-looping + let r6 = rt.tick_synced(&comp, t0 + step * 6 + Duration::from_millis(4)); + assert!(r6.frame_changed); + assert!(!r6.looped); + assert_eq!(rt.current_frame, 21.0); + + // EveryFrame: steps +1 per >=1/fps, preserves cadence across minor jitter, wraps 22 -> 20 + let mut ef = PlaybackClock::new(); + ef.init_from_comp(&comp); + ef.sync_mode = SyncMode::EveryFrame; + ef.in_out_range = [Some(20), Some(22)]; + ef.set_frame(&comp, 20.0, t0); + ef.toggle_play_with_comp(&comp, t0); + + // Minor 4ms jitter on step 1 + let e1 = ef.tick_synced(&comp, t0 + step + Duration::from_millis(4)); + assert_eq!((e1.frame_changed, e1.looped, ef.current_frame), (true, false, 21.0)); + // Step 2 fires at t0 + 2*step (doesn't lose the 4ms jitter!) + let e2 = ef.tick_synced(&comp, t0 + step * 2 + Duration::from_millis(1)); + assert_eq!((e2.frame_changed, e2.looped, ef.current_frame), (true, false, 22.0)); + // Step 3 wraps 22 -> 20 with looped = true + let e3 = ef.tick_synced(&comp, t0 + step * 3 + Duration::from_millis(1)); + assert_eq!((e3.frame_changed, e3.looped, ef.current_frame), (true, true, 20.0)); + } + + #[test] + fn audio_sync_target_time_computation() { + let mut comp = test_comp(); + comp.fps = 24.0; + comp.audio_offset = 12.0; + + let t0 = Instant::now(); + let mut clock = PlaybackClock::new(); + clock.init_from_comp(&comp); + clock.in_out_range = [Some(12), Some(36)]; + clock.set_frame(&comp, 0.0, t0); + assert!((clock.audio_target_secs(&comp) - (-0.5)).abs() < 1e-9); + + clock.set_frame(&comp, 12.0, t0); + assert!((clock.audio_target_secs(&comp) - 0.0).abs() < 1e-9); + + clock.set_frame(&comp, 36.0, t0); + assert!((clock.audio_target_secs(&comp) - 1.0).abs() < 1e-9); + + // RealtimeDrop expected_audio_secs tracks continuous sub-frame progress & wraparound + clock.set_frame(&comp, 24.0, t0); + clock.toggle_play_with_comp(&comp, t0); + let half_sec = Duration::from_millis(500); + let exp_rt = clock.expected_audio_secs(&comp, t0 + half_sec); + assert!((exp_rt - 1.0).abs() < 1e-6, "expected 1.0s at frame 36, got {exp_rt}"); + + // EveryFrame expected_audio_secs caps sub-frame progress at 1/fps when a frame stalls + clock.sync_mode = SyncMode::EveryFrame; + clock.set_frame(&comp, 24.0, t0); // expected base = (24 - 12) / 24 = 0.5s + let exp_stalled = clock.expected_audio_secs(&comp, t0 + Duration::from_millis(400)); + let max_expected = 0.5 + (1.0 / 24.0); + assert!( + (exp_stalled - max_expected).abs() < 1e-6, + "EveryFrame stalled expected_audio_secs should cap at {max_expected}, got {exp_stalled}" + ); + } + + #[test] + fn loop_wraparound_keeps_the_sub_frame_overshoot() { + let comp = test_comp(); // 30 fps + let t0 = Instant::now(); + let step = Duration::from_secs_f64(1.0 / 30.0); + let mut clock = PlaybackClock::new(); + clock.init_from_comp(&comp); + clock.in_out_range = [Some(20), Some(24)]; + clock.set_frame(&comp, 20.0, t0); + clock.toggle_play_with_comp(&comp, t0); + + // Wrap with half a frame of overshoot... + let wrap = clock.tick_synced(&comp, t0 + step.mul_f64(5.5)); + assert!(wrap.looped); + assert_eq!(clock.current_frame, 20.0); + // ...so 0.6 frames later a whole frame has elapsed on the original timeline. + let next = clock.tick_synced(&comp, t0 + step.mul_f64(6.1)); + assert!(!next.looped); + assert_eq!(clock.current_frame, 21.0); + } +} diff --git a/crates/viewer/src/lib.rs b/crates/viewer/src/lib.rs index f753d89705f4d1045e34ba2f408c8f313765a355..eff7211383fc3b415c2d7fcd4d4b7349e12e9140 100644 --- a/crates/viewer/src/lib.rs +++ b/crates/viewer/src/lib.rs @@ -6,8 +6,11 @@ //! - Proxy scaling (1:1, 1:2, 1:4) with identical framing & proportions //! - Surgical cache-busting controls + live GPU telemetry + `Cmd+F` / Numpad `.` fit-to-view. +mod clock; pub mod gizmos; +mod paint; +pub use clock::{PlaybackClock, SyncMode, TickResult}; pub use gizmos::{GizmoEdit, GizmoHandle, GizmoState}; use draw::{Glyphs, Primitive, RasterImage}; @@ -15,310 +18,9 @@ use engine::{CacheMode, DisplaySettings, Engine, EvalStats, RamFrameCache, RamFr use model::{Comp, NodeId}; use std::collections::HashSet; use std::sync::Arc; -use std::time::{Duration, Instant}; use winit::event::{ElementState, MouseButton}; use winit::keyboard::{Key, KeyCode, ModifiersState, NamedKey, PhysicalKey}; -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum SyncMode { - /// Wall/audio clock master: skips frames to hold real-time FPS. - RealtimeDrop, - /// Steps exactly +1 integer frame, throttled so it never runs faster than `comp.fps`. - EveryFrame, -} - -/// Outcome of advancing [`PlaybackClock::tick_synced`]. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct TickResult { - pub playing: bool, - pub frame_changed: bool, - pub looped: bool, -} - -/// Shared timeline & playback clock shared across all open viewers (Viewer 1, Viewer 2, Spline). -pub struct PlaybackClock { - pub current_frame: f64, - pub playing: bool, - pub sync_mode: SyncMode, - /// Optional user-defined preview/export `[in, out]` frame markers (inclusive). - pub in_out_range: [Option; 2], - anchor_time: Instant, - anchor_frame: f64, - last_every_step: Instant, -} - -impl Default for PlaybackClock { - fn default() -> Self { - Self::new() - } -} - -impl PlaybackClock { - pub fn new() -> Self { - let now = Instant::now(); - Self { - current_frame: 0.0, - playing: false, - sync_mode: SyncMode::RealtimeDrop, - in_out_range: [None, None], - anchor_time: now, - anchor_frame: 0.0, - last_every_step: now, - } - } - - pub fn init_from_comp(&mut self, comp: &Comp) { - let cur = comp.current_time.round(); - let r0 = comp.render_range[0] as f64; - let r1 = comp.render_range[1] as f64; - self.current_frame = if cur >= r0 && cur <= r1 { cur } else { r0 }; - self.in_out_range = [None, None]; - self.anchor_frame = self.current_frame; - self.anchor_time = Instant::now(); - self.last_every_step = self.anchor_time; - } - - /// Returns the active inclusive preview/export range `[in.unwrap_or(r0), out.unwrap_or(r1)]`, - /// clamped to `comp.render_range` and sorted ascending. - pub fn effective_preview_range(&self, comp: &Comp) -> [i64; 2] { - let r0 = comp.render_range[0]; - let r1 = comp.render_range[1].max(r0); - let a = self.in_out_range[0].unwrap_or(r0).clamp(r0, r1); - let b = self.in_out_range[1].unwrap_or(r1).clamp(r0, r1); - if a <= b { [a, b] } else { [b, a] } - } - - pub fn set_in_point(&mut self, comp: &Comp) { - let r0 = comp.render_range[0]; - let r1 = comp.render_range[1].max(r0); - let f = (self.current_frame.round() as i64).clamp(r0, r1); - self.in_out_range[0] = Some(f); - if self.playing { - let [p0, p1] = self.effective_preview_range(comp); - if self.current_frame < p0 as f64 || self.current_frame > p1 as f64 { - self.current_frame = p0 as f64; - } - let now = Instant::now(); - self.anchor_time = now; - self.anchor_frame = self.current_frame; - self.last_every_step = now; - } - } - - pub fn set_out_point(&mut self, comp: &Comp) { - let r0 = comp.render_range[0]; - let r1 = comp.render_range[1].max(r0); - let f = (self.current_frame.round() as i64).clamp(r0, r1); - self.in_out_range[1] = Some(f); - if self.playing { - let [p0, p1] = self.effective_preview_range(comp); - if self.current_frame < p0 as f64 || self.current_frame > p1 as f64 { - self.current_frame = p0 as f64; - } - let now = Instant::now(); - self.anchor_time = now; - self.anchor_frame = self.current_frame; - self.last_every_step = now; - } - } - - pub fn clear_in_out(&mut self) { - self.in_out_range = [None, None]; - if self.playing { - let now = Instant::now(); - self.anchor_time = now; - self.anchor_frame = self.current_frame; - self.last_every_step = now; - } - } - - /// Exact audio track timestamp (in seconds) for `frame` under `comp.fps` and `comp.audio_offset`. - pub fn audio_time_for_frame(comp: &Comp, frame: f64) -> f64 { - (frame - comp.audio_offset) / comp.fps.max(1.0) - } - - /// Exact audio track timestamp (in seconds) for the current playhead frame. - pub fn audio_target_secs(&self, comp: &Comp) -> f64 { - Self::audio_time_for_frame(comp, self.current_frame) - } - - /// Expected live audio playback timestamp (in seconds) at wall-clock `now`. - /// - /// In `RealtimeDrop`, tracks continuous wall-clock frame progress across the preview range. - /// In `EveryFrame`, bounds sub-frame progress to `[0, 1/fps]` so slow frame renders do not - /// let the audio stream drift ahead of the displayed frame. - pub fn expected_audio_secs(&self, comp: &Comp, now: Instant) -> f64 { - let fps = comp.fps.max(1.0); - if !self.playing { - return Self::audio_time_for_frame(comp, self.current_frame); - } - match self.sync_mode { - SyncMode::RealtimeDrop => { - let [p0, p1] = self.effective_preview_range(comp); - let r0 = p0 as f64; - let r1 = p1.max(p0) as f64; - let span = (r1 - r0 + 1.0).max(1.0); - if span <= 1.0 { - return Self::audio_time_for_frame(comp, r0); - } - let base = if self.anchor_frame < r0 || self.anchor_frame > r1 { - r0 - } else { - self.anchor_frame - }; - let elapsed = now.saturating_duration_since(self.anchor_time).as_secs_f64(); - let continuous = r0 + (base - r0 + elapsed * fps).rem_euclid(span); - Self::audio_time_for_frame(comp, continuous) - } - SyncMode::EveryFrame => { - let frame_dur = 1.0 / fps; - let sub = now - .saturating_duration_since(self.last_every_step) - .as_secs_f64() - .clamp(0.0, frame_dur); - Self::audio_time_for_frame(comp, self.current_frame) + sub - } - } - } - - pub fn set_frame(&mut self, comp: &Comp, frame: f64, now: Instant) -> bool { - let clamped = frame - .round() - .clamp(comp.global_range[0] as f64, comp.global_range[1] as f64); - let changed = (clamped - self.current_frame).abs() > 1e-6; - self.current_frame = clamped; - if self.playing { - self.anchor_time = now; - self.anchor_frame = self.current_frame; - self.last_every_step = now; - } - changed - } - - pub fn toggle_play(&mut self, now: Instant) { - self.playing = !self.playing; - self.anchor_time = now; - self.anchor_frame = self.current_frame; - self.last_every_step = now; - } - - /// Toggles playback and, when starting, snaps playhead into `effective_preview_range(comp)` - /// if it was outside so video and audio start locked on the same frame. - pub fn toggle_play_with_comp(&mut self, comp: &Comp, now: Instant) { - self.playing = !self.playing; - if self.playing { - let [p0, p1] = self.effective_preview_range(comp); - let r0 = p0 as f64; - let r1 = p1.max(p0) as f64; - if self.current_frame < r0 || self.current_frame > r1 { - self.current_frame = r0; - } - } - self.anchor_time = now; - self.anchor_frame = self.current_frame; - self.last_every_step = now; - } - - /// Advances the playback clock; returns `(still_playing, frame_changed)`. - /// In `EveryFrame` mode, throttles to `<= comp.fps` so it never runs faster than realtime! - pub fn tick(&mut self, comp: &Comp, now: Instant) -> (bool, bool) { - let res = self.tick_synced(comp, now); - (res.playing, res.frame_changed) - } - - /// Advances the playback clock and reports frame change plus exact loop wraparound. - pub fn tick_synced(&mut self, comp: &Comp, now: Instant) -> TickResult { - if !self.playing { - return TickResult { - playing: false, - frame_changed: false, - looped: false, - }; - } - let [p0, p1] = self.effective_preview_range(comp); - let r0 = p0 as f64; - let r1 = p1.max(p0) as f64; - let span = (r1 - r0 + 1.0).max(1.0); - let fps = comp.fps.max(1.0); - let frame_dur = Duration::from_secs_f64(1.0 / fps); - - let mut changed = false; - let mut looped = false; - match self.sync_mode { - SyncMode::RealtimeDrop => { - if span <= 1.0 { - if (self.current_frame - r0).abs() >= 1.0 { - self.current_frame = r0; - changed = true; - } - self.anchor_frame = r0; - self.anchor_time = now; - } else { - if self.anchor_frame < r0 || self.anchor_frame > r1 { - self.anchor_frame = r0; - self.anchor_time = now; - if (self.current_frame - r0).abs() >= 1.0 { - self.current_frame = r0; - changed = true; - looped = true; - } - } - let elapsed = now.saturating_duration_since(self.anchor_time).as_secs_f64(); - let adv = (elapsed * fps).floor(); - let raw = (self.anchor_frame - r0) + adv; - let wrapped = raw >= span; - let next = r0 + raw.rem_euclid(span); - if wrapped { - // Keep the sub-frame overshoot so looping never drifts behind the wall clock. - let overshoot = Duration::from_secs_f64((elapsed * fps - adv) / fps); - self.anchor_frame = next; - self.anchor_time = now.checked_sub(overshoot).unwrap_or(now); - looped = true; - } - if (next - self.current_frame).abs() >= 1.0 { - self.current_frame = next; - changed = true; - } - } - } - SyncMode::EveryFrame => { - let elapsed = now.saturating_duration_since(self.last_every_step); - if elapsed >= frame_dur { - let out_or_end = self.current_frame + 1.0 > r1 || self.current_frame < r0; - let next = if out_or_end { - if span > 1.0 { - looped = true; - } - r0 - } else { - self.current_frame + 1.0 - }; - if (next - self.current_frame).abs() >= 1.0 { - changed = true; - } - self.current_frame = next; - // Preserve exact cadence under minor timer jitter while avoiding catch-up bursts after stalls. - if elapsed < frame_dur.mul_f64(2.0) { - self.last_every_step += frame_dur; - } else { - self.last_every_step = now; - } - } - } - } - TickResult { - playing: true, - frame_changed: changed, - looped, - } - } - - pub fn next_wake(&self, comp: &Comp) -> Duration { - let fps = comp.fps.max(1.0); - Duration::from_secs_f64((0.5 / fps).min(0.016)) - } -} - pub enum ViewerAction { TogglePlay, SetFrame(f64), @@ -648,230 +350,6 @@ impl ViewerState { } } - pub fn prepare_hud(&mut self, comp: &Comp, engine: &Engine, clock: &PlaybackClock) { - self.in_out_range = clock.in_out_range; - let node_name = self - .viewed_node - .and_then(|id| comp.nodes.get(id.0)) - .map_or("(empty)", |n| n.name.as_str()); - let cache_lbl = match engine.cache.mode { - CacheMode::Enabled => "CACHE", - CacheMode::Bypass => "BYPASS", - }; - let sync_lbl = match clock.sync_mode { - SyncMode::RealtimeDrop => "RT", - SyncMode::EveryFrame => "EVERY", - }; - let hiq_lbl = if engine.hiq { "HiQ" } else { "FAST" }; - let (_, _, _, eff_scale) = self.image_layout(comp); - let zoom_pct = (eff_scale * 100.0).round() as i32; - let s = &self.last_stats; - let io_suffix = if clock.in_out_range[0].is_some() || clock.in_out_range[1].is_some() { - let [a, b] = clock.effective_preview_range(comp); - format!(" · [{a}..{b}]") - } else { - String::new() - }; - let line = format!( - "[V{}] {} · f{}{} · {}% · {:.1}ms · ev:{} h:{} m:{} · {:.0}MB · 1:{} · {} · {} · {}", - self.slot + 1, - node_name, - clock.current_frame.round() as i64, - io_suffix, - zoom_pct, - s.eval_ms, - s.nodes_evaluated, - s.cache_hits, - s.cache_misses, - s.cached_vram_mb, - engine.proxy_scale, - hiq_lbl, - cache_lbl, - sync_lbl, - ); - if self.hud_layout.as_ref().is_none_or(|(prev, _)| prev != &line) { - let font = text::Font { - families: Arc::from([text::Family::Mono]), - size: 10.5, - weight: 500, - italic: false, - }; - let styles = [text::Style::new(font)]; - let layout = text::Paragraph { - text: &line, - styles: &styles, - spans: &[], - replacements: &[], - width: None, - indent: 0.0, - line_height: 1.2, - align: text::Align::Left, - tab: 32.0, - } - .layout(); - self.hud_layout = Some((line, layout)); - } - - if self.menu_item_layouts.len() != CONTEXT_MENU_ITEMS.len() { - let font = text::Font { - families: Arc::from([text::Family::Sans]), - size: 12.0, - weight: 500, - italic: false, - }; - let styles = [text::Style::new(font)]; - self.menu_item_layouts = CONTEXT_MENU_ITEMS - .iter() - .map(|(_, label)| { - text::Paragraph { - text: label, - styles: &styles, - spans: &[], - replacements: &[], - width: None, - indent: 0.0, - line_height: 1.2, - align: text::Align::Left, - tab: 32.0, - } - .layout() - }) - .collect(); - } - } - - pub fn build_ui( - &mut self, - ui: &mut ui::Ui, - pane_id: ui::Id, - canvas_id: ui::Id, - engine: &Engine, - clock: &PlaybackClock, - ) -> Vec { - self.in_out_range = clock.in_out_range; - let mut actions = Vec::new(); - ui.open_as( - pane_id, - ui::Spec { - size: [ui::fill(), ui::fill()], - axis: ui::Axis::Y, - fill: Some(self.background()), - ..ui::Spec::default() - }, - ); - - ui.open( - ("top_bar", self.slot), - ui::Spec { - size: [ui::fill(), ui::px(30.0)], - axis: ui::Axis::X, - pad: [6.0, 4.0], - gap: 4.0, - fill: Some(self.palette.bar), - ..ui::Spec::default() - }, - ); - - if self.slot == 0 { - let play_lbl = if clock.playing { "Pause" } else { "Play" }; - if tool_btn(ui, ("play", self.slot), play_lbl, clock.playing).clicked { - actions.push(ViewerAction::TogglePlay); - } - if tool_btn(ui, ("prev", self.slot), "<", false).clicked { - actions.push(ViewerAction::SetFrame(clock.current_frame - 1.0)); - } - if tool_btn(ui, ("next", self.slot), ">", false).clicked { - actions.push(ViewerAction::SetFrame(clock.current_frame + 1.0)); - } - let sync_lbl = match clock.sync_mode { - SyncMode::RealtimeDrop => "RT", - SyncMode::EveryFrame => "Every", - }; - if tool_btn(ui, ("sync", self.slot), sync_lbl, clock.sync_mode == SyncMode::EveryFrame).clicked { - actions.push(ViewerAction::ToggleSyncMode); - } - for scale in [1u32, 2, 4] { - let lbl = format!("1:{scale}"); - if tool_btn(ui, ("proxy", self.slot, scale), &lbl, engine.proxy_scale == scale).clicked { - actions.push(ViewerAction::SetProxy(scale)); - } - } - if tool_btn(ui, ("hiq", self.slot), "HiQ", engine.hiq).clicked { - actions.push(ViewerAction::ToggleHiQ); - } - } - - let ch_lbl = match self.display.channel { - 1 => "R", - 2 => "G", - 3 => "B", - 4 => "A", - _ => "RGBA", - }; - if tool_btn(ui, ("chan", self.slot), ch_lbl, self.display.channel != 0).clicked { - self.display.channel = (self.display.channel + 1) % 5; - self.dirty = true; - actions.push(ViewerAction::NeedRender); - } - let filt_lbl = if self.display.smooth_resize { "Smooth" } else { "Pixel" }; - if tool_btn(ui, ("smooth", self.slot), filt_lbl, self.display.smooth_resize).clicked { - self.display.smooth_resize = !self.display.smooth_resize; - self.dirty = true; - actions.push(ViewerAction::NeedRender); - } - if tool_btn(ui, ("fit", self.slot), "Fit", self.fit_mode).clicked { - self.fit(); - } - if tool_btn(ui, ("gizmo", self.slot), "Gizmo", self.gizmos.enabled).clicked { - self.gizmos.enabled = !self.gizmos.enabled; - } - - if self.slot == 0 { - let bypass_lbl = match engine.cache.mode { - CacheMode::Enabled => "Cache", - CacheMode::Bypass => "Bypass", - }; - if tool_btn(ui, ("cache_mode", self.slot), bypass_lbl, engine.cache.mode == CacheMode::Bypass).clicked { - actions.push(ViewerAction::ToggleCacheBypass); - } - if tool_btn(ui, ("bust_frame", self.slot), "Bust F", false).clicked { - let f = clock.current_frame.round() as i64; - self.cached_frames.remove(&f); - self.dirty = true; - actions.push(ViewerAction::BustFrame(f)); - } - if tool_btn(ui, ("bust_sub", self.slot), "Node", false).clicked { - self.cached_frames.clear(); - self.dirty = true; - actions.push(ViewerAction::BustSubtree); - } - if tool_btn(ui, ("bust_gpu", self.slot), "GPU", false).clicked { - self.cached_frames.clear(); - self.dirty = true; - actions.push(ViewerAction::BustGpu); - } - if tool_btn(ui, ("bust_all", self.slot), "All", false).clicked { - self.cached_frames.clear(); - self.dirty = true; - actions.push(ViewerAction::BustAll); - } - } - ui.close(); - - ui.open_as( - canvas_id, - ui::Spec { - flags: ui::Flags::CUSTOM | ui::Flags::FOCUSABLE | ui::Flags::KEY_INPUT, - size: [ui::fill(), ui::fill()], - ..ui::Spec::default() - }, - ); - ui.close(); - - ui.close(); - actions - } - fn scrubber_rect(&self) -> [f32; 4] { [ 10.0, @@ -1108,285 +586,14 @@ impl ViewerState { } actions } - - pub fn paint<'a>(&'a self, comp: &'a Comp, current_frame: f64) -> Vec> { - let mut out = Vec::with_capacity(64); - let [w, _h] = self.size; - - if self.viewed_node.is_some() { - if let Some(img) = &self.output_image { - let (full_rect, vis, _, _) = self.image_layout(comp); - if vis[2] > vis[0] + 0.5 && vis[3] > vis[1] + 0.5 { - out.push(Primitive::Image { image: img, rect: vis, radius: 0.0 }); - out.push(Primitive::RoundedRect { - rect: [ - full_rect[0].max(vis[0]), - full_rect[1].max(vis[1]), - full_rect[2].min(vis[2]), - full_rect[3].min(vis[3]), - ], - radius: 1.0, - stroke: Some(1.0), - color: self.palette.border, - }); - if let Some(sel) = self.selected_node { - out.extend(self.gizmos.paint(comp, sel, current_frame, full_rect, vis)); - } - } - } - } - - if let Some((_, layout)) = &self.hud_layout { - out.push(Primitive::RoundedRect { - rect: [8.0, 5.0, (w - 8.0).max(20.0), 24.0], - radius: 4.0, - stroke: None, - color: [self.palette.bg[0] * 0.72, self.palette.bg[1] * 0.72, self.palette.bg[2] * 0.72, 0.82], - }); - out.push(Primitive::Text { - text: layout as &dyn Glyphs, - origin: [14.0, 8.0], - clip: Some([12.0, 5.0, w - 12.0, 24.0]), - ink: self.palette.text, - }); - } - - let sr = self.scrubber_rect(); - out.push(Primitive::RoundedRect { rect: sr, radius: 4.0, stroke: None, color: self.palette.scrub_bg }); - let r0 = comp.render_range[0] as f64; - let r1 = comp.render_range[1].max(comp.render_range[0] + 1) as f64; - let span = (r1 - r0).max(1.0); - let bar_w = (sr[2] - sr[0]).max(1.0); - let tick_w = (bar_w / span as f32).max(2.0); - - // Audio waveform overlay across the timeline scrubber - if !self.audio_peaks.is_empty() && bar_w > 16.0 { - let max_bars = (bar_w / 3.0).floor().clamp(8.0, 480.0) as usize; - let n = self.audio_peaks.len(); - let mid_y = 0.5 * (sr[1] + sr[3] - 3.0); - let max_half = ((sr[3] - sr[1] - 5.0) * 0.5).max(1.5); - let step_w = bar_w / max_bars as f32; - for b in 0..max_bars { - let i0 = (b * n) / max_bars; - let i1 = (((b + 1) * n) / max_bars).max(i0 + 1).min(n); - let mut peak = 0.0_f32; - for &v in &self.audio_peaks[i0..i1] { - if v > peak { peak = v; } - } - if peak > 0.015 { - let h = (peak * max_half).max(1.0); - let x = sr[0] + b as f32 * step_w; - out.push(Primitive::Rect { - rect: [x, mid_y - h, (x + (step_w - 0.8).max(1.0)).min(sr[2]), mid_y + h], - color: [0.46, 0.72, 0.96, 0.36], - }); - } - } - } - - // Green RAM cache ranges along the bottom of the scrubber - for &(c0, c1) in &self.ram_cached_ranges { - let f0 = (c0 as f64).max(r0); - let f1 = (c1 as f64).min(r1); - if f1 < f0 { - continue; - } - let x0 = sr[0] + ((f0 - r0) / span) as f32 * bar_w; - let x1 = (sr[0] + ((f1 - r0) / span) as f32 * bar_w + tick_w).min(sr[2]); - out.push(Primitive::Rect { - rect: [x0, sr[3] - 4.0, x1.max(x0 + 2.0), sr[3] - 1.0], - color: [0.22, 0.86, 0.48, 0.92], - }); - } - // Individual GPU-cached frames from this session - for &cf in &self.cached_frames { - if (cf as f64) >= r0 && (cf as f64) <= r1 { - let frac = ((cf as f64 - r0) / span) as f32; - let x = sr[0] + frac * bar_w; - out.push(Primitive::Rect { - rect: [x, sr[3] - 4.0, (x + tick_w).min(sr[2]), sr[3] - 1.0], - color: [0.24, 0.84, 0.50, 0.85], - }); - } - } - - // Crisp In/Out preview range highlight & bracket markers - if self.in_out_range[0].is_some() || self.in_out_range[1].is_some() { - let rr0 = comp.render_range[0]; - let rr1 = comp.render_range[1].max(rr0); - let raw_a = self.in_out_range[0].unwrap_or(rr0).clamp(rr0, rr1); - let raw_b = self.in_out_range[1].unwrap_or(rr1).clamp(rr0, rr1); - let (in_f, out_f) = if raw_a <= raw_b { (raw_a, raw_b) } else { (raw_b, raw_a) }; - let ix0 = sr[0] + ((in_f as f64 - r0) / span).clamp(0.0, 1.0) as f32 * bar_w; - let ix1 = sr[0] + ((out_f as f64 - r0) / span).clamp(0.0, 1.0) as f32 * bar_w; - let span_x1 = ix1.max(ix0 + 2.0).min(sr[2]); - let acc = self.palette.accent; - out.push(Primitive::RoundedRect { - rect: [ix0, sr[1], span_x1, sr[3]], - radius: 3.0, - stroke: None, - color: [acc[0], acc[1], acc[2], 0.22], - }); - out.push(Primitive::Rect { - rect: [ix0, sr[1], span_x1, sr[1] + 2.0], - color: [acc[0], acc[1], acc[2], 0.85], - }); - let bracket_col = [ - (acc[0] + 0.16).min(1.0), - (acc[1] + 0.16).min(1.0), - (acc[2] + 0.16).min(1.0), - 0.98, - ]; - // In bracket `[` - out.push(Primitive::Rect { - rect: [ix0, sr[1] - 1.0, (ix0 + 2.0).min(sr[2]), sr[3] + 1.0], - color: bracket_col, - }); - out.push(Primitive::Rect { - rect: [ix0, sr[1] - 1.0, (ix0 + 6.0).min(sr[2]), sr[1] + 1.0], - color: bracket_col, - }); - out.push(Primitive::Rect { - rect: [ix0, sr[3] - 1.0, (ix0 + 6.0).min(sr[2]), sr[3] + 1.0], - color: bracket_col, - }); - // Out bracket `]` - let ox = span_x1; - out.push(Primitive::Rect { - rect: [(ox - 2.0).max(sr[0]), sr[1] - 1.0, ox, sr[3] + 1.0], - color: bracket_col, - }); - out.push(Primitive::Rect { - rect: [(ox - 6.0).max(sr[0]), sr[1] - 1.0, ox, sr[1] + 1.0], - color: bracket_col, - }); - out.push(Primitive::Rect { - rect: [(ox - 6.0).max(sr[0]), sr[3] - 1.0, ox, sr[3] + 1.0], - color: bracket_col, - }); - } - - let frac = ((current_frame - r0) / span).clamp(0.0, 1.0) as f32; - let px = sr[0] + frac * bar_w; - out.push(Primitive::RoundedRect { - rect: [sr[0], sr[1], px.max(sr[0] + 2.0), sr[3]], - radius: 4.0, - stroke: None, - color: [self.palette.accent[0], self.palette.accent[1], self.palette.accent[2], 0.25], - }); - out.push(Primitive::RoundedRect { - rect: [px - 3.0, sr[1] - 2.0, px + 3.0, sr[3] + 2.0], - radius: 2.0, - stroke: None, - color: [0.98, 0.40, 0.36, 1.0], - }); - - // Knife-styled right-click floating context menu - if let Some(anchor) = self.context_menu { - let mr = self.context_menu_rect(anchor); - // Soft drop shadow - out.push(Primitive::RoundedRect { - rect: [mr[0] + 2.0, mr[1] + 4.0, mr[2] + 2.0, mr[3] + 4.0], - radius: 8.0, - stroke: None, - color: [0.0, 0.0, 0.0, 0.38], - }); - let bg = self.palette.bar; - let panel_fill = [ - (bg[0] + 0.03).min(1.0), - (bg[1] + 0.03).min(1.0), - (bg[2] + 0.035).min(1.0), - 0.97, - ]; - out.push(Primitive::RoundedRect { - rect: mr, - radius: 7.0, - stroke: None, - color: panel_fill, - }); - out.push(Primitive::RoundedRect { - rect: mr, - radius: 7.0, - stroke: Some(1.0), - color: self.palette.border, - }); - - // Hairline separator after export actions - let sep_y = mr[1] - + CONTEXT_MENU_PAD_Y - + (CONTEXT_MENU_SEP_AFTER + 1) as f32 * CONTEXT_MENU_ITEM_H - + CONTEXT_MENU_SEP_H * 0.5; - out.push(Primitive::Rect { - rect: [mr[0] + 8.0, sep_y - 0.5, mr[2] - 8.0, sep_y + 0.5], - color: self.palette.border, - }); - - let acc = self.palette.accent; - for (idx, layout) in self.menu_item_layouts.iter().enumerate() { - let item_r = self.context_menu_item_rect(mr, idx); - if self.context_menu_hover == Some(idx) { - out.push(Primitive::RoundedRect { - rect: item_r, - radius: 4.0, - stroke: None, - color: [acc[0], acc[1], acc[2], 0.24], - }); - } - out.push(Primitive::Text { - text: layout as &dyn Glyphs, - origin: [item_r[0] + 10.0, item_r[1] + 5.0], - clip: Some([item_r[0] + 4.0, item_r[1], item_r[2] - 4.0, item_r[3]]), - ink: self.palette.text, - }); - } - } - - out - } -} - -/// Sleek Knife-style compact toolbar control (soft tinted surface + hairline border, -/// accent tint when active — replaces the chunky generic `ui::button`). -fn tool_btn(ui: &mut ui::Ui, part: impl std::hash::Hash, label: &str, active: bool) -> ui::Signal { - let t = &ui.theme; - let fill = if active { - [t.accent[0], t.accent[1], t.accent[2], 0.24] - } else { - [t.base[0], t.base[1], t.base[2], 0.65] - }; - let border = if active { - [t.accent[0], t.accent[1], t.accent[2], 0.65] - } else { - t.rule - }; - let ink = if active { t.text } else { t.text_dim }; - ui.leaf( - part, - ui::Spec { - cursor: Some(winit::window::CursorIcon::Pointer), - flags: ui::Flags::CLICKABLE, - size: [ui::fit(), ui::px(22.0)], - text: Some(label), - font_size: Some(11.5), - medium: true, - color: Some(ink), - fill: Some(fill), - border: Some(border), - hover_fill: Some(t.ghost_soft), - hover_border: Some(t.accent), - radius: 5.0, - pad: [7.0, 0.0], - center: true, - ..ui::Spec::default() - }, - ) } #[cfg(test)] mod tests { use super::*; + use std::time::Instant; - fn test_comp() -> Comp { + pub(crate) fn test_comp() -> Comp { let src = r#"Composition { CurrentTime = 15, RenderRange = { 10, 50 }, @@ -1404,27 +611,6 @@ mod tests { Comp::from_fusion_str(src).expect("parse test comp") } - #[test] - fn effective_preview_range_sorts_and_clamps() { - let comp = test_comp(); - let mut clock = PlaybackClock::new(); - clock.init_from_comp(&comp); - assert_eq!(clock.effective_preview_range(&comp), [10, 50]); - - clock.in_out_range = [Some(20), None]; - assert_eq!(clock.effective_preview_range(&comp), [20, 50]); - - clock.in_out_range = [None, Some(30)]; - assert_eq!(clock.effective_preview_range(&comp), [10, 30]); - - // Reversed and out-of-bounds points get clamped and sorted cleanly - clock.in_out_range = [Some(99), Some(2)]; - assert_eq!(clock.effective_preview_range(&comp), [10, 50]); - - clock.in_out_range = [Some(35), Some(18)]; - assert_eq!(clock.effective_preview_range(&comp), [18, 35]); - } - #[test] fn hotkeys_and_right_click_menu_emit_actions() { let comp = test_comp(); @@ -1542,117 +728,6 @@ mod tests { assert!(!viewer.is_context_menu_open()); } - #[test] - fn playback_clock_in_out_wraparound_realtime_and_every_frame() { - let comp = test_comp(); // fps = 30, render_range = [10, 50] - let t0 = Instant::now(); - - // RealtimeDrop: starting outside [20, 24] snaps cleanly to 20, then wraps 24 -> 20 - let mut rt = PlaybackClock::new(); - rt.init_from_comp(&comp); - rt.in_out_range = [Some(20), Some(24)]; - rt.set_frame(&comp, 12.0, t0); // outside In/Out range - rt.toggle_play_with_comp(&comp, t0); - assert_eq!(rt.current_frame, 20.0); - - let step = Duration::from_secs_f64(1.0 / 30.0); - // Advance 4 frames -> frame 24 (last frame in [20..=24]) - let r4 = rt.tick_synced(&comp, t0 + step * 4 + Duration::from_millis(2)); - assert!(r4.playing); - assert!(r4.frame_changed); - assert!(!r4.looped); - assert_eq!(rt.current_frame, 24.0); - - // Advance 5th frame -> wraps cleanly back to 20 and reports looped = true - let r5 = rt.tick_synced(&comp, t0 + step * 5 + Duration::from_millis(2)); - assert!(r5.playing); - assert!(r5.frame_changed); - assert!(r5.looped); - assert_eq!(rt.current_frame, 20.0); - - // Next frame after wrap advances from 20 -> 21 without double-looping - let r6 = rt.tick_synced(&comp, t0 + step * 6 + Duration::from_millis(4)); - assert!(r6.frame_changed); - assert!(!r6.looped); - assert_eq!(rt.current_frame, 21.0); - - // EveryFrame: steps +1 per >=1/fps, preserves cadence across minor jitter, wraps 22 -> 20 - let mut ef = PlaybackClock::new(); - ef.init_from_comp(&comp); - ef.sync_mode = SyncMode::EveryFrame; - ef.in_out_range = [Some(20), Some(22)]; - ef.set_frame(&comp, 20.0, t0); - ef.toggle_play_with_comp(&comp, t0); - - // Minor 4ms jitter on step 1 - let e1 = ef.tick_synced(&comp, t0 + step + Duration::from_millis(4)); - assert_eq!((e1.frame_changed, e1.looped, ef.current_frame), (true, false, 21.0)); - // Step 2 fires at t0 + 2*step (doesn't lose the 4ms jitter!) - let e2 = ef.tick_synced(&comp, t0 + step * 2 + Duration::from_millis(1)); - assert_eq!((e2.frame_changed, e2.looped, ef.current_frame), (true, false, 22.0)); - // Step 3 wraps 22 -> 20 with looped = true - let e3 = ef.tick_synced(&comp, t0 + step * 3 + Duration::from_millis(1)); - assert_eq!((e3.frame_changed, e3.looped, ef.current_frame), (true, true, 20.0)); - } - - #[test] - fn audio_sync_target_time_computation() { - let mut comp = test_comp(); - comp.fps = 24.0; - comp.audio_offset = 12.0; - - let t0 = Instant::now(); - let mut clock = PlaybackClock::new(); - clock.init_from_comp(&comp); - clock.in_out_range = [Some(12), Some(36)]; - clock.set_frame(&comp, 0.0, t0); - assert!((clock.audio_target_secs(&comp) - (-0.5)).abs() < 1e-9); - - clock.set_frame(&comp, 12.0, t0); - assert!((clock.audio_target_secs(&comp) - 0.0).abs() < 1e-9); - - clock.set_frame(&comp, 36.0, t0); - assert!((clock.audio_target_secs(&comp) - 1.0).abs() < 1e-9); - - // RealtimeDrop expected_audio_secs tracks continuous sub-frame progress & wraparound - clock.set_frame(&comp, 24.0, t0); - clock.toggle_play_with_comp(&comp, t0); - let half_sec = Duration::from_millis(500); - let exp_rt = clock.expected_audio_secs(&comp, t0 + half_sec); - assert!((exp_rt - 1.0).abs() < 1e-6, "expected 1.0s at frame 36, got {exp_rt}"); - - // EveryFrame expected_audio_secs caps sub-frame progress at 1/fps when a frame stalls - clock.sync_mode = SyncMode::EveryFrame; - clock.set_frame(&comp, 24.0, t0); // expected base = (24 - 12) / 24 = 0.5s - let exp_stalled = clock.expected_audio_secs(&comp, t0 + Duration::from_millis(400)); - let max_expected = 0.5 + (1.0 / 24.0); - assert!( - (exp_stalled - max_expected).abs() < 1e-6, - "EveryFrame stalled expected_audio_secs should cap at {max_expected}, got {exp_stalled}" - ); - } - - #[test] - fn loop_wraparound_keeps_the_sub_frame_overshoot() { - let comp = test_comp(); // 30 fps - let t0 = Instant::now(); - let step = Duration::from_secs_f64(1.0 / 30.0); - let mut clock = PlaybackClock::new(); - clock.init_from_comp(&comp); - clock.in_out_range = [Some(20), Some(24)]; - clock.set_frame(&comp, 20.0, t0); - clock.toggle_play_with_comp(&comp, t0); - - // Wrap with half a frame of overshoot... - let wrap = clock.tick_synced(&comp, t0 + step.mul_f64(5.5)); - assert!(wrap.looped); - assert_eq!(clock.current_frame, 20.0); - // ...so 0.6 frames later a whole frame has elapsed on the original timeline. - let next = clock.tick_synced(&comp, t0 + step.mul_f64(6.1)); - assert!(!next.looped); - assert_eq!(clock.current_frame, 21.0); - } - #[test] fn gizmo_needs_a_viewed_node_and_reports_drag_end() { let comp = Comp::from_fusion_str( diff --git a/crates/viewer/src/paint.rs b/crates/viewer/src/paint.rs new file mode 100644 index 0000000000000000000000000000000000000000..cfa86547ce1f886dbe0a6a154033b45beffbba00 --- /dev/null +++ b/crates/viewer/src/paint.rs @@ -0,0 +1,499 @@ +use super::*; + +impl ViewerState { + pub fn prepare_hud(&mut self, comp: &Comp, engine: &Engine, clock: &PlaybackClock) { + self.in_out_range = clock.in_out_range; + let node_name = self + .viewed_node + .and_then(|id| comp.nodes.get(id.0)) + .map_or("(empty)", |n| n.name.as_str()); + let cache_lbl = match engine.cache.mode { + CacheMode::Enabled => "CACHE", + CacheMode::Bypass => "BYPASS", + }; + let sync_lbl = match clock.sync_mode { + SyncMode::RealtimeDrop => "RT", + SyncMode::EveryFrame => "EVERY", + }; + let hiq_lbl = if engine.hiq { "HiQ" } else { "FAST" }; + let (_, _, _, eff_scale) = self.image_layout(comp); + let zoom_pct = (eff_scale * 100.0).round() as i32; + let s = &self.last_stats; + let io_suffix = if clock.in_out_range[0].is_some() || clock.in_out_range[1].is_some() { + let [a, b] = clock.effective_preview_range(comp); + format!(" · [{a}..{b}]") + } else { + String::new() + }; + let line = format!( + "[V{}] {} · f{}{} · {}% · {:.1}ms · ev:{} h:{} m:{} · {:.0}MB · 1:{} · {} · {} · {}", + self.slot + 1, + node_name, + clock.current_frame.round() as i64, + io_suffix, + zoom_pct, + s.eval_ms, + s.nodes_evaluated, + s.cache_hits, + s.cache_misses, + s.cached_vram_mb, + engine.proxy_scale, + hiq_lbl, + cache_lbl, + sync_lbl, + ); + if self.hud_layout.as_ref().is_none_or(|(prev, _)| prev != &line) { + let font = text::Font { + families: Arc::from([text::Family::Mono]), + size: 10.5, + weight: 500, + italic: false, + }; + let styles = [text::Style::new(font)]; + let layout = text::Paragraph { + text: &line, + styles: &styles, + spans: &[], + replacements: &[], + width: None, + indent: 0.0, + line_height: 1.2, + align: text::Align::Left, + tab: 32.0, + } + .layout(); + self.hud_layout = Some((line, layout)); + } + + if self.menu_item_layouts.len() != CONTEXT_MENU_ITEMS.len() { + let font = text::Font { + families: Arc::from([text::Family::Sans]), + size: 12.0, + weight: 500, + italic: false, + }; + let styles = [text::Style::new(font)]; + self.menu_item_layouts = CONTEXT_MENU_ITEMS + .iter() + .map(|(_, label)| { + text::Paragraph { + text: label, + styles: &styles, + spans: &[], + replacements: &[], + width: None, + indent: 0.0, + line_height: 1.2, + align: text::Align::Left, + tab: 32.0, + } + .layout() + }) + .collect(); + } + } + + pub fn build_ui( + &mut self, + ui: &mut ui::Ui, + pane_id: ui::Id, + canvas_id: ui::Id, + engine: &Engine, + clock: &PlaybackClock, + ) -> Vec { + self.in_out_range = clock.in_out_range; + let mut actions = Vec::new(); + ui.open_as( + pane_id, + ui::Spec { + size: [ui::fill(), ui::fill()], + axis: ui::Axis::Y, + fill: Some(self.background()), + ..ui::Spec::default() + }, + ); + + ui.open( + ("top_bar", self.slot), + ui::Spec { + size: [ui::fill(), ui::px(30.0)], + axis: ui::Axis::X, + pad: [6.0, 4.0], + gap: 4.0, + fill: Some(self.palette.bar), + ..ui::Spec::default() + }, + ); + + if self.slot == 0 { + let play_lbl = if clock.playing { "Pause" } else { "Play" }; + if tool_btn(ui, ("play", self.slot), play_lbl, clock.playing).clicked { + actions.push(ViewerAction::TogglePlay); + } + if tool_btn(ui, ("prev", self.slot), "<", false).clicked { + actions.push(ViewerAction::SetFrame(clock.current_frame - 1.0)); + } + if tool_btn(ui, ("next", self.slot), ">", false).clicked { + actions.push(ViewerAction::SetFrame(clock.current_frame + 1.0)); + } + let sync_lbl = match clock.sync_mode { + SyncMode::RealtimeDrop => "RT", + SyncMode::EveryFrame => "Every", + }; + if tool_btn(ui, ("sync", self.slot), sync_lbl, clock.sync_mode == SyncMode::EveryFrame).clicked { + actions.push(ViewerAction::ToggleSyncMode); + } + for scale in [1u32, 2, 4] { + let lbl = format!("1:{scale}"); + if tool_btn(ui, ("proxy", self.slot, scale), &lbl, engine.proxy_scale == scale).clicked { + actions.push(ViewerAction::SetProxy(scale)); + } + } + if tool_btn(ui, ("hiq", self.slot), "HiQ", engine.hiq).clicked { + actions.push(ViewerAction::ToggleHiQ); + } + } + + let ch_lbl = match self.display.channel { + 1 => "R", + 2 => "G", + 3 => "B", + 4 => "A", + _ => "RGBA", + }; + if tool_btn(ui, ("chan", self.slot), ch_lbl, self.display.channel != 0).clicked { + self.display.channel = (self.display.channel + 1) % 5; + self.dirty = true; + actions.push(ViewerAction::NeedRender); + } + let filt_lbl = if self.display.smooth_resize { "Smooth" } else { "Pixel" }; + if tool_btn(ui, ("smooth", self.slot), filt_lbl, self.display.smooth_resize).clicked { + self.display.smooth_resize = !self.display.smooth_resize; + self.dirty = true; + actions.push(ViewerAction::NeedRender); + } + if tool_btn(ui, ("fit", self.slot), "Fit", self.fit_mode).clicked { + self.fit(); + } + if tool_btn(ui, ("gizmo", self.slot), "Gizmo", self.gizmos.enabled).clicked { + self.gizmos.enabled = !self.gizmos.enabled; + } + + if self.slot == 0 { + let bypass_lbl = match engine.cache.mode { + CacheMode::Enabled => "Cache", + CacheMode::Bypass => "Bypass", + }; + if tool_btn(ui, ("cache_mode", self.slot), bypass_lbl, engine.cache.mode == CacheMode::Bypass).clicked { + actions.push(ViewerAction::ToggleCacheBypass); + } + if tool_btn(ui, ("bust_frame", self.slot), "Bust F", false).clicked { + let f = clock.current_frame.round() as i64; + self.cached_frames.remove(&f); + self.dirty = true; + actions.push(ViewerAction::BustFrame(f)); + } + if tool_btn(ui, ("bust_sub", self.slot), "Node", false).clicked { + self.cached_frames.clear(); + self.dirty = true; + actions.push(ViewerAction::BustSubtree); + } + if tool_btn(ui, ("bust_gpu", self.slot), "GPU", false).clicked { + self.cached_frames.clear(); + self.dirty = true; + actions.push(ViewerAction::BustGpu); + } + if tool_btn(ui, ("bust_all", self.slot), "All", false).clicked { + self.cached_frames.clear(); + self.dirty = true; + actions.push(ViewerAction::BustAll); + } + } + ui.close(); + + ui.open_as( + canvas_id, + ui::Spec { + flags: ui::Flags::CUSTOM | ui::Flags::FOCUSABLE | ui::Flags::KEY_INPUT, + size: [ui::fill(), ui::fill()], + ..ui::Spec::default() + }, + ); + ui.close(); + + ui.close(); + actions + } + + pub fn paint<'a>(&'a self, comp: &'a Comp, current_frame: f64) -> Vec> { + let mut out = Vec::with_capacity(64); + let [w, _h] = self.size; + + if self.viewed_node.is_some() { + if let Some(img) = &self.output_image { + let (full_rect, vis, _, _) = self.image_layout(comp); + if vis[2] > vis[0] + 0.5 && vis[3] > vis[1] + 0.5 { + out.push(Primitive::Image { image: img, rect: vis, radius: 0.0 }); + out.push(Primitive::RoundedRect { + rect: [ + full_rect[0].max(vis[0]), + full_rect[1].max(vis[1]), + full_rect[2].min(vis[2]), + full_rect[3].min(vis[3]), + ], + radius: 1.0, + stroke: Some(1.0), + color: self.palette.border, + }); + if let Some(sel) = self.selected_node { + out.extend(self.gizmos.paint(comp, sel, current_frame, full_rect, vis)); + } + } + } + } + + if let Some((_, layout)) = &self.hud_layout { + out.push(Primitive::RoundedRect { + rect: [8.0, 5.0, (w - 8.0).max(20.0), 24.0], + radius: 4.0, + stroke: None, + color: [self.palette.bg[0] * 0.72, self.palette.bg[1] * 0.72, self.palette.bg[2] * 0.72, 0.82], + }); + out.push(Primitive::Text { + text: layout as &dyn Glyphs, + origin: [14.0, 8.0], + clip: Some([12.0, 5.0, w - 12.0, 24.0]), + ink: self.palette.text, + }); + } + + let sr = self.scrubber_rect(); + out.push(Primitive::RoundedRect { rect: sr, radius: 4.0, stroke: None, color: self.palette.scrub_bg }); + let r0 = comp.render_range[0] as f64; + let r1 = comp.render_range[1].max(comp.render_range[0] + 1) as f64; + let span = (r1 - r0).max(1.0); + let bar_w = (sr[2] - sr[0]).max(1.0); + let tick_w = (bar_w / span as f32).max(2.0); + + // Audio waveform overlay across the timeline scrubber + if !self.audio_peaks.is_empty() && bar_w > 16.0 { + let max_bars = (bar_w / 3.0).floor().clamp(8.0, 480.0) as usize; + let n = self.audio_peaks.len(); + let mid_y = 0.5 * (sr[1] + sr[3] - 3.0); + let max_half = ((sr[3] - sr[1] - 5.0) * 0.5).max(1.5); + let step_w = bar_w / max_bars as f32; + for b in 0..max_bars { + let i0 = (b * n) / max_bars; + let i1 = (((b + 1) * n) / max_bars).max(i0 + 1).min(n); + let mut peak = 0.0_f32; + for &v in &self.audio_peaks[i0..i1] { + if v > peak { peak = v; } + } + if peak > 0.015 { + let h = (peak * max_half).max(1.0); + let x = sr[0] + b as f32 * step_w; + out.push(Primitive::Rect { + rect: [x, mid_y - h, (x + (step_w - 0.8).max(1.0)).min(sr[2]), mid_y + h], + color: [0.46, 0.72, 0.96, 0.36], + }); + } + } + } + + // Green RAM cache ranges along the bottom of the scrubber + for &(c0, c1) in &self.ram_cached_ranges { + let f0 = (c0 as f64).max(r0); + let f1 = (c1 as f64).min(r1); + if f1 < f0 { + continue; + } + let x0 = sr[0] + ((f0 - r0) / span) as f32 * bar_w; + let x1 = (sr[0] + ((f1 - r0) / span) as f32 * bar_w + tick_w).min(sr[2]); + out.push(Primitive::Rect { + rect: [x0, sr[3] - 4.0, x1.max(x0 + 2.0), sr[3] - 1.0], + color: [0.22, 0.86, 0.48, 0.92], + }); + } + // Individual GPU-cached frames from this session + for &cf in &self.cached_frames { + if (cf as f64) >= r0 && (cf as f64) <= r1 { + let frac = ((cf as f64 - r0) / span) as f32; + let x = sr[0] + frac * bar_w; + out.push(Primitive::Rect { + rect: [x, sr[3] - 4.0, (x + tick_w).min(sr[2]), sr[3] - 1.0], + color: [0.24, 0.84, 0.50, 0.85], + }); + } + } + + // Crisp In/Out preview range highlight & bracket markers + if self.in_out_range[0].is_some() || self.in_out_range[1].is_some() { + let rr0 = comp.render_range[0]; + let rr1 = comp.render_range[1].max(rr0); + let raw_a = self.in_out_range[0].unwrap_or(rr0).clamp(rr0, rr1); + let raw_b = self.in_out_range[1].unwrap_or(rr1).clamp(rr0, rr1); + let (in_f, out_f) = if raw_a <= raw_b { (raw_a, raw_b) } else { (raw_b, raw_a) }; + let ix0 = sr[0] + ((in_f as f64 - r0) / span).clamp(0.0, 1.0) as f32 * bar_w; + let ix1 = sr[0] + ((out_f as f64 - r0) / span).clamp(0.0, 1.0) as f32 * bar_w; + let span_x1 = ix1.max(ix0 + 2.0).min(sr[2]); + let acc = self.palette.accent; + out.push(Primitive::RoundedRect { + rect: [ix0, sr[1], span_x1, sr[3]], + radius: 3.0, + stroke: None, + color: [acc[0], acc[1], acc[2], 0.22], + }); + out.push(Primitive::Rect { + rect: [ix0, sr[1], span_x1, sr[1] + 2.0], + color: [acc[0], acc[1], acc[2], 0.85], + }); + let bracket_col = [ + (acc[0] + 0.16).min(1.0), + (acc[1] + 0.16).min(1.0), + (acc[2] + 0.16).min(1.0), + 0.98, + ]; + // In bracket `[` + out.push(Primitive::Rect { + rect: [ix0, sr[1] - 1.0, (ix0 + 2.0).min(sr[2]), sr[3] + 1.0], + color: bracket_col, + }); + out.push(Primitive::Rect { + rect: [ix0, sr[1] - 1.0, (ix0 + 6.0).min(sr[2]), sr[1] + 1.0], + color: bracket_col, + }); + out.push(Primitive::Rect { + rect: [ix0, sr[3] - 1.0, (ix0 + 6.0).min(sr[2]), sr[3] + 1.0], + color: bracket_col, + }); + // Out bracket `]` + let ox = span_x1; + out.push(Primitive::Rect { + rect: [(ox - 2.0).max(sr[0]), sr[1] - 1.0, ox, sr[3] + 1.0], + color: bracket_col, + }); + out.push(Primitive::Rect { + rect: [(ox - 6.0).max(sr[0]), sr[1] - 1.0, ox, sr[1] + 1.0], + color: bracket_col, + }); + out.push(Primitive::Rect { + rect: [(ox - 6.0).max(sr[0]), sr[3] - 1.0, ox, sr[3] + 1.0], + color: bracket_col, + }); + } + + let frac = ((current_frame - r0) / span).clamp(0.0, 1.0) as f32; + let px = sr[0] + frac * bar_w; + out.push(Primitive::RoundedRect { + rect: [sr[0], sr[1], px.max(sr[0] + 2.0), sr[3]], + radius: 4.0, + stroke: None, + color: [self.palette.accent[0], self.palette.accent[1], self.palette.accent[2], 0.25], + }); + out.push(Primitive::RoundedRect { + rect: [px - 3.0, sr[1] - 2.0, px + 3.0, sr[3] + 2.0], + radius: 2.0, + stroke: None, + color: [0.98, 0.40, 0.36, 1.0], + }); + + // Knife-styled right-click floating context menu + if let Some(anchor) = self.context_menu { + let mr = self.context_menu_rect(anchor); + // Soft drop shadow + out.push(Primitive::RoundedRect { + rect: [mr[0] + 2.0, mr[1] + 4.0, mr[2] + 2.0, mr[3] + 4.0], + radius: 8.0, + stroke: None, + color: [0.0, 0.0, 0.0, 0.38], + }); + let bg = self.palette.bar; + let panel_fill = [ + (bg[0] + 0.03).min(1.0), + (bg[1] + 0.03).min(1.0), + (bg[2] + 0.035).min(1.0), + 0.97, + ]; + out.push(Primitive::RoundedRect { + rect: mr, + radius: 7.0, + stroke: None, + color: panel_fill, + }); + out.push(Primitive::RoundedRect { + rect: mr, + radius: 7.0, + stroke: Some(1.0), + color: self.palette.border, + }); + + // Hairline separator after export actions + let sep_y = mr[1] + + CONTEXT_MENU_PAD_Y + + (CONTEXT_MENU_SEP_AFTER + 1) as f32 * CONTEXT_MENU_ITEM_H + + CONTEXT_MENU_SEP_H * 0.5; + out.push(Primitive::Rect { + rect: [mr[0] + 8.0, sep_y - 0.5, mr[2] - 8.0, sep_y + 0.5], + color: self.palette.border, + }); + + let acc = self.palette.accent; + for (idx, layout) in self.menu_item_layouts.iter().enumerate() { + let item_r = self.context_menu_item_rect(mr, idx); + if self.context_menu_hover == Some(idx) { + out.push(Primitive::RoundedRect { + rect: item_r, + radius: 4.0, + stroke: None, + color: [acc[0], acc[1], acc[2], 0.24], + }); + } + out.push(Primitive::Text { + text: layout as &dyn Glyphs, + origin: [item_r[0] + 10.0, item_r[1] + 5.0], + clip: Some([item_r[0] + 4.0, item_r[1], item_r[2] - 4.0, item_r[3]]), + ink: self.palette.text, + }); + } + } + + out + } +} + +/// Sleek Knife-style compact toolbar control (soft tinted surface + hairline border, +/// accent tint when active — replaces the chunky generic `ui::button`). +fn tool_btn(ui: &mut ui::Ui, part: impl std::hash::Hash, label: &str, active: bool) -> ui::Signal { + let t = &ui.theme; + let fill = if active { + [t.accent[0], t.accent[1], t.accent[2], 0.24] + } else { + [t.base[0], t.base[1], t.base[2], 0.65] + }; + let border = if active { + [t.accent[0], t.accent[1], t.accent[2], 0.65] + } else { + t.rule + }; + let ink = if active { t.text } else { t.text_dim }; + ui.leaf( + part, + ui::Spec { + cursor: Some(winit::window::CursorIcon::Pointer), + flags: ui::Flags::CLICKABLE, + size: [ui::fit(), ui::px(22.0)], + text: Some(label), + font_size: Some(11.5), + medium: true, + color: Some(ink), + fill: Some(fill), + border: Some(border), + hover_fill: Some(t.ghost_soft), + hover_border: Some(t.accent), + radius: 5.0, + pad: [7.0, 0.0], + center: true, + ..ui::Spec::default() + }, + ) +} -- 2.54.1