Merge main into menu-parity branch; point AE menu entries at main's real commands
- Integrate main (render queue, timeline/keys, time remap, masks/pen, 3D, MCP/CLI). - Menu tree now runs renderQueue.add, layer.enableTimeRemap, layer.timeReverse, layer.freezeFrame/OnLastFrame, prop.separateDimensions, mask.setClosed, layer.cameraSettings, view.3d.* / view.3d.last / view.reset3DView, main's layer.autoOrient and keyframe velocity/interpolation/time-stretch dialogs; matching stubs deleted (view.3d.default stays disabled). - Keyframe clipboard is main's (keys.copy/paste); Paste Reversed Keyframes reuses it. Animation-menu commands moved to commands/animation.rs. - Main's spec menu paths/labels aligned with AE (Camera Settings under Layer > Camera, "..." labels, Freeze On Last Frame). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -16,7 +16,10 @@
|
||||
//! - `ui.timeline.locate {layer, time?}`: screen point of a layer bar (at a comp time)
|
||||
//! - `ui.playback {action: play|stop|toggle}`
|
||||
//! - `ui.screenshot {path?, panel?, id?}`: PNG of the window (or one panel / element)
|
||||
//! - `render.frame {comp?, time?, max_side?, path?, base64?}`: PNG of a comp frame rendered by the session
|
||||
//! - `ui.resize {width, height}` / `ui.focus` / `app.quit`
|
||||
//!
|
||||
//! The full reference with examples is `docs/control-protocol.md`.
|
||||
|
||||
use std::sync::mpsc::Sender;
|
||||
|
||||
@@ -86,13 +89,24 @@ pub fn handle(app: &mut EffectcraftApp, ctx: &egui::Context, req: &ControlReques
|
||||
match req.method.as_str() {
|
||||
"engine.execute" | "ui.menu.invoke" => {
|
||||
let Some(id) = s("command").or(s("id")) else { return err("missing `command`") };
|
||||
let params = p.get("params").cloned().unwrap_or(json!({}));
|
||||
match crate::menus::invoke(app, ctx, id, params) {
|
||||
let params = p.get("params").cloned().filter(|v| !v.is_null()).unwrap_or(json!({}));
|
||||
// `engine.execute` runs engine commands exactly as headless (never opens a dialog, e.g.
|
||||
// `comp.new {}` creates a default comp); UI-only ids (`tool.*`, `view.*`, `window.*`,
|
||||
// `playback.*` …) and `ui.menu.invoke` go through the menu dispatcher like a click.
|
||||
let r = if req.method == "engine.execute" && effectcraft_engine::find_command(id).is_some() {
|
||||
app.session.execute_checked(id, params).map_err(|e| e.to_string())
|
||||
} else {
|
||||
crate::menus::invoke(app, ctx, id, params)
|
||||
};
|
||||
match r {
|
||||
Ok(v) => ok(v),
|
||||
Err(e) => err(e),
|
||||
Err(e) => {
|
||||
app.ui.status = e.clone();
|
||||
err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
"engine.commands" => match app.session.execute("command.list", json!({})) {
|
||||
"engine.commands" => match app.session.execute("command.list", json!({"filter": p.get("filter"), "enabledOnly": p.get("enabledOnly")})) {
|
||||
Ok(v) => ok(v),
|
||||
Err(e) => err(e),
|
||||
},
|
||||
@@ -301,6 +315,7 @@ pub fn handle(app: &mut EffectcraftApp, ctx: &egui::Context, req: &ControlReques
|
||||
app.raise_for_control(ctx);
|
||||
Outcome::Screenshot { path: s("path").map(str::to_string), crop }
|
||||
}
|
||||
"render.frame" => render_frame(app, p),
|
||||
"ui.resize" => {
|
||||
let w = p.get("width").and_then(Value::as_f64).unwrap_or(1600.0) as f32;
|
||||
let h = p.get("height").and_then(Value::as_f64).unwrap_or(1000.0) as f32;
|
||||
@@ -320,6 +335,61 @@ pub fn handle(app: &mut EffectcraftApp, ctx: &egui::Context, req: &ControlReques
|
||||
}
|
||||
}
|
||||
|
||||
/// `render.frame {comp?, time?, max_side?, path?, base64?}`: render a comp frame through the session
|
||||
/// (independent of the viewer zoom/resolution) and return it as PNG, written to `path` (default a
|
||||
/// temp file) or inline as base64 when `base64: true`.
|
||||
fn render_frame(app: &EffectcraftApp, p: &Value) -> Outcome {
|
||||
let s = &app.session;
|
||||
let cid = match s.resolve_comp(p.get("comp")) {
|
||||
Ok(c) => c,
|
||||
Err(e) => return err(e),
|
||||
};
|
||||
let t = p.get("time").or(p.get("seconds")).and_then(Value::as_f64).map(effectcraft_time::Tick::from_seconds_f64).unwrap_or_else(|| s.time());
|
||||
let max_side = p.get("max_side").or(p.get("maxSide")).and_then(Value::as_u64).unwrap_or(0) as u32;
|
||||
let (w, h, rgba) = match s.render_rgba8(cid, t, max_side) {
|
||||
Ok(r) => r,
|
||||
Err(e) => return err(e),
|
||||
};
|
||||
let png = match encode_png(&rgba, w, h) {
|
||||
Ok(p) => p,
|
||||
Err(e) => return err(e),
|
||||
};
|
||||
let mut out = json!({"comp": cid.0, "time": t.seconds(), "width": w, "height": h});
|
||||
if p.get("base64").and_then(Value::as_bool) == Some(true) {
|
||||
out["png"] = json!(base64(&png));
|
||||
return ok(out);
|
||||
}
|
||||
let path = p
|
||||
.get("path")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| std::env::temp_dir().join(format!("effectcraft-frame-{}.png", std::process::id())).to_string_lossy().to_string());
|
||||
match std::fs::write(&path, png) {
|
||||
Ok(()) => {
|
||||
out["path"] = json!(path);
|
||||
ok(out)
|
||||
}
|
||||
Err(e) => err(format!("cannot write {path}: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Standard base64 (RFC 4648, padded).
|
||||
pub fn base64(data: &[u8]) -> String {
|
||||
const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
let mut s = String::with_capacity(data.len().div_ceil(3) * 4);
|
||||
for c in data.chunks(3) {
|
||||
let n = (c[0] as u32) << 16 | (*c.get(1).unwrap_or(&0) as u32) << 8 | *c.get(2).unwrap_or(&0) as u32;
|
||||
for i in 0..4 {
|
||||
if i <= c.len() {
|
||||
s.push(A[(n >> (18 - 6 * i) & 63) as usize] as char);
|
||||
} else {
|
||||
s.push('=');
|
||||
}
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
pub fn inspect(app: &EffectcraftApp, ctx: &egui::Context) -> Value {
|
||||
let size = ctx.content_rect().size();
|
||||
json!({
|
||||
@@ -417,3 +487,13 @@ pub fn encode_png(rgba: &[u8], w: u32, h: u32) -> Result<Vec<u8>, String> {
|
||||
chunk(&mut out, b"IEND", &[]);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn base64_rfc4648_vectors() {
|
||||
for (i, o) in [("", ""), ("f", "Zg=="), ("fo", "Zm8="), ("foo", "Zm9v"), ("foob", "Zm9vYg=="), ("fooba", "Zm9vYmE="), ("foobar", "Zm9vYmFy")] {
|
||||
assert_eq!(super::base64(i.as_bytes()), o);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,8 +8,9 @@ use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use effectcraft_engine::project::{ItemId, Project};
|
||||
use effectcraft_engine::render::{ExprHost, FootageSource, RenderOpts, Renderer};
|
||||
use effectcraft_engine::render::{ExprHost, FootageSource, LayerCache, RenderOpts, Renderer};
|
||||
use effectcraft_engine::time::Tick;
|
||||
use rayon::prelude::*;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct FrameKey {
|
||||
@@ -18,6 +19,8 @@ pub struct FrameKey {
|
||||
pub frame: i64,
|
||||
/// Render scale × 1000.
|
||||
pub scale: u32,
|
||||
/// Hash of the 3D view camera (0 = the comp's active camera).
|
||||
pub view: u64,
|
||||
}
|
||||
|
||||
struct Cache {
|
||||
@@ -49,14 +52,18 @@ pub struct RenderSource {
|
||||
pub project: Arc<Project>,
|
||||
pub footage: Arc<dyn FootageSource>,
|
||||
pub expr: Option<Arc<dyn ExprHost>>,
|
||||
pub layer_cache: Arc<LayerCache>,
|
||||
}
|
||||
|
||||
pub struct Frames {
|
||||
cache: Arc<Mutex<Cache>>,
|
||||
/// Keys queued or rendering.
|
||||
inflight: Arc<Mutex<HashSet<FrameKey>>>,
|
||||
/// Pending jobs, picked by priority when a pool thread frees up (the viewer's frame first).
|
||||
queue: Arc<Mutex<Queue>>,
|
||||
pool: rayon::ThreadPool,
|
||||
ctx: Option<egui::Context>,
|
||||
/// Last render time per frame (ms), for the Info panel / perf readout.
|
||||
/// Render time of the last viewer (urgent) frame in ms, for the Info panel / perf readout.
|
||||
pub last_ms: Arc<Mutex<f64>>,
|
||||
}
|
||||
|
||||
@@ -66,6 +73,7 @@ impl Default for Frames {
|
||||
Frames {
|
||||
cache: Arc::new(Mutex::new(Cache { map: HashMap::new(), order: VecDeque::new(), bytes: 0, budget: 3 << 30 })),
|
||||
inflight: Arc::new(Mutex::new(HashSet::new())),
|
||||
queue: Arc::new(Mutex::new(Queue::default())),
|
||||
pool: rayon::ThreadPoolBuilder::new().num_threads(threads).thread_name(|i| format!("ec-frame-{i}")).build().expect("frame pool"),
|
||||
ctx: None,
|
||||
last_ms: Arc::new(Mutex::new(0.0)),
|
||||
@@ -78,7 +86,7 @@ impl Default for Frames {
|
||||
pub fn to_color_image(img: &effectcraft_engine::render::Image) -> egui::ColorImage {
|
||||
let px: Vec<egui::Color32> = img
|
||||
.data
|
||||
.iter()
|
||||
.par_iter()
|
||||
.map(|p| {
|
||||
let a = p[3].clamp(0.0, 1.0);
|
||||
let c = |v: f32| (v.clamp(0.0, a) * 255.0 + 0.5) as u8;
|
||||
@@ -123,36 +131,92 @@ impl Frames {
|
||||
}
|
||||
}
|
||||
|
||||
/// Queue a frame (no-op if cached or already rendering).
|
||||
/// Queue a prefetch frame (no-op if cached or already queued/rendering).
|
||||
pub fn request(&self, src: &RenderSource, key: FrameKey, comp: ItemId, t: Tick, opts: RenderOpts) {
|
||||
self.request_with(src, key, comp, t, opts, false);
|
||||
}
|
||||
|
||||
/// Queue the frame the viewer is showing: it jumps ahead of every prefetch job.
|
||||
pub fn request_urgent(&self, src: &RenderSource, key: FrameKey, comp: ItemId, t: Tick, opts: RenderOpts) {
|
||||
self.request_with(src, key, comp, t, opts, true);
|
||||
}
|
||||
|
||||
/// An urgent (viewer) frame is queued or rendering.
|
||||
pub fn urgent_pending(&self) -> bool {
|
||||
self.queue.lock().map(|q| q.urgent_running > 0 || q.jobs.iter().any(|j| j.urgent)).unwrap_or(false)
|
||||
}
|
||||
|
||||
fn request_with(&self, src: &RenderSource, key: FrameKey, comp: ItemId, t: Tick, opts: RenderOpts, urgent: bool) {
|
||||
if self.is_cached(&key) {
|
||||
return;
|
||||
}
|
||||
let Ok(mut q) = self.queue.lock() else { return };
|
||||
// Jobs for an older project revision can never be shown: drop them.
|
||||
let before = q.jobs.len();
|
||||
q.jobs.retain(|j| j.key.revision >= key.revision);
|
||||
let dropped = before - q.jobs.len();
|
||||
if dropped > 0
|
||||
&& let Ok(mut inf) = self.inflight.lock()
|
||||
{
|
||||
inf.retain(|k| k.revision >= key.revision || q.running.contains(k));
|
||||
}
|
||||
if urgent {
|
||||
// Only the newest viewer frame is urgent; earlier ones become prefetch.
|
||||
for j in q.jobs.iter_mut() {
|
||||
j.urgent = j.key == key;
|
||||
}
|
||||
}
|
||||
{
|
||||
let Ok(mut inf) = self.inflight.lock() else { return };
|
||||
if !inf.insert(key) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
let src = src.clone();
|
||||
q.seq += 1;
|
||||
let seq = q.seq;
|
||||
q.jobs.push(Job { key, src: src.clone(), comp, t, opts, urgent, seq });
|
||||
drop(q);
|
||||
let queue = self.queue.clone();
|
||||
let cache = self.cache.clone();
|
||||
let inflight = self.inflight.clone();
|
||||
let ctx = self.ctx.clone();
|
||||
let last = self.last_ms.clone();
|
||||
// One spawn per job; each spawn renders whichever queued job matters most right now.
|
||||
self.pool.spawn(move || {
|
||||
let job = {
|
||||
let Ok(mut q) = queue.lock() else { return };
|
||||
// Urgent first (newest), then prefetch in request order.
|
||||
let best = q.jobs.iter().enumerate().max_by_key(|(_, j)| (j.urgent, if j.urgent { j.seq as i64 } else { -(j.seq as i64) })).map(|(i, _)| i);
|
||||
let Some(i) = best else { return };
|
||||
let job = q.jobs.swap_remove(i);
|
||||
q.running.insert(job.key);
|
||||
if job.urgent {
|
||||
q.urgent_running += 1;
|
||||
}
|
||||
job
|
||||
};
|
||||
let t0 = std::time::Instant::now();
|
||||
let mut r = Renderer::new(&src.project, src.footage.as_ref(), opts);
|
||||
r.expr = src.expr.as_deref();
|
||||
let img = r.comp_frame(comp, t);
|
||||
let mut r = Renderer::new(&job.src.project, job.src.footage.as_ref(), job.opts);
|
||||
r.expr = job.src.expr.as_deref();
|
||||
r.cache = Some(&job.src.layer_cache);
|
||||
let img = r.comp_frame(job.comp, job.t);
|
||||
let ci = Arc::new(to_color_image(&img));
|
||||
if let Ok(mut l) = last.lock() {
|
||||
if job.urgent
|
||||
&& let Ok(mut l) = last.lock()
|
||||
{
|
||||
*l = t0.elapsed().as_secs_f64() * 1000.0;
|
||||
}
|
||||
if let Ok(mut c) = cache.lock() {
|
||||
c.insert(key, ci);
|
||||
c.insert(job.key, ci);
|
||||
}
|
||||
if let Ok(mut inf) = inflight.lock() {
|
||||
inf.remove(&key);
|
||||
inf.remove(&job.key);
|
||||
}
|
||||
if let Ok(mut q) = queue.lock() {
|
||||
q.running.remove(&job.key);
|
||||
if job.urgent {
|
||||
q.urgent_running -= 1;
|
||||
}
|
||||
}
|
||||
if let Some(ctx) = ctx {
|
||||
ctx.request_repaint();
|
||||
@@ -160,3 +224,21 @@ impl Frames {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
struct Job {
|
||||
key: FrameKey,
|
||||
src: RenderSource,
|
||||
comp: ItemId,
|
||||
t: Tick,
|
||||
opts: RenderOpts,
|
||||
urgent: bool,
|
||||
seq: u64,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Queue {
|
||||
jobs: Vec<Job>,
|
||||
running: HashSet<FrameKey>,
|
||||
urgent_running: usize,
|
||||
seq: u64,
|
||||
}
|
||||
|
||||
@@ -51,6 +51,11 @@ pub enum Dialog {
|
||||
Info,
|
||||
/// View ▸ View Options.
|
||||
ViewOptions,
|
||||
CameraSettings,
|
||||
LightSettings,
|
||||
KeyVelocity,
|
||||
KeyInterpolation,
|
||||
TimeStretch,
|
||||
}
|
||||
|
||||
/// Host hooks provided by the native app (file pickers etc.).
|
||||
@@ -172,7 +177,12 @@ impl EffectcraftApp {
|
||||
}
|
||||
|
||||
pub fn render_source(&self) -> RenderSource {
|
||||
RenderSource { project: self.session.project.clone(), footage: self.session.footage.clone(), expr: self.session.expr.clone() }
|
||||
RenderSource {
|
||||
project: self.session.project.clone(),
|
||||
footage: self.session.footage.clone(),
|
||||
expr: self.session.expr.clone(),
|
||||
layer_cache: self.session.layer_cache.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The render scale used by the viewer right now.
|
||||
@@ -185,16 +195,44 @@ impl EffectcraftApp {
|
||||
}
|
||||
|
||||
pub fn frame_key(&self, comp: ItemId, frame: i64, scale: f64) -> FrameKey {
|
||||
FrameKey { revision: self.session.revision, comp: comp.0, frame, scale: (scale * 1000.0).round() as u32 }
|
||||
FrameKey { revision: self.session.revision, comp: comp.0, frame, scale: (scale * 1000.0).round() as u32, view: self.view_hash(comp) }
|
||||
}
|
||||
|
||||
/// Request a frame render (no-op if cached/in flight).
|
||||
/// Hash of the comp viewer's 3D view camera (0 for the active camera view).
|
||||
pub fn view_hash(&self, comp: ItemId) -> u64 {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let Some(cam) = self.session.view_camera(comp) else { return 0 };
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
for row in cam.view.0 {
|
||||
for v in row {
|
||||
v.to_bits().hash(&mut h);
|
||||
}
|
||||
}
|
||||
cam.zoom.to_bits().hash(&mut h);
|
||||
cam.ortho.hash(&mut h);
|
||||
h.finish() | 1
|
||||
}
|
||||
|
||||
/// Request a prefetch frame render (no-op if cached/in flight).
|
||||
pub fn request_frame(&self, comp: ItemId, frame: i64, scale: f64) {
|
||||
self.request_frame_with(comp, frame, scale, false);
|
||||
}
|
||||
|
||||
/// Request the frame on screen: rendered before any queued prefetch.
|
||||
pub fn request_frame_urgent(&self, comp: ItemId, frame: i64, scale: f64) {
|
||||
self.request_frame_with(comp, frame, scale, true);
|
||||
}
|
||||
|
||||
fn request_frame_with(&self, comp: ItemId, frame: i64, scale: f64, urgent: bool) {
|
||||
let Some(c) = self.session.project.comp(comp) else { return };
|
||||
let key = self.frame_key(comp, frame, scale);
|
||||
let t = c.frame_rate.tick_of(frame);
|
||||
let opts = RenderOpts { scale, motion_blur: true, guides: true, draft: self.ui.viewer.fast_preview };
|
||||
self.frames.request(&self.render_source(), key, comp, t, opts);
|
||||
let opts = RenderOpts { scale, motion_blur: true, guides: true, draft: self.ui.viewer.fast_preview, view: self.session.view_camera(comp) };
|
||||
if urgent {
|
||||
self.frames.request_urgent(&self.render_source(), key, comp, t, opts);
|
||||
} else {
|
||||
self.frames.request(&self.render_source(), key, comp, t, opts);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- playback
|
||||
@@ -236,7 +274,15 @@ impl EffectcraftApp {
|
||||
let (wa, wb) = (fr.frame_at(c.work_area.0), fr.frame_at(c.work_area.1 - c.frame_duration()));
|
||||
// Prefetch ahead.
|
||||
let cur = fr.frame_at(self.session.time());
|
||||
let ahead = (self.frames_parallelism() * 2).max(4) as i64;
|
||||
// While paused (scrubbing, editing) the viewer's frame comes first: prefetch only a few
|
||||
// frames, and only once it is done, so prefetch never delays what is on screen.
|
||||
let ahead = if self.playback.playing {
|
||||
(self.frames_parallelism() * 2).max(4) as i64
|
||||
} else if self.frames.urgent_pending() {
|
||||
0
|
||||
} else {
|
||||
(self.frames_parallelism() / 2).max(2) as i64
|
||||
};
|
||||
let mut queued = self.frames.inflight();
|
||||
for k in 0..ahead * 3 {
|
||||
if queued >= ahead as usize {
|
||||
@@ -422,6 +468,10 @@ impl EffectcraftApp {
|
||||
let ctx = ui.ctx().clone();
|
||||
self.auto.begin_frame();
|
||||
self.frames.set_context(&ctx);
|
||||
if self.session.render_job.is_some() {
|
||||
self.session.poll_render();
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(100));
|
||||
}
|
||||
self.handle_events(&ctx);
|
||||
if let Some(rx) = self.command_inbox.take() {
|
||||
while let Ok(id) = rx.try_recv() {
|
||||
@@ -533,6 +583,14 @@ impl EffectcraftApp {
|
||||
}
|
||||
}
|
||||
|
||||
impl EffectcraftApp {
|
||||
/// Take the pending synthetic input (from `ui.click`, `ui.key`, …). Hosts that don't call
|
||||
/// [`eframe::App::raw_input_hook`] (the headless test harness) feed these in themselves.
|
||||
pub fn take_synthetic_input(&mut self) -> Vec<egui::Event> {
|
||||
std::mem::take(&mut self.synthetic)
|
||||
}
|
||||
}
|
||||
|
||||
impl eframe::App for EffectcraftApp {
|
||||
fn raw_input_hook(&mut self, _ctx: &egui::Context, raw_input: &mut egui::RawInput) {
|
||||
if !self.synthetic.is_empty() {
|
||||
|
||||
@@ -105,6 +105,10 @@ fn no_params(p: &Value) -> bool {
|
||||
/// Execute a UI or engine command by id.
|
||||
pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: Value) -> Result<Value, String> {
|
||||
let now = ctx.input(|i| i.time);
|
||||
// New Camera/Light and Camera/Light Settings without parameters open their dialogs.
|
||||
if crate::panels::dialogs_3d::route(app, id, ¶ms)? {
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
// Legacy per-panel / per-workspace ids (`window.panel.Project`, `window.workspace.default`).
|
||||
if let Some(rest) = id.strip_prefix("window.panel.") {
|
||||
return frontend(app, ctx, "window.panel", json!({"panel": rest}));
|
||||
@@ -205,13 +209,54 @@ pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: V
|
||||
"app.newComp" | "comp.new" if no_params(¶ms) => crate::panels::dialogs::open_new_comp(app),
|
||||
"app.compSettings" | "comp.settings" if no_params(¶ms) => crate::panels::dialogs::open_comp_settings(app)?,
|
||||
"app.solidSettings" | "layer.newSolid" if no_params(¶ms) => crate::panels::dialogs::open_new_solid(app)?,
|
||||
"keys.velocity" if no_params(¶ms) => crate::panels::key_dialogs::open_velocity(app)?,
|
||||
"keys.interpolation" if no_params(¶ms) => crate::panels::key_dialogs::open_interpolation(app)?,
|
||||
"layer.timeStretch" if no_params(¶ms) => crate::panels::key_dialogs::open_time_stretch(app)?,
|
||||
_ => {
|
||||
if id == "renderQueue.render" && params.get("wait").is_none() {
|
||||
// The UI renders in the background; the panel shows progress.
|
||||
let mut p = params.clone();
|
||||
if let Some(m) = p.as_object_mut() {
|
||||
m.insert("wait".into(), json!(false));
|
||||
} else {
|
||||
p = json!({"wait": false});
|
||||
}
|
||||
app.show_panel(PanelKind::RenderQueue);
|
||||
return app.session.execute(id, p).map_err(|e| e.to_string());
|
||||
}
|
||||
if id == "renderQueue.add" {
|
||||
let r = app.session.execute(id, params).map_err(|e| e.to_string());
|
||||
match &r {
|
||||
Ok(_) => app.show_panel(PanelKind::RenderQueue),
|
||||
Err(e) => app.ui.status = e.clone(),
|
||||
}
|
||||
return r;
|
||||
}
|
||||
if let Some(r) = file_dialog(app, id, ¶ms) {
|
||||
return r;
|
||||
}
|
||||
if crate::panels::dialogs::open_form(app, id, ¶ms) {
|
||||
return Ok(json!({"dialog": id}));
|
||||
}
|
||||
if id == "renderQueue.render" && params.get("wait").is_none() {
|
||||
// The UI renders in the background; the panel shows progress.
|
||||
let mut p = params.clone();
|
||||
if let Some(m) = p.as_object_mut() {
|
||||
m.insert("wait".into(), json!(false));
|
||||
} else {
|
||||
p = json!({"wait": false});
|
||||
}
|
||||
app.show_panel(PanelKind::RenderQueue);
|
||||
return app.session.execute(id, p).map_err(|e| e.to_string());
|
||||
}
|
||||
if id == "renderQueue.add" {
|
||||
let r = app.session.execute(id, params).map_err(|e| e.to_string());
|
||||
match &r {
|
||||
Ok(_) => app.show_panel(PanelKind::RenderQueue),
|
||||
Err(e) => app.ui.status = e.clone(),
|
||||
}
|
||||
return r;
|
||||
}
|
||||
if id == "layer.rename" && params.get("name").is_none() {
|
||||
crate::panels::timeline::begin_rename(app, ctx);
|
||||
return Ok(Value::Null);
|
||||
|
||||
@@ -0,0 +1,357 @@
|
||||
//! Composition Settings dialog (also New Composition), laid out like After Effects': name, then
|
||||
//! Basic / Advanced / 3D Renderer tabs, Preview checkbox, Cancel / OK.
|
||||
|
||||
use effectcraft_engine::time::{FrameRate, format_timecode_frames, parse_timecode};
|
||||
use egui::{Color32, vec2};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::theme::Tokens;
|
||||
|
||||
/// AE's composition presets: (name, width, height, pixel aspect, fps). "Custom" is implicit.
|
||||
pub const PRESETS: &[(&str, u32, u32, f64, f64)] = &[
|
||||
("Social Media Portrait HD · 1080x1920 · 30 fps", 1080, 1920, 1.0, 30.0),
|
||||
("Social Media Landscape HD · 1920x1080 · 30 fps", 1920, 1080, 1.0, 30.0),
|
||||
("Social Media Square · 1080x1080 · 30 fps", 1080, 1080, 1.0, 30.0),
|
||||
("Social Media Portrait · 1080x1350 · 30 fps", 1080, 1350, 1.0, 30.0),
|
||||
("NTSC DV", 720, 480, 0.9091, 29.97),
|
||||
("NTSC DV Widescreen", 720, 480, 1.2121, 29.97),
|
||||
("NTSC D1", 720, 486, 0.9091, 29.97),
|
||||
("NTSC D1 Widescreen", 720, 486, 1.2121, 29.97),
|
||||
("NTSC D1 Square Pix", 720, 540, 1.0, 29.97),
|
||||
("NTSC D1 Widescreen Square Pix", 872, 486, 1.0, 29.97),
|
||||
("PAL D1/DV", 720, 576, 1.0940, 25.0),
|
||||
("PAL D1/DV Widescreen", 720, 576, 1.4587, 25.0),
|
||||
("PAL D1/DV Square Pix", 788, 576, 1.0, 25.0),
|
||||
("PAL D1/DV Widescreen Square Pix", 1050, 576, 1.0, 25.0),
|
||||
("HDV/HDTV 720 29.97", 1280, 720, 1.0, 29.97),
|
||||
("HDV/HDTV 720 25", 1280, 720, 1.0, 25.0),
|
||||
("DVCPRO HD 720 23.976", 960, 720, 1.3333, 23.976),
|
||||
("DVCPRO HD 720 25", 960, 720, 1.3333, 25.0),
|
||||
("DVCPRO HD 720 29.97", 960, 720, 1.3333, 29.97),
|
||||
("HDTV 1080 24", 1920, 1080, 1.0, 24.0),
|
||||
("HDTV 1080 25", 1920, 1080, 1.0, 25.0),
|
||||
("HDTV 1080 29.97", 1920, 1080, 1.0, 29.97),
|
||||
("HDV 1080 25", 1440, 1080, 1.3333, 25.0),
|
||||
("HDV 1080 29.97", 1440, 1080, 1.3333, 29.97),
|
||||
("DVCPRO HD 1080 25", 1440, 1080, 1.3333, 25.0),
|
||||
("DVCPRO HD 1080 29.97", 1280, 1080, 1.5, 29.97),
|
||||
("Cineon Half", 1828, 1332, 1.0, 24.0),
|
||||
("Cineon Full", 3656, 2664, 1.0, 24.0),
|
||||
("Film (2K)", 2048, 1556, 1.0, 24.0),
|
||||
("Film (4K)", 4096, 3112, 1.0, 24.0),
|
||||
("UHD 4K 23.976", 3840, 2160, 1.0, 23.976),
|
||||
("UHD 4K 25", 3840, 2160, 1.0, 25.0),
|
||||
("UHD 4K 29.97", 3840, 2160, 1.0, 29.97),
|
||||
("UHD 8K 23.976", 7680, 4320, 1.0, 23.976),
|
||||
("UHD 8K 25", 7680, 4320, 1.0, 25.0),
|
||||
("UHD 8K 29.97", 7680, 4320, 1.0, 29.97),
|
||||
];
|
||||
|
||||
/// AE's Pixel Aspect Ratio choices.
|
||||
pub const PIXEL_ASPECTS: &[(&str, f64)] = &[
|
||||
("Square Pixels", 1.0),
|
||||
("D1/DV NTSC (0.91)", 0.9091),
|
||||
("D1/DV NTSC Widescreen (1.21)", 1.2121),
|
||||
("D1/DV PAL (1.09)", 1.0940),
|
||||
("D1/DV PAL Widescreen (1.46)", 1.4587),
|
||||
("Anamorphic 2:1 (2)", 2.0),
|
||||
("HDV 1080/DVCPRO HD 720 (1.33)", 1.3333),
|
||||
("DVCPRO HD 1080 (1.5)", 1.5),
|
||||
];
|
||||
|
||||
const FRAME_RATES: &[f64] = &[8.0, 10.0, 12.0, 12.5, 15.0, 23.976, 24.0, 25.0, 29.97, 30.0, 48.0, 50.0, 59.94, 60.0, 120.0];
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum Tab {
|
||||
#[default]
|
||||
Basic,
|
||||
Advanced,
|
||||
Renderer,
|
||||
}
|
||||
|
||||
/// The dialog's working copy.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct CompDraft {
|
||||
pub name: String,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub pixel_aspect: f64,
|
||||
pub fps: f64,
|
||||
pub duration: f64,
|
||||
pub start: f64,
|
||||
pub bg: [f32; 3],
|
||||
pub lock_aspect: bool,
|
||||
pub anchor: u8,
|
||||
pub shutter_angle: f64,
|
||||
pub shutter_phase: f64,
|
||||
pub samples: u32,
|
||||
pub advanced_3d: bool,
|
||||
pub tab: Tab,
|
||||
/// Timecode text being edited (start, duration).
|
||||
pub start_tc: Option<String>,
|
||||
pub dur_tc: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for CompDraft {
|
||||
fn default() -> Self {
|
||||
CompDraft {
|
||||
name: "Comp 1".into(),
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
pixel_aspect: 1.0,
|
||||
fps: 29.97,
|
||||
duration: 10.0,
|
||||
start: 0.0,
|
||||
bg: [0.0, 0.0, 0.0],
|
||||
lock_aspect: true,
|
||||
anchor: 4,
|
||||
shutter_angle: 180.0,
|
||||
shutter_phase: -90.0,
|
||||
samples: 16,
|
||||
advanced_3d: false,
|
||||
tab: Tab::Basic,
|
||||
start_tc: None,
|
||||
dur_tc: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `16:9 (1.78)`: the nearest small whole-number ratio and its decimal.
|
||||
pub fn aspect_label(w: f64, h: f64) -> String {
|
||||
let r = w / h.max(1.0);
|
||||
let best = (1..=32u32).map(|b| ((r * b as f64).round() as u32, b)).filter(|(a, _)| *a > 0).find(|(a, b)| (*a as f64 / *b as f64 - r).abs() < 0.006);
|
||||
match best {
|
||||
Some((a, b)) => format!("{a}:{b} ({r:.2})"),
|
||||
None => format!("{r:.2}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// AE's name for a background color when it is one of the obvious ones.
|
||||
fn color_name(c: [f32; 3]) -> &'static str {
|
||||
match c.map(|v| (v * 255.0).round() as u8) {
|
||||
[0, 0, 0] => "Black",
|
||||
[255, 255, 255] => "White",
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
|
||||
/// AE prints the hour without a leading zero: `0;00;10;00`.
|
||||
fn ae_timecode(smpte: &str) -> String {
|
||||
let (neg, rest) = smpte.strip_prefix('-').map_or((false, smpte), |r| (true, r));
|
||||
let rest = rest.strip_prefix('0').filter(|r| r.as_bytes().first().is_some_and(u8::is_ascii_digit)).unwrap_or(rest);
|
||||
format!("{}{rest}", if neg { "-" } else { "" })
|
||||
}
|
||||
|
||||
fn timecode_field(ui: &mut egui::Ui, buf: &mut Option<String>, secs: &mut f64, rate: FrameRate, min_frames: i64) {
|
||||
let df = rate.supports_drop_frame();
|
||||
// Durations are whole frames in AE: 10 s at 29.97 fps is 0;00;10;00, not 9;29.
|
||||
let shown = ae_timecode(&format_timecode_frames((*secs * rate.as_f64()).round() as i64, rate, df));
|
||||
let mut text = buf.clone().unwrap_or_else(|| shown.clone());
|
||||
let r = ui.add(egui::TextEdit::singleline(&mut text).desired_width(96.0).font(Tokens::mono(12.0)));
|
||||
if r.changed() {
|
||||
*buf = Some(text.clone());
|
||||
}
|
||||
if r.lost_focus() {
|
||||
if let Ok(f) = parse_timecode(&text, rate, df, 0) {
|
||||
*secs = rate.tick_of(f.max(min_frames)).seconds();
|
||||
}
|
||||
*buf = None;
|
||||
}
|
||||
let base = format!("Base {}{}", rate.timecode_base(), if df { "drop" } else { "" });
|
||||
ui.label(egui::RichText::new(format!("is {shown} {base}")).color(Color32::GRAY));
|
||||
}
|
||||
|
||||
/// Draw the dialog. Returns `Some(params)` when OK is pressed, `Some(Null)` on Cancel.
|
||||
pub fn show(ui: &mut egui::Ui, d: &mut CompDraft, t: &Tokens) -> Option<serde_json::Value> {
|
||||
let mut out = None;
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Composition Name:");
|
||||
ui.add(egui::TextEdit::singleline(&mut d.name).desired_width(300.0));
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
ui.horizontal(|ui| {
|
||||
for (tab, label) in [(Tab::Basic, "Basic"), (Tab::Advanced, "Advanced"), (Tab::Renderer, "3D Renderer")] {
|
||||
if ui.selectable_label(d.tab == tab, label).clicked() {
|
||||
d.tab = tab;
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
let rate = FrameRate::from_f64(d.fps);
|
||||
match d.tab {
|
||||
Tab::Basic => {
|
||||
egui::Grid::new("comp-basic").num_columns(2).spacing([12.0, 9.0]).show(ui, |ui| {
|
||||
ui.label("Preset:");
|
||||
let current = PRESETS
|
||||
.iter()
|
||||
.find(|(_, w, h, par, f)| *w == d.width && *h == d.height && (par - d.pixel_aspect).abs() < 1e-3 && (f - d.fps).abs() < 1e-3)
|
||||
.map(|p| p.0)
|
||||
.unwrap_or("Custom");
|
||||
egui::ComboBox::from_id_salt("comp-preset").width(300.0).selected_text(current).show_ui(ui, |ui| {
|
||||
for (name, w, h, par, f) in PRESETS {
|
||||
if ui.selectable_label(*name == current, *name).clicked() {
|
||||
(d.width, d.height, d.pixel_aspect, d.fps) = (*w, *h, *par, *f);
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label("Width:");
|
||||
ui.horizontal(|ui| {
|
||||
let (ow, oh) = (d.width, d.height);
|
||||
ui.add(egui::DragValue::new(&mut d.width).range(4..=30000).suffix(" px"));
|
||||
let lbl = format!("Lock Aspect Ratio to {}", aspect_label(ow as f64, oh as f64));
|
||||
ui.checkbox(&mut d.lock_aspect, lbl);
|
||||
if d.lock_aspect && ow != d.width && ow > 0 {
|
||||
d.height = ((d.width as f64) * oh as f64 / ow as f64).round().max(4.0) as u32;
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label("Height:");
|
||||
let (ow, oh) = (d.width, d.height);
|
||||
ui.add(egui::DragValue::new(&mut d.height).range(4..=30000).suffix(" px"));
|
||||
if d.lock_aspect && oh != d.height && oh > 0 {
|
||||
d.width = ((d.height as f64) * ow as f64 / oh as f64).round().max(4.0) as u32;
|
||||
}
|
||||
ui.end_row();
|
||||
ui.label("Pixel Aspect Ratio:");
|
||||
ui.horizontal(|ui| {
|
||||
let cur = PIXEL_ASPECTS
|
||||
.iter()
|
||||
.find(|(_, v)| (v - d.pixel_aspect).abs() < 1e-3)
|
||||
.map(|p| p.0.to_string())
|
||||
.unwrap_or_else(|| format!("{:.2}", d.pixel_aspect));
|
||||
egui::ComboBox::from_id_salt("comp-par").width(220.0).selected_text(cur).show_ui(ui, |ui| {
|
||||
for (name, v) in PIXEL_ASPECTS {
|
||||
if ui.selectable_label((v - d.pixel_aspect).abs() < 1e-3, *name).clicked() {
|
||||
d.pixel_aspect = *v;
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.label(
|
||||
egui::RichText::new(format!("Frame Aspect Ratio: {}", aspect_label(d.width as f64 * d.pixel_aspect, d.height as f64)))
|
||||
.color(Color32::GRAY),
|
||||
);
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label("Frame Rate:");
|
||||
ui.horizontal(|ui| {
|
||||
let txt = format!("{:.3}", d.fps).trim_end_matches('0').trim_end_matches('.').to_string();
|
||||
egui::ComboBox::from_id_salt("comp-fps").width(80.0).selected_text(txt).show_ui(ui, |ui| {
|
||||
for f in FRAME_RATES {
|
||||
if ui.selectable_label((d.fps - f).abs() < 1e-3, format!("{f}")).clicked() {
|
||||
d.fps = *f;
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.label("frames per second");
|
||||
if rate.supports_drop_frame() {
|
||||
ui.label(egui::RichText::new("Drop Frame").color(Color32::GRAY));
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label("");
|
||||
let mb = d.width as f64 * d.height as f64 * 4.0 / (1024.0 * 1024.0);
|
||||
ui.label(egui::RichText::new(format!("{} x {}, {mb:.1}MB per 8bpc frame", d.width, d.height)).color(Color32::GRAY));
|
||||
ui.end_row();
|
||||
ui.label("Start Timecode:");
|
||||
ui.horizontal(|ui| timecode_field(ui, &mut d.start_tc, &mut d.start, rate, i64::MIN / 4));
|
||||
ui.end_row();
|
||||
ui.label("Duration:");
|
||||
ui.horizontal(|ui| timecode_field(ui, &mut d.dur_tc, &mut d.duration, rate, 1));
|
||||
ui.end_row();
|
||||
ui.label("Background Color:");
|
||||
ui.horizontal(|ui| {
|
||||
ui.color_edit_button_rgb(&mut d.bg);
|
||||
ui.label(color_name(d.bg));
|
||||
});
|
||||
ui.end_row();
|
||||
});
|
||||
}
|
||||
Tab::Advanced => {
|
||||
egui::Grid::new("comp-adv").num_columns(2).spacing([12.0, 9.0]).show(ui, |ui| {
|
||||
ui.label("Anchor:");
|
||||
egui::Grid::new("comp-anchor").spacing([2.0, 2.0]).show(ui, |ui| {
|
||||
for i in 0..9u8 {
|
||||
let on = d.anchor == i;
|
||||
let b = egui::Button::new(if on { "●" } else { "" }).min_size(vec2(22.0, 22.0)).fill(if on { t.accent } else { t.field_bg });
|
||||
if ui.add(b).clicked() {
|
||||
d.anchor = i;
|
||||
}
|
||||
if i % 3 == 2 {
|
||||
ui.end_row();
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label(egui::RichText::new("Motion Blur").strong());
|
||||
ui.end_row();
|
||||
ui.label("Shutter Angle:");
|
||||
ui.add(egui::DragValue::new(&mut d.shutter_angle).range(0.0..=720.0).suffix("°"));
|
||||
ui.end_row();
|
||||
ui.label("Shutter Phase:");
|
||||
ui.add(egui::DragValue::new(&mut d.shutter_phase).range(-360.0..=360.0).suffix("°"));
|
||||
ui.end_row();
|
||||
ui.label("Samples Per Frame:");
|
||||
ui.add(egui::DragValue::new(&mut d.samples).range(2..=64));
|
||||
ui.end_row();
|
||||
});
|
||||
}
|
||||
Tab::Renderer => {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Renderer:");
|
||||
egui::ComboBox::from_id_salt("comp-renderer").selected_text(if d.advanced_3d { "Advanced 3D" } else { "Classic 3D" }).show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut d.advanced_3d, false, "Classic 3D");
|
||||
ui.selectable_value(&mut d.advanced_3d, true, "Advanced 3D");
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
ui.add_space(14.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.add(egui::Button::new(egui::RichText::new(" OK ").color(Color32::WHITE)).fill(t.accent)).clicked() {
|
||||
out = Some(params(d));
|
||||
}
|
||||
if ui.button("Cancel").clicked() {
|
||||
out = Some(serde_json::Value::Null);
|
||||
}
|
||||
});
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// `comp.new` / `comp.settings` parameters for the draft.
|
||||
pub fn params(d: &CompDraft) -> serde_json::Value {
|
||||
json!({
|
||||
"name": d.name, "width": d.width, "height": d.height, "pixelAspect": d.pixel_aspect, "frameRate": d.fps,
|
||||
"duration": d.duration, "startTime": d.start, "background": [d.bg[0], d.bg[1], d.bg[2]], "anchor": d.anchor,
|
||||
"shutterAngle": d.shutter_angle, "shutterPhase": d.shutter_phase, "motionBlurSamples": d.samples,
|
||||
"renderer": if d.advanced_3d { "advanced3D" } else { "classic3D" },
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn aspect_labels_match_ae() {
|
||||
assert_eq!(aspect_label(1920.0, 1080.0), "16:9 (1.78)");
|
||||
assert_eq!(aspect_label(1080.0, 1080.0), "1:1 (1.00)");
|
||||
assert_eq!(aspect_label(1080.0, 1350.0), "4:5 (0.80)");
|
||||
assert_eq!(aspect_label(720.0 * 0.9091, 480.0), "15:11 (1.36)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ae_timecode_drops_hour_padding() {
|
||||
assert_eq!(ae_timecode("00;00;10;00"), "0;00;10;00");
|
||||
assert_eq!(ae_timecode("12:00:00:00"), "12:00:00:00");
|
||||
assert_eq!(ae_timecode("-00:00:01:00"), "-0:00:01:00");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn presets_resolve_by_value() {
|
||||
let p = PRESETS.iter().find(|p| p.0 == "HDTV 1080 29.97").unwrap();
|
||||
assert_eq!((p.1, p.2), (1920, 1080));
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Modal dialogs: About (with community links), New Composition / Composition Settings, Solid
|
||||
//! Settings and the command palette.
|
||||
//! Settings and the command palette (Camera/Light Settings live in `dialogs_3d`).
|
||||
|
||||
use egui::{Align2, Color32, Rect, Sense, pos2, vec2};
|
||||
use serde_json::json;
|
||||
@@ -9,22 +9,7 @@ use crate::icons::{self, Icon};
|
||||
use crate::theme::Tokens;
|
||||
use crate::{Dialog, EffectcraftApp};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct CompDraft {
|
||||
pub name: String,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub fps: f64,
|
||||
pub duration: f64,
|
||||
pub bg: [f32; 3],
|
||||
pub lock_aspect: bool,
|
||||
}
|
||||
|
||||
impl Default for CompDraft {
|
||||
fn default() -> Self {
|
||||
CompDraft { name: "Comp 1".into(), width: 1920, height: 1080, fps: 29.97, duration: 10.0, bg: [0.0, 0.0, 0.0], lock_aspect: true }
|
||||
}
|
||||
}
|
||||
pub use super::comp_settings::CompDraft;
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct DialogState {
|
||||
@@ -41,6 +26,11 @@ pub struct DialogState {
|
||||
pub form: super::forms::Form,
|
||||
/// Message box (title, body).
|
||||
pub info: (String, String),
|
||||
pub camera: super::dialogs_3d::CameraDraft,
|
||||
pub light: super::dialogs_3d::LightDraft,
|
||||
pub velocity: super::key_dialogs::VelocityDraft,
|
||||
pub interp: super::key_dialogs::InterpDraft,
|
||||
pub stretch: super::key_dialogs::StretchDraft,
|
||||
}
|
||||
|
||||
pub fn open_new_comp(app: &mut EffectcraftApp) {
|
||||
@@ -57,10 +47,16 @@ pub fn open_comp_settings(app: &mut EffectcraftApp) -> Result<(), String> {
|
||||
name: app.session.project.item(cid).map(|i| i.name.clone()).unwrap_or_default(),
|
||||
width: c.width,
|
||||
height: c.height,
|
||||
pixel_aspect: c.pixel_aspect,
|
||||
fps: c.frame_rate.as_f64(),
|
||||
duration: c.duration.seconds(),
|
||||
start: c.display_start.seconds(),
|
||||
bg: c.background,
|
||||
lock_aspect: true,
|
||||
shutter_angle: c.shutter_angle,
|
||||
shutter_phase: c.shutter_phase,
|
||||
samples: c.motion_blur_samples,
|
||||
advanced_3d: c.renderer == effectcraft_engine::project::Renderer::Advanced3D,
|
||||
..Default::default()
|
||||
};
|
||||
app.dialog_state.editing_existing = true;
|
||||
app.dialog = Some(Dialog::CompSettings);
|
||||
@@ -107,6 +103,11 @@ pub fn show(app: &mut EffectcraftApp, ctx: &egui::Context) {
|
||||
Dialog::Form => super::forms::show_form(app, ctx, &t),
|
||||
Dialog::Info => super::forms::show_info(app, ctx, &t),
|
||||
Dialog::ViewOptions => super::forms::show_view_options(app, ctx, &t),
|
||||
Dialog::CameraSettings => super::dialogs_3d::camera(app, ctx, &t),
|
||||
Dialog::LightSettings => super::dialogs_3d::light(app, ctx, &t),
|
||||
Dialog::KeyVelocity => super::key_dialogs::velocity(app, ctx, &t),
|
||||
Dialog::KeyInterpolation => super::key_dialogs::interpolation(app, ctx, &t),
|
||||
Dialog::TimeStretch => super::key_dialogs::time_stretch(app, ctx, &t),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,97 +185,29 @@ fn about(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
|
||||
}
|
||||
|
||||
fn comp_settings(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens, existing: bool) {
|
||||
let mut close = false;
|
||||
let mut ok = false;
|
||||
let mut d = app.dialog_state.comp.clone();
|
||||
modal(ctx, if existing { "Composition Settings" } else { "Composition Settings — New" }, vec2(520.0, 420.0), t, |ui| {
|
||||
egui::Grid::new("comp-grid").num_columns(2).spacing([14.0, 10.0]).show(ui, |ui| {
|
||||
ui.label("Composition Name");
|
||||
ui.add(egui::TextEdit::singleline(&mut d.name).desired_width(260.0));
|
||||
ui.end_row();
|
||||
ui.label("Preset");
|
||||
egui::ComboBox::from_id_salt("comp-preset").selected_text(format!("{}x{} {:.2}", d.width, d.height, d.fps)).show_ui(ui, |ui| {
|
||||
for (label, w, h, f) in [
|
||||
("HD · 1920x1080 · 29.97 fps", 1920, 1080, 29.97),
|
||||
("HD · 1920x1080 · 25 fps", 1920, 1080, 25.0),
|
||||
("HD · 1920x1080 · 23.976 fps", 1920, 1080, 23.976),
|
||||
("HD · 1280x720 · 29.97 fps", 1280, 720, 29.97),
|
||||
("UHD 4K · 3840x2160 · 29.97 fps", 3840, 2160, 29.97),
|
||||
("Social 9:16 · 1080x1920 · 30 fps", 1080, 1920, 30.0),
|
||||
("Social 1:1 · 1080x1080 · 30 fps", 1080, 1080, 30.0),
|
||||
("Social 4:5 · 1080x1350 · 30 fps", 1080, 1350, 30.0),
|
||||
("Cinema 4K · 4096x2160 · 24 fps", 4096, 2160, 24.0),
|
||||
] {
|
||||
if ui.selectable_label(false, label).clicked() {
|
||||
d.width = w;
|
||||
d.height = h;
|
||||
d.fps = f;
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label("Width / Height");
|
||||
ui.horizontal(|ui| {
|
||||
let ow = d.width;
|
||||
ui.add(egui::DragValue::new(&mut d.width).range(4..=30000).suffix(" px"));
|
||||
ui.label("×");
|
||||
let oh = d.height;
|
||||
ui.add(egui::DragValue::new(&mut d.height).range(4..=30000).suffix(" px"));
|
||||
ui.checkbox(&mut d.lock_aspect, "Lock aspect");
|
||||
if d.lock_aspect && ow != d.width && ow > 0 {
|
||||
d.height = ((d.width as f64) * oh as f64 / ow as f64).round().max(4.0) as u32;
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label("Frame Rate");
|
||||
egui::ComboBox::from_id_salt("comp-fps").selected_text(format!("{:.3}", d.fps).trim_end_matches('0').trim_end_matches('.').to_string()).show_ui(
|
||||
ui,
|
||||
|ui| {
|
||||
for f in [23.976, 24.0, 25.0, 29.97, 30.0, 50.0, 59.94, 60.0, 120.0] {
|
||||
if ui.selectable_label((d.fps - f).abs() < 1e-3, format!("{f}")).clicked() {
|
||||
d.fps = f;
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
ui.end_row();
|
||||
ui.label("Duration");
|
||||
ui.add(egui::DragValue::new(&mut d.duration).range(0.04..=86400.0).speed(0.1).suffix(" s"));
|
||||
ui.end_row();
|
||||
ui.label("Background Color");
|
||||
ui.color_edit_button_rgb(&mut d.bg);
|
||||
ui.end_row();
|
||||
});
|
||||
ui.add_space(18.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.add(egui::Button::new(egui::RichText::new(" OK ").color(Color32::WHITE)).fill(t.accent)).clicked() {
|
||||
ok = true;
|
||||
}
|
||||
if ui.button("Cancel").clicked() {
|
||||
close = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
let mut result = None;
|
||||
modal(ctx, "Composition Settings", vec2(600.0, 470.0), t, |ui| {
|
||||
result = super::comp_settings::show(ui, &mut d, t);
|
||||
});
|
||||
if ui_enter(ctx) {
|
||||
ok = true;
|
||||
if result.is_none() && ui_enter(ctx) {
|
||||
result = Some(super::comp_settings::params(&d));
|
||||
}
|
||||
app.dialog_state.comp = d.clone();
|
||||
if ok {
|
||||
let params = json!({"name": d.name, "width": d.width, "height": d.height, "frameRate": d.fps, "duration": d.duration, "background": [d.bg[0], d.bg[1], d.bg[2]]});
|
||||
let r = if existing { app.session.execute("comp.settings", params) } else { app.session.execute("comp.new", params) };
|
||||
if let Err(e) = r {
|
||||
app.ui.status = e.to_string();
|
||||
app.dialog_state.comp = d;
|
||||
match result {
|
||||
Some(serde_json::Value::Null) => app.dialog = None,
|
||||
Some(params) => {
|
||||
let r = if existing { app.session.execute("comp.settings", params) } else { app.session.execute("comp.new", params) };
|
||||
if let Err(e) = r {
|
||||
app.ui.status = e.to_string();
|
||||
}
|
||||
app.dialog = None;
|
||||
}
|
||||
close = true;
|
||||
}
|
||||
if close {
|
||||
app.dialog = None;
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn ui_enter(ctx: &egui::Context) -> bool {
|
||||
pub(crate) fn ui_enter(ctx: &egui::Context) -> bool {
|
||||
!ctx.egui_wants_keyboard_input() && ctx.input(|i| i.key_pressed(egui::Key::Enter))
|
||||
}
|
||||
|
||||
@@ -284,23 +217,55 @@ fn solid(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
|
||||
let mut name = app.dialog_state.solid_name.clone();
|
||||
let mut col = app.dialog_state.solid_color;
|
||||
let mut size = app.dialog_state.solid_size;
|
||||
modal(ctx, "Solid Settings", vec2(420.0, 300.0), t, |ui| {
|
||||
egui::Grid::new("solid-grid").num_columns(2).spacing([14.0, 10.0]).show(ui, |ui| {
|
||||
ui.label("Name");
|
||||
ui.add(egui::TextEdit::singleline(&mut name).desired_width(220.0));
|
||||
ui.end_row();
|
||||
ui.label("Size");
|
||||
let comp_size = app.session.active_comp().map(|c| (c.width, c.height)).unwrap_or((1920, 1080));
|
||||
let lock_id = egui::Id::new("solid-lock-aspect");
|
||||
let mut lock = ctx.data(|d| d.get_temp::<bool>(lock_id)).unwrap_or(true);
|
||||
modal(ctx, "Solid Settings", vec2(460.0, 360.0), t, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Name:");
|
||||
ui.add(egui::TextEdit::singleline(&mut name).desired_width(320.0));
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
ui.label(egui::RichText::new("Size").strong());
|
||||
egui::Grid::new("solid-grid").num_columns(2).spacing([14.0, 8.0]).show(ui, |ui| {
|
||||
let (ow, oh) = (size[0], size[1]);
|
||||
ui.label("Width:");
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(egui::DragValue::new(&mut size[0]).range(1..=30000));
|
||||
ui.label("×");
|
||||
ui.add(egui::DragValue::new(&mut size[1]).range(1..=30000));
|
||||
ui.add(egui::DragValue::new(&mut size[0]).range(1..=30000).suffix(" px"));
|
||||
ui.checkbox(&mut lock, format!("Lock Aspect Ratio to {}", super::comp_settings::aspect_label(ow as f64, oh as f64)));
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label("Color");
|
||||
ui.color_edit_button_rgb(&mut col);
|
||||
ui.label("Height:");
|
||||
ui.add(egui::DragValue::new(&mut size[1]).range(1..=30000).suffix(" px"));
|
||||
ui.end_row();
|
||||
if lock && ow > 0 && oh > 0 {
|
||||
if size[0] != ow {
|
||||
size[1] = ((size[0] as f64) * oh as f64 / ow as f64).round().max(1.0) as u32;
|
||||
} else if size[1] != oh {
|
||||
size[0] = ((size[1] as f64) * ow as f64 / oh as f64).round().max(1.0) as u32;
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.add_space(18.0);
|
||||
let pct = |a: u32, b: u32| 100.0 * a as f64 / b.max(1) as f64;
|
||||
ui.label(
|
||||
egui::RichText::new(format!(
|
||||
"Width: {:.1}% of comp\nHeight: {:.1}% of comp\nFrame Aspect Ratio: {}",
|
||||
pct(size[0], comp_size.0),
|
||||
pct(size[1], comp_size.1),
|
||||
super::comp_settings::aspect_label(size[0] as f64, size[1] as f64)
|
||||
))
|
||||
.color(Color32::GRAY),
|
||||
);
|
||||
ui.add_space(4.0);
|
||||
if ui.button("Make Comp Size").clicked() {
|
||||
size = [comp_size.0, comp_size.1];
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Color:");
|
||||
ui.color_edit_button_rgb(&mut col);
|
||||
});
|
||||
ui.add_space(14.0);
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.add(egui::Button::new(egui::RichText::new(" OK ").color(Color32::WHITE)).fill(t.accent)).clicked() {
|
||||
ok = true;
|
||||
@@ -310,6 +275,7 @@ fn solid(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
|
||||
}
|
||||
});
|
||||
});
|
||||
ctx.data_mut(|d| d.insert_temp(lock_id, lock));
|
||||
app.dialog_state.solid_name = name.clone();
|
||||
app.dialog_state.solid_color = col;
|
||||
app.dialog_state.solid_size = size;
|
||||
|
||||
@@ -0,0 +1,378 @@
|
||||
//! Camera Settings and Light Settings dialogs (Layer ▸ New ▸ Camera/Light, Layer ▸ Camera/Light
|
||||
//! Settings, Layer Settings on a camera or light). OK runs `layer.newCamera` / `layer.newLight`
|
||||
//! or `layer.cameraSettings` / `layer.lightSettings` with the dialog's values.
|
||||
|
||||
use effectcraft_engine::project::{AutoOrient, LayerSource, LightKind};
|
||||
use effectcraft_engine::render::three_d::camera::{PRESETS, angle_of_view, default_aperture, focal_for_zoom, zoom_for_focal};
|
||||
use egui::{Color32, vec2};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::theme::Tokens;
|
||||
use crate::{Dialog, EffectcraftApp};
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct CameraDraft {
|
||||
/// Existing camera layer (Camera Settings) or None (New Camera).
|
||||
pub layer: Option<u64>,
|
||||
pub name: String,
|
||||
pub two_node: bool,
|
||||
pub zoom: f64,
|
||||
pub dof: bool,
|
||||
pub focus: f64,
|
||||
pub lock_to_zoom: bool,
|
||||
pub aperture: f64,
|
||||
pub blur: f64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct LightDraft {
|
||||
pub layer: Option<u64>,
|
||||
pub name: String,
|
||||
pub kind: usize,
|
||||
pub color: [f32; 3],
|
||||
pub intensity: f64,
|
||||
pub cone_angle: f64,
|
||||
pub cone_feather: f64,
|
||||
pub falloff: usize,
|
||||
pub radius: f64,
|
||||
pub falloff_distance: f64,
|
||||
pub casts_shadows: bool,
|
||||
pub shadow_darkness: f64,
|
||||
pub shadow_diffusion: f64,
|
||||
}
|
||||
|
||||
const KINDS: [LightKind; 4] = [LightKind::Parallel, LightKind::Spot, LightKind::Point, LightKind::Ambient];
|
||||
const FALLOFFS: [&str; 3] = ["None", "Smooth", "Inverse Square Clamped"];
|
||||
|
||||
fn comp_w(app: &EffectcraftApp) -> f64 {
|
||||
app.session.active_comp().map(|c| c.width as f64).unwrap_or(1920.0)
|
||||
}
|
||||
|
||||
/// Open Camera Settings: for `layer` (existing) or a new camera.
|
||||
pub fn open_camera(app: &mut EffectcraftApp, layer: Option<u64>) -> Result<(), String> {
|
||||
let comp = app.session.active_comp().ok_or("no composition is open")?.clone();
|
||||
let w = comp.width as f64;
|
||||
let t = app.session.time();
|
||||
let d = match layer.and_then(|id| comp.layer(effectcraft_engine::project::LayerId(id))) {
|
||||
Some(l) => {
|
||||
let f = |p: &str, d: f64| l.props.prop(p).map(|pr| pr.value_at(l.layer_time(t)).as_f64()).unwrap_or(d);
|
||||
let zoom = f("cameraOptions/zoom", 1000.0);
|
||||
let focus = f("cameraOptions/focusDistance", zoom);
|
||||
CameraDraft {
|
||||
layer: Some(l.id.0),
|
||||
name: l.name.clone(),
|
||||
two_node: l.auto_orient == AutoOrient::TowardsPointOfInterest,
|
||||
zoom,
|
||||
dof: l.props.prop("cameraOptions/dof").map(|p| p.value_at(l.layer_time(t)).as_bool()).unwrap_or(false),
|
||||
focus,
|
||||
lock_to_zoom: (focus - zoom).abs() < 1e-6,
|
||||
aperture: f("cameraOptions/aperture", default_aperture(w)),
|
||||
blur: f("cameraOptions/blurLevel", 100.0),
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let n = comp.layers.iter().filter(|l| l.is_camera()).count() + 1;
|
||||
let zoom = zoom_for_focal(w, 50.0);
|
||||
CameraDraft {
|
||||
layer: None,
|
||||
name: format!("Camera {n}"),
|
||||
two_node: true,
|
||||
zoom,
|
||||
dof: false,
|
||||
focus: zoom,
|
||||
lock_to_zoom: true,
|
||||
aperture: default_aperture(w),
|
||||
blur: 100.0,
|
||||
}
|
||||
}
|
||||
};
|
||||
app.dialog_state.camera = d;
|
||||
app.dialog = Some(Dialog::CameraSettings);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Open Light Settings: for `layer` (existing) or a new light.
|
||||
pub fn open_light(app: &mut EffectcraftApp, layer: Option<u64>) -> Result<(), String> {
|
||||
let comp = app.session.active_comp().ok_or("no composition is open")?.clone();
|
||||
let t = app.session.time();
|
||||
let d = match layer.and_then(|id| comp.layer(effectcraft_engine::project::LayerId(id))) {
|
||||
Some(l) => {
|
||||
let LayerSource::Light { kind } = l.source else { return Err("not a light".into()) };
|
||||
let v = |p: &str| l.props.prop(&format!("lightOptions/{p}")).map(|pr| pr.value_at(l.layer_time(t)));
|
||||
let f = |p: &str, d: f64| v(p).map(|x| x.as_f64()).unwrap_or(d);
|
||||
let c = v("color").map(|x| x.as_color()).unwrap_or([1.0; 4]);
|
||||
LightDraft {
|
||||
layer: Some(l.id.0),
|
||||
name: l.name.clone(),
|
||||
kind: KINDS.iter().position(|k| *k == kind).unwrap_or(1),
|
||||
color: [c[0], c[1], c[2]],
|
||||
intensity: f("intensity", 100.0),
|
||||
cone_angle: f("coneAngle", 90.0),
|
||||
cone_feather: f("coneFeather", 50.0),
|
||||
falloff: v("falloff").map(|x| x.as_enum() as usize).unwrap_or(0).min(2),
|
||||
radius: f("radius", 500.0),
|
||||
falloff_distance: f("falloffDistance", 500.0),
|
||||
casts_shadows: v("castsShadows").map(|x| x.as_bool()).unwrap_or(false),
|
||||
shadow_darkness: f("shadowDarkness", 100.0),
|
||||
shadow_diffusion: f("shadowDiffusion", 0.0),
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let n = comp.layers.iter().filter(|l| l.is_light()).count() + 1;
|
||||
LightDraft {
|
||||
layer: None,
|
||||
name: format!("Light {n}"),
|
||||
kind: 1,
|
||||
color: [1.0, 1.0, 1.0],
|
||||
intensity: 100.0,
|
||||
cone_angle: 90.0,
|
||||
cone_feather: 50.0,
|
||||
falloff: 0,
|
||||
radius: 500.0,
|
||||
falloff_distance: 500.0,
|
||||
casts_shadows: false,
|
||||
shadow_darkness: 100.0,
|
||||
shadow_diffusion: 0.0,
|
||||
}
|
||||
}
|
||||
};
|
||||
app.dialog_state.light = d;
|
||||
app.dialog = Some(Dialog::LightSettings);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn buttons(ui: &mut egui::Ui, t: &Tokens, ok: &mut bool, close: &mut bool) -> (egui::Rect, egui::Rect) {
|
||||
let mut r = (egui::Rect::NOTHING, egui::Rect::NOTHING);
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let b = ui.add(egui::Button::new(egui::RichText::new(" OK ").color(Color32::WHITE)).fill(t.accent));
|
||||
r.0 = b.rect;
|
||||
if b.clicked() {
|
||||
*ok = true;
|
||||
}
|
||||
let c = ui.button("Cancel");
|
||||
r.1 = c.rect;
|
||||
if c.clicked() {
|
||||
*close = true;
|
||||
}
|
||||
});
|
||||
r
|
||||
}
|
||||
|
||||
pub fn camera(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
|
||||
let w = comp_w(app);
|
||||
let mut d = app.dialog_state.camera.clone();
|
||||
let (mut ok, mut close) = (false, false);
|
||||
let mut rects = (egui::Rect::NOTHING, egui::Rect::NOTHING);
|
||||
super::dialogs::modal(ctx, "Camera Settings", vec2(520.0, 420.0), t, |ui| {
|
||||
egui::Grid::new("cam-grid").num_columns(2).spacing([14.0, 9.0]).show(ui, |ui| {
|
||||
ui.label("Type");
|
||||
egui::ComboBox::from_id_salt("cam-type").selected_text(if d.two_node { "Two-Node Camera" } else { "One-Node Camera" }).show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut d.two_node, true, "Two-Node Camera");
|
||||
ui.selectable_value(&mut d.two_node, false, "One-Node Camera");
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label("Name");
|
||||
ui.add(egui::TextEdit::singleline(&mut d.name).desired_width(240.0));
|
||||
ui.end_row();
|
||||
ui.label("Preset");
|
||||
let focal = focal_for_zoom(w, d.zoom);
|
||||
let cur = PRESETS.iter().find(|(_, f)| (f - focal).abs() < 1e-6).map(|(n, _)| *n).unwrap_or("Custom");
|
||||
egui::ComboBox::from_id_salt("cam-preset").selected_text(cur).show_ui(ui, |ui| {
|
||||
for (n, f) in PRESETS {
|
||||
if ui.selectable_label(cur == n, n).clicked() {
|
||||
d.zoom = zoom_for_focal(w, f);
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label("Zoom");
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(egui::DragValue::new(&mut d.zoom).range(1.0..=100000.0).speed(1.0).suffix(" px"));
|
||||
let mut aov = angle_of_view(w, d.zoom);
|
||||
if ui.add(egui::DragValue::new(&mut aov).range(0.1..=179.0).speed(0.1).suffix("°")).changed() {
|
||||
d.zoom = w * 0.5 / (aov.to_radians() * 0.5).tan();
|
||||
}
|
||||
let mut fl = focal_for_zoom(w, d.zoom);
|
||||
if ui.add(egui::DragValue::new(&mut fl).range(0.1..=10000.0).speed(0.1).suffix(" mm")).changed() {
|
||||
d.zoom = zoom_for_focal(w, fl);
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label("Depth of Field");
|
||||
ui.checkbox(&mut d.dof, "Enable Depth of Field");
|
||||
ui.end_row();
|
||||
ui.label("Focus Distance");
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_enabled(!d.lock_to_zoom, egui::DragValue::new(&mut d.focus).range(0.0..=100000.0).suffix(" px"));
|
||||
ui.checkbox(&mut d.lock_to_zoom, "Lock to Zoom");
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label("Aperture");
|
||||
ui.add(egui::DragValue::new(&mut d.aperture).range(0.0..=10000.0).speed(0.1).suffix(" px"));
|
||||
ui.end_row();
|
||||
ui.label("Blur Level");
|
||||
ui.add(egui::DragValue::new(&mut d.blur).range(0.0..=10000.0).suffix(" %"));
|
||||
ui.end_row();
|
||||
});
|
||||
ui.add_space(14.0);
|
||||
rects = buttons(ui, t, &mut ok, &mut close);
|
||||
});
|
||||
if d.lock_to_zoom {
|
||||
d.focus = d.zoom;
|
||||
}
|
||||
app.auto.add("dialog.camera.ok", rects.0, "OK");
|
||||
app.auto.add("dialog.camera.cancel", rects.1, "Cancel");
|
||||
app.dialog_state.camera = d.clone();
|
||||
if ok || super::dialogs::ui_enter(ctx) {
|
||||
let mut p = json!({
|
||||
"name": d.name,
|
||||
"type": if d.two_node { "twoNode" } else { "oneNode" },
|
||||
"zoom": d.zoom,
|
||||
"dof": d.dof,
|
||||
"focusDistance": d.focus,
|
||||
"aperture": d.aperture,
|
||||
"blurLevel": d.blur,
|
||||
});
|
||||
let id = match d.layer {
|
||||
Some(l) => {
|
||||
p["layer"] = json!(l);
|
||||
"layer.cameraSettings"
|
||||
}
|
||||
None => "layer.newCamera",
|
||||
};
|
||||
if let Err(e) = app.session.execute(id, p) {
|
||||
app.ui.status = e.to_string();
|
||||
}
|
||||
close = true;
|
||||
}
|
||||
if close {
|
||||
app.dialog = None;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn light(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
|
||||
let mut d = app.dialog_state.light.clone();
|
||||
let (mut ok, mut close) = (false, false);
|
||||
let mut rects = (egui::Rect::NOTHING, egui::Rect::NOTHING);
|
||||
super::dialogs::modal(ctx, "Light Settings", vec2(480.0, 470.0), t, |ui| {
|
||||
egui::Grid::new("light-grid").num_columns(2).spacing([14.0, 9.0]).show(ui, |ui| {
|
||||
ui.label("Name");
|
||||
ui.add(egui::TextEdit::singleline(&mut d.name).desired_width(220.0));
|
||||
ui.end_row();
|
||||
ui.label("Light Type");
|
||||
egui::ComboBox::from_id_salt("light-type").selected_text(KINDS[d.kind.min(3)].label()).show_ui(ui, |ui| {
|
||||
for (i, k) in KINDS.iter().enumerate() {
|
||||
ui.selectable_value(&mut d.kind, i, k.label());
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label("Color");
|
||||
ui.color_edit_button_rgb(&mut d.color);
|
||||
ui.end_row();
|
||||
ui.label("Intensity");
|
||||
ui.add(egui::DragValue::new(&mut d.intensity).range(-10000.0..=10000.0).suffix(" %"));
|
||||
ui.end_row();
|
||||
let kind = KINDS[d.kind.min(3)];
|
||||
if kind == LightKind::Spot {
|
||||
ui.label("Cone Angle");
|
||||
ui.add(egui::DragValue::new(&mut d.cone_angle).range(0.0..=180.0).suffix("°"));
|
||||
ui.end_row();
|
||||
ui.label("Cone Feather");
|
||||
ui.add(egui::DragValue::new(&mut d.cone_feather).range(0.0..=100.0).suffix(" %"));
|
||||
ui.end_row();
|
||||
}
|
||||
if kind != LightKind::Ambient {
|
||||
ui.label("Falloff");
|
||||
egui::ComboBox::from_id_salt("light-falloff").selected_text(FALLOFFS[d.falloff.min(2)]).show_ui(ui, |ui| {
|
||||
for (i, f) in FALLOFFS.iter().enumerate() {
|
||||
ui.selectable_value(&mut d.falloff, i, *f);
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
if d.falloff > 0 {
|
||||
ui.label("Radius");
|
||||
ui.add(egui::DragValue::new(&mut d.radius).range(0.0..=100000.0).suffix(" px"));
|
||||
ui.end_row();
|
||||
ui.label("Falloff Distance");
|
||||
ui.add(egui::DragValue::new(&mut d.falloff_distance).range(0.0..=100000.0).suffix(" px"));
|
||||
ui.end_row();
|
||||
}
|
||||
ui.label("Shadows");
|
||||
ui.checkbox(&mut d.casts_shadows, "Casts Shadows");
|
||||
ui.end_row();
|
||||
ui.label("Shadow Darkness");
|
||||
ui.add_enabled(d.casts_shadows, egui::DragValue::new(&mut d.shadow_darkness).range(0.0..=100.0).suffix(" %"));
|
||||
ui.end_row();
|
||||
ui.label("Shadow Diffusion");
|
||||
ui.add_enabled(d.casts_shadows, egui::DragValue::new(&mut d.shadow_diffusion).range(0.0..=1000.0).suffix(" px"));
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
ui.add_space(14.0);
|
||||
ui.label(egui::RichText::new("Note: Shadows are only cast from layers with Cast Shadows enabled.").font(Tokens::ui(11.0)).color(t.text_dim));
|
||||
ui.add_space(8.0);
|
||||
rects = buttons(ui, t, &mut ok, &mut close);
|
||||
});
|
||||
app.auto.add("dialog.light.ok", rects.0, "OK");
|
||||
app.auto.add("dialog.light.cancel", rects.1, "Cancel");
|
||||
app.dialog_state.light = d.clone();
|
||||
if ok || super::dialogs::ui_enter(ctx) {
|
||||
let kind = KINDS[d.kind.min(3)];
|
||||
let mut p = json!({
|
||||
"name": d.name,
|
||||
"kind": kind.label(),
|
||||
"color": [d.color[0], d.color[1], d.color[2]],
|
||||
"intensity": d.intensity,
|
||||
});
|
||||
if kind == LightKind::Spot {
|
||||
p["coneAngle"] = json!(d.cone_angle);
|
||||
p["coneFeather"] = json!(d.cone_feather);
|
||||
}
|
||||
if kind != LightKind::Ambient {
|
||||
p["falloff"] = json!(d.falloff);
|
||||
p["radius"] = json!(d.radius);
|
||||
p["falloffDistance"] = json!(d.falloff_distance);
|
||||
p["castsShadows"] = json!(d.casts_shadows);
|
||||
p["shadowDarkness"] = json!(d.shadow_darkness);
|
||||
p["shadowDiffusion"] = json!(d.shadow_diffusion);
|
||||
}
|
||||
let id = match d.layer {
|
||||
Some(l) => {
|
||||
p["layer"] = json!(l);
|
||||
"layer.lightSettings"
|
||||
}
|
||||
None => "layer.newLight",
|
||||
};
|
||||
if let Err(e) = app.session.execute(id, p) {
|
||||
app.ui.status = e.to_string();
|
||||
}
|
||||
close = true;
|
||||
}
|
||||
if close {
|
||||
app.dialog = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Menu/shortcut routing: commands that open a 3D settings dialog when invoked without params.
|
||||
/// Returns true when a dialog was opened.
|
||||
pub fn route(app: &mut EffectcraftApp, id: &str, params: &Value) -> Result<bool, String> {
|
||||
if !params.as_object().is_none_or(|m| m.is_empty() || m.keys().all(|k| k == "layer")) {
|
||||
return Ok(false);
|
||||
}
|
||||
let selected = || -> Option<(u64, bool, bool)> {
|
||||
let c = app.session.active_comp()?;
|
||||
let id = params.get("layer").and_then(Value::as_u64).or_else(|| app.session.state.selected_layers.first().map(|l| l.0))?;
|
||||
let l = c.layer(effectcraft_engine::project::LayerId(id))?;
|
||||
Some((id, l.is_camera(), l.is_light()))
|
||||
};
|
||||
match id {
|
||||
"layer.newCamera" if params.get("layer").is_none() => open_camera(app, None).map(|_| true),
|
||||
"layer.newLight" if params.get("layer").is_none() => open_light(app, None).map(|_| true),
|
||||
"layer.cameraSettings" | "layer.lightSettings" | "layer.settings" => match selected() {
|
||||
Some((l, true, _)) => open_camera(app, Some(l)).map(|_| true),
|
||||
Some((l, _, true)) => open_light(app, Some(l)).map(|_| true),
|
||||
_ => Ok(false),
|
||||
},
|
||||
_ => Ok(false),
|
||||
}
|
||||
}
|
||||
@@ -89,24 +89,18 @@ fn prop_row(
|
||||
if let Some(nv) = nv {
|
||||
set(actions, json!(nv));
|
||||
}
|
||||
// Slider track for slider params.
|
||||
if let ParamUi::Slider { slider_min, slider_max, .. } = prop.ui {
|
||||
let tr = Rect::from_min_max(pos2(vr.max.x + 10.0, cy - 2.0), pos2(r.max.x - 12.0, cy + 2.0));
|
||||
if tr.width() > 40.0 {
|
||||
p.rect_filled(tr, 2.0, t.field_bg);
|
||||
let f = ((v - slider_min) / (slider_max - slider_min)).clamp(0.0, 1.0) as f32;
|
||||
p.rect_filled(Rect::from_min_max(tr.min, pos2(tr.min.x + tr.width() * f, tr.max.y)), 2.0, t.accent.gamma_multiply(0.7));
|
||||
let knob = pos2(tr.min.x + tr.width() * f, cy);
|
||||
p.circle_filled(knob, 5.0, t.text);
|
||||
let sresp = ui.interact(tr.expand2(vec2(4.0, 6.0)), egui::Id::new(("ec-slider", uid)), Sense::click_and_drag());
|
||||
app.auto.add(&format!("effectControls.prop.{uid}.slider"), tr, &prop.name);
|
||||
if (sresp.dragged() || sresp.clicked())
|
||||
&& let Some(pt) = sresp.interact_pointer_pos()
|
||||
{
|
||||
let f = ((pt.x - tr.min.x) / tr.width()).clamp(0.0, 1.0) as f64;
|
||||
set(actions, json!(slider_min + (slider_max - slider_min) * f));
|
||||
// AE hides a slider param's slider until its twirl is opened (see `slider_row`).
|
||||
if matches!(prop.ui, ParamUi::Slider { .. }) {
|
||||
let open = app.ui.fx_slider_open.contains(&uid);
|
||||
let tw = Rect::from_center_size(pos2(swr.min.x - 9.0, cy), vec2(10.0, 10.0));
|
||||
if widgets::twirl(ui, tw, open, egui::Id::new(("ec-stw", uid)), &t).clicked() {
|
||||
if open {
|
||||
app.ui.fx_slider_open.remove(&uid);
|
||||
} else {
|
||||
app.ui.fx_slider_open.insert(uid);
|
||||
}
|
||||
}
|
||||
app.auto.add(&format!("effectControls.prop.{uid}.twirl"), tw, &prop.name);
|
||||
}
|
||||
}
|
||||
Value::Vec2(_) | Value::Vec3(_) => {
|
||||
@@ -139,13 +133,6 @@ fn prop_row(
|
||||
if crate::header::color_popup(ui, pop, sr.left_bottom(), &mut rgb) {
|
||||
set(actions, json!([rgb[0], rgb[1], rgb[2], 1.0]));
|
||||
}
|
||||
p.text(
|
||||
pos2(sr.max.x + 8.0, cy),
|
||||
Align2::LEFT_CENTER,
|
||||
effectcraft_engine::color::Rgba::from_array([c[0] as f32, c[1] as f32, c[2] as f32, 1.0]).to_hex(),
|
||||
Tokens::mono(11.0),
|
||||
t.text_dim,
|
||||
);
|
||||
}
|
||||
Value::Bool(b) => {
|
||||
let cr = Rect::from_min_size(pos2(vx, cy - 8.0), vec2(16.0, 16.0));
|
||||
@@ -187,6 +174,48 @@ fn prop_row(
|
||||
}
|
||||
}
|
||||
|
||||
/// The twirled-open slider under a slider param: track, knob and the slider range's ends.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn slider_row(
|
||||
app: &mut EffectcraftApp,
|
||||
ui: &mut egui::Ui,
|
||||
p: &egui::Painter,
|
||||
layer: &Layer,
|
||||
prop: &Property,
|
||||
ectx: &EvalCtx,
|
||||
r: Rect,
|
||||
x0: f32,
|
||||
actions: &mut Actions,
|
||||
) {
|
||||
let t = app.tokens;
|
||||
let ParamUi::Slider { slider_min, slider_max, decimals, .. } = prop.ui else { return };
|
||||
let Value::Scalar(v) = ectx.value(layer, prop) else { return };
|
||||
let uid = prop.uid;
|
||||
let tr = Rect::from_min_max(pos2(r.min.x + x0, r.min.y + 8.0), pos2(r.max.x - 16.0, r.min.y + 12.0));
|
||||
if tr.width() < 40.0 {
|
||||
return;
|
||||
}
|
||||
p.rect_filled(tr, 2.0, t.field_bg);
|
||||
let f = ((v - slider_min) / (slider_max - slider_min)).clamp(0.0, 1.0) as f32;
|
||||
p.rect_filled(Rect::from_min_max(tr.min, pos2(tr.min.x + tr.width() * f, tr.max.y)), 2.0, t.accent.gamma_multiply(0.7));
|
||||
p.circle_filled(pos2(tr.min.x + tr.width() * f, tr.center().y), 5.0, t.text);
|
||||
let dec = decimals as usize;
|
||||
p.text(pos2(tr.min.x, tr.max.y + 4.0), Align2::LEFT_TOP, format!("{slider_min:.dec$}"), Tokens::ui(10.5), t.text_dim);
|
||||
p.text(pos2(tr.max.x, tr.max.y + 4.0), Align2::RIGHT_TOP, format!("{slider_max:.dec$}"), Tokens::ui(10.5), t.text_dim);
|
||||
let sresp = ui.interact(tr.expand2(vec2(4.0, 6.0)), egui::Id::new(("ec-slider", uid)), Sense::click_and_drag());
|
||||
app.auto.add(&format!("effectControls.prop.{uid}.slider"), tr, &prop.name);
|
||||
if (sresp.dragged() || sresp.clicked())
|
||||
&& let Some(pt) = sresp.interact_pointer_pos()
|
||||
{
|
||||
let f = ((pt.x - tr.min.x) / tr.width()).clamp(0.0, 1.0) as f64;
|
||||
actions.push((
|
||||
"prop.set".into(),
|
||||
json!({"layer": layer.id.0, "prop": uid, "value": slider_min + (slider_max - slider_min) * f, "merge": format!("ec-{uid}")}),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn group_rows(
|
||||
app: &mut EffectcraftApp,
|
||||
ui: &mut egui::Ui,
|
||||
@@ -212,6 +241,11 @@ fn group_rows(
|
||||
continue;
|
||||
}
|
||||
prop_row(app, ui, p, layer, pr, ectx, r, 24.0 + 14.0 * depth as f32, actions);
|
||||
if app.ui.fx_slider_open.contains(&pr.uid) {
|
||||
let sr = Rect::from_min_size(pos2(rect.min.x, *y), vec2(rect.width(), 34.0));
|
||||
*y += 34.0;
|
||||
slider_row(app, ui, p, layer, pr, ectx, sr, 24.0 + 14.0 * depth as f32 + 22.0, actions);
|
||||
}
|
||||
}
|
||||
Node::Group(sg) => {
|
||||
*y += 24.0;
|
||||
@@ -291,7 +325,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
}
|
||||
}
|
||||
bp.text(pos2(tw.max.x + 6.0, r.center().y), Align2::LEFT_CENTER, &g.name, Tokens::semibold(12.0), t.text);
|
||||
let reset = Rect::from_min_size(pos2(r.max.x - 92.0, r.min.y + 4.0), vec2(40.0, 18.0));
|
||||
let reset = Rect::from_min_size(pos2(r.max.x - 96.0, r.min.y + 4.0), vec2(40.0, 18.0));
|
||||
let rresp = ui.interact(reset, egui::Id::new(("ec-reset", g.uid)), Sense::click());
|
||||
bp.text(reset.center(), Align2::CENTER_CENTER, "Reset", Tokens::ui(11.5), if rresp.hovered() { t.hot_text } else { t.text_dim });
|
||||
app.auto.add(&format!("effectControls.effect.{}.reset", g.uid), reset, "Reset");
|
||||
@@ -309,11 +343,19 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
}
|
||||
}
|
||||
}
|
||||
let rm = Rect::from_min_size(pos2(r.max.x - 28.0, r.min.y + 4.0), vec2(18.0, 18.0));
|
||||
if widgets::icon_button(ui, rm, Icon::Close, false, &t, egui::Id::new(("ec-rm", g.uid))).on_hover_text("Remove effect").clicked() {
|
||||
actions.push(("effect.remove".into(), json!({"layer": layer.id.0, "effect": g.uid})));
|
||||
// About…: the effect's name and category (AE's About dialog).
|
||||
let about = Rect::from_min_size(pos2(r.max.x - 50.0, r.min.y + 4.0), vec2(44.0, 18.0));
|
||||
let aresp = ui.interact(about, egui::Id::new(("ec-about", g.uid)), Sense::click());
|
||||
bp.text(about.center(), Align2::CENTER_CENTER, "About...", Tokens::ui(11.5), if aresp.hovered() { t.hot_text } else { t.text_dim });
|
||||
app.auto.add(&format!("effectControls.effect.{}.about", g.uid), about, "About");
|
||||
let apop = egui::Id::new(("ec-about-pop", g.uid));
|
||||
if aresp.clicked() {
|
||||
widgets::open_popup(ui, apop);
|
||||
}
|
||||
if let Some(spec) = g.kind_effect().and_then(effectcraft_engine::effects::find) {
|
||||
let lines = vec![spec.name.to_string(), format!("Category: {}", spec.category), "EffectCraft built-in effect (MIT OR Apache-2.0)".to_string()];
|
||||
let _ = widgets::popup_menu(ui, apop, about.left_bottom(), &lines, None);
|
||||
}
|
||||
app.auto.add(&format!("effectControls.effect.{}.remove", g.uid), rm, "Remove");
|
||||
let hresp =
|
||||
ui.interact(Rect::from_min_max(pos2(tw.max.x, r.min.y), pos2(reset.min.x - 4.0, r.max.y)), egui::Id::new(("ec-hdr", g.uid)), Sense::click());
|
||||
app.auto.add(&format!("effectControls.effect.{}", g.uid), r, &g.name);
|
||||
|
||||
@@ -255,9 +255,6 @@ pub fn open_form(app: &mut EffectcraftApp, id: &str, p: &Value) -> bool {
|
||||
],
|
||||
)
|
||||
}
|
||||
"layer.timeStretch" if !has(p, &["percent", "op"]) => {
|
||||
("Time Stretch".into(), vec![Field::num("percent", "Stretch factor (%)", layer.map(|l| l.stretch).unwrap_or(100.0))])
|
||||
}
|
||||
"layer.precompose" if !has(p, &["name"]) => {
|
||||
let n = s.project.comps().count() + 1;
|
||||
("Pre-compose".into(), vec![Field::text("name", "New composition name", &format!("Pre-comp {n}"))])
|
||||
|
||||
@@ -0,0 +1,452 @@
|
||||
//! The Graph Editor (Timeline ▸ Shift+F3): value graph and speed graph of the selected (or all
|
||||
//! animated) properties, keyframes you can drag in time and value, Bezier/influence handles on
|
||||
//! selected keys, auto-zoom / fit, and the bottom button bar (graph type, show selected,
|
||||
//! auto-zoom, fit, separate dimensions, hold/linear/auto Bezier, Easy Ease family).
|
||||
//!
|
||||
//! Every edit is an engine command (`keys.set`, `keys.setEase`, `keys.select`, `keys.*`).
|
||||
|
||||
use effectcraft_engine::KeyRef;
|
||||
use effectcraft_engine::keyframe::{Interp, Value, side_ease};
|
||||
use effectcraft_engine::project::{Comp, Layer, LayerId, Property};
|
||||
use effectcraft_engine::render::EvalCtx;
|
||||
use effectcraft_engine::time::Tick;
|
||||
use egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
|
||||
use serde_json::json;
|
||||
|
||||
use super::timeline::TMap;
|
||||
use crate::EffectcraftApp;
|
||||
use crate::theme::Tokens;
|
||||
|
||||
type Actions = Vec<(String, serde_json::Value)>;
|
||||
|
||||
const DIM_COLORS: [Color32; 4] =
|
||||
[Color32::from_rgb(0xe0, 0x55, 0x55), Color32::from_rgb(0x5c, 0xc8, 0x5c), Color32::from_rgb(0x50, 0x8c, 0xf0), Color32::from_rgb(0xe8, 0xc8, 0x40)];
|
||||
const PROP_COLORS: [Color32; 6] = [
|
||||
Color32::from_rgb(0xe8, 0xc8, 0x40),
|
||||
Color32::from_rgb(0xd0, 0x70, 0xe0),
|
||||
Color32::from_rgb(0x40, 0xc8, 0xc8),
|
||||
Color32::from_rgb(0xf0, 0x90, 0x40),
|
||||
Color32::from_rgb(0x9c, 0xd8, 0x50),
|
||||
Color32::from_rgb(0xf0, 0x70, 0x90),
|
||||
];
|
||||
|
||||
struct Handle {
|
||||
out: bool,
|
||||
/// Comp seconds / graph value of the handle end.
|
||||
t: f64,
|
||||
v: f64,
|
||||
/// Original speed (sign is kept when dragging in the speed graph).
|
||||
speed: f64,
|
||||
/// Segment duration (layer seconds) the influence is relative to.
|
||||
dur: f64,
|
||||
}
|
||||
|
||||
struct KeyPt {
|
||||
idx: usize,
|
||||
time: Tick,
|
||||
/// Comp seconds.
|
||||
t: f64,
|
||||
v: f64,
|
||||
sel: bool,
|
||||
handles: Vec<Handle>,
|
||||
}
|
||||
|
||||
struct Curve<'a> {
|
||||
layer: &'a Layer,
|
||||
prop: &'a Property,
|
||||
dim: usize,
|
||||
color: Color32,
|
||||
pts: Vec<(f64, f64)>,
|
||||
keys: Vec<KeyPt>,
|
||||
/// Values editable in the value graph (not spatial / combined dimensions).
|
||||
editable: bool,
|
||||
}
|
||||
|
||||
/// Properties shown: the selected ones, or every animated property of the selected layers.
|
||||
fn shown_props(app: &EffectcraftApp, comp: &Comp) -> Vec<(LayerId, u64)> {
|
||||
let st = &app.session.state;
|
||||
let numeric = |pr: &Property| !pr.value.components().is_empty() && pr.value.interpolates();
|
||||
if app.ui.timeline.graph_show_selected && !st.selected_props.is_empty() {
|
||||
return st.selected_props.iter().filter(|(l, u)| comp.layer(*l).and_then(|l| l.props.find(*u)).is_some_and(numeric)).copied().collect();
|
||||
}
|
||||
let mut v = vec![];
|
||||
for l in comp.layers.iter().filter(|l| st.selected_layers.contains(&l.id)) {
|
||||
l.props.walk("", &mut |_, pr| {
|
||||
if (pr.is_animated() || pr.has_expression()) && numeric(pr) {
|
||||
v.push((l.id, pr.uid));
|
||||
}
|
||||
});
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
fn shown_dims(l: &Layer, pr: &Property) -> usize {
|
||||
let n = pr.value.components().len();
|
||||
if pr.shown_dims > 0 && !l.is_3d() { (pr.shown_dims as usize).min(n) } else { n.min(4) }
|
||||
}
|
||||
|
||||
/// Build the curves for the visible time span.
|
||||
fn curves<'a>(app: &EffectcraftApp, comp: &'a Comp, ectx: &EvalCtx, tm: TMap, plot: Rect, speed: bool) -> Vec<Curve<'a>> {
|
||||
let sel = &app.session.state.selected_keys;
|
||||
let n = ((plot.width() / 2.0) as usize).max(2);
|
||||
let mut out = vec![];
|
||||
for (pi, (lid, uid)) in shown_props(app, comp).into_iter().enumerate() {
|
||||
let Some(l) = comp.layer(lid) else { continue };
|
||||
let Some(pr) = l.props.find(uid) else { continue };
|
||||
let spatial = pr.spatial && matches!(pr.value, Value::Vec2(_) | Value::Vec3(_));
|
||||
let dims = if speed && spatial { 1 } else { shown_dims(l, pr) };
|
||||
for d in 0..dims {
|
||||
let color = if dims > 1 { DIM_COLORS[d % 4] } else { PROP_COLORS[pi % PROP_COLORS.len()] };
|
||||
let mut pts = Vec::with_capacity(n);
|
||||
for i in 0..n {
|
||||
let x = plot.min.x + plot.width() * i as f32 / (n - 1) as f32;
|
||||
let ct = tm.t(x);
|
||||
let tt = Tick::from_seconds_f64(ct);
|
||||
let v = if speed {
|
||||
let lt = l.layer_time(tt);
|
||||
if spatial {
|
||||
effectcraft_engine::keyframe::speed(&pr.keys, lt, true)
|
||||
} else {
|
||||
effectcraft_engine::keyframe::velocity(&pr.keys, lt, false).get(d).copied().unwrap_or(0.0).abs()
|
||||
}
|
||||
} else {
|
||||
ectx.at(tt).value(l, pr).components().get(d).copied().unwrap_or(0.0)
|
||||
};
|
||||
pts.push((ct, v));
|
||||
}
|
||||
let mut keys = vec![];
|
||||
for (i, k) in pr.keys.iter().enumerate() {
|
||||
let ks = sel.contains(&KeyRef { layer: lid, prop: uid, time: k.time });
|
||||
let kt = l.comp_time(k.time).seconds();
|
||||
let ed = if spatial { 0 } else { d };
|
||||
let mut handles = vec![];
|
||||
let mut side_speeds = vec![];
|
||||
for out_side in [false, true] {
|
||||
let Some(e) = side_ease(&pr.keys, i, ed, pr.spatial, out_side) else { continue };
|
||||
let j = if out_side { i + 1 } else { i - 1 };
|
||||
let dur = (pr.keys[j].time.seconds() - k.time.seconds()).abs();
|
||||
side_speeds.push(e.speed.abs());
|
||||
let dt = e.influence * dur * if out_side { 1.0 } else { -1.0 };
|
||||
let (hv, show) = if speed { (e.speed.abs(), true) } else { (k.value.components().get(d).copied().unwrap_or(0.0) + e.speed * dt, !spatial) };
|
||||
let bezier = if out_side { k.out_interp == Interp::Bezier } else { k.in_interp == Interp::Bezier };
|
||||
if ks && show && (bezier || speed) {
|
||||
handles.push(Handle { out: out_side, t: kt + dt, v: hv, speed: e.speed, dur });
|
||||
}
|
||||
}
|
||||
let v = if speed {
|
||||
if side_speeds.is_empty() { 0.0 } else { side_speeds.iter().sum::<f64>() / side_speeds.len() as f64 }
|
||||
} else {
|
||||
k.value.components().get(d).copied().unwrap_or(0.0)
|
||||
};
|
||||
keys.push(KeyPt { idx: i, time: k.time, t: kt, v, sel: ks, handles });
|
||||
}
|
||||
out.push(Curve { layer: l, prop: pr, dim: d, color, pts, keys, editable: !spatial });
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn text_button(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, x: &mut f32, y: f32, label: &str, on: bool, id: &str, tip: &str) -> bool {
|
||||
let t = app.tokens;
|
||||
let w = p.layout_no_wrap(label.to_string(), Tokens::ui(11.0), t.text).size().x + 14.0;
|
||||
let r = Rect::from_min_size(pos2(*x, y - 9.0), vec2(w, 18.0));
|
||||
let resp = ui.interact(r, egui::Id::new(("graph-btn", id)), Sense::click()).on_hover_text(tip);
|
||||
p.rect_filled(
|
||||
r,
|
||||
3.0,
|
||||
if on {
|
||||
t.accent.gamma_multiply(0.55)
|
||||
} else if resp.hovered() {
|
||||
t.hover
|
||||
} else {
|
||||
Color32::from_rgb(0x2c, 0x2c, 0x2c)
|
||||
},
|
||||
);
|
||||
p.text(r.center(), Align2::CENTER_CENTER, label, Tokens::ui(11.0), if on { Color32::WHITE } else { t.text });
|
||||
app.auto.add(&format!("timeline.graph.{id}"), r, tip);
|
||||
*x += w + 4.0;
|
||||
resp.clicked()
|
||||
}
|
||||
|
||||
/// Draw the Graph Editor into `area` (the right side of the Timeline) and queue edits.
|
||||
pub(crate) fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, comp: &Comp, ectx: &EvalCtx, tm: TMap, area: Rect, actions: &mut Actions) {
|
||||
let t = app.tokens;
|
||||
let ctx = ui.ctx().clone();
|
||||
let footer_h = 28.0;
|
||||
let plot = Rect::from_min_max(area.min + vec2(0.0, 6.0), pos2(area.max.x, area.max.y - footer_h));
|
||||
let bar = Rect::from_min_max(pos2(area.min.x, area.max.y - footer_h), area.max);
|
||||
// Background first so keys and handles (added later) sit on top for hit-testing.
|
||||
let bg = ui.interact(plot, egui::Id::new("graph-bg"), Sense::click_and_drag());
|
||||
p.rect_filled(area, 0.0, Color32::from_rgb(0x1d, 0x1d, 0x1d));
|
||||
app.auto.add("timeline.graph", plot, &app.ui.timeline.graph_mode.clone());
|
||||
let speed = app.ui.timeline.graph_mode == "speed";
|
||||
let cs = curves(app, comp, ectx, tm, plot, speed);
|
||||
|
||||
// Vertical range: auto-zoom to the curves + handles, or the stored manual range.
|
||||
let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
|
||||
for c in &cs {
|
||||
for (_, v) in &c.pts {
|
||||
lo = lo.min(*v);
|
||||
hi = hi.max(*v);
|
||||
}
|
||||
for k in &c.keys {
|
||||
for v in std::iter::once(k.v).chain(k.handles.iter().map(|h| h.v)) {
|
||||
lo = lo.min(v);
|
||||
hi = hi.max(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !lo.is_finite() {
|
||||
(lo, hi) = (0.0, 100.0);
|
||||
}
|
||||
if speed {
|
||||
lo = lo.min(0.0);
|
||||
}
|
||||
if (hi - lo).abs() < 1e-9 {
|
||||
hi = lo + 1.0;
|
||||
}
|
||||
let pad = (hi - lo) * 0.08;
|
||||
let auto = (lo - pad, hi + pad);
|
||||
// While a key or handle is being dragged the scale stays put (no feedback loop).
|
||||
let drag_id = egui::Id::new("graph-dragging");
|
||||
let dragging = ctx.data(|d| d.get_temp::<bool>(drag_id)).unwrap_or(false) && ctx.input(|i| i.pointer.any_down());
|
||||
let (lo, hi) = if app.ui.timeline.graph_auto_zoom && !dragging { auto } else { app.ui.timeline.graph_range.unwrap_or(auto) };
|
||||
if app.ui.timeline.graph_auto_zoom && !dragging {
|
||||
app.ui.timeline.graph_range = Some((lo, hi));
|
||||
}
|
||||
let ymap = |v: f64| plot.max.y - ((v - lo) / (hi - lo)) as f32 * plot.height();
|
||||
let vmap = |y: f32| lo + (plot.max.y - y) as f64 / plot.height() as f64 * (hi - lo);
|
||||
|
||||
// Grid + value labels.
|
||||
let pc = p.with_clip_rect(plot);
|
||||
let step = nice_step((hi - lo) / 6.0);
|
||||
let mut gv = (lo / step).ceil() * step;
|
||||
while gv <= hi {
|
||||
let y = ymap(gv);
|
||||
pc.line_segment([pos2(plot.min.x, y), pos2(plot.max.x, y)], Stroke::new(1.0, Color32::from_white_alpha(12)));
|
||||
pc.text(pos2(plot.min.x + 4.0, y - 1.0), Align2::LEFT_BOTTOM, fmt(gv, step), Tokens::ui(10.0), t.text_faint);
|
||||
gv += step;
|
||||
}
|
||||
if cs.is_empty() {
|
||||
p.text(plot.center(), Align2::CENTER_CENTER, "Select animated properties to show them in the Graph Editor", Tokens::ui(12.0), t.text_faint);
|
||||
}
|
||||
|
||||
// Curves.
|
||||
for c in &cs {
|
||||
let pts: Vec<Pos2> = c.pts.iter().map(|(ct, v)| pos2(tm.x(*ct), ymap(*v))).collect();
|
||||
pc.add(egui::Shape::line(pts, Stroke::new(1.5, c.color)));
|
||||
}
|
||||
// Keys and handles.
|
||||
let mut key_screens: Vec<(serde_json::Value, Pos2)> = vec![];
|
||||
let fr = comp.frame_rate;
|
||||
for c in &cs {
|
||||
let (lid, uid, d) = (c.layer.id, c.prop.uid, c.dim);
|
||||
for k in &c.keys {
|
||||
let kp = pos2(tm.x(k.t), ymap(k.v));
|
||||
if !plot.expand(6.0).contains(kp) {
|
||||
continue;
|
||||
}
|
||||
let kjson = json!({"layer": lid.0, "prop": uid, "time": k.time.seconds()});
|
||||
key_screens.push((kjson.clone(), kp));
|
||||
// Handles (selected keys).
|
||||
for h in &k.handles {
|
||||
let hp = pos2(tm.x(h.t), ymap(h.v));
|
||||
pc.line_segment([kp, hp], Stroke::new(1.0, Color32::from_rgb(0xd8, 0xd8, 0x60)));
|
||||
pc.circle_filled(hp, 3.5, Color32::from_rgb(0xd8, 0xd8, 0x60));
|
||||
let side = if h.out { "out" } else { "in" };
|
||||
let hr = Rect::from_center_size(hp, vec2(10.0, 10.0));
|
||||
let hresp = ui.interact(hr, egui::Id::new(("ghandle", uid, d, k.idx, side)), Sense::drag());
|
||||
app.auto.add(&format!("timeline.graph.handle.{uid}.{d}.{}.{side}", k.idx), hr, "Bezier handle");
|
||||
if hresp.dragged()
|
||||
&& let Some(pt) = hresp.interact_pointer_pos()
|
||||
{
|
||||
ctx.data_mut(|dd| dd.insert_temp(drag_id, true));
|
||||
let mut dt = (tm.t(pt.x) - k.t) * if h.out { 1.0 } else { -1.0 };
|
||||
dt = dt.max(h.dur * 0.001);
|
||||
let influence = (dt / h.dur.max(1e-9) * 100.0).clamp(0.1, 100.0);
|
||||
let sp = if speed {
|
||||
let mag = vmap(pt.y).max(0.0);
|
||||
if h.speed < 0.0 { -mag } else { mag }
|
||||
} else {
|
||||
let dv = vmap(pt.y) - k.v;
|
||||
dv / dt * if h.out { 1.0 } else { -1.0 }
|
||||
};
|
||||
let mut params = json!({"layer": lid.0, "prop": uid, "time": k.time.seconds(), "side": side, "speed": sp, "influence": influence, "merge": format!("ghandle-{uid}-{}", k.idx)});
|
||||
if c.editable {
|
||||
params["dim"] = json!(d);
|
||||
}
|
||||
actions.push(("keys.setEase".into(), params));
|
||||
}
|
||||
if hresp.drag_stopped() {
|
||||
ctx.data_mut(|dd| dd.insert_temp(drag_id, false));
|
||||
actions.push(("__endMerge".into(), json!({})));
|
||||
}
|
||||
}
|
||||
// The key itself.
|
||||
let col = if k.sel { t.keyframe_selected } else { Color32::from_gray(0xe0) };
|
||||
pc.rect_filled(Rect::from_center_size(kp, vec2(7.0, 7.0)), 0.0, col);
|
||||
pc.rect_stroke(Rect::from_center_size(kp, vec2(7.0, 7.0)), 0.0, Stroke::new(1.0, c.color), StrokeKind::Outside);
|
||||
let kr = Rect::from_center_size(kp, vec2(11.0, 11.0));
|
||||
let kresp = ui.interact(kr, egui::Id::new(("gkey", uid, d, k.idx)), Sense::click_and_drag());
|
||||
app.auto.add(&format!("timeline.graph.key.{uid}.{d}.{}", k.idx), kr, &c.prop.name);
|
||||
let shift = ui.input(|i| i.modifiers.shift);
|
||||
if (kresp.clicked() || kresp.drag_started()) && (!k.sel || shift) {
|
||||
actions.push(("keys.select".into(), json!({"keys": [kjson.clone()], "add": shift})));
|
||||
}
|
||||
if kresp.dragged()
|
||||
&& let Some(pt) = kresp.interact_pointer_pos()
|
||||
{
|
||||
ctx.data_mut(|dd| dd.insert_temp(drag_id, true));
|
||||
let merge = format!("gkey-{uid}-{}", k.idx);
|
||||
let nt = c.layer.layer_time(fr.snap_nearest(Tick::from_seconds_f64(tm.t(pt.x).max(0.0))));
|
||||
let mut params = json!({"layer": lid.0, "prop": uid, "time": k.time.seconds(), "newTime": nt.seconds(), "merge": merge});
|
||||
if !speed && c.editable {
|
||||
let mut comps = c.prop.keys[k.idx].value.components();
|
||||
if d < comps.len() {
|
||||
comps[d] = vmap(pt.y);
|
||||
}
|
||||
params["value"] = if comps.len() == 1 { json!(comps[0]) } else { json!(comps) };
|
||||
}
|
||||
actions.push(("keys.set".into(), params));
|
||||
}
|
||||
if kresp.drag_stopped() {
|
||||
ctx.data_mut(|dd| dd.insert_temp(drag_id, false));
|
||||
actions.push(("__endMerge".into(), json!({})));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Background: click deselects keys, drag box-selects.
|
||||
if bg.clicked() {
|
||||
actions.push(("keys.select".into(), json!({"keys": []})));
|
||||
}
|
||||
if bg.dragged()
|
||||
&& let (Some(o), Some(cur)) = (ctx.input(|i| i.pointer.press_origin()), bg.interact_pointer_pos())
|
||||
{
|
||||
let br = Rect::from_two_pos(o, cur);
|
||||
pc.rect_filled(br, 0.0, t.accent.gamma_multiply(0.12));
|
||||
pc.rect_stroke(br, 0.0, Stroke::new(1.0, t.accent), StrokeKind::Middle);
|
||||
ctx.data_mut(|d| d.insert_temp(egui::Id::new("graph-box"), br));
|
||||
}
|
||||
if bg.drag_stopped()
|
||||
&& let Some(br) = ctx.data(|d| d.get_temp::<Rect>(egui::Id::new("graph-box")))
|
||||
{
|
||||
ctx.data_mut(|d| d.remove::<Rect>(egui::Id::new("graph-box")));
|
||||
let keys: Vec<serde_json::Value> = key_screens.iter().filter(|(_, sp)| br.contains(*sp)).map(|(k, _)| k.clone()).collect();
|
||||
actions.push(("keys.select".into(), json!({"keys": keys, "add": ui.input(|i| i.modifiers.shift)})));
|
||||
}
|
||||
// Wheel over the graph with Alt/Ctrl zooms the value axis (turns auto-zoom off).
|
||||
if ui.rect_contains_pointer(plot) {
|
||||
let (dy, zoom) = ui.input(|i| (i.smooth_scroll_delta.y, i.modifiers.ctrl || i.modifiers.command));
|
||||
if zoom && dy.abs() > 0.0 {
|
||||
let k = (-dy as f64 / 200.0).exp();
|
||||
let mid = (lo + hi) / 2.0;
|
||||
app.ui.timeline.graph_auto_zoom = false;
|
||||
app.ui.timeline.graph_range = Some((mid - (mid - lo) * k, mid + (hi - mid) * k));
|
||||
}
|
||||
}
|
||||
|
||||
// Button bar.
|
||||
p.rect_filled(bar, 0.0, t.panel_bg);
|
||||
p.line_segment([bar.left_top(), bar.right_top()], Stroke::new(1.0, t.separator));
|
||||
let y = bar.center().y;
|
||||
let mut x = bar.min.x + 8.0;
|
||||
let tl = &app.ui.timeline;
|
||||
let (is_value, show_sel, auto_on) = (tl.graph_mode != "speed", tl.graph_show_selected, tl.graph_auto_zoom);
|
||||
if text_button(app, ui, p, &mut x, y, "Value", is_value, "valueGraph", "Edit Value Graph") {
|
||||
app.ui.timeline.graph_mode = "value".into();
|
||||
}
|
||||
if text_button(app, ui, p, &mut x, y, "Speed", !is_value, "speedGraph", "Edit Speed Graph") {
|
||||
app.ui.timeline.graph_mode = "speed".into();
|
||||
}
|
||||
x += 6.0;
|
||||
if text_button(app, ui, p, &mut x, y, "Selected", show_sel, "showSelected", "Show Selected Properties (else all animated properties)") {
|
||||
app.ui.timeline.graph_show_selected = !show_sel;
|
||||
}
|
||||
if text_button(app, ui, p, &mut x, y, "Auto-zoom", auto_on, "autoZoom", "Auto-zoom graph height") {
|
||||
app.ui.timeline.graph_auto_zoom = !auto_on;
|
||||
}
|
||||
if text_button(app, ui, p, &mut x, y, "Fit", false, "fit", "Fit all graphs to view") {
|
||||
app.ui.timeline.graph_auto_zoom = true;
|
||||
app.ui.timeline.pps = None;
|
||||
}
|
||||
if text_button(app, ui, p, &mut x, y, "Fit Selection", false, "fitSelection", "Fit selection to view") {
|
||||
fit_selection(app, &cs, tm, plot);
|
||||
}
|
||||
x += 6.0;
|
||||
let pos_sel = app.session.state.selected_props.iter().find_map(|(l, u)| {
|
||||
let layer = comp.layer(*l)?;
|
||||
let tr = layer.transform()?;
|
||||
(tr.get("position").is_some_and(|p| p.uid == *u) || ["positionX", "positionY", "positionZ"].iter().any(|m| tr.get(m).is_some_and(|p| p.uid == *u)))
|
||||
.then_some(l.0)
|
||||
});
|
||||
if text_button(app, ui, p, &mut x, y, "Separate Dimensions", false, "separateDimensions", "Separate Dimensions (Position)")
|
||||
&& let Some(l) = pos_sel.or(app.session.state.selected_layers.first().map(|l| l.0))
|
||||
{
|
||||
actions.push(("prop.separateDimensions".into(), json!({"layer": l})));
|
||||
}
|
||||
x += 6.0;
|
||||
for (label, cmd, params, tip) in [
|
||||
("Hold", "keys.interpolation", json!({"interpolation": "hold"}), "Convert selected keyframes to Hold"),
|
||||
("Linear", "keys.interpolation", json!({"interpolation": "linear"}), "Convert selected keyframes to Linear"),
|
||||
("Auto Bezier", "keys.interpolation", json!({"interpolation": "autoBezier"}), "Convert selected keyframes to Auto Bezier"),
|
||||
("Easy Ease", "keys.easyEase", json!({}), "Easy Ease (F9)"),
|
||||
("Ease In", "keys.easyEaseIn", json!({}), "Easy Ease In (Shift+F9)"),
|
||||
("Ease Out", "keys.easyEaseOut", json!({}), "Easy Ease Out (Ctrl+Shift+F9)"),
|
||||
] {
|
||||
let id = cmd.trim_start_matches("keys.").to_string() + label.split_whitespace().next().unwrap_or("");
|
||||
if text_button(app, ui, p, &mut x, y, label, false, &id, tip) {
|
||||
actions.push((cmd.into(), params));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Zoom time and value to the selected keys (and their handles).
|
||||
fn fit_selection(app: &mut EffectcraftApp, cs: &[Curve], tm: TMap, plot: Rect) {
|
||||
let mut t0 = f64::INFINITY;
|
||||
let mut t1 = f64::NEG_INFINITY;
|
||||
let mut v0 = f64::INFINITY;
|
||||
let mut v1 = f64::NEG_INFINITY;
|
||||
for c in cs {
|
||||
for k in c.keys.iter().filter(|k| k.sel) {
|
||||
for (t, v) in std::iter::once((k.t, k.v)).chain(k.handles.iter().map(|h| (h.t, h.v))) {
|
||||
t0 = t0.min(t);
|
||||
t1 = t1.max(t);
|
||||
v0 = v0.min(v);
|
||||
v1 = v1.max(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !t0.is_finite() {
|
||||
return;
|
||||
}
|
||||
let span = (t1 - t0).max(0.2);
|
||||
let pps = (plot.width() as f64 * 0.8 / span).clamp(5.0, 4000.0);
|
||||
app.ui.timeline.pps = Some(pps);
|
||||
app.ui.timeline.start = (t0 - span * 0.1).max(0.0);
|
||||
let pad = ((v1 - v0) * 0.15).max(1.0);
|
||||
app.ui.timeline.graph_auto_zoom = false;
|
||||
app.ui.timeline.graph_range = Some((v0 - pad, v1 + pad));
|
||||
let _ = tm;
|
||||
}
|
||||
|
||||
fn nice_step(raw: f64) -> f64 {
|
||||
let raw = raw.abs().max(1e-9);
|
||||
let mag = 10f64.powf(raw.log10().floor());
|
||||
let n = raw / mag;
|
||||
mag * if n < 1.5 {
|
||||
1.0
|
||||
} else if n < 3.5 {
|
||||
2.0
|
||||
} else if n < 7.5 {
|
||||
5.0
|
||||
} else {
|
||||
10.0
|
||||
}
|
||||
}
|
||||
|
||||
fn fmt(v: f64, step: f64) -> String {
|
||||
let dec = if step >= 1.0 { 0 } else { (-step.log10()).ceil() as usize };
|
||||
let s = format!("{v:.dec$}");
|
||||
if s.trim_start_matches('-').chars().all(|c| c == '0' || c == '.') { s.trim_start_matches('-').to_string() } else { s }
|
||||
}
|
||||
@@ -62,11 +62,32 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let tc = crate::panels::timecode(&app.session, &c, app.session.time());
|
||||
p.text(pos2(x0, y), Align2::LEFT_CENTER, if sel.is_empty() { "No layer selected".to_string() } else { sel.join(", ") }, Tokens::semibold(12.0), t.text);
|
||||
p.text(pos2(x0, y + 18.0), Align2::LEFT_CENTER, format!("Time: {tc}"), Tokens::ui(12.0), t.text_dim);
|
||||
// One layer selected: Duration, In and Out like AE's Info panel.
|
||||
let mut ly = y + 36.0;
|
||||
if let [id] = app.session.state.selected_layers.as_slice()
|
||||
&& let Some(l) = c.layer(*id)
|
||||
{
|
||||
let tc = |t| crate::panels::timecode(&app.session, &c, t);
|
||||
let lines = [
|
||||
// A length, so no start-timecode offset.
|
||||
format!("Duration: {}", {
|
||||
let fr = c.frame_rate;
|
||||
let n = fr.frame_at(l.out_point) - fr.frame_at(l.in_point);
|
||||
let s = effectcraft_engine::time::format_timecode_frames(n, fr, fr.supports_drop_frame());
|
||||
if fr.supports_drop_frame() { s } else { s.replace(';', ":") }
|
||||
}),
|
||||
format!("In: {}, Out: {}", tc(l.in_point), tc(effectcraft_engine::time::Tick(l.out_point.0 - c.frame_duration().0))),
|
||||
];
|
||||
for line in lines {
|
||||
p.text(pos2(x0, ly), Align2::LEFT_CENTER, line, Tokens::ui(12.0), t.text_dim);
|
||||
ly += 18.0;
|
||||
}
|
||||
}
|
||||
let ms = app.frames.last_ms.lock().map(|v| *v).unwrap_or(0.0);
|
||||
p.text(pos2(x0, y + 36.0), Align2::LEFT_CENTER, format!("Render: {ms:.0} ms • UI {:.0} fps", app.fps), Tokens::ui(11.5), t.text_faint);
|
||||
p.text(pos2(x0, ly), Align2::LEFT_CENTER, format!("Render: {ms:.0} ms • UI {:.0} fps", app.fps), Tokens::ui(11.5), t.text_faint);
|
||||
if !app.session.state.selected_keys.is_empty() {
|
||||
p.text(
|
||||
pos2(x0, y + 54.0),
|
||||
pos2(x0, ly + 18.0),
|
||||
Align2::LEFT_CENTER,
|
||||
format!("{} keyframes selected", app.session.state.selected_keys.len()),
|
||||
Tokens::ui(11.5),
|
||||
|
||||
@@ -0,0 +1,287 @@
|
||||
//! Animation dialogs: Keyframe Velocity, Keyframe Interpolation and Time Stretch. Each one is
|
||||
//! pre-filled from the engine (`keys.info`, the layer) and commits through one engine command.
|
||||
|
||||
use egui::{Color32, vec2};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::theme::Tokens;
|
||||
use crate::{Dialog, EffectcraftApp};
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct VelocityDraft {
|
||||
pub dims: usize,
|
||||
pub units: String,
|
||||
pub name: String,
|
||||
pub in_speed: Vec<f64>,
|
||||
pub in_inf: Vec<f64>,
|
||||
pub out_speed: Vec<f64>,
|
||||
pub out_inf: Vec<f64>,
|
||||
/// Which sides exist (first key has no incoming side, last none outgoing).
|
||||
pub has_in: bool,
|
||||
pub has_out: bool,
|
||||
pub continuous: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct InterpDraft {
|
||||
/// Index into TEMPORAL / SPATIAL / ROVING (0 = Current Settings).
|
||||
pub temporal: usize,
|
||||
pub spatial: usize,
|
||||
pub roving: usize,
|
||||
pub has_spatial: bool,
|
||||
pub count: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct StretchDraft {
|
||||
pub percent: f64,
|
||||
pub duration: f64,
|
||||
/// 0 = Layer In-point, 1 = Current Frame, 2 = Layer Out-point.
|
||||
pub hold: usize,
|
||||
pub orig_duration: f64,
|
||||
pub orig_percent: f64,
|
||||
}
|
||||
|
||||
pub const TEMPORAL: [(&str, &str); 6] = [
|
||||
("Current Settings", ""),
|
||||
("Linear", "linear"),
|
||||
("Bezier", "bezier"),
|
||||
("Continuous Bezier", "continuousBezier"),
|
||||
("Auto Bezier", "autoBezier"),
|
||||
("Hold", "hold"),
|
||||
];
|
||||
pub const SPATIAL: [(&str, &str); 5] =
|
||||
[("Current Settings", ""), ("Linear", "linear"), ("Bezier", "bezier"), ("Continuous Bezier", "continuousBezier"), ("Auto Bezier", "autoBezier")];
|
||||
pub const ROVING: [&str; 3] = ["Current Settings", "Lock To Time", "Rove Across Time"];
|
||||
|
||||
fn num(v: &Value) -> f64 {
|
||||
v.as_f64().unwrap_or(0.0)
|
||||
}
|
||||
|
||||
/// Animation ▸ Keyframe Velocity… (⇧⌘K) with keys selected.
|
||||
pub fn open_velocity(app: &mut EffectcraftApp) -> Result<(), String> {
|
||||
let info = app.session.execute("keys.info", json!({})).map_err(|e| e.to_string())?;
|
||||
let first = info.as_array().and_then(|a| a.first()).ok_or("select keyframes first")?;
|
||||
let dims = first["dims"].as_u64().unwrap_or(1).max(1) as usize;
|
||||
let side = |k: &str| -> (Vec<f64>, Vec<f64>, bool) {
|
||||
let a = first[k].as_array().cloned().unwrap_or_default();
|
||||
let has = a.iter().any(|e| !e.is_null());
|
||||
let sp = (0..dims).map(|d| a.get(d).map(|e| num(&e["speed"])).unwrap_or(0.0)).collect();
|
||||
let inf = (0..dims).map(|d| a.get(d).map(|e| num(&e["influence"])).filter(|v| *v > 0.0).unwrap_or(33.33)).collect();
|
||||
(sp, inf, has)
|
||||
};
|
||||
let (in_speed, in_inf, has_in) = side("inEase");
|
||||
let (out_speed, out_inf, has_out) = side("outEase");
|
||||
app.dialog_state.velocity = VelocityDraft {
|
||||
dims,
|
||||
units: first["units"].as_str().unwrap_or("units/sec").into(),
|
||||
name: first["name"].as_str().unwrap_or("").into(),
|
||||
in_speed,
|
||||
in_inf,
|
||||
out_speed,
|
||||
out_inf,
|
||||
has_in,
|
||||
has_out,
|
||||
continuous: first["continuous"].as_bool().unwrap_or(false),
|
||||
};
|
||||
app.dialog = Some(Dialog::KeyVelocity);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Animation ▸ Keyframe Interpolation… (⌥⌘K).
|
||||
pub fn open_interpolation(app: &mut EffectcraftApp) -> Result<(), String> {
|
||||
let info = app.session.execute("keys.info", json!({})).map_err(|e| e.to_string())?;
|
||||
let a = info.as_array().cloned().unwrap_or_default();
|
||||
if a.is_empty() {
|
||||
return Err("select keyframes first".into());
|
||||
}
|
||||
app.dialog_state.interp = InterpDraft { has_spatial: a.iter().any(|k| !k["spatial"].is_null()), count: a.len(), ..Default::default() };
|
||||
app.dialog = Some(Dialog::KeyInterpolation);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Layer ▸ Time ▸ Time Stretch…
|
||||
pub fn open_time_stretch(app: &mut EffectcraftApp) -> Result<(), String> {
|
||||
let lid = *app.session.state.selected_layers.first().ok_or("select a layer first")?;
|
||||
let l = app.session.active_comp().and_then(|c| c.layer(lid)).ok_or("no layer")?;
|
||||
let dur = (l.out_point - l.in_point).seconds();
|
||||
app.dialog_state.stretch = StretchDraft { percent: l.stretch, duration: dur, hold: 0, orig_duration: dur, orig_percent: l.stretch };
|
||||
app.dialog = Some(Dialog::TimeStretch);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn buttons(ui: &mut egui::Ui, app: &mut EffectcraftApp, t: &Tokens, prefix: &str) -> (bool, bool) {
|
||||
let (mut ok, mut cancel) = (false, false);
|
||||
ui.add_space(14.0);
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let r = ui.add(egui::Button::new(egui::RichText::new(" OK ").color(Color32::WHITE)).fill(t.accent));
|
||||
app.auto.add(&format!("{prefix}.ok"), r.rect, "OK");
|
||||
ok = r.clicked();
|
||||
let r = ui.button("Cancel");
|
||||
app.auto.add(&format!("{prefix}.cancel"), r.rect, "Cancel");
|
||||
cancel = r.clicked();
|
||||
});
|
||||
(ok, cancel)
|
||||
}
|
||||
|
||||
fn drag(ui: &mut egui::Ui, app: &mut EffectcraftApp, id: &str, v: &mut f64, speed: f64, range: std::ops::RangeInclusive<f64>, suffix: &str, enabled: bool) {
|
||||
let r = ui.add_enabled(enabled, egui::DragValue::new(v).speed(speed).range(range).max_decimals(2).suffix(suffix));
|
||||
app.auto.add(id, r.rect, id);
|
||||
}
|
||||
|
||||
pub fn velocity(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
|
||||
let mut d = app.dialog_state.velocity.clone();
|
||||
let (mut ok, mut cancel) = (false, false);
|
||||
let title = if d.name.is_empty() { "Keyframe Velocity".to_string() } else { format!("Keyframe Velocity: {}", d.name) };
|
||||
let h = 250.0 + 2.0 * 26.0 * d.dims as f32;
|
||||
super::dialogs::modal(ctx, &title, vec2(440.0, h), t, |ui| {
|
||||
for (label, out) in [("Incoming Velocity", false), ("Outgoing Velocity", true)] {
|
||||
ui.label(egui::RichText::new(label).font(Tokens::medium(12.5)));
|
||||
let enabled = if out { d.has_out } else { d.has_in };
|
||||
egui::Grid::new(("vel", out)).num_columns(3).spacing([12.0, 6.0]).show(ui, |ui| {
|
||||
for dim in 0..d.dims {
|
||||
let tag = if d.dims > 1 { format!("Dimension {}", ["X", "Y", "Z", "W"][dim.min(3)]) } else { String::new() };
|
||||
ui.label(egui::RichText::new(tag).color(t.text_dim));
|
||||
let side = if out { "out" } else { "in" };
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Speed:");
|
||||
let v = if out { &mut d.out_speed[dim] } else { &mut d.in_speed[dim] };
|
||||
drag(ui, app, &format!("dialog.velocity.{side}Speed.{dim}"), v, 1.0, -1e7..=1e7, "", enabled);
|
||||
ui.label(egui::RichText::new(&d.units).color(t.text_dim));
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Influence:");
|
||||
let v = if out { &mut d.out_inf[dim] } else { &mut d.in_inf[dim] };
|
||||
drag(ui, app, &format!("dialog.velocity.{side}Influence.{dim}"), v, 0.2, 0.1..=100.0, " %", enabled);
|
||||
});
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
}
|
||||
let r = ui.checkbox(&mut d.continuous, "Continuous (Lock Outgoing to Incoming)");
|
||||
app.auto.add("dialog.velocity.continuous", r.rect, "Continuous");
|
||||
if d.continuous {
|
||||
d.out_speed = d.in_speed.clone();
|
||||
}
|
||||
(ok, cancel) = buttons(ui, app, t, "dialog.velocity");
|
||||
});
|
||||
app.dialog_state.velocity = d.clone();
|
||||
if ok || super::dialogs::ui_enter(ctx) {
|
||||
let mut params = json!({"continuous": d.continuous});
|
||||
if d.has_in {
|
||||
params["inSpeed"] = json!(d.in_speed);
|
||||
params["inInfluence"] = json!(d.in_inf);
|
||||
}
|
||||
if d.has_out {
|
||||
params["outSpeed"] = json!(d.out_speed);
|
||||
params["outInfluence"] = json!(d.out_inf);
|
||||
}
|
||||
if let Err(e) = app.session.execute("keys.velocity", params) {
|
||||
app.ui.status = e.to_string();
|
||||
}
|
||||
cancel = true;
|
||||
}
|
||||
if cancel {
|
||||
app.dialog = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn combo(ui: &mut egui::Ui, app: &mut EffectcraftApp, id: &str, sel: &mut usize, opts: &[&str], enabled: bool) {
|
||||
ui.add_enabled_ui(enabled, |ui| {
|
||||
let r = egui::ComboBox::from_id_salt(id).width(200.0).selected_text(opts[*sel]).show_ui(ui, |ui| {
|
||||
for (i, o) in opts.iter().enumerate() {
|
||||
ui.selectable_value(sel, i, *o);
|
||||
}
|
||||
});
|
||||
app.auto.add(id, r.response.rect, id);
|
||||
});
|
||||
}
|
||||
|
||||
pub fn interpolation(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
|
||||
let mut d = app.dialog_state.interp.clone();
|
||||
let (mut ok, mut cancel) = (false, false);
|
||||
super::dialogs::modal(ctx, "Keyframe Interpolation", vec2(440.0, 250.0), t, |ui| {
|
||||
egui::Grid::new("interp-grid").num_columns(2).spacing([14.0, 10.0]).show(ui, |ui| {
|
||||
ui.label("Temporal Interpolation:");
|
||||
combo(ui, app, "dialog.interpolation.temporal", &mut d.temporal, &TEMPORAL.map(|x| x.0), true);
|
||||
ui.end_row();
|
||||
ui.label("Spatial Interpolation:");
|
||||
combo(ui, app, "dialog.interpolation.spatial", &mut d.spatial, &SPATIAL.map(|x| x.0), d.has_spatial);
|
||||
ui.end_row();
|
||||
ui.label("Roving:");
|
||||
combo(ui, app, "dialog.interpolation.roving", &mut d.roving, &ROVING, d.has_spatial);
|
||||
ui.end_row();
|
||||
});
|
||||
ui.add_space(6.0);
|
||||
ui.label(egui::RichText::new(format!("{} keyframe{} selected", d.count, if d.count == 1 { "" } else { "s" })).color(t.text_dim));
|
||||
(ok, cancel) = buttons(ui, app, t, "dialog.interpolation");
|
||||
});
|
||||
app.dialog_state.interp = d.clone();
|
||||
if ok || super::dialogs::ui_enter(ctx) {
|
||||
let mut params = json!({});
|
||||
if d.temporal > 0 {
|
||||
params["interpolation"] = json!(TEMPORAL[d.temporal].1);
|
||||
}
|
||||
if d.spatial > 0 && d.has_spatial {
|
||||
params["spatial"] = json!(SPATIAL[d.spatial].1);
|
||||
}
|
||||
if d.roving > 0 && d.has_spatial {
|
||||
params["roving"] = json!(d.roving == 2);
|
||||
}
|
||||
if params.as_object().is_some_and(|m| !m.is_empty())
|
||||
&& let Err(e) = app.session.execute("keys.interpolation", params)
|
||||
{
|
||||
app.ui.status = e.to_string();
|
||||
}
|
||||
cancel = true;
|
||||
}
|
||||
if cancel {
|
||||
app.dialog = None;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn time_stretch(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
|
||||
let mut d = app.dialog_state.stretch.clone();
|
||||
let (mut ok, mut cancel) = (false, false);
|
||||
super::dialogs::modal(ctx, "Time Stretch", vec2(420.0, 300.0), t, |ui| {
|
||||
ui.label(egui::RichText::new("Stretch").font(Tokens::medium(12.5)));
|
||||
egui::Grid::new("stretch-grid").num_columns(2).spacing([14.0, 8.0]).show(ui, |ui| {
|
||||
ui.label("Original Duration:");
|
||||
ui.label(format!("{:.2} s", d.orig_duration));
|
||||
ui.end_row();
|
||||
ui.label("Stretch Factor:");
|
||||
let before = d.percent;
|
||||
drag(ui, app, "dialog.timeStretch.percent", &mut d.percent, 0.5, -10000.0..=10000.0, " %", true);
|
||||
if (before - d.percent).abs() > 1e-9 && d.orig_percent.abs() > 1e-9 {
|
||||
d.duration = d.orig_duration * d.percent.abs() / d.orig_percent.abs();
|
||||
}
|
||||
ui.end_row();
|
||||
ui.label("New Duration:");
|
||||
let before = d.duration;
|
||||
drag(ui, app, "dialog.timeStretch.duration", &mut d.duration, 0.05, 0.01..=100000.0, " s", true);
|
||||
if (before - d.duration).abs() > 1e-9 && d.orig_duration > 1e-9 {
|
||||
d.percent = d.orig_percent.signum() * d.orig_percent.abs() * d.duration / d.orig_duration;
|
||||
}
|
||||
ui.end_row();
|
||||
});
|
||||
ui.add_space(10.0);
|
||||
ui.label(egui::RichText::new("Hold In Place").font(Tokens::medium(12.5)));
|
||||
for (i, l) in ["Layer In-point", "Current Frame", "Layer Out-point"].into_iter().enumerate() {
|
||||
let r = ui.radio_value(&mut d.hold, i, l);
|
||||
app.auto.add(&format!("dialog.timeStretch.hold.{i}"), r.rect, l);
|
||||
}
|
||||
(ok, cancel) = buttons(ui, app, t, "dialog.timeStretch");
|
||||
});
|
||||
app.dialog_state.stretch = d.clone();
|
||||
if ok || super::dialogs::ui_enter(ctx) {
|
||||
let hold = ["in", "current", "out"][d.hold.min(2)];
|
||||
if let Err(e) = app.session.execute("layer.timeStretch", json!({"percent": d.percent, "hold": hold})) {
|
||||
app.ui.status = e.to_string();
|
||||
}
|
||||
cancel = true;
|
||||
}
|
||||
if cancel {
|
||||
app.dialog = None;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
//! Smaller panels: Preview, Audio, History, Markers, Wiggler, Render Queue, the Home screen and
|
||||
//! placeholders.
|
||||
//! Smaller panels: Preview, Audio, History, Markers, Wiggler, the Home screen and placeholders.
|
||||
|
||||
use egui::{Align2, Color32, Rect, Sense, Stroke, pos2, vec2};
|
||||
use egui::{Align2, Color32, Rect, Sense, pos2, vec2};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::dock::PanelKind;
|
||||
@@ -185,25 +184,6 @@ pub fn wiggler(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
app.auto.add("wiggler.apply", b, "Apply");
|
||||
}
|
||||
|
||||
/// Render Queue: comps queued for export with output settings.
|
||||
pub fn render_queue(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let t = app.tokens;
|
||||
let p = ui.painter().with_clip_rect(rect);
|
||||
let hdr = Rect::from_min_size(rect.min, vec2(rect.width(), 40.0));
|
||||
p.text(pos2(hdr.min.x + 14.0, hdr.center().y), Align2::LEFT_CENTER, "Render Queue", Tokens::semibold(13.0), t.text);
|
||||
let b = Rect::from_min_size(pos2(hdr.max.x - 100.0, hdr.min.y + 8.0), vec2(84.0, 24.0));
|
||||
let _ = widgets::text_button(ui, b, "Render", true, &t, egui::Id::new("rq-render"));
|
||||
app.auto.add("renderQueue.render", b, "Render");
|
||||
p.line_segment([hdr.left_bottom(), hdr.right_bottom()], Stroke::new(1.0, t.separator));
|
||||
p.text(
|
||||
pos2(rect.min.x + 14.0, hdr.max.y + 20.0),
|
||||
Align2::LEFT_CENTER,
|
||||
"Composition ▸ Add to Render Queue (⌃⌘M) to queue a render.",
|
||||
Tokens::ui(12.0),
|
||||
t.text_faint,
|
||||
);
|
||||
}
|
||||
|
||||
/// Home screen: new/open, recent, and community links.
|
||||
pub fn start_screen(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let t = app.tokens;
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
//! Panel bodies.
|
||||
|
||||
pub mod comp_settings;
|
||||
pub mod dialogs;
|
||||
pub mod dialogs_3d;
|
||||
pub mod effect_controls;
|
||||
pub mod effects_presets;
|
||||
pub mod forms;
|
||||
pub mod graph;
|
||||
pub mod info;
|
||||
pub mod key_dialogs;
|
||||
pub mod misc;
|
||||
pub mod project;
|
||||
pub mod properties;
|
||||
pub mod render_queue;
|
||||
pub mod text_panels;
|
||||
pub mod timeline;
|
||||
pub mod viewer;
|
||||
@@ -34,11 +39,8 @@ pub fn timecode(session: &Session, comp: &Comp, t: Tick) -> String {
|
||||
let fr = comp.frame_rate;
|
||||
match session.project.settings.time_display {
|
||||
TimeDisplayStyle::Frames => format!("{:05}", fr.frame_at(t) + session.project.settings.frame_start),
|
||||
TimeDisplayStyle::Timecode => {
|
||||
let df = fr.supports_drop_frame();
|
||||
let s = effectcraft_engine::time::format_timecode_frames(fr.frame_at(t + comp.display_start), fr, df);
|
||||
if df { s } else { s.replace(';', ":") }
|
||||
}
|
||||
// AE's display: `0:00:02:15` (non-drop-frame counting, as AE shows new comps).
|
||||
TimeDisplayStyle::Timecode => effectcraft_engine::time::format_timecode_ae(fr.frame_at(t + comp.display_start), fr, false),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,7 +67,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: PanelKind, rect: Rec
|
||||
PanelKind::History => misc::history(app, ui, rect),
|
||||
PanelKind::Markers => misc::markers(app, ui, rect),
|
||||
PanelKind::Wiggler => misc::wiggler(app, ui, rect),
|
||||
PanelKind::RenderQueue => misc::render_queue(app, ui, rect),
|
||||
PanelKind::RenderQueue => render_queue::show(app, ui, rect),
|
||||
other => misc::placeholder(app, ui, rect, other),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,10 +23,48 @@ fn item_icon(it: &Item) -> Icon {
|
||||
}
|
||||
}
|
||||
|
||||
fn fmt_dur(secs: f64, fps: f64) -> String {
|
||||
let f = (secs * fps).round() as i64;
|
||||
/// Duration as AE prints it in the Project panel header: `0:00:10:00` (h:mm:ss:ff).
|
||||
pub fn fmt_dur(secs: f64, fps: f64) -> String {
|
||||
let fpsi = fps.round().max(1.0) as i64;
|
||||
format!("0;{:02};{:02};{:02}", f / fpsi / 60, (f / fpsi) % 60, f % fpsi)
|
||||
let f = (secs * fps).round() as i64;
|
||||
let s = f / fpsi;
|
||||
format!("{}:{:02}:{:02}:{:02}", s / 3600, (s / 60) % 60, s % 60, f % fpsi)
|
||||
}
|
||||
|
||||
/// File size the way AE's Size column shows it (`512 KB`, `12.3 MB`).
|
||||
pub fn fmt_size(bytes: u64) -> String {
|
||||
const K: f64 = 1024.0;
|
||||
let b = bytes as f64;
|
||||
if b < K * K {
|
||||
format!("{} KB", (b / K).ceil() as u64)
|
||||
} else if b < K * K * K {
|
||||
format!("{:.1} MB", b / (K * K))
|
||||
} else {
|
||||
format!("{:.2} GB", b / (K * K * K))
|
||||
}
|
||||
}
|
||||
|
||||
/// Footage file size on disk (comps, solids and folders have none).
|
||||
fn file_size(it: &Item) -> Option<u64> {
|
||||
match &it.kind {
|
||||
ItemKind::Footage(f) => std::fs::metadata(&f.path).ok().map(|m| m.len()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sort siblings by the Project panel's sort column; ties fall back to the name.
|
||||
pub fn sort_items(items: &mut [&Item], col: &str, desc: bool) {
|
||||
let name = |i: &Item| i.name.to_lowercase();
|
||||
items.sort_by(|a, b| {
|
||||
let o = match col {
|
||||
"type" => a.type_name().cmp(b.type_name()),
|
||||
"size" => file_size(a).cmp(&file_size(b)),
|
||||
"fps" => a.frame_rate().map(|r| r.as_f64()).partial_cmp(&b.frame_rate().map(|r| r.as_f64())).unwrap_or(std::cmp::Ordering::Equal),
|
||||
_ => std::cmp::Ordering::Equal,
|
||||
}
|
||||
.then_with(|| name(a).cmp(&name(b)));
|
||||
if desc { o.reverse() } else { o }
|
||||
});
|
||||
}
|
||||
|
||||
pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
@@ -82,13 +120,41 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
// Column header.
|
||||
let hdr = Rect::from_min_size(pos2(rect.min.x, sr.max.y + 6.0), vec2(rect.width(), 20.0));
|
||||
p.line_segment([hdr.left_bottom(), hdr.right_bottom()], Stroke::new(1.0, t.separator));
|
||||
let name_w = (rect.width() * 0.48).max(140.0);
|
||||
let name_w = (rect.width() * 0.40).max(120.0);
|
||||
let col_type = rect.min.x + name_w + 30.0;
|
||||
let col_size = col_type + 76.0;
|
||||
p.text(pos2(rect.min.x + 26.0, hdr.center().y), Align2::LEFT_CENTER, "Name", Tokens::ui(11.0), t.text_dim);
|
||||
let col_size = col_type + 80.0;
|
||||
let col_fps = col_size + 52.0;
|
||||
// Clickable headers sort (click again to reverse), with AE's ▲/▼ indicator.
|
||||
let cols = [
|
||||
("name", "Name", rect.min.x + 26.0, name_w - 26.0),
|
||||
("type", "Type", col_type, 76.0),
|
||||
("size", "Size", col_size, 48.0),
|
||||
("fps", "Frame Rate", col_fps, 70.0),
|
||||
];
|
||||
for (key, label, x, w) in cols {
|
||||
let hr = Rect::from_min_size(pos2(x - 4.0, hdr.min.y), vec2(w, hdr.height()));
|
||||
let resp = ui.interact(hr, egui::Id::new(("proj-sort", key)), Sense::click());
|
||||
p.with_clip_rect(hr).text(pos2(x, hdr.center().y), Align2::LEFT_CENTER, label, Tokens::ui(11.0), if resp.hovered() { t.text } else { t.text_dim });
|
||||
if app.ui.project_sort == key {
|
||||
let c = pos2(hr.max.x - 10.0, hdr.center().y);
|
||||
let d = if app.ui.project_sort_desc { 1.0 } else { -1.0 };
|
||||
p.add(egui::Shape::convex_polygon(
|
||||
vec![pos2(c.x - 4.0, c.y - 2.0 * d), pos2(c.x + 4.0, c.y - 2.0 * d), pos2(c.x, c.y + 2.5 * d)],
|
||||
t.text_dim,
|
||||
Stroke::NONE,
|
||||
));
|
||||
}
|
||||
app.auto.add(&format!("project.sort.{key}"), hr, label);
|
||||
if resp.clicked() {
|
||||
if app.ui.project_sort == key {
|
||||
app.ui.project_sort_desc = !app.ui.project_sort_desc;
|
||||
} else {
|
||||
app.ui.project_sort = key.to_string();
|
||||
app.ui.project_sort_desc = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
icons::paint(&p, Rect::from_center_size(pos2(rect.min.x + name_w + 14.0, hdr.center().y), vec2(10.0, 10.0)), Icon::Keyframe, t.text_dim);
|
||||
p.text(pos2(col_type, hdr.center().y), Align2::LEFT_CENTER, "Type", Tokens::ui(11.0), t.text_dim);
|
||||
p.text(pos2(col_size, hdr.center().y), Align2::LEFT_CENTER, "Size", Tokens::ui(11.0), t.text_dim);
|
||||
// Rows.
|
||||
let footer_h = 28.0;
|
||||
let list = Rect::from_min_max(pos2(rect.min.x, hdr.max.y), pos2(rect.max.x, rect.max.y - footer_h));
|
||||
@@ -97,7 +163,9 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let query = app.ui.project_search.to_lowercase();
|
||||
let mut rows: Vec<(ItemId, usize)> = vec![];
|
||||
fn walk(app: &EffectcraftApp, folder: Option<ItemId>, depth: usize, q: &str, out: &mut Vec<(ItemId, usize)>) {
|
||||
for it in app.session.project.children(folder) {
|
||||
let mut kids = app.session.project.children(folder);
|
||||
sort_items(&mut kids, &app.ui.project_sort, app.ui.project_sort_desc);
|
||||
for it in kids {
|
||||
if !q.is_empty() && !it.is_folder() && !it.name.to_lowercase().contains(q) {
|
||||
continue;
|
||||
}
|
||||
@@ -140,17 +208,22 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
}
|
||||
}
|
||||
}
|
||||
icons::paint(
|
||||
&lp,
|
||||
Rect::from_center_size(pos2(x0 + 18.0, r.center().y), vec2(14.0, 14.0)),
|
||||
item_icon(&it),
|
||||
if it.is_folder() { Color32::from_rgb(0xd8, 0xc0, 0x60) } else { t.text_dim },
|
||||
icons::paint(&lp, Rect::from_center_size(pos2(x0 + 18.0, r.center().y), vec2(14.0, 14.0)), item_icon(&it), t.text_dim);
|
||||
let name_clip = Rect::from_min_max(pos2(x0 + 30.0, r.min.y), pos2(r.min.x + name_w + 6.0, r.max.y)).intersect(list);
|
||||
lp.with_clip_rect(name_clip).text(
|
||||
pos2(x0 + 30.0, r.center().y),
|
||||
Align2::LEFT_CENTER,
|
||||
&it.name,
|
||||
Tokens::ui(12.0),
|
||||
if selected { Color32::WHITE } else { t.text },
|
||||
);
|
||||
lp.text(pos2(x0 + 30.0, r.center().y), Align2::LEFT_CENTER, &it.name, Tokens::ui(12.0), if selected { Color32::WHITE } else { t.text });
|
||||
lp.rect_filled(Rect::from_center_size(pos2(r.min.x + name_w + 14.0, r.center().y), vec2(10.0, 10.0)), 2.0, Tokens::label(it.label));
|
||||
lp.text(pos2(col_type, r.center().y), Align2::LEFT_CENTER, it.type_name(), Tokens::ui(11.5), t.text_dim);
|
||||
if let Some((w, h)) = it.dimensions() {
|
||||
lp.text(pos2(col_size, r.center().y), Align2::LEFT_CENTER, format!("{w} x {h}"), Tokens::ui(11.5), t.text_dim);
|
||||
if let Some(b) = file_size(&it) {
|
||||
lp.text(pos2(col_size, r.center().y), Align2::LEFT_CENTER, fmt_size(b), Tokens::ui(11.5), t.text_dim);
|
||||
}
|
||||
if let Some(fr) = it.frame_rate() {
|
||||
lp.text(pos2(col_fps + 66.0, r.center().y), Align2::RIGHT_CENTER, format!("{:.2}", fr.as_f64()), Tokens::ui(11.5), t.text_dim);
|
||||
}
|
||||
let resp = ui.interact(r.intersect(list), egui::Id::new(("pitem", id.0)), Sense::click_and_drag());
|
||||
app.auto.add(&format!("project.item.{}", id.0), r, &it.name);
|
||||
@@ -260,3 +333,31 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ae_duration_and_size_formats() {
|
||||
assert_eq!(fmt_dur(10.0, 29.97), "0:00:10:00");
|
||||
assert_eq!(fmt_dur(3725.48, 25.0), "1:02:05:12");
|
||||
assert_eq!(fmt_size(1000), "1 KB");
|
||||
assert_eq!(fmt_size(5 * 1024 * 1024 + 300_000), "5.3 MB");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folders_sort_with_items_by_name() {
|
||||
let mut p = effectcraft_engine::project::Project::default();
|
||||
let l = effectcraft_engine::color::Label::Yellow;
|
||||
p.add_item("Solids", l, None, ItemKind::Folder);
|
||||
p.add_item("Precomps", l, None, ItemKind::Folder);
|
||||
p.add_item("EffectCraft Intro", l, None, ItemKind::Folder);
|
||||
let mut kids = p.children(None);
|
||||
sort_items(&mut kids, "name", false);
|
||||
let names: Vec<&str> = kids.iter().map(|i| i.name.as_str()).collect();
|
||||
assert_eq!(names, ["EffectCraft Intro", "Precomps", "Solids"]);
|
||||
sort_items(&mut kids, "name", true);
|
||||
assert_eq!(kids[0].name, "Solids");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,504 @@
|
||||
//! Render Queue panel, laid out like After Effects': a Current Render strip (progress bar,
|
||||
//! elapsed / estimated remaining, Stop and Render buttons), the queue list (twirl, Render
|
||||
//! checkbox, label, #, Comp Name, Status, Started, Render Time) with expandable Render Settings,
|
||||
//! Output Module and Output To rows, and a status footer.
|
||||
//!
|
||||
//! Every control dispatches an engine `renderQueue.*` command (so agents can do the same) and
|
||||
//! registers an automation id: `renderQueue.render`, `renderQueue.stop`,
|
||||
//! `renderQueue.item.<n>.{row,twirl,render,renderSettings,outputModule,outputTo,outputPath}`.
|
||||
|
||||
use effectcraft_engine::project::render_queue::{AudioOutput, Channels, OutputFormat, ProResProfile, RenderQuality, RenderQueueItem, RenderStatus, TimeSpan};
|
||||
use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::theme::Tokens;
|
||||
use crate::{EffectcraftApp, widgets};
|
||||
|
||||
const TOP_H: f32 = 74.0;
|
||||
const HEAD_H: f32 = 22.0;
|
||||
const ROW_H: f32 = 24.0;
|
||||
const FOOT_H: f32 = 24.0;
|
||||
|
||||
/// `h:mm:ss` for a duration in seconds.
|
||||
pub fn hms(secs: f64) -> String {
|
||||
let s = secs.max(0.0).round() as u64;
|
||||
format!("{}:{:02}:{:02}", s / 3600, s / 60 % 60, s % 60)
|
||||
}
|
||||
|
||||
/// Unix seconds → `YYYY-MM-DD hh:mm:ss` (UTC).
|
||||
pub fn utc_stamp(unix: u64) -> String {
|
||||
let days = (unix / 86_400) as i64;
|
||||
let rem = unix % 86_400;
|
||||
// Civil-from-days (proleptic Gregorian).
|
||||
let z = days + 719_468;
|
||||
let era = z.div_euclid(146_097);
|
||||
let doe = z - era * 146_097;
|
||||
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let d = doy - (153 * mp + 2) / 5 + 1;
|
||||
let m = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||
let y = yoe + era * 400 + i64::from(m <= 2);
|
||||
format!("{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}", rem / 3600, rem / 60 % 60, rem % 60)
|
||||
}
|
||||
|
||||
fn status_color(t: &Tokens, s: &RenderStatus) -> Color32 {
|
||||
match s {
|
||||
RenderStatus::Done => Color32::from_rgb(0x6c, 0xc0, 0x6c),
|
||||
RenderStatus::Rendering => t.accent_hover,
|
||||
RenderStatus::Failed(_) | RenderStatus::NeedsOutput => t.danger,
|
||||
RenderStatus::UserStopped => t.warning,
|
||||
RenderStatus::Unqueued => t.text_faint,
|
||||
RenderStatus::Queued => t.text,
|
||||
}
|
||||
}
|
||||
|
||||
/// Render Settings menu: (label, params).
|
||||
fn settings_menu(it: &RenderQueueItem) -> Vec<(String, Value)> {
|
||||
let s = &it.settings;
|
||||
let mark = |on: bool, l: &str| if on { format!("✓ {l}") } else { format!(" {l}") };
|
||||
let mut v = vec![
|
||||
(mark(s.quality == RenderQuality::Best, "Best Settings"), json!({"quality": "best"})),
|
||||
(mark(s.quality == RenderQuality::Draft, "Draft Settings"), json!({"quality": "draft"})),
|
||||
("-".into(), Value::Null),
|
||||
];
|
||||
for (l, k) in [("Full", "full"), ("Half", "half"), ("Third", "third"), ("Quarter", "quarter")] {
|
||||
v.push((mark(s.resolution_label() == l, &format!("Resolution: {l}")), json!({"resolution": k})));
|
||||
}
|
||||
v.push(("-".into(), Value::Null));
|
||||
v.push((mark(s.time_span == TimeSpan::WorkArea, "Time Span: Work Area Only"), json!({"timeSpan": "workArea"})));
|
||||
v.push((mark(s.time_span == TimeSpan::LengthOfComp, "Time Span: Length of Comp"), json!({"timeSpan": "comp"})));
|
||||
v.push(("-".into(), Value::Null));
|
||||
v.push((mark(s.frame_rate.is_none(), "Frame Rate: Use comp's frame rate"), json!({"frameRate": null})));
|
||||
for fps in [12.0, 15.0, 23.976, 24.0, 25.0, 29.97, 30.0, 50.0, 60.0] {
|
||||
let on = s.frame_rate.is_some_and(|r| (r.as_f64() - fps).abs() < 0.01);
|
||||
v.push((mark(on, &format!("Frame Rate: {fps}")), json!({"frameRate": fps})));
|
||||
}
|
||||
v.push(("-".into(), Value::Null));
|
||||
v.push((mark(s.motion_blur, "Motion Blur: On for Checked Layers"), json!({"motionBlur": !s.motion_blur})));
|
||||
v.push((mark(s.skip_existing, "Skip Existing Files"), json!({"skipExisting": !s.skip_existing})));
|
||||
v
|
||||
}
|
||||
|
||||
/// Output Module menu: (label, params).
|
||||
fn output_menu(it: &RenderQueueItem, available: &[OutputFormat]) -> Vec<(String, Value)> {
|
||||
let o = &it.output;
|
||||
let mark = |on: bool, l: &str| if on { format!("✓ {l}") } else { format!(" {l}") };
|
||||
let mut v = Vec::new();
|
||||
for f in OutputFormat::ALL {
|
||||
if available.contains(&f) {
|
||||
v.push((mark(o.format == f, &format!("Format: {}", f.label())), json!({"format": format!("{f:?}")})));
|
||||
}
|
||||
}
|
||||
v.push(("-".into(), Value::Null));
|
||||
v.push((mark(o.channels == Channels::Rgb, "Channels: RGB"), json!({"channels": "rgb"})));
|
||||
if o.format.supports_alpha() {
|
||||
v.push((mark(o.channels == Channels::Rgba, "Channels: RGB + Alpha"), json!({"channels": "rgba"})));
|
||||
}
|
||||
match o.format {
|
||||
OutputFormat::ProRes => {
|
||||
v.push(("-".into(), Value::Null));
|
||||
for p in ProResProfile::ALL {
|
||||
v.push((mark(o.prores_profile == p, p.label()), json!({"proresProfile": format!("{p:?}")})));
|
||||
}
|
||||
}
|
||||
OutputFormat::H264 => {
|
||||
v.push(("-".into(), Value::Null));
|
||||
for kbps in [2_000, 5_000, 10_000, 20_000, 40_000] {
|
||||
v.push((mark(o.bitrate_kbps == kbps, &format!("Bitrate: {} Mbps", kbps / 1000)), json!({"bitrate": kbps})));
|
||||
}
|
||||
}
|
||||
OutputFormat::JpegSequence => {
|
||||
v.push(("-".into(), Value::Null));
|
||||
for q in [60u8, 80, 90, 100] {
|
||||
v.push((mark(o.quality == q, &format!("Quality: {q}")), json!({"quality": q})));
|
||||
}
|
||||
}
|
||||
OutputFormat::Gif => {
|
||||
v.push(("-".into(), Value::Null));
|
||||
v.push((mark(o.gif_loop, "Loop Forever"), json!({"loop": !o.gif_loop})));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if o.format.supports_audio() {
|
||||
v.push(("-".into(), Value::Null));
|
||||
for (a, l) in [(AudioOutput::Auto, "auto"), (AudioOutput::On, "on"), (AudioOutput::Off, "off")] {
|
||||
let label = match a {
|
||||
AudioOutput::Auto => "Audio Output: Auto",
|
||||
AudioOutput::On => "Audio Output: On (48 kHz stereo)",
|
||||
AudioOutput::Off => "Audio Output: Off",
|
||||
};
|
||||
v.push((mark(o.audio == a, label), json!({"audio": l})));
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
const OUTPUT_TEMPLATES: [&str; 4] = [
|
||||
"[compName].[fileExtension]",
|
||||
"[compName]_[width]x[height].[fileExtension]",
|
||||
"[projectName]_[compName].[fileExtension]",
|
||||
"[compName]/[compName].[fileExtension]",
|
||||
];
|
||||
|
||||
fn output_to_menu(it: &RenderQueueItem) -> Vec<(String, Value)> {
|
||||
let mut v: Vec<(String, Value)> = OUTPUT_TEMPLATES
|
||||
.iter()
|
||||
.map(|t| {
|
||||
let t = if it.output.format.is_sequence() { t.replace(".[fileExtension]", "_[#####].[fileExtension]") } else { t.to_string() };
|
||||
(t.clone(), json!({"path": t}))
|
||||
})
|
||||
.collect();
|
||||
v.push(("-".into(), Value::Null));
|
||||
v.push(("Choose File…".into(), json!({"choose": true})));
|
||||
v
|
||||
}
|
||||
|
||||
pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let t = app.tokens;
|
||||
let p = ui.painter().with_clip_rect(rect);
|
||||
let queue: Vec<RenderQueueItem> = app.session.project.render_queue.clone();
|
||||
let progress = app.session.render_progress();
|
||||
let rendering = app.session.is_rendering();
|
||||
let available = app.session.exporter.as_ref().map(|e| e.formats()).unwrap_or_default();
|
||||
let mut actions: Vec<(&'static str, Value)> = Vec::new();
|
||||
let state_id = egui::Id::new("rq-ui");
|
||||
let (mut open, mut selected): (Vec<u64>, Option<u64>) = ui.data(|d| d.get_temp(state_id).unwrap_or_default());
|
||||
|
||||
// ---------------------------------------------------------- Current Render strip
|
||||
let top = Rect::from_min_size(rect.min, vec2(rect.width(), TOP_H));
|
||||
p.rect_filled(top, 0.0, t.tl_ruler_bg);
|
||||
let x0 = rect.min.x + 12.0;
|
||||
p.text(pos2(x0, top.min.y + 16.0), Align2::LEFT_CENTER, "Current Render", Tokens::semibold(12.5), t.text);
|
||||
let cur_item = progress.as_ref().and_then(|p| p.current).and_then(|id| queue.iter().find(|i| i.id == id));
|
||||
let cur_name = cur_item.and_then(|i| app.session.project.item(i.comp)).map(|i| i.name.clone());
|
||||
if let Some(pr) = &progress {
|
||||
let rem = pr.remaining.map(hms).unwrap_or_else(|| "–".into());
|
||||
p.text(
|
||||
pos2(top.max.x - 12.0, top.min.y + 16.0),
|
||||
Align2::RIGHT_CENTER,
|
||||
format!("Elapsed: {} Est. Remain: {rem}", hms(pr.item_elapsed)),
|
||||
Tokens::ui(11.5),
|
||||
t.text_dim,
|
||||
);
|
||||
}
|
||||
let bw = 76.0;
|
||||
let render_b = Rect::from_min_size(pos2(top.max.x - 12.0 - bw, top.min.y + 34.0), vec2(bw, 26.0));
|
||||
let stop_b = Rect::from_min_size(pos2(render_b.min.x - 8.0 - bw, render_b.min.y), vec2(bw, 26.0));
|
||||
let can_render = !rendering && queue.iter().any(RenderQueueItem::is_queued) && !available.is_empty();
|
||||
if widgets::text_button(ui, render_b, "Render", can_render, &t, egui::Id::new("rq-render")).clicked() && can_render {
|
||||
actions.push(("renderQueue.render", json!({"wait": false})));
|
||||
}
|
||||
app.auto.add("renderQueue.render", render_b, "Render");
|
||||
if rendering {
|
||||
if widgets::text_button(ui, stop_b, "Stop", false, &t, egui::Id::new("rq-stop")).clicked() {
|
||||
actions.push(("renderQueue.stop", json!({})));
|
||||
}
|
||||
app.auto.add("renderQueue.stop", stop_b, "Stop");
|
||||
}
|
||||
// Progress bar.
|
||||
let bar =
|
||||
Rect::from_min_max(pos2(x0, render_b.min.y + 4.0), pos2(if rendering { stop_b.min.x - 16.0 } else { render_b.min.x - 16.0 }, render_b.max.y - 4.0));
|
||||
p.rect_filled(bar, 3.0, t.field_bg);
|
||||
p.rect_stroke(bar, 3.0, Stroke::new(1.0, t.field_border), StrokeKind::Inside);
|
||||
let frac = progress.as_ref().filter(|p| p.total > 0).map(|p| (p.done as f32 / p.total as f32).clamp(0.0, 1.0)).unwrap_or(0.0);
|
||||
if frac > 0.0 {
|
||||
let fill = Rect::from_min_size(bar.min, vec2(bar.width() * frac, bar.height()));
|
||||
p.rect_filled(fill, 3.0, t.accent);
|
||||
}
|
||||
let bar_text = match (&progress, &cur_name) {
|
||||
(Some(pr), Some(n)) if rendering => format!("Rendering “{n}” {} / {} frames", pr.done, pr.total),
|
||||
_ => {
|
||||
let n = queue.iter().filter(|i| i.is_queued()).count();
|
||||
if available.is_empty() {
|
||||
"Export is not available in this build".to_string()
|
||||
} else if n == 0 {
|
||||
"Composition ▸ Add to Render Queue (Ctrl/⌘ M) to queue a render".to_string()
|
||||
} else {
|
||||
format!("{n} item(s) queued")
|
||||
}
|
||||
}
|
||||
};
|
||||
p.text(pos2(bar.min.x + 8.0, bar.center().y), Align2::LEFT_CENTER, bar_text, Tokens::ui(11.5), t.text);
|
||||
app.auto.add("renderQueue.progress", bar, &format!("{:.0}%", frac * 100.0));
|
||||
|
||||
// ---------------------------------------------------------- column header
|
||||
let head = Rect::from_min_size(pos2(rect.min.x, top.max.y), vec2(rect.width(), HEAD_H));
|
||||
p.rect_filled(head, 0.0, t.panel_bg);
|
||||
p.line_segment([head.left_bottom(), head.right_bottom()], Stroke::new(1.0, t.separator));
|
||||
// Columns: twirl | Render | label | # | Comp Name | Status | Started | Render Time
|
||||
let cx_twirl = rect.min.x + 4.0;
|
||||
let cx_render = cx_twirl + 20.0;
|
||||
let cx_label = cx_render + 48.0;
|
||||
let cx_num = cx_label + 20.0;
|
||||
let cx_name = cx_num + 28.0;
|
||||
let w_time = 92.0;
|
||||
let w_started = 156.0;
|
||||
let w_status = 112.0;
|
||||
let cx_time = (rect.max.x - w_time).max(cx_name + 120.0);
|
||||
let cx_started = cx_time - w_started;
|
||||
let cx_status = cx_started - w_status;
|
||||
let hy = head.center().y;
|
||||
for (x, l) in [(cx_render, "Render"), (cx_num, "#"), (cx_name, "Comp Name"), (cx_status, "Status"), (cx_started, "Started"), (cx_time, "Render Time")] {
|
||||
p.text(pos2(x + 2.0, hy), Align2::LEFT_CENTER, l, Tokens::ui(11.0), t.text_dim);
|
||||
}
|
||||
for x in [cx_render, cx_label, cx_num, cx_name, cx_status, cx_started, cx_time] {
|
||||
p.line_segment([pos2(x - 3.0, head.min.y + 4.0), pos2(x - 3.0, head.max.y - 4.0)], Stroke::new(1.0, t.separator));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------- items
|
||||
let list = Rect::from_min_max(pos2(rect.min.x, head.max.y), pos2(rect.max.x, rect.max.y - FOOT_H));
|
||||
let lp = p.with_clip_rect(list);
|
||||
let mut y = list.min.y;
|
||||
if queue.is_empty() {
|
||||
lp.text(pos2(list.center().x, list.min.y + 30.0), Align2::CENTER_CENTER, "The render queue is empty.", Tokens::ui(12.0), t.text_faint);
|
||||
}
|
||||
let editing_id = egui::Id::new("rq-edit-output");
|
||||
let mut editing: Option<(u64, String)> = ui.data(|d| d.get_temp(editing_id));
|
||||
for (k, it) in queue.iter().enumerate() {
|
||||
let n = k + 1;
|
||||
let aid = |s: &str| format!("renderQueue.item.{n}.{s}");
|
||||
let row = Rect::from_min_size(pos2(list.min.x, y), vec2(list.width(), ROW_H));
|
||||
y += ROW_H;
|
||||
let is_sel = selected == Some(it.id);
|
||||
lp.rect_filled(
|
||||
row,
|
||||
0.0,
|
||||
if is_sel {
|
||||
t.row_selected
|
||||
} else if k % 2 == 0 {
|
||||
t.row
|
||||
} else {
|
||||
t.row_alt
|
||||
},
|
||||
);
|
||||
let row_resp = ui.interact(row, egui::Id::new(("rq-row", it.id)), Sense::click());
|
||||
if row_resp.clicked() {
|
||||
selected = Some(it.id);
|
||||
app.ui.focused = crate::dock::PanelKind::RenderQueue;
|
||||
}
|
||||
let item_id = it.id;
|
||||
row_resp.context_menu(|ui| {
|
||||
if ui.button("Duplicate").clicked() {
|
||||
actions.push(("renderQueue.duplicate", json!({"item": item_id})));
|
||||
ui.close();
|
||||
}
|
||||
if ui.button("Remove").clicked() {
|
||||
actions.push(("renderQueue.remove", json!({"item": item_id})));
|
||||
ui.close();
|
||||
}
|
||||
if k > 0 && ui.button("Move Up").clicked() {
|
||||
actions.push(("renderQueue.move", json!({"item": item_id, "to": n - 1})));
|
||||
ui.close();
|
||||
}
|
||||
if n < queue.len() && ui.button("Move Down").clicked() {
|
||||
actions.push(("renderQueue.move", json!({"item": item_id, "to": n + 1})));
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
app.auto.add(&aid("row"), row, &format!("#{n}"));
|
||||
let is_open = open.contains(&it.id);
|
||||
let tw = Rect::from_center_size(pos2(cx_twirl + 8.0, row.center().y), vec2(14.0, 14.0));
|
||||
if widgets::twirl(ui, tw, is_open, egui::Id::new(("rq-twirl", it.id)), &t).clicked() {
|
||||
if is_open {
|
||||
open.retain(|i| *i != it.id);
|
||||
} else {
|
||||
open.push(it.id);
|
||||
}
|
||||
}
|
||||
app.auto.add(&aid("twirl"), tw, "Twirl");
|
||||
let cb = Rect::from_center_size(pos2(cx_render + 20.0, row.center().y), vec2(18.0, 18.0));
|
||||
if widgets::checkbox(ui, cb, it.render, &t, egui::Id::new(("rq-cb", it.id))).clicked() && !rendering {
|
||||
actions.push(("renderQueue.setRender", json!({"item": it.id, "render": !it.render})));
|
||||
}
|
||||
app.auto.add(&aid("render"), cb, if it.render { "Render: on" } else { "Render: off" });
|
||||
let comp_item = app.session.project.item(it.comp);
|
||||
let label_col = comp_item.map(|i| Tokens::label(i.label)).unwrap_or(t.text_faint);
|
||||
lp.rect_filled(Rect::from_center_size(pos2(cx_label + 6.0, row.center().y), vec2(10.0, 10.0)), 2.0, label_col);
|
||||
lp.text(pos2(cx_num + 2.0, row.center().y), Align2::LEFT_CENTER, n.to_string(), Tokens::ui(12.0), t.text_dim);
|
||||
let name = comp_item.map(|i| i.name.clone()).unwrap_or_else(|| "(missing composition)".into());
|
||||
lp.text(pos2(cx_name + 2.0, row.center().y), Align2::LEFT_CENTER, &name, Tokens::ui(12.0), t.text);
|
||||
let status = if rendering && progress.as_ref().and_then(|p| p.current) == Some(it.id) {
|
||||
let pr = progress.as_ref().expect("progress");
|
||||
format!("Rendering {:.0}%", if pr.total > 0 { pr.done as f64 * 100.0 / pr.total as f64 } else { 0.0 })
|
||||
} else {
|
||||
it.status.label().to_string()
|
||||
};
|
||||
let st_rect = Rect::from_min_size(pos2(cx_status, row.min.y), vec2(w_status, ROW_H));
|
||||
lp.text(pos2(cx_status + 2.0, row.center().y), Align2::LEFT_CENTER, &status, Tokens::ui(12.0), status_color(&t, &it.status));
|
||||
if let RenderStatus::Failed(e) = &it.status {
|
||||
ui.interact(st_rect, egui::Id::new(("rq-st", it.id)), Sense::hover()).on_hover_text(e);
|
||||
}
|
||||
app.auto.add(&aid("status"), st_rect, &status);
|
||||
if let Some(s) = it.started {
|
||||
lp.text(pos2(cx_started + 2.0, row.center().y), Align2::LEFT_CENTER, utc_stamp(s), Tokens::ui(11.5), t.text_dim);
|
||||
} else {
|
||||
lp.text(pos2(cx_started + 2.0, row.center().y), Align2::LEFT_CENTER, "-", Tokens::ui(11.5), t.text_faint);
|
||||
}
|
||||
let rt = if progress.as_ref().and_then(|p| p.current) == Some(it.id) && rendering {
|
||||
progress.as_ref().map(|p| hms(p.item_elapsed)).unwrap_or_default()
|
||||
} else {
|
||||
it.render_time.map(|s| if s < 60.0 { format!("{s:.1} s") } else { hms(s) }).unwrap_or_else(|| "-".into())
|
||||
};
|
||||
lp.text(pos2(cx_time + 2.0, row.center().y), Align2::LEFT_CENTER, rt, Tokens::ui(11.5), t.text_dim);
|
||||
|
||||
if !is_open {
|
||||
continue;
|
||||
}
|
||||
// Expanded: Render Settings / Output Module + Output To.
|
||||
let ix = cx_name;
|
||||
for sub in 0..2 {
|
||||
let r = Rect::from_min_size(pos2(list.min.x, y), vec2(list.width(), ROW_H));
|
||||
y += ROW_H;
|
||||
lp.rect_filled(r, 0.0, t.panel_bg);
|
||||
let (label, summary, key, menu): (&str, String, &str, Vec<(String, Value)>) = if sub == 0 {
|
||||
("Render Settings:", it.settings.summary(), "renderSettings", settings_menu(it))
|
||||
} else {
|
||||
("Output Module:", it.output.summary(), "outputModule", output_menu(it, &available))
|
||||
};
|
||||
lp.text(pos2(cx_num - 6.0, r.center().y), Align2::LEFT_CENTER, label, Tokens::ui(11.5), t.text_dim);
|
||||
let dd = Rect::from_min_size(pos2(ix + 70.0, r.min.y + 3.0), vec2(220.0, ROW_H - 6.0));
|
||||
let did = egui::Id::new(("rq-dd", it.id, sub));
|
||||
if widgets::dropdown(ui, dd, &summary, &t, did).clicked() && !rendering {
|
||||
widgets::open_popup(ui, did);
|
||||
}
|
||||
let labels: Vec<String> = menu.iter().map(|(l, _)| l.clone()).collect();
|
||||
if let Some(i) = widgets::popup_menu(ui, did, dd.left_bottom(), &labels, None) {
|
||||
let mut params = menu[i].1.clone();
|
||||
params["item"] = json!(it.id);
|
||||
actions.push((if sub == 0 { "renderQueue.setRenderSettings" } else { "renderQueue.setOutputModule" }, params));
|
||||
}
|
||||
app.auto.add(&aid(key), dd, &summary);
|
||||
if sub == 0 {
|
||||
let comp = app.session.project.comp(it.comp);
|
||||
if let Some(c) = comp {
|
||||
let (w, h) = it.settings.output_size(c);
|
||||
let (a, b) = it.settings.span(c);
|
||||
let info = format!(
|
||||
"{w}×{h} · {:.3} fps · {:.2}s – {:.2}s · {} frames",
|
||||
it.settings.rate(c).as_f64(),
|
||||
a.seconds(),
|
||||
b.seconds(),
|
||||
it.settings.frame_count(c)
|
||||
);
|
||||
lp.text(pos2(dd.max.x + 14.0, r.center().y), Align2::LEFT_CENTER, info, Tokens::ui(11.0), t.text_faint);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Output To.
|
||||
let ox = dd.max.x + 14.0;
|
||||
lp.text(pos2(ox, r.center().y), Align2::LEFT_CENTER, "Output To:", Tokens::ui(11.5), t.text_dim);
|
||||
let odd = Rect::from_min_size(pos2(ox + 62.0, r.min.y + 3.0), vec2(22.0, ROW_H - 6.0));
|
||||
let oid = egui::Id::new(("rq-out", it.id));
|
||||
if widgets::dropdown(ui, odd, "", &t, oid).clicked() && !rendering {
|
||||
widgets::open_popup(ui, oid);
|
||||
}
|
||||
app.auto.add(&aid("outputTo"), odd, "Output To");
|
||||
let omenu = output_to_menu(it);
|
||||
let olabels: Vec<String> = omenu.iter().map(|(l, _)| l.clone()).collect();
|
||||
if let Some(i) = widgets::popup_menu(ui, oid, odd.left_bottom(), &olabels, None) {
|
||||
if omenu[i].1.get("choose").is_some() {
|
||||
let default = app.session.resolve_output(it).unwrap_or_default();
|
||||
let picked = app
|
||||
.hooks
|
||||
.pick_save
|
||||
.as_ref()
|
||||
.and_then(|f| f(std::path::Path::new(&default).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default().as_str()));
|
||||
match picked {
|
||||
Some(path) => actions.push(("renderQueue.setOutput", json!({"item": it.id, "path": path}))),
|
||||
None if app.hooks.pick_save.is_none() => editing = Some((it.id, it.output.output.clone())),
|
||||
None => {}
|
||||
}
|
||||
} else {
|
||||
let mut params = omenu[i].1.clone();
|
||||
params["item"] = json!(it.id);
|
||||
actions.push(("renderQueue.setOutput", params));
|
||||
}
|
||||
}
|
||||
let path_rect = Rect::from_min_max(pos2(odd.max.x + 6.0, r.min.y + 2.0), pos2(r.max.x - 8.0, r.max.y - 2.0));
|
||||
if editing.as_ref().is_some_and(|(id, _)| *id == it.id) {
|
||||
let mut buf = editing.as_ref().map(|(_, b)| b.clone()).unwrap_or_default();
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(path_rect));
|
||||
let resp = child.add(egui::TextEdit::singleline(&mut buf).desired_width(path_rect.width()).font(Tokens::ui(11.5)));
|
||||
if resp.lost_focus() {
|
||||
if ui.input(|i| i.key_pressed(egui::Key::Enter)) && !buf.trim().is_empty() {
|
||||
actions.push(("renderQueue.setOutput", json!({"item": it.id, "path": buf.trim()})));
|
||||
}
|
||||
editing = None;
|
||||
} else {
|
||||
resp.request_focus();
|
||||
editing = Some((it.id, buf));
|
||||
}
|
||||
} else {
|
||||
let shown = app.session.resolve_output(it).unwrap_or_else(|| "Not yet specified".into());
|
||||
let resp = ui.interact(path_rect, egui::Id::new(("rq-path", it.id)), Sense::click());
|
||||
let col = if resp.hovered() { t.accent_hover } else { t.hot_text };
|
||||
lp.with_clip_rect(path_rect.intersect(list)).text(pos2(path_rect.min.x, r.center().y), Align2::LEFT_CENTER, &shown, Tokens::ui(11.5), col);
|
||||
if resp.clicked() && !rendering {
|
||||
editing = Some((it.id, it.output.output.clone()));
|
||||
}
|
||||
resp.on_hover_text(format!("Template: {}\nClick to edit", it.output.output));
|
||||
app.auto.add(&aid("outputPath"), path_rect, &shown);
|
||||
}
|
||||
}
|
||||
}
|
||||
ui.data_mut(|d| match &editing {
|
||||
Some(e) => {
|
||||
d.insert_temp(editing_id, e.clone());
|
||||
}
|
||||
None => d.remove::<(u64, String)>(editing_id),
|
||||
});
|
||||
|
||||
// Delete removes the selected item when the panel has focus.
|
||||
if app.ui.focused == crate::dock::PanelKind::RenderQueue
|
||||
&& editing.is_none()
|
||||
&& !rendering
|
||||
&& let Some(id) = selected
|
||||
&& ui.input(|i| i.key_pressed(egui::Key::Delete) || i.key_pressed(egui::Key::Backspace))
|
||||
&& !ui.ctx().egui_wants_keyboard_input()
|
||||
{
|
||||
actions.push(("renderQueue.remove", json!({"item": id})));
|
||||
selected = None;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------- footer
|
||||
let foot = Rect::from_min_max(pos2(rect.min.x, rect.max.y - FOOT_H), rect.max);
|
||||
p.rect_filled(foot, 0.0, t.tl_ruler_bg);
|
||||
p.line_segment([foot.left_top(), foot.right_top()], Stroke::new(1.0, t.separator));
|
||||
let msg = match &progress {
|
||||
Some(pr) if rendering => format!("Message: Rendering {} of {}", (pr.items_done + 1).min(pr.items_total), pr.items_total),
|
||||
_ => {
|
||||
let done = queue.iter().filter(|i| i.status == RenderStatus::Done).count();
|
||||
format!("Message: {done} of {} done", queue.len())
|
||||
}
|
||||
};
|
||||
p.text(pos2(foot.min.x + 12.0, foot.center().y), Align2::LEFT_CENTER, msg, Tokens::ui(11.0), t.text_dim);
|
||||
let started = queue.iter().filter(|i| i.started.is_some()).count();
|
||||
let total: f64 = queue.iter().filter_map(|i| i.render_time).sum();
|
||||
p.text(
|
||||
pos2(foot.max.x - 12.0, foot.center().y),
|
||||
Align2::RIGHT_CENTER,
|
||||
format!("Renders Started: {started} Total Time Elapsed: {}", hms(progress.as_ref().filter(|_| rendering).map(|p| p.elapsed).unwrap_or(total))),
|
||||
Tokens::ui(11.0),
|
||||
t.text_dim,
|
||||
);
|
||||
|
||||
open.retain(|id| queue.iter().any(|i| i.id == *id));
|
||||
ui.data_mut(|d| d.insert_temp(state_id, (open, selected)));
|
||||
let ctx = ui.ctx().clone();
|
||||
for (id, params) in actions {
|
||||
if let Err(e) = crate::menus::invoke(app, &ctx, id, params) {
|
||||
app.ui.status = e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn stamps() {
|
||||
assert_eq!(super::utc_stamp(0), "1970-01-01 00:00:00");
|
||||
assert_eq!(super::utc_stamp(1_700_000_000), "2023-11-14 22:13:20");
|
||||
assert_eq!(super::hms(3725.4), "1:02:05");
|
||||
}
|
||||
}
|
||||
@@ -57,16 +57,21 @@ pub fn character(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
actions.push(json!({"style": styles[i]}));
|
||||
}
|
||||
y += 34.0;
|
||||
// Numeric fields in a 2-column grid.
|
||||
let fields: [(&str, &str, f64, (f64, f64), &str); 6] = [
|
||||
// Numeric fields in AE's two-column grid.
|
||||
let fields: [(&str, &str, f64, (f64, f64), &str); 8] = [
|
||||
("size", "T", doc.size, (1.0, 2000.0), " px"),
|
||||
("leading", "A", doc.leading.unwrap_or(doc.size * 1.2), (0.0, 5000.0), " px"),
|
||||
("tracking", "VA", doc.tracking, (-1000.0, 10000.0), ""),
|
||||
("strokeWidth", "≡", doc.stroke_width, (0.0, 500.0), " px"),
|
||||
("strokeWidth", "W", doc.stroke_width, (0.0, 500.0), " px"),
|
||||
("vScale", "↕T", doc.v_scale, (1.0, 1000.0), " %"),
|
||||
("hScale", "↔T", doc.h_scale, (1.0, 1000.0), " %"),
|
||||
("baselineShift", "A↑", doc.baseline_shift, (-1000.0, 1000.0), " px"),
|
||||
("hScale", "↔", doc.h_scale, (1.0, 1000.0), "%"),
|
||||
("", "", 0.0, (0.0, 0.0), ""),
|
||||
];
|
||||
for (i, (key, glyph, v, range, suffix)) in fields.into_iter().enumerate() {
|
||||
if key.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let col = i % 2;
|
||||
let row = i / 2;
|
||||
let fx = x0 + col as f32 * (w / 2.0);
|
||||
@@ -77,13 +82,25 @@ pub fn character(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
if let Some(nv) = nv
|
||||
&& enabled
|
||||
{
|
||||
let k = if key == "baselineShift" || key == "hScale" { "tracking" } else { key };
|
||||
if k == key {
|
||||
actions.push(json!({key: nv, "merge": format!("char-{key}")}));
|
||||
}
|
||||
actions.push(json!({key: nv, "merge": format!("char-{key}")}));
|
||||
}
|
||||
}
|
||||
y += 3.0 * 28.0 + 8.0;
|
||||
// Stroke Over Fill / Fill Over Stroke (bottom-right cell).
|
||||
{
|
||||
let fx = x0 + w / 2.0;
|
||||
let fy = y + 3.0 * 28.0;
|
||||
let dr = Rect::from_min_size(pos2(fx, fy), vec2(w / 2.0, 20.0));
|
||||
let labels = vec!["Fill Over Stroke".to_string(), "Stroke Over Fill".to_string()];
|
||||
let pop = egui::Id::new("char-stroke-order-pop");
|
||||
if widgets::dropdown(ui, dr, &labels[doc.stroke_over_fill as usize], &t, egui::Id::new("char-stroke-order")).clicked() && enabled {
|
||||
widgets::open_popup(ui, pop);
|
||||
}
|
||||
app.auto.add("character.strokeOverFill", dr, "Stroke order");
|
||||
if let Some(i) = widgets::popup_menu(ui, pop, dr.left_bottom(), &labels, Some(doc.stroke_over_fill as usize)) {
|
||||
actions.push(json!({"strokeOverFill": i == 1}));
|
||||
}
|
||||
}
|
||||
y += 4.0 * 28.0 + 8.0;
|
||||
// Fill / stroke swatches.
|
||||
p.text(pos2(x0, y + 10.0), Align2::LEFT_CENTER, "Fill", Tokens::ui(11.5), t.text_dim);
|
||||
let fs = Rect::from_min_size(pos2(x0 + 34.0, y), vec2(26.0, 20.0));
|
||||
@@ -107,7 +124,8 @@ pub fn character(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
}
|
||||
y += 32.0;
|
||||
// Style toggles.
|
||||
let toggles = [("fauxBold", "T", doc.faux_bold), ("fauxItalic", "T", doc.faux_italic), ("allCaps", "TT", doc.all_caps)];
|
||||
let toggles =
|
||||
[("fauxBold", "T", doc.faux_bold), ("fauxItalic", "T", doc.faux_italic), ("allCaps", "TT", doc.all_caps), ("smallCaps", "Tт", doc.small_caps)];
|
||||
for (i, (key, label, on)) in toggles.into_iter().enumerate() {
|
||||
let r = Rect::from_min_size(pos2(x0 + i as f32 * 34.0, y), vec2(30.0, 24.0));
|
||||
let resp = ui.interact(r, egui::Id::new(("char-t", key)), Sense::click());
|
||||
|
||||
@@ -21,8 +21,54 @@ use crate::{EffectcraftApp, widgets};
|
||||
#[derive(Clone, Debug)]
|
||||
enum RowKind {
|
||||
Layer,
|
||||
Group { uid: u64, name: String, open: bool, has_children: bool, fx: Option<bool> },
|
||||
Prop { uid: u64 },
|
||||
Group {
|
||||
uid: u64,
|
||||
name: String,
|
||||
open: bool,
|
||||
has_children: bool,
|
||||
fx: Option<bool>,
|
||||
},
|
||||
Prop {
|
||||
uid: u64,
|
||||
},
|
||||
/// Inline expression editor under a property with an expression.
|
||||
Expr {
|
||||
uid: u64,
|
||||
lines: usize,
|
||||
},
|
||||
}
|
||||
|
||||
/// Row height (expression editors grow with their text).
|
||||
fn row_height(row: &Row, rh: f32) -> f32 {
|
||||
match row.kind {
|
||||
RowKind::Expr { lines, .. } => rh * lines.clamp(1, 8) as f32 + 6.0,
|
||||
_ => rh,
|
||||
}
|
||||
}
|
||||
|
||||
/// Insert an expression editor row after every property that has an expression.
|
||||
fn with_expr_rows(rows: Vec<Row>, comp: &Comp, closed: &std::collections::BTreeSet<u64>) -> Vec<Row> {
|
||||
let mut out = Vec::with_capacity(rows.len());
|
||||
for r in rows {
|
||||
let extra = match r.kind {
|
||||
RowKind::Prop { uid } if !closed.contains(&uid) => comp.layer(r.layer).and_then(|l| l.props.find(uid)).and_then(|p| p.expr.as_ref()).map(|e| Row {
|
||||
layer: r.layer,
|
||||
depth: r.depth,
|
||||
kind: RowKind::Expr { uid, lines: e.text.lines().count().max(1) },
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
out.push(r);
|
||||
out.extend(extra);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A pick-whip drag in progress: (parent = 0 / property = 1, layer, prop uid, start point).
|
||||
type PickWhip = (u8, u64, u64, Pos2);
|
||||
|
||||
fn pick_whip_id() -> egui::Id {
|
||||
egui::Id::new("tl-pickwhip")
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -42,8 +88,6 @@ struct Cols {
|
||||
label: f32,
|
||||
num: f32,
|
||||
name: f32,
|
||||
#[allow(dead_code)]
|
||||
name_w: f32,
|
||||
switches: f32,
|
||||
mode: f32,
|
||||
trkmat: f32,
|
||||
@@ -62,22 +106,22 @@ fn cols(x0: f32, width: f32, show_modes: bool) -> Cols {
|
||||
let mode = switches + SW * 8.0 + 6.0;
|
||||
let trkmat = mode + if show_modes { 92.0 } else { 0.0 };
|
||||
let parent = trkmat + if show_modes { 112.0 } else { 0.0 };
|
||||
Cols { av, label, num, name, name_w, switches, mode, trkmat, parent, end: parent + 116.0 }
|
||||
Cols { av, label, num, name, switches, mode, trkmat, parent, end: parent + 116.0 }
|
||||
}
|
||||
|
||||
/// Timeline horizontal mapping.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct TMap {
|
||||
x0: f32,
|
||||
start: f64,
|
||||
pps: f64,
|
||||
pub(crate) struct TMap {
|
||||
pub x0: f32,
|
||||
pub start: f64,
|
||||
pub pps: f64,
|
||||
}
|
||||
|
||||
impl TMap {
|
||||
fn x(&self, secs: f64) -> f32 {
|
||||
pub fn x(&self, secs: f64) -> f32 {
|
||||
self.x0 + ((secs - self.start) * self.pps) as f32
|
||||
}
|
||||
fn t(&self, x: f32) -> f64 {
|
||||
pub fn t(&self, x: f32) -> f64 {
|
||||
self.start + (x - self.x0) as f64 / self.pps
|
||||
}
|
||||
}
|
||||
@@ -142,6 +186,14 @@ fn prop_visible(p: &Property, layer: &Layer) -> bool {
|
||||
if p.two_d_only && layer.is_3d() {
|
||||
return false;
|
||||
}
|
||||
// One-node cameras (and lights with auto-orient off) have no Point of Interest.
|
||||
if p.match_id == "poi" && (layer.is_camera() || layer.is_light()) && layer.auto_orient != effectcraft_engine::project::AutoOrient::TowardsPointOfInterest {
|
||||
return false;
|
||||
}
|
||||
// Separate Dimensions: X/Y/Z Position replace Position.
|
||||
if p.match_id == "position" && layer.transform().is_some_and(|tr| tr.get("positionX").is_some() && tr.get("position").is_some_and(|q| q.uid == p.uid)) {
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
@@ -169,7 +221,7 @@ fn build_rows(app: &EffectcraftApp, comp: &Comp) -> Vec<Row> {
|
||||
}
|
||||
if let Some(kind) = tl.reveal.first() {
|
||||
let (group, props): (&str, Vec<&str>) = match kind.as_str() {
|
||||
"position" => ("transform", vec!["position"]),
|
||||
"position" => ("transform", vec!["position", "positionX", "positionY", "positionZ"]),
|
||||
"scale" => ("transform", vec!["scale"]),
|
||||
"rotation" => ("transform", vec!["rotation", "rotationX", "rotationY", "orientation"]),
|
||||
"opacity" => ("transform", vec!["opacity"]),
|
||||
@@ -353,7 +405,8 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let ruler_h = 34.0;
|
||||
let colhdr_h = 22.0;
|
||||
let footer_h = 24.0;
|
||||
let left_w = (rect.width() * 0.5).clamp(420.0, 860.0);
|
||||
let fixed = AV_W + LABEL_W + NUM_W + SW * 8.0 + if app.ui.timeline.show_modes { 92.0 + 112.0 } else { 0.0 } + 116.0 + 6.0;
|
||||
let left_w = (fixed + 190.0).clamp(420.0, (rect.width() * 0.62).max(420.0));
|
||||
let cw = cols(rect.min.x, left_w, app.ui.timeline.show_modes);
|
||||
let graph_x0 = rect.min.x + left_w + 1.0;
|
||||
let graph_x1 = rect.max.x - 10.0;
|
||||
@@ -377,7 +430,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let tc_rect = Rect::from_min_size(pos2(rect.min.x + 12.0, top + 6.0), vec2(150.0, 24.0));
|
||||
let tc_resp = ui.interact(tc_rect, egui::Id::new("tl-timecode"), Sense::click_and_drag());
|
||||
p.text(tc_rect.left_center(), Align2::LEFT_CENTER, &tc, Tokens::semibold(20.0), t.timecode);
|
||||
let sub = format!("{} ({:.2} fps)", fr.frame_at(time), fr.as_f64());
|
||||
let sub = format!("{:05} ({:.2} fps)", fr.frame_at(time) + app.session.project.settings.frame_start, fr.as_f64());
|
||||
p.text(pos2(tc_rect.min.x, tc_rect.max.y + 8.0), Align2::LEFT_CENTER, sub, Tokens::ui(10.5), t.text_faint);
|
||||
app.auto.add("timeline.timecode", tc_rect, &tc);
|
||||
if tc_resp.dragged() {
|
||||
@@ -489,14 +542,26 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
draw_run(a, b);
|
||||
}
|
||||
// Ticks + labels.
|
||||
let secs_per_label = [0.0333, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 30.0, 60.0].into_iter().find(|s| s * pps >= 70.0).unwrap_or(60.0);
|
||||
// Label spacing in whole frames (AE: `00:15f`-style seconds:frames labels).
|
||||
let fps_i = fr.as_f64().round().max(1.0) as i64;
|
||||
let half = (fps_i / 2).max(1);
|
||||
let label_frames = [1, 2, 5, 10, half, fps_i, 2 * fps_i, 5 * fps_i, 10 * fps_i, 30 * fps_i, 60 * fps_i]
|
||||
.into_iter()
|
||||
.find(|f| *f as f64 * fd * pps >= 52.0)
|
||||
.unwrap_or(60 * fps_i);
|
||||
let secs_per_label = label_frames as f64 * fd;
|
||||
let first = (tm.start / secs_per_label).floor() * secs_per_label;
|
||||
let mut s = first;
|
||||
let pr = p.with_clip_rect(Rect::from_min_max(pos2(graph_x0, ruler.min.y), ruler.max));
|
||||
while s <= tm.t(graph_x1) + secs_per_label {
|
||||
let x = tm.x(s);
|
||||
pr.line_segment([pos2(x, ruler.max.y - 10.0), pos2(x, ruler.max.y)], Stroke::new(1.0, t.tl_ruler_tick));
|
||||
let label = if secs_per_label < 1.0 { format!("{:02}f", fr.frame_at(Tick::from_seconds_f64(s + 1e-9))) } else { format!("{:02}s", s.round() as i64) };
|
||||
let fno = (s / fd).round() as i64;
|
||||
let label = if fno >= 60 * fps_i * 60 {
|
||||
format!("{}:{:02}:{:02}f", fno / (fps_i * 60), (fno / fps_i) % 60, fno % fps_i)
|
||||
} else {
|
||||
format!("{:02}:{:02}f", fno / fps_i, fno % fps_i)
|
||||
};
|
||||
pr.text(pos2(x + 3.0, ruler.max.y - 16.0), Align2::LEFT_CENTER, label, Tokens::ui(10.0), t.tl_ruler_text);
|
||||
for k in 1..5 {
|
||||
let xx = tm.x(s + secs_per_label * k as f64 / 5.0);
|
||||
@@ -551,9 +616,9 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let _ = cw.end;
|
||||
|
||||
// ---- rows.
|
||||
let rows = build_rows(app, &comp);
|
||||
let rows = with_expr_rows(build_rows(app, &comp), &comp, &app.ui.timeline.expr_closed);
|
||||
let rh = t.row_h;
|
||||
let total_h = rows.len() as f32 * rh;
|
||||
let total_h: f32 = rows.iter().map(|r| row_height(r, rh)).sum();
|
||||
let max_scroll = (total_h - rows_rect.height() + rh).max(0.0);
|
||||
if ui.rect_contains_pointer(rows_rect) {
|
||||
let (dy, dx, zoom) = ui.input(|i| (i.smooth_scroll_delta.y, i.smooth_scroll_delta.x, i.modifiers.alt));
|
||||
@@ -579,16 +644,27 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let mut ui_actions: Vec<UiAct> = Vec::new();
|
||||
let idx_of = |id: LayerId| comp.index_of(id).unwrap_or(0);
|
||||
let graph_on = app.ui.timeline.graph_editor;
|
||||
let full_clip = ui.clip_rect();
|
||||
let left_clip = full_clip.intersect(Rect::from_min_max(pos2(rect.min.x, rows_rect.min.y), pos2(graph_x0 - 1.0, rows_rect.max.y)));
|
||||
let right_clip = full_clip.intersect(Rect::from_min_max(pos2(graph_x0, rows_rect.min.y), rows_rect.max));
|
||||
// Registered before the rows so keys, bars and editors on top of it get the pointer first.
|
||||
let empty_rect = if graph_on { Rect::NOTHING } else { Rect::from_min_max(pos2(graph_x0, rows_rect.min.y), rows_rect.max) };
|
||||
let empty = ui.interact(empty_rect, egui::Id::new("tl-graph-bg"), Sense::click_and_drag());
|
||||
let mut hit_rows: Vec<(Rect, Row)> = vec![];
|
||||
for (ri, row) in rows.iter().enumerate() {
|
||||
let r = Rect::from_min_size(pos2(rect.min.x, y), vec2(rect.width(), rh));
|
||||
y += rh;
|
||||
// Outline widgets never spill into the time graph (narrow timelines).
|
||||
ui.set_clip_rect(left_clip);
|
||||
let hh = row_height(row, rh);
|
||||
let r = Rect::from_min_size(pos2(rect.min.x, y), vec2(rect.width(), hh));
|
||||
y += hh;
|
||||
if r.max.y < rows_rect.min.y || r.min.y > rows_rect.max.y {
|
||||
continue;
|
||||
}
|
||||
hit_rows.push((r, row.clone()));
|
||||
let Some(layer) = comp.layer(row.layer) else { continue };
|
||||
let is_sel = selected.contains(&layer.id);
|
||||
let left = Rect::from_min_max(r.min, pos2(graph_x0 - 1.0, r.max.y));
|
||||
let cy = r.center().y;
|
||||
let cy = r.min.y + rh / 2.0;
|
||||
match &row.kind {
|
||||
RowKind::Layer => {
|
||||
lp.rect_filled(
|
||||
@@ -770,7 +846,15 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
}
|
||||
}
|
||||
// Parent.
|
||||
let pr_rect = Rect::from_min_size(pos2(cw.parent + 2.0, cy - 9.0), vec2(110.0, 18.0));
|
||||
let pw_rect = Rect::from_center_size(pos2(cw.parent + 9.0, cy), vec2(15.0, 15.0));
|
||||
let pw = ui.interact(pw_rect, egui::Id::new(("parent-whip", layer.id.0)), Sense::drag()).on_hover_text("Parent pick whip: drag onto a layer");
|
||||
icons::paint(&lp, pw_rect.shrink(1.0), Icon::PickWhip, if pw.hovered() || pw.dragged() { t.text } else { t.text_dim });
|
||||
app.auto.add(&format!("timeline.layer.{}.pickWhip", layer.id.0), pw_rect, "Parent pick whip");
|
||||
if pw.drag_started() {
|
||||
let pw_state: PickWhip = (0, layer.id.0, 0, pw_rect.center());
|
||||
ctx.data_mut(|d| d.insert_temp(pick_whip_id(), pw_state));
|
||||
}
|
||||
let pr_rect = Rect::from_min_size(pos2(cw.parent + 20.0, cy - 9.0), vec2(94.0, 18.0));
|
||||
let plabel = layer.parent.and_then(|p| comp.layer(p)).map(|l| format!("{}. {}", idx_of(l.id), l.name)).unwrap_or_else(|| "None".into());
|
||||
let presp = widgets::dropdown(ui, pr_rect, &plabel, &t, egui::Id::new(("parent", layer.id.0)));
|
||||
app.auto.add(&format!("timeline.layer.{}.parent", layer.id.0), pr_rect, "Parent");
|
||||
@@ -786,6 +870,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
actions.push(("layer.setParent".into(), json!({"layers": [layer.id.0], "parent": par})));
|
||||
}
|
||||
// Layer bar.
|
||||
ui.set_clip_rect(right_clip);
|
||||
if !graph_on {
|
||||
let x_in = tm.x(layer.in_point.seconds());
|
||||
let x_out = tm.x(layer.out_point.seconds());
|
||||
@@ -904,6 +989,75 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
ui_actions.push(UiAct::ToggleGroup(*uid));
|
||||
}
|
||||
}
|
||||
RowKind::Expr { uid, lines } => {
|
||||
let Some(prop) = layer.props.find(*uid) else { continue };
|
||||
let Some(ex) = prop.expr.clone() else { continue };
|
||||
lp.rect_filled(left, 0.0, t.row_alt);
|
||||
let indent = cw.name + 6.0 + 14.0 * row.depth as f32;
|
||||
lp.text(pos2(indent + 12.0, cy), Align2::LEFT_CENTER, "Expression:", Tokens::ui(11.5), t.text_dim);
|
||||
lp.text(pos2(indent + 82.0, cy), Align2::LEFT_CENTER, &prop.name, Tokens::ui(11.5), t.text);
|
||||
// "=" enable switch and the property pick whip (AE's expression controls).
|
||||
let en_r = Rect::from_center_size(pos2(cw.switches + 10.0, cy), vec2(16.0, 16.0));
|
||||
let en = ui.interact(en_r, egui::Id::new(("expr-en", uid)), Sense::click()).on_hover_text("Enable Expression");
|
||||
lp.rect_stroke(en_r.shrink(1.0), 2.0, Stroke::new(1.0, t.separator), StrokeKind::Inside);
|
||||
let expr_col = Color32::from_rgb(0xe8, 0x7c, 0x5c);
|
||||
lp.text(
|
||||
en_r.center(),
|
||||
Align2::CENTER_CENTER,
|
||||
if ex.enabled { "=" } else { "≠" },
|
||||
Tokens::semibold(13.0),
|
||||
if ex.enabled { expr_col } else { t.text_dim },
|
||||
);
|
||||
app.auto.add(&format!("timeline.prop.{uid}.exprEnable"), en_r, "Enable Expression");
|
||||
if en.clicked() {
|
||||
actions.push(("prop.setExpression".into(), json!({"layer": layer.id.0, "prop": uid, "enabled": !ex.enabled})));
|
||||
}
|
||||
let pw_rect = Rect::from_center_size(pos2(cw.switches + 30.0, cy), vec2(15.0, 15.0));
|
||||
let pw = ui.interact(pw_rect, egui::Id::new(("expr-whip", uid)), Sense::drag()).on_hover_text("Expression pick whip: drag onto a property");
|
||||
icons::paint(&lp, pw_rect.shrink(1.0), Icon::PickWhip, if pw.hovered() || pw.dragged() { t.text } else { t.text_dim });
|
||||
app.auto.add(&format!("timeline.prop.{uid}.pickWhip"), pw_rect, "Expression pick whip");
|
||||
if pw.drag_started() {
|
||||
let pw_state: PickWhip = (1, layer.id.0, *uid, pw_rect.center());
|
||||
ctx.data_mut(|d| d.insert_temp(pick_whip_id(), pw_state));
|
||||
}
|
||||
// Syntax errors: warning in the outline (the expression is disabled).
|
||||
if let Some(check) = app.session.expr_check
|
||||
&& let Err(e) = check(&ex.text)
|
||||
{
|
||||
let wr = Rect::from_center_size(pos2(cw.switches + 50.0, cy), vec2(14.0, 14.0));
|
||||
lp.text(wr.center(), Align2::CENTER_CENTER, "⚠", Tokens::ui(12.0), Color32::from_rgb(0xf0, 0xa0, 0x30));
|
||||
let _ = ui.interact(wr, egui::Id::new(("expr-err", uid)), Sense::hover()).on_hover_text(e);
|
||||
}
|
||||
// The editor in the time-graph area.
|
||||
ui.set_clip_rect(right_clip);
|
||||
gp.rect_filled(Rect::from_min_max(pos2(graph_x0, r.min.y), r.max), 0.0, Color32::from_rgb(0x1a, 0x1a, 0x1a));
|
||||
let er = Rect::from_min_max(pos2(graph_x0 + 8.0, r.min.y + 3.0), pos2(rect.max.x - 14.0, r.max.y - 3.0));
|
||||
let buf_id = egui::Id::new(("expr-buf", uid));
|
||||
let mut buf: String = ctx.data(|d| d.get_temp(buf_id)).unwrap_or_else(|| ex.text.clone());
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(er));
|
||||
let resp = child.add(
|
||||
egui::TextEdit::multiline(&mut buf)
|
||||
.id(egui::Id::new(("expr-edit", uid)))
|
||||
.font(Tokens::mono(11.5))
|
||||
.text_color(if ex.enabled { expr_col } else { t.text_dim })
|
||||
.desired_width(er.width())
|
||||
.desired_rows((*lines).clamp(1, 8))
|
||||
.frame(egui::Frame::NONE),
|
||||
);
|
||||
app.auto.add(&format!("timeline.prop.{uid}.expression"), er, &prop.name);
|
||||
let commit = resp.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter) && (i.modifiers.command || i.modifiers.ctrl));
|
||||
if commit {
|
||||
resp.surrender_focus();
|
||||
}
|
||||
if resp.has_focus() && !commit {
|
||||
ctx.data_mut(|d| d.insert_temp(buf_id, buf));
|
||||
} else {
|
||||
if (resp.lost_focus() || commit) && buf.trim_end() != ex.text {
|
||||
actions.push(("prop.setExpression".into(), json!({"layer": layer.id.0, "prop": uid, "expression": buf.trim_end()})));
|
||||
}
|
||||
ctx.data_mut(|d| d.remove::<String>(buf_id));
|
||||
}
|
||||
}
|
||||
RowKind::Prop { uid } => {
|
||||
let Some(prop) = layer.props.find(*uid) else { continue };
|
||||
let sel_prop = app.session.state.selected_props.contains(&(layer.id, *uid));
|
||||
@@ -973,7 +1127,10 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
}
|
||||
}
|
||||
let name_x = indent + 12.0;
|
||||
let pname = if prop.has_expression() { format!("{} =", prop.name) } else { prop.name.clone() };
|
||||
// 3D layers show Rotation as "Z Rotation" next to X/Y Rotation.
|
||||
let is_tr_rot = layer.transform().and_then(|t| t.get("rotation")).is_some_and(|r| r.uid == prop.uid);
|
||||
let base = if is_tr_rot && prop.name == "Rotation" && layer.is_3d() { "Z Rotation".to_string() } else { prop.name.clone() };
|
||||
let pname = if prop.has_expression() { format!("{base} =") } else { base };
|
||||
lp.text(
|
||||
pos2(name_x, cy),
|
||||
Align2::LEFT_CENTER,
|
||||
@@ -990,8 +1147,9 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let value = ectx.value(layer, prop);
|
||||
let vx = (cw.switches + 4.0).max(name_x + 120.0);
|
||||
value_editor(app, ui, &lp, layer, prop, &value, pos2(vx, cy), &mut actions);
|
||||
ui.set_clip_rect(right_clip);
|
||||
// Expression text row hint.
|
||||
if let Some(e) = prop.expr.as_ref().filter(|e| e.enabled) {
|
||||
if let Some(e) = prop.expr.as_ref().filter(|e| e.enabled && app.ui.timeline.expr_closed.contains(uid)) {
|
||||
gp.text(
|
||||
pos2(graph_x0 + 8.0, cy),
|
||||
Align2::LEFT_CENTER,
|
||||
@@ -1030,15 +1188,32 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
}
|
||||
kresp.context_menu(|ui| {
|
||||
for (lbl, cmd, params) in [
|
||||
("Copy", "keys.copy", json!({})),
|
||||
("Paste", "keys.paste", json!({})),
|
||||
("-", "", json!({})),
|
||||
("Keyframe Interpolation…", "keys.interpolation", json!({})),
|
||||
("Keyframe Velocity…", "keys.velocity", json!({})),
|
||||
("Toggle Hold Keyframe", "keys.toggleHold", json!({})),
|
||||
("Rove Across Time", "keys.interpolation", json!({"roving": !k.roving})),
|
||||
("-", "", json!({})),
|
||||
("Easy Ease", "keys.easyEase", json!({})),
|
||||
("Easy Ease In", "keys.easyEaseIn", json!({})),
|
||||
("Easy Ease Out", "keys.easyEaseOut", json!({})),
|
||||
("Toggle Hold Keyframe", "keys.toggleHold", json!({})),
|
||||
("Time-Reverse Keyframes", "keys.timeReverse", json!({})),
|
||||
("-", "", json!({})),
|
||||
("Linear", "keys.interpolation", json!({"interpolation": "linear"})),
|
||||
("Bezier", "keys.interpolation", json!({"interpolation": "bezier"})),
|
||||
("Auto Bezier", "keys.interpolation", json!({"autoBezier": true})),
|
||||
("Auto Bezier", "keys.interpolation", json!({"interpolation": "autoBezier"})),
|
||||
("Select All Keyframes", "keys.selectAll", json!({})),
|
||||
("Delete", "keys.delete", json!({})),
|
||||
] {
|
||||
if lbl == "-" {
|
||||
ui.separator();
|
||||
continue;
|
||||
}
|
||||
if lbl == "Rove Across Time" && !prop.spatial {
|
||||
continue;
|
||||
}
|
||||
if ui.button(lbl).clicked() {
|
||||
if !ks {
|
||||
actions.push(("keys.select".into(), json!({"keys": [{"layer": layer.id.0, "prop": uid, "time": k.time.seconds()}]})));
|
||||
@@ -1068,12 +1243,35 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
}
|
||||
}
|
||||
}
|
||||
ui.set_clip_rect(full_clip);
|
||||
// Pick whips: a line follows the pointer; releasing over a row links to it.
|
||||
if let Some((kind, src_layer, src_prop, start)) = ctx.data(|d| d.get_temp::<PickWhip>(pick_whip_id())) {
|
||||
let ptr = ctx.input(|i| i.pointer.latest_pos()).unwrap_or(start);
|
||||
let fg = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::new("tl-pickwhip-line")));
|
||||
fg.line_segment([start, ptr], Stroke::new(1.5, t.accent));
|
||||
fg.circle_stroke(ptr, 4.0, Stroke::new(1.5, t.accent));
|
||||
let target = hit_rows.iter().find(|(r, _)| r.contains(ptr)).map(|(r, row)| (*r, row.clone()));
|
||||
if let Some((tr, _)) = &target {
|
||||
fg.rect_stroke(Rect::from_min_max(tr.min, pos2(graph_x0 - 1.0, tr.max.y)), 0.0, Stroke::new(1.0, t.accent), StrokeKind::Inside);
|
||||
}
|
||||
if ctx.input(|i| !i.pointer.any_down()) {
|
||||
ctx.data_mut(|d| d.remove::<PickWhip>(pick_whip_id()));
|
||||
match (kind, target) {
|
||||
(0, Some((_, row))) if row.layer.0 != src_layer => {
|
||||
actions.push(("layer.setParent".into(), json!({"layers": [src_layer], "parent": row.layer.0})));
|
||||
}
|
||||
(1, Some((_, Row { layer, kind: RowKind::Prop { uid }, .. }))) if uid != src_prop => {
|
||||
actions.push(("prop.pickWhip".into(), json!({"layer": src_layer, "prop": src_prop, "target": {"layer": layer.0, "prop": uid}})));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Graph editor.
|
||||
if graph_on {
|
||||
graph_editor(app, ui, &gp, &comp, &ectx, tm, Rect::from_min_max(pos2(graph_x0, rows_rect.min.y), rows_rect.max));
|
||||
super::graph::show(app, ui, &gp, &comp, &ectx, tm, Rect::from_min_max(pos2(graph_x0, rows_rect.min.y), rows_rect.max), &mut actions);
|
||||
}
|
||||
// Empty-area click in the graph: deselect keys; drag: box-select keys.
|
||||
let empty = ui.interact(Rect::from_min_max(pos2(graph_x0, rows_rect.min.y), rows_rect.max), egui::Id::new("tl-graph-bg"), Sense::click_and_drag());
|
||||
if empty.clicked() {
|
||||
actions.push(("keys.select".into(), json!({"keys": []})));
|
||||
}
|
||||
@@ -1093,7 +1291,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let mut yy = rows_rect.min.y - app.ui.timeline.scroll_y;
|
||||
for row in &rows {
|
||||
let cy = yy + rh / 2.0;
|
||||
yy += rh;
|
||||
yy += row_height(row, rh);
|
||||
if let RowKind::Prop { uid } = row.kind
|
||||
&& cy >= br.min.y
|
||||
&& cy <= br.max.y
|
||||
@@ -1169,8 +1367,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
p.rect_stroke(rows_rect, 0.0, Stroke::new(2.0, t.accent), StrokeKind::Inside);
|
||||
if ctx.input(|i| i.pointer.any_released()) {
|
||||
let hover_y = ctx.input(|i| i.pointer.hover_pos()).map(|p| p.y).unwrap_or(0.0);
|
||||
let row_i = ((hover_y - rows_rect.min.y + app.ui.timeline.scroll_y) / rh).floor() as usize;
|
||||
let target = rows.get(row_i).map(|r| r.layer);
|
||||
let target = hit_rows.iter().find(|(r, _)| hover_y >= r.min.y && hover_y < r.max.y).map(|(_, row)| row.layer);
|
||||
match payload.as_ref() {
|
||||
crate::panels::DragPayload::Item(id) => actions.push(("layer.addItem".into(), json!({"item": id}))),
|
||||
crate::panels::DragPayload::Effect(e) => {
|
||||
@@ -1217,6 +1414,10 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
}
|
||||
}
|
||||
for (id, params) in actions {
|
||||
if id == "__endMerge" {
|
||||
app.session.history.merge_key = None;
|
||||
continue;
|
||||
}
|
||||
if let Err(e) = crate::menus::invoke(app, &ctx, &id, params) {
|
||||
app.ui.status = e;
|
||||
}
|
||||
@@ -1286,7 +1487,11 @@ fn layer_context_menu(resp: &egui::Response, layer: &Layer, actions: &mut Vec<(S
|
||||
item(ui, "Flip Vertical", "layer.transform", json!({"layers": [id], "op": "flipV"}));
|
||||
});
|
||||
ui.menu_button("Time", |ui| {
|
||||
item(ui, "Time-Reverse Layer", "layer.timeStretch", json!({"layers": [id], "op": "reverse"}));
|
||||
item(ui, "Enable Time Remapping", "layer.enableTimeRemap", json!({"layers": [id]}));
|
||||
item(ui, "Time-Reverse Layer", "layer.timeReverse", json!({"layers": [id]}));
|
||||
item(ui, "Time Stretch…", "layer.timeStretch", json!({}));
|
||||
item(ui, "Freeze Frame", "layer.freezeFrame", json!({"layers": [id]}));
|
||||
item(ui, "Freeze on Last Frame", "layer.freezeOnLastFrame", json!({"layers": [id]}));
|
||||
});
|
||||
ui.menu_button("Blending Mode", |ui| {
|
||||
for m in BlendMode::ALL {
|
||||
@@ -1441,86 +1646,3 @@ fn value_editor(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Value graph of the selected properties (numeric dimensions over time) with key markers.
|
||||
fn graph_editor(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, comp: &Comp, ectx: &EvalCtx, tm: TMap, area: Rect) {
|
||||
let t = app.tokens;
|
||||
let props: Vec<(LayerId, u64)> = if app.session.state.selected_props.is_empty() {
|
||||
// Default: animated properties of selected layers.
|
||||
let mut v = vec![];
|
||||
for l in comp.layers.iter().filter(|l| app.session.state.selected_layers.contains(&l.id)) {
|
||||
l.props.walk("", &mut |_, pr| {
|
||||
if pr.is_animated() && !pr.value.components().is_empty() {
|
||||
v.push((l.id, pr.uid));
|
||||
}
|
||||
});
|
||||
}
|
||||
v
|
||||
} else {
|
||||
app.session.state.selected_props.clone()
|
||||
};
|
||||
p.rect_filled(area, 0.0, Color32::from_rgb(0x1e, 0x1e, 0x1e));
|
||||
// Grid.
|
||||
for i in 1..8 {
|
||||
let y = area.min.y + area.height() * i as f32 / 8.0;
|
||||
p.line_segment([pos2(area.min.x, y), pos2(area.max.x, y)], Stroke::new(1.0, Color32::from_white_alpha(10)));
|
||||
}
|
||||
if props.is_empty() {
|
||||
p.text(area.center(), Align2::CENTER_CENTER, "Select animated properties to show them in the Graph Editor", Tokens::ui(12.0), t.text_faint);
|
||||
return;
|
||||
}
|
||||
let colors =
|
||||
[Color32::from_rgb(0xe0, 0x50, 0x50), Color32::from_rgb(0x60, 0xd0, 0x60), Color32::from_rgb(0x50, 0x8c, 0xf0), Color32::from_rgb(0xe8, 0xc8, 0x40)];
|
||||
// Sample all curves over the visible span; normalise to a common range.
|
||||
let n = ((area.width() / 2.0) as usize).max(2);
|
||||
let mut curves: Vec<(Vec<Vec<f64>>, &Layer, &Property)> = vec![];
|
||||
let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
|
||||
for (lid, uid) in &props {
|
||||
let Some(l) = comp.layer(*lid) else { continue };
|
||||
let Some(pr) = l.props.find(*uid) else { continue };
|
||||
let mut dims: Vec<Vec<f64>> = vec![];
|
||||
for i in 0..n {
|
||||
let x = area.min.x + area.width() * i as f32 / (n - 1) as f32;
|
||||
let tt = Tick::from_seconds_f64(tm.t(x));
|
||||
let v = ectx.at(tt).value(l, pr).components();
|
||||
if dims.is_empty() {
|
||||
dims = vec![Vec::with_capacity(n); v.len().min(3)];
|
||||
}
|
||||
for (d, c) in v.iter().take(dims.len()).enumerate() {
|
||||
dims[d].push(*c);
|
||||
lo = lo.min(*c);
|
||||
hi = hi.max(*c);
|
||||
}
|
||||
}
|
||||
curves.push((dims, l, pr));
|
||||
}
|
||||
if !lo.is_finite() || !hi.is_finite() {
|
||||
return;
|
||||
}
|
||||
if (hi - lo).abs() < 1e-9 {
|
||||
hi = lo + 1.0;
|
||||
}
|
||||
let pad = (hi - lo) * 0.1;
|
||||
let (lo, hi) = (lo - pad, hi + pad);
|
||||
let ymap = |v: f64| area.max.y - ((v - lo) / (hi - lo)) as f32 * area.height();
|
||||
for (dims, l, pr) in &curves {
|
||||
for (d, vals) in dims.iter().enumerate() {
|
||||
let pts: Vec<Pos2> = vals.iter().enumerate().map(|(i, v)| pos2(area.min.x + area.width() * i as f32 / (n - 1) as f32, ymap(*v))).collect();
|
||||
p.add(egui::Shape::line(pts, Stroke::new(1.5, colors[d % colors.len()])));
|
||||
}
|
||||
for k in &pr.keys {
|
||||
let x = tm.x(l.comp_time(k.time).seconds());
|
||||
for (d, v) in k.value.components().iter().take(dims.len()).enumerate() {
|
||||
let c = pos2(x, ymap(*v));
|
||||
p.rect_filled(Rect::from_center_size(c, vec2(6.0, 6.0)), 0.0, Color32::WHITE);
|
||||
p.rect_stroke(Rect::from_center_size(c, vec2(6.0, 6.0)), 0.0, Stroke::new(1.0, colors[d % colors.len()]), StrokeKind::Outside);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Value labels.
|
||||
for i in 0..=4 {
|
||||
let v = lo + (hi - lo) * i as f64 / 4.0;
|
||||
p.text(pos2(area.min.x + 4.0, ymap(v)), Align2::LEFT_BOTTOM, format!("{v:.1}"), Tokens::ui(10.0), t.text_faint);
|
||||
}
|
||||
let _ = ui;
|
||||
}
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
//! The Composition viewer: pasteboard + comp frame, magnification and resolution, transparency
|
||||
//! grid, guides, layer bounding boxes with handles, anchor points, motion paths and masks, and
|
||||
//! direct manipulation (move, scale, rotate, pan behind, shape/type creation, hand and zoom).
|
||||
//! direct manipulation (move, scale, rotate, pan behind, shape/type creation, hand and zoom),
|
||||
//! 3D views (Active Camera / Front / … / Custom View 3), camera tools (orbit, pan, dolly) and
|
||||
//! camera/light wireframes.
|
||||
|
||||
use effectcraft_engine::geom::{Mat3, vec2 as gv2};
|
||||
use effectcraft_engine::project::{GroupKind, Layer, LayerId};
|
||||
use effectcraft_engine::render::EvalCtx;
|
||||
use effectcraft_engine::render::three_d::{self, CameraState, View3D};
|
||||
use effectcraft_engine::time::Tick;
|
||||
use egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
|
||||
use serde_json::json;
|
||||
@@ -55,18 +58,19 @@ pub fn last_fit(ctx: &egui::Context) -> f32 {
|
||||
/// What a drag in the viewer is doing.
|
||||
#[derive(Clone, Debug)]
|
||||
enum Gesture {
|
||||
/// Per layer: start position and the parent-space change per comp pixel of drag in x and y.
|
||||
Move {
|
||||
layers: Vec<(LayerId, [f64; 3], Mat3)>,
|
||||
layers: Vec<(LayerId, [f64; 3], [f64; 3], [f64; 3])>,
|
||||
start: [f64; 2],
|
||||
},
|
||||
#[allow(dead_code)]
|
||||
Camera {
|
||||
tool: Tool,
|
||||
},
|
||||
Scale {
|
||||
layer: LayerId,
|
||||
anchor_screen: Pos2,
|
||||
start_scale: [f64; 3],
|
||||
start_local: [f64; 2],
|
||||
inv: Mat3,
|
||||
uniform: bool,
|
||||
},
|
||||
Rotate {
|
||||
layer: LayerId,
|
||||
@@ -92,14 +96,74 @@ enum Gesture {
|
||||
Marquee {
|
||||
start: Pos2,
|
||||
},
|
||||
/// Dragging selected mask vertices (comp-space point of the previous frame, comp → layer).
|
||||
Vertices {
|
||||
last: [f64; 2],
|
||||
inv: Mat3,
|
||||
},
|
||||
/// Dragging a vertex's Bezier tangent (both sides symmetric unless Alt breaks them).
|
||||
Tangent {
|
||||
layer: LayerId,
|
||||
mask: u64,
|
||||
index: usize,
|
||||
out: bool,
|
||||
vertex: [f64; 2],
|
||||
inv: Mat3,
|
||||
},
|
||||
/// Pen tool: pulling the tangents of the vertex just placed.
|
||||
Pen {
|
||||
layer: LayerId,
|
||||
mask: u64,
|
||||
index: usize,
|
||||
vertex: [f64; 2],
|
||||
inv: Mat3,
|
||||
press: Pos2,
|
||||
},
|
||||
}
|
||||
|
||||
/// Pen tool path in progress: (layer, mask uid).
|
||||
fn pen_id() -> egui::Id {
|
||||
egui::Id::new("viewer-pen")
|
||||
}
|
||||
|
||||
/// Mask vertex / tangent hit targets drawn this frame.
|
||||
#[derive(Clone, Copy)]
|
||||
struct VertexHit {
|
||||
layer: LayerId,
|
||||
mask: u64,
|
||||
index: usize,
|
||||
pos: Pos2,
|
||||
/// None = the vertex itself, Some(out?) = a tangent handle.
|
||||
tangent: Option<bool>,
|
||||
/// Layer-space vertex position and layer → comp matrix.
|
||||
vertex: [f64; 2],
|
||||
l2c: Mat3,
|
||||
}
|
||||
|
||||
const HANDLE: f32 = 7.0;
|
||||
|
||||
thread_local! {
|
||||
/// The 3D view camera of the viewer being drawn (None = the comp's active camera).
|
||||
static VIEW_CAM: std::cell::Cell<Option<CameraState>> = const { std::cell::Cell::new(None) };
|
||||
}
|
||||
|
||||
/// The camera the viewer shows (view camera or the comp's active camera).
|
||||
fn cam_state(ctx: &EvalCtx) -> CameraState {
|
||||
VIEW_CAM.with(|c| c.get()).unwrap_or_else(|| three_d::active_camera(ctx))
|
||||
}
|
||||
|
||||
/// Layer → comp (viewer) matrix through the current 3D view.
|
||||
fn l2c(ctx: &EvalCtx, layer: &Layer) -> (Mat3, f64) {
|
||||
match VIEW_CAM.with(|c| c.get()) {
|
||||
Some(cam) if layer.is_3d() => (three_d::layer_to_view(ctx, layer, &cam), 0.0),
|
||||
_ => ctx.layer_to_comp(layer),
|
||||
}
|
||||
}
|
||||
|
||||
/// Layer → comp matrix and its bounds quad (in comp pixels).
|
||||
fn layer_quad(ctx: &EvalCtx, layer: &Layer) -> Option<(Mat3, [[f64; 2]; 4], [f64; 4])> {
|
||||
let b = effectcraft_engine::render::content_bounds(ctx, layer)?;
|
||||
let (m, _) = ctx.layer_to_comp(layer);
|
||||
let (m, _) = l2c(ctx, layer);
|
||||
let pts = [[b[0], b[1]], [b[2], b[1]], [b[2], b[3]], [b[0], b[3]]].map(|p| {
|
||||
let q = m.apply(gv2(p[0], p[1]));
|
||||
[q.x, q.y]
|
||||
@@ -163,6 +227,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let comp = app.session.project.comp(cid).cloned().unwrap_or_else(|| effectcraft_engine::project::Comp::new(1920, 1080, Default::default(), Tick::ZERO));
|
||||
let comp_name = app.session.project.item(cid).map(|i| i.name.clone()).unwrap_or_default();
|
||||
let p = ui.painter().clone();
|
||||
VIEW_CAM.with(|c| c.set(app.session.view_camera(cid)));
|
||||
|
||||
// Navigator bar (open comps as breadcrumbs).
|
||||
let nav = Rect::from_min_size(rect.min, vec2(rect.width(), 24.0));
|
||||
@@ -215,11 +280,15 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
// Frame.
|
||||
let ppp = ctx.pixels_per_point();
|
||||
let scale = app.viewer_scale(zoom, ppp);
|
||||
if !app.playback.playing {
|
||||
// Queue the frame on screen before any prefetch.
|
||||
app.request_frame_urgent(cid, comp.frame_rate.frame_at(app.session.time()), scale);
|
||||
}
|
||||
crate::tick_playback(app, &ctx, scale);
|
||||
let time = app.session.time();
|
||||
let frame = comp.frame_rate.frame_at(time);
|
||||
let key = app.frame_key(cid, frame, scale);
|
||||
app.request_frame(cid, frame, scale);
|
||||
app.request_frame_urgent(cid, frame, scale);
|
||||
if let Some(img) = app.frames.get(&key) {
|
||||
let stale = app.viewer_tex.as_ref().is_none_or(|(_, k)| *k != key);
|
||||
if stale {
|
||||
@@ -296,6 +365,12 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let ectx = EvalCtx { project: &snap_project, comp_id: cid, comp: &comp, time, expr: snap_expr.as_deref() };
|
||||
let selected = app.session.state.selected_layers.clone();
|
||||
let mut handle_hits: Vec<(LayerId, usize, Pos2)> = Vec::new();
|
||||
let mut vertex_hits: Vec<VertexHit> = Vec::new();
|
||||
let sel_vertices = app.session.state.selected_vertices.clone();
|
||||
// Pen path in progress ends when the tool changes or its mask is gone.
|
||||
if app.ui.tool != Tool::Pen || ui.input(|i| i.key_pressed(egui::Key::Escape) || i.key_pressed(egui::Key::Enter)) {
|
||||
ui.data_mut(|d| d.remove::<(LayerId, u64)>(pen_id()));
|
||||
}
|
||||
if app.ui.viewer.show_layer_controls {
|
||||
for l in comp.layers.iter().filter(|l| selected.contains(&l.id) && l.is_active_at(time)) {
|
||||
let col = Tokens::label(l.label);
|
||||
@@ -328,7 +403,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
if app.ui.viewer.show_masks
|
||||
&& let Some(masks) = l.masks()
|
||||
{
|
||||
let (m, _) = ectx.layer_to_comp(l);
|
||||
let (m, _) = l2c(&ectx, l);
|
||||
for g in masks.groups() {
|
||||
let GroupKind::Mask { color, .. } = g.kind else { continue };
|
||||
let Some(path) = g.get("path").map(|pr| ectx.value(l, pr)) else { continue };
|
||||
@@ -345,14 +420,37 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
if sp.closed && !pts.is_empty() {
|
||||
pts.push(pts[0]);
|
||||
}
|
||||
painter.add(egui::Shape::line(pts, Stroke::new(1.0, Color32::from_rgb(color[0], color[1], color[2]))));
|
||||
for v in &sp.vertices {
|
||||
let c = m.apply(gv2(v[0], v[1]));
|
||||
painter.rect_filled(
|
||||
Rect::from_center_size(map.to_screen([c.x, c.y]), vec2(5.0, 5.0)),
|
||||
0.0,
|
||||
Color32::from_rgb(color[0], color[1], color[2]),
|
||||
);
|
||||
let mc = Color32::from_rgb(color[0], color[1], color[2]);
|
||||
painter.add(egui::Shape::line(pts, Stroke::new(1.0, mc)));
|
||||
let scr = |p: [f64; 2]| {
|
||||
let c = m.apply(gv2(p[0], p[1]));
|
||||
map.to_screen([c.x, c.y])
|
||||
};
|
||||
for (i, v) in sp.vertices.iter().enumerate() {
|
||||
let s = scr(*v);
|
||||
let selected = sel_vertices.iter().any(|x| x.layer == l.id && x.mask == g.uid && x.index == i);
|
||||
// Selected vertices: filled with their tangent handles; others hollow.
|
||||
if selected {
|
||||
for (out, tg) in [(false, sp.in_tangents.get(i)), (true, sp.out_tangents.get(i))] {
|
||||
let Some(tg) = tg.filter(|t| t[0] != 0.0 || t[1] != 0.0) else { continue };
|
||||
let h = scr([v[0] + tg[0], v[1] + tg[1]]);
|
||||
painter.line_segment([s, h], Stroke::new(1.0, mc));
|
||||
painter.circle_filled(h, 3.0, mc);
|
||||
vertex_hits.push(VertexHit { layer: l.id, mask: g.uid, index: i, pos: h, tangent: Some(out), vertex: *v, l2c: m });
|
||||
}
|
||||
painter.rect_filled(Rect::from_center_size(s, vec2(6.0, 6.0)), 0.0, mc);
|
||||
} else {
|
||||
painter.rect_filled(Rect::from_center_size(s, vec2(6.0, 6.0)), 0.0, Color32::from_black_alpha(160));
|
||||
painter.rect_stroke(Rect::from_center_size(s, vec2(6.0, 6.0)), 0.0, Stroke::new(1.0, mc), StrokeKind::Inside);
|
||||
}
|
||||
app.auto.add(&format!("viewer.mask.{}.vertex.{i}", g.uid), Rect::from_center_size(s, vec2(8.0, 8.0)), &g.name);
|
||||
vertex_hits.push(VertexHit { layer: l.id, mask: g.uid, index: i, pos: s, tangent: None, vertex: *v, l2c: m });
|
||||
}
|
||||
// Pen rubber band from the last vertex to the pointer.
|
||||
if ui.data(|d| d.get_temp::<(LayerId, u64)>(pen_id())) == Some((l.id, g.uid))
|
||||
&& let (Some(last), Some(hp)) = (sp.vertices.last(), ui.input(|i| i.pointer.hover_pos()))
|
||||
{
|
||||
painter.line_segment([scr(*last), hp], Stroke::new(1.0, mc.gamma_multiply(0.6)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -387,8 +485,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
// 3D axis gizmo.
|
||||
if l.is_3d() {
|
||||
let w = ectx.world_matrix(l);
|
||||
let (cam, _, _) = ectx.camera();
|
||||
let pc = cam * w;
|
||||
let pc = cam_state(&ectx).projection(cw as f64, ch as f64) * w;
|
||||
let a3 = effectcraft_engine::geom::vec3(a[0], a[1], a[2]);
|
||||
let o = pc.apply(a3);
|
||||
let len = 60.0 / zoom as f64;
|
||||
@@ -405,6 +502,17 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
}
|
||||
}
|
||||
|
||||
// Cameras and lights (wireframes) and the 3D view name.
|
||||
if comp.has_3d() {
|
||||
draw_rigs(app, &painter, &map, &ectx, &selected);
|
||||
let view = app.session.state.views3d.get(&cid).map(|v| v.current).unwrap_or_default();
|
||||
let label = match (view, comp.active_camera(time)) {
|
||||
(View3D::ActiveCamera, Some(c)) => format!("Active Camera ({})", c.name),
|
||||
(v, _) => v.label().to_string(),
|
||||
};
|
||||
painter.text(area.left_top() + vec2(12.0, 10.0), Align2::LEFT_TOP, label, Tokens::ui(12.0), t.text_dim);
|
||||
}
|
||||
|
||||
// Interaction.
|
||||
let resp = ui.interact(area, egui::Id::new("viewer-interact"), Sense::click_and_drag());
|
||||
let gid = egui::Id::new("viewer-gesture");
|
||||
@@ -417,6 +525,9 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
Tool::Hand => egui::CursorIcon::Grab,
|
||||
Tool::Zoom => egui::CursorIcon::ZoomIn,
|
||||
Tool::Type | Tool::TypeVertical => egui::CursorIcon::Text,
|
||||
Tool::Orbit => egui::CursorIcon::Alias,
|
||||
Tool::PanCamera => egui::CursorIcon::Move,
|
||||
Tool::Dolly => egui::CursorIcon::ResizeVertical,
|
||||
t if t.is_shape() || t == Tool::Pen => egui::CursorIcon::Crosshair,
|
||||
_ => {
|
||||
if handle_hits.iter().any(|(_, _, h)| h.distance(hp) < HANDLE) {
|
||||
@@ -444,10 +555,31 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
}
|
||||
let mods = ui.input(|i| i.modifiers);
|
||||
let space_pan = ui.input(|i| i.key_down(egui::Key::Space)) && !ctx.egui_wants_keyboard_input();
|
||||
// Pen tool: each press places a vertex (dragging pulls Bezier tangents); pressing on the
|
||||
// first vertex closes the path.
|
||||
if app.ui.tool == Tool::Pen
|
||||
&& !space_pan
|
||||
&& resp.hovered()
|
||||
&& ui.input(|i| i.pointer.primary_pressed())
|
||||
&& let Some(pos) = ui.input(|i| i.pointer.press_origin())
|
||||
{
|
||||
pen_press(app, ui, &ectx, &map, &vertex_hits, pos);
|
||||
}
|
||||
// A pen click (press + release without a drag) ends its tangent gesture on release.
|
||||
if ui.input(|i| i.pointer.primary_released())
|
||||
&& matches!(ui.data(|d| d.get_temp::<Gesture>(egui::Id::new("viewer-gesture"))), Some(Gesture::Pen { .. }))
|
||||
&& !resp.drag_stopped()
|
||||
{
|
||||
ui.data_mut(|d| d.remove::<Gesture>(egui::Id::new("viewer-gesture")));
|
||||
}
|
||||
let vertex_at = |pos: Pos2, tangents: bool| -> Option<VertexHit> {
|
||||
vertex_hits.iter().rev().filter(|h| h.tangent.is_some() == tangents).find(|h| h.pos.distance(pos) < 6.0).copied()
|
||||
};
|
||||
if resp.drag_started()
|
||||
&& let Some(pos) = resp.interact_pointer_pos()
|
||||
{
|
||||
let cpt = map.to_comp(pos);
|
||||
let press = ui.input(|i| i.pointer.press_origin()).unwrap_or(pos);
|
||||
let tool = if space_pan || resp.dragged_by(egui::PointerButton::Middle) { Tool::Hand } else { app.ui.tool };
|
||||
let g = match tool {
|
||||
Tool::Hand => Some(Gesture::Pan { start_pan: app.ui.viewer.pan }),
|
||||
@@ -464,7 +596,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
Tool::PanBehind => pick(app, &ectx, cpt, false).and_then(|l| {
|
||||
let layer = comp.layer(l)?;
|
||||
let tr = layer.transform()?;
|
||||
let (l2c, _) = ectx.layer_to_comp(layer);
|
||||
let (l2c, _) = l2c(&ectx, layer);
|
||||
let l2p = ectx.local_matrix(layer);
|
||||
let l2p = Mat3([[l2p.0[0][0], l2p.0[0][1], 0.0], [l2p.0[1][0], l2p.0[1][1], 0.0], [0.0, 0.0, 1.0]]);
|
||||
Some(Gesture::Anchor {
|
||||
@@ -477,35 +609,48 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
})
|
||||
}),
|
||||
t if t.is_shape() => Some(Gesture::Create { tool: t, start: cpt }),
|
||||
Tool::Orbit | Tool::PanCamera | Tool::Dolly => Some(Gesture::Camera { tool }),
|
||||
Tool::Selection if vertex_at(press, true).is_some() => vertex_at(press, true).map(|h| Gesture::Tangent {
|
||||
layer: h.layer,
|
||||
mask: h.mask,
|
||||
index: h.index,
|
||||
out: h.tangent == Some(true),
|
||||
vertex: h.vertex,
|
||||
inv: h.l2c.inverse().unwrap_or(Mat3::IDENTITY),
|
||||
}),
|
||||
Tool::Selection if vertex_at(press, false).is_some() => vertex_at(press, false).map(|h| {
|
||||
let me = json!({"layer": h.layer.0, "mask": h.mask, "index": h.index});
|
||||
let selected = app.session.state.selected_vertices.iter().any(|v| v.layer == h.layer && v.mask == h.mask && v.index == h.index);
|
||||
if !selected {
|
||||
let _ = app.session.execute("mask.selectVertices", json!({"vertices": [me], "add": mods.shift}));
|
||||
}
|
||||
Gesture::Vertices { last: cpt, inv: h.l2c.inverse().unwrap_or(Mat3::IDENTITY) }
|
||||
}),
|
||||
Tool::Selection => {
|
||||
if let Some((lid, hi, _)) = handle_hits.iter().find(|(_, _, h)| h.distance(pos) < HANDLE + 2.0).cloned() {
|
||||
let layer = comp.layer(lid).cloned();
|
||||
layer.and_then(|layer| {
|
||||
let tr = layer.transform()?;
|
||||
let (l2c, _) = ectx.layer_to_comp(&layer);
|
||||
let (l2c, _) = l2c(&ectx, &layer);
|
||||
let inv = l2c.inverse()?;
|
||||
let a = ectx.v3(&layer, tr, "anchor", [0.0; 3]);
|
||||
let ac = l2c.apply(gv2(a[0], a[1]));
|
||||
let lp = inv.apply(gv2(cpt[0], cpt[1]));
|
||||
let _ = hi;
|
||||
Some(Gesture::Scale {
|
||||
layer: lid,
|
||||
anchor_screen: map.to_screen([ac.x, ac.y]),
|
||||
start_scale: ectx.v3(&layer, tr, "scale", [100.0; 3]),
|
||||
start_local: [lp.x - a[0], lp.y - a[1]],
|
||||
inv,
|
||||
uniform: hi < 4,
|
||||
})
|
||||
Some(Gesture::Scale { layer: lid, start_scale: ectx.v3(&layer, tr, "scale", [100.0; 3]), start_local: [lp.x - a[0], lp.y - a[1]], inv })
|
||||
})
|
||||
} else if let Some(l) = pick(app, &ectx, cpt, mods.shift) {
|
||||
let layers: Vec<(LayerId, [f64; 3], Mat3)> = app
|
||||
let layers: Vec<(LayerId, [f64; 3], [f64; 3], [f64; 3])> = app
|
||||
.session
|
||||
.state
|
||||
.selected_layers
|
||||
.iter()
|
||||
.filter_map(|id| comp.layer(*id))
|
||||
.filter(|l| !l.switches.locked)
|
||||
.filter_map(|l| Some((l.id, ectx.v3(l, l.transform()?, "position", [0.0; 3]), parent_inverse(&ectx, l))))
|
||||
.filter_map(|l| {
|
||||
let p0 = ectx.v3(l, l.transform()?, "position", [0.0; 3]);
|
||||
let (ax, ay) = drag_axes(&ectx, l);
|
||||
Some((l.id, p0, ax, ay))
|
||||
})
|
||||
.collect();
|
||||
let _ = l;
|
||||
(!layers.is_empty()).then_some(Gesture::Move { layers, start: cpt })
|
||||
@@ -534,9 +679,8 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
if mods.shift {
|
||||
if d[0].abs() > d[1].abs() { d[1] = 0.0 } else { d[0] = 0.0 }
|
||||
}
|
||||
for (lid, p0, inv) in layers {
|
||||
let dd = inv.apply_vec(gv2(d[0], d[1]));
|
||||
let v = json!([p0[0] + dd.x, p0[1] + dd.y, p0[2]]);
|
||||
for (lid, p0, ax, ay) in layers {
|
||||
let v = json!([p0[0] + ax[0] * d[0] + ay[0] * d[1], p0[1] + ax[1] * d[0] + ay[1] * d[1], p0[2] + ax[2] * d[0] + ay[2] * d[1]]);
|
||||
let _ = app.session.execute("prop.set", json!({"layer": lid.0, "path": "transform/position", "value": v, "merge": merge}));
|
||||
}
|
||||
}
|
||||
@@ -577,7 +721,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
time,
|
||||
expr: app.session.expr.as_deref(),
|
||||
};
|
||||
if let Some(m) = e2.layer_to_comp(&l).0.inverse() {
|
||||
if let Some(m) = l2c(&e2, &l).0.inverse() {
|
||||
*i2 = m;
|
||||
}
|
||||
}
|
||||
@@ -604,11 +748,51 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let _ = app.session.execute("prop.set", json!({"layer": layer.0, "path": "transform/anchor", "value": na, "merge": merge}));
|
||||
let _ = app.session.execute("prop.set", json!({"layer": layer.0, "path": "transform/position", "value": np, "merge": merge}));
|
||||
}
|
||||
Gesture::Camera { tool } => {
|
||||
let d = resp.drag_delta();
|
||||
if d != egui::Vec2::ZERO {
|
||||
let (dx, dy) = ((d.x / zoom) as f64, (d.y / zoom) as f64);
|
||||
let (id, params) = match tool {
|
||||
Tool::Orbit => ("camera.orbit", json!({"yaw": -d.x as f64 * 0.4, "pitch": d.y as f64 * 0.4, "merge": merge})),
|
||||
Tool::PanCamera => ("camera.pan", json!({"dx": dx, "dy": dy, "merge": merge})),
|
||||
_ => ("camera.dolly", json!({"amount": -dy * 2.0, "merge": merge})),
|
||||
};
|
||||
if let Err(e) = app.session.execute(id, params) {
|
||||
app.ui.status = e.to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
Gesture::Create { start, .. } => {
|
||||
let a = map.to_screen(start);
|
||||
let r = Rect::from_two_pos(a, pos);
|
||||
painter.rect_stroke(r, 0.0, Stroke::new(1.0, t.accent), StrokeKind::Middle);
|
||||
}
|
||||
Gesture::Vertices { last, inv } => {
|
||||
let d = inv.apply_vec(gv2(cpt[0] - last[0], cpt[1] - last[1]));
|
||||
if d.x != 0.0 || d.y != 0.0 {
|
||||
let _ = app.session.execute("mask.moveVertices", json!({"delta": [d.x, d.y], "merge": merge}));
|
||||
}
|
||||
ui.data_mut(|dd| dd.insert_temp(gid, Gesture::Vertices { last: cpt, inv }));
|
||||
}
|
||||
Gesture::Tangent { layer, mask, index, out, vertex, inv } => {
|
||||
let lp = inv.apply(gv2(cpt[0], cpt[1]));
|
||||
let t = [lp.x - vertex[0], lp.y - vertex[1]];
|
||||
let mut params = json!({"layer": layer.0, "mask": mask, "index": index, "merge": merge});
|
||||
params[if out { "out" } else { "in" }] = json!(t);
|
||||
if !mods.alt {
|
||||
params[if out { "in" } else { "out" }] = json!([-t[0], -t[1]]);
|
||||
}
|
||||
let _ = app.session.execute("mask.setVertex", params);
|
||||
}
|
||||
Gesture::Pen { layer, mask, index, vertex, inv, press } => {
|
||||
if pos.distance(press) > 3.0 {
|
||||
let lp = inv.apply(gv2(cpt[0], cpt[1]));
|
||||
let t = [lp.x - vertex[0], lp.y - vertex[1]];
|
||||
let _ = app
|
||||
.session
|
||||
.execute("mask.setVertex", json!({"layer": layer.0, "mask": mask, "index": index, "out": t, "in": [-t[0], -t[1]], "merge": merge}));
|
||||
}
|
||||
}
|
||||
Gesture::Marquee { start } => {
|
||||
let r = Rect::from_two_pos(start, pos);
|
||||
painter.rect_filled(r, 0.0, t.accent.gamma_multiply(0.12));
|
||||
@@ -665,6 +849,13 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
ui.data_mut(|d| d.insert_temp(egui::Id::new("viewer-text-edit"), (v["layer"].as_u64().unwrap_or(0), "Text".to_string())));
|
||||
}
|
||||
}
|
||||
Tool::Pen => {}
|
||||
Tool::Selection if vertex_at(pos, false).is_some() => {
|
||||
if let Some(h) = vertex_at(pos, false) {
|
||||
let me = json!({"layer": h.layer.0, "mask": h.mask, "index": h.index});
|
||||
let _ = app.session.execute("mask.selectVertices", json!({"vertices": [me], "add": mods.shift, "toggle": mods.shift}));
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if pick(app, &ectx, cpt, mods.shift).is_none() {
|
||||
let _ = app.session.execute("edit.deselectAll", json!({}));
|
||||
@@ -673,6 +864,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
}
|
||||
}
|
||||
if resp.double_clicked()
|
||||
&& app.ui.tool != Tool::Pen
|
||||
&& let Some(pos) = resp.interact_pointer_pos()
|
||||
{
|
||||
let cpt = map.to_comp(pos);
|
||||
@@ -699,6 +891,144 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
bottom_bar(app, ui, bar, zoom, fit, time, &comp);
|
||||
}
|
||||
|
||||
/// Parent-space position change per comp pixel of drag (x and y) for a layer: 2D layers map
|
||||
/// through the parent transform; 3D layers move in the view plane at their depth.
|
||||
fn drag_axes(ctx: &EvalCtx, l: &Layer) -> ([f64; 3], [f64; 3]) {
|
||||
if !l.is_3d() {
|
||||
let inv = parent_inverse(ctx, l);
|
||||
let a = inv.apply_vec(gv2(1.0, 0.0));
|
||||
let b = inv.apply_vec(gv2(0.0, 1.0));
|
||||
return ([a.x, a.y, 0.0], [b.x, b.y, 0.0]);
|
||||
}
|
||||
let cam = cam_state(ctx);
|
||||
let anchor = l.transform().map(|tr| ctx.v3(l, tr, "anchor", [0.0; 3])).unwrap_or([0.0; 3]);
|
||||
let wp = ctx.world_matrix(l).apply(anchor.into());
|
||||
let k = if cam.ortho { 1.0 / cam.zoom.max(1e-9) } else { cam.depth(wp).max(1.0) / cam.zoom.max(1e-9) };
|
||||
let pinv = match l.parent.and_then(|p| ctx.comp.layer(p)) {
|
||||
Some(p) => ctx.world_matrix(p).inverse().unwrap_or_default(),
|
||||
None => effectcraft_engine::geom::Mat4::IDENTITY,
|
||||
};
|
||||
let a = pinv.apply_vec(cam.right() * k);
|
||||
let b = pinv.apply_vec(cam.down() * k);
|
||||
([a.x, a.y, a.z], [b.x, b.y, b.z])
|
||||
}
|
||||
|
||||
/// Wireframes of cameras (frustum, point of interest) and lights (position, direction) as seen
|
||||
/// through the current 3D view.
|
||||
fn draw_rigs(app: &mut EffectcraftApp, painter: &egui::Painter, map: &ViewerMap, ectx: &EvalCtx, selected: &[LayerId]) {
|
||||
use effectcraft_engine::geom::Vec3;
|
||||
use effectcraft_engine::project::{LayerSource, LightKind};
|
||||
let cam = cam_state(ectx);
|
||||
let (w, h) = (ectx.comp.width as f64, ectx.comp.height as f64);
|
||||
let active = ectx.comp.active_camera(ectx.time).map(|c| c.id);
|
||||
let through_active = VIEW_CAM.with(|c| c.get()).is_none();
|
||||
let proj = |p: Vec3| cam.project(w, h, p).map(|v| map.to_screen([v.x, v.y]));
|
||||
let seg = |a: Vec3, b: Vec3, stroke: Stroke| {
|
||||
if let (Some(x), Some(y)) = (proj(a), proj(b)) {
|
||||
painter.line_segment([x, y], stroke);
|
||||
}
|
||||
};
|
||||
for l in ectx.comp.layers.iter().filter(|l| (l.is_camera() || l.is_light()) && l.is_active_at(ectx.time)) {
|
||||
let sel = selected.contains(&l.id);
|
||||
let col = Tokens::label(l.label).gamma_multiply(if sel { 1.0 } else { 0.6 });
|
||||
let stroke = Stroke::new(if sel { 1.5 } else { 1.0 }, col);
|
||||
let (eye, fwd, down) = three_d::camera::layer_frame(ectx, l);
|
||||
let poi = |l: &Layer| -> Option<Vec3> {
|
||||
let pr = l.transform()?.get("poi").filter(|_| three_d::camera::is_two_node(l))?;
|
||||
Some(three_d::camera::parent_world(ectx, l).apply(ectx.value(l, pr).as_vec3().into()))
|
||||
};
|
||||
if l.is_camera() {
|
||||
if through_active && Some(l.id) == active {
|
||||
continue;
|
||||
}
|
||||
let zoom = l.props.prop("cameraOptions/zoom").map(|p| ectx.value(l, p).as_f64()).unwrap_or(1000.0);
|
||||
let right = down.cross(fwd);
|
||||
// Frustum to a plane at a quarter of the zoom distance.
|
||||
let k = 0.25;
|
||||
let c = eye + fwd * (zoom * k);
|
||||
let corners = [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)].map(|(sx, sy)| c + right * (sx * w * 0.5 * k) + down * (sy * h * 0.5 * k));
|
||||
for i in 0..4 {
|
||||
seg(eye, corners[i], stroke);
|
||||
seg(corners[i], corners[(i + 1) % 4], stroke);
|
||||
}
|
||||
if let Some(poi) = poi(l) {
|
||||
seg(eye, poi, Stroke::new(1.0, col.gamma_multiply(0.6)));
|
||||
if let Some(s) = proj(poi) {
|
||||
painter.circle_stroke(s, 4.0, stroke);
|
||||
}
|
||||
}
|
||||
if let Some(s) = proj(eye) {
|
||||
app.auto.add(&format!("viewer.camera.{}", l.id.0), Rect::from_center_size(s, vec2(14.0, 14.0)), &l.name);
|
||||
}
|
||||
} else {
|
||||
let LayerSource::Light { kind } = l.source else { continue };
|
||||
if kind == LightKind::Ambient {
|
||||
continue;
|
||||
}
|
||||
let Some(s) = proj(eye) else { continue };
|
||||
painter.circle_stroke(s, 6.0, stroke);
|
||||
for i in 0..8 {
|
||||
let a = i as f32 * std::f32::consts::FRAC_PI_4;
|
||||
let d = vec2(a.cos(), a.sin());
|
||||
painter.line_segment([s + d * 8.0, s + d * 12.0], stroke);
|
||||
}
|
||||
if matches!(kind, LightKind::Spot | LightKind::Parallel) {
|
||||
let target = poi(l).unwrap_or(eye + fwd * 300.0);
|
||||
seg(eye, target, Stroke::new(1.0, col.gamma_multiply(0.7)));
|
||||
if let Some(q) = proj(target) {
|
||||
painter.circle_stroke(q, 3.0, stroke);
|
||||
}
|
||||
}
|
||||
app.auto.add(&format!("viewer.light.{}", l.id.0), Rect::from_center_size(s, vec2(16.0, 16.0)), &l.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Pen tool press at `pos`: start a mask on the selected layer, add a vertex, or close the path.
|
||||
fn pen_press(app: &mut EffectcraftApp, ui: &mut egui::Ui, ectx: &EvalCtx, map: &ViewerMap, hits: &[VertexHit], pos: Pos2) {
|
||||
let gid = egui::Id::new("viewer-gesture");
|
||||
let current: Option<(LayerId, u64)> = ui.data(|d| d.get_temp(pen_id()));
|
||||
let target = current.map(|c| c.0).or_else(|| {
|
||||
app.session.state.selected_layers.iter().copied().find(|id| ectx.comp.layer(*id).is_some_and(|l| l.masks().is_some() && !l.switches.locked))
|
||||
});
|
||||
let Some(lid) = target else {
|
||||
app.ui.status = "Select a layer to draw a mask with the Pen tool".into();
|
||||
return;
|
||||
};
|
||||
let Some(layer) = ectx.comp.layer(lid) else { return };
|
||||
let l2c = l2c(ectx, layer).0;
|
||||
let Some(inv) = l2c.inverse() else { return };
|
||||
let c = map.to_comp(pos);
|
||||
let lp = inv.apply(gv2(c[0], c[1]));
|
||||
let lp = [lp.x, lp.y];
|
||||
let still_there = current.is_some_and(|(l, m)| layer.masks().is_some_and(|ms| ms.find_group(m).is_some()) && l == lid);
|
||||
if let (true, Some((_, mask))) = (still_there, current) {
|
||||
let count = hits.iter().filter(|h| h.layer == lid && h.mask == mask && h.tangent.is_none()).count();
|
||||
let first = hits.iter().find(|h| h.layer == lid && h.mask == mask && h.index == 0 && h.tangent.is_none());
|
||||
if count >= 2 && first.is_some_and(|f| f.pos.distance(pos) < 8.0) {
|
||||
let _ = app.session.execute("mask.setClosed", json!({"layer": lid.0, "mask": mask, "closed": true}));
|
||||
ui.data_mut(|d| {
|
||||
d.remove::<(LayerId, u64)>(pen_id());
|
||||
d.remove::<Gesture>(gid);
|
||||
});
|
||||
return;
|
||||
}
|
||||
if let Ok(v) = app.session.execute("mask.addVertex", json!({"layer": lid.0, "mask": mask, "point": lp})) {
|
||||
let index = v.as_u64().unwrap_or(0) as usize;
|
||||
ui.data_mut(|d| d.insert_temp(gid, Gesture::Pen { layer: lid, mask, index, vertex: lp, inv, press: pos }));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if let Ok(v) = app.session.execute("mask.new", json!({"layer": lid.0, "vertices": [lp]}))
|
||||
&& let Some(mask) = v["mask"].as_u64()
|
||||
{
|
||||
ui.data_mut(|d| {
|
||||
d.insert_temp(pen_id(), (lid, mask));
|
||||
d.insert_temp(gid, Gesture::Pen { layer: lid, mask, index: 0, vertex: lp, inv, press: pos });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Topmost layer under a comp point (selects it; shift toggles). Returns the hit layer.
|
||||
fn pick(app: &mut EffectcraftApp, ectx: &EvalCtx, cpt: [f64; 2], toggle: bool) -> Option<LayerId> {
|
||||
let hit = ectx
|
||||
@@ -754,7 +1084,7 @@ fn create_shape(app: &mut EffectcraftApp, tool: Tool, a: [f64; 2], b: [f64; 2],
|
||||
time: app.session.time(),
|
||||
expr: None,
|
||||
};
|
||||
let inv = ectx.layer_to_comp(&l).0.inverse().unwrap_or(Mat3::IDENTITY);
|
||||
let inv = l2c(&ectx, &l).0.inverse().unwrap_or(Mat3::IDENTITY);
|
||||
let p0 = inv.apply(gv2(cx - w / 2.0, cy - h / 2.0));
|
||||
let p1 = inv.apply(gv2(cx + w / 2.0, cy + h / 2.0));
|
||||
let _ = app.session.execute(
|
||||
@@ -916,9 +1246,20 @@ fn bottom_bar(app: &mut EffectcraftApp, ui: &mut egui::Ui, bar: Rect, zoom: f32,
|
||||
if comp.has_3d() {
|
||||
let r = Rect::from_min_size(pos2(x + 2.0, cy - 10.0), vec2(96.0, 20.0));
|
||||
let _ = widgets::dropdown(ui, r, "Classic 3D", &t, egui::Id::new("vw-3d"));
|
||||
app.auto.add("viewer.renderer3d", r, "3D Renderer");
|
||||
x = r.max.x + 4.0;
|
||||
let r = Rect::from_min_size(pos2(x, cy - 10.0), vec2(110.0, 20.0));
|
||||
let _ = widgets::dropdown(ui, r, "Active Camera", &t, egui::Id::new("vw-cam"));
|
||||
let cid = app.session.active_comp_id();
|
||||
let cur = cid.and_then(|c| app.session.state.views3d.get(&c)).map(|v| v.current).unwrap_or_default();
|
||||
let r = Rect::from_min_size(pos2(x, cy - 10.0), vec2(118.0, 20.0));
|
||||
if widgets::dropdown(ui, r, cur.label(), &t, egui::Id::new("vw-cam")).clicked() {
|
||||
widgets::open_popup(ui, egui::Id::new("vw-cam-pop"));
|
||||
}
|
||||
app.auto.add("viewer.view3d", r, "3D View");
|
||||
let opts: Vec<String> = View3D::ALL.iter().map(|v| v.label().to_string()).collect();
|
||||
let at = r.left_top() - vec2(0.0, 22.0 * opts.len() as f32 + 12.0);
|
||||
if let Some(i) = widgets::popup_menu(ui, egui::Id::new("vw-cam-pop"), at, &opts, View3D::ALL.iter().position(|v| *v == cur)) {
|
||||
let _ = app.session.execute("view.set3DView", json!({"view": View3D::ALL[i].id()}));
|
||||
}
|
||||
}
|
||||
// Right: render time.
|
||||
let ms = app.frames.last_ms.lock().map(|v| *v).unwrap_or(0.0);
|
||||
|
||||
@@ -267,6 +267,28 @@ pub struct TimelineState {
|
||||
/// Properties / groups (uids) shown by the `props` reveal (Animation ▸ Reveal Properties…).
|
||||
#[serde(default)]
|
||||
pub reveal_props: BTreeSet<u64>,
|
||||
/// Graph Editor: `value` or `speed` graph.
|
||||
#[serde(default = "value_graph")]
|
||||
pub graph_mode: String,
|
||||
/// Show only the selected properties (else every animated property of the selected layers).
|
||||
#[serde(default = "yes")]
|
||||
pub graph_show_selected: bool,
|
||||
/// Auto-zoom the graph height to the visible curves.
|
||||
#[serde(default = "yes")]
|
||||
pub graph_auto_zoom: bool,
|
||||
/// Manual graph value range (when auto-zoom is off).
|
||||
#[serde(default)]
|
||||
pub graph_range: Option<(f64, f64)>,
|
||||
/// Properties whose inline expression editor is collapsed.
|
||||
#[serde(default)]
|
||||
pub expr_closed: BTreeSet<u64>,
|
||||
}
|
||||
|
||||
fn value_graph() -> String {
|
||||
"value".into()
|
||||
}
|
||||
fn yes() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
impl Default for TimelineState {
|
||||
@@ -276,17 +298,26 @@ impl Default for TimelineState {
|
||||
pps: None,
|
||||
scroll_y: 0.0,
|
||||
columns_w: 560.0,
|
||||
show_modes: true,
|
||||
show_modes: false,
|
||||
graph_editor: false,
|
||||
search: String::new(),
|
||||
open_layers: BTreeSet::new(),
|
||||
open_groups: BTreeSet::new(),
|
||||
reveal: vec![],
|
||||
reveal_props: BTreeSet::new(),
|
||||
graph_mode: value_graph(),
|
||||
graph_show_selected: true,
|
||||
graph_auto_zoom: true,
|
||||
graph_range: None,
|
||||
expr_closed: BTreeSet::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn default_project_sort() -> String {
|
||||
"name".into()
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct UiState {
|
||||
pub tool: Tool,
|
||||
@@ -305,8 +336,17 @@ pub struct UiState {
|
||||
pub effects_open: BTreeSet<String>,
|
||||
pub project_search: String,
|
||||
pub project_open_folders: BTreeSet<u64>,
|
||||
/// Project panel sort column (`name`, `type`, `size`, `fps`) and direction, as in AE's
|
||||
/// clickable column headers. Folders sort with everything else.
|
||||
#[serde(default = "default_project_sort")]
|
||||
pub project_sort: String,
|
||||
#[serde(default)]
|
||||
pub project_sort_desc: bool,
|
||||
/// Effect Controls twirl state (group uids that are collapsed).
|
||||
pub fx_closed: BTreeSet<u64>,
|
||||
/// Slider params whose slider row is twirled open (AE hides sliders by default).
|
||||
#[serde(default)]
|
||||
pub fx_slider_open: BTreeSet<u64>,
|
||||
/// Shape tool options.
|
||||
pub fill_color: [f32; 3],
|
||||
pub stroke_color: [f32; 3],
|
||||
@@ -339,7 +379,10 @@ impl Default for UiState {
|
||||
effects_open: BTreeSet::new(),
|
||||
project_search: String::new(),
|
||||
project_open_folders: BTreeSet::new(),
|
||||
project_sort: default_project_sort(),
|
||||
project_sort_desc: false,
|
||||
fx_closed: BTreeSet::new(),
|
||||
fx_slider_open: BTreeSet::new(),
|
||||
fill_color: [0.24, 0.55, 0.96],
|
||||
stroke_color: [1.0, 1.0, 1.0],
|
||||
stroke_width: 0.0,
|
||||
|
||||
Reference in New Issue
Block a user