diff --git a/crates/engine/src/cmd/three_d.rs b/crates/engine/src/cmd/three_d.rs index 3355b68e3..786787dd2 100644 --- a/crates/engine/src/cmd/three_d.rs +++ b/crates/engine/src/cmd/three_d.rs @@ -459,37 +459,192 @@ fn get_3d(s: &mut Session, p: &Value) -> Result { // ---------------------------------------------------------------- camera tools +#[derive(Clone, Copy)] enum ToolOp { Orbit(f64, f64), Pan(f64, f64), Dolly(f64), } +/// Which of After Effects' variants of a camera tool runs: what it turns about, pans at or +/// dollies towards (`mode` of `camera.orbit` / `camera.pan` / `camera.dolly`). +#[derive(Clone, Copy, PartialEq, Eq)] +enum ToolMode { + /// Without `mode`, `camera.dolly` keeps its original behaviour: a camera layer travels with + /// its point of interest along the view axis, a 3D view approaches its point of interest. + Plain, + /// The point under the cursor: Orbit Around Cursor, Pan Under Cursor, Dolly Towards Cursor. + Cursor, + /// Dolly to Cursor: towards the point under the cursor, stopping short of it. + ToCursor, + /// Orbit Around Scene: the centre of the comp's 3D layers. + Scene, + /// The camera's point of interest: Orbit Around Camera POI, Pan Camera POI, Dolly to Camera POI. + Target, +} + +impl ToolMode { + /// Reads the `mode` parameter of a camera tool into the variant that applies to `op`. + /// Without a mode, orbit and pan act about the point of interest and dolly moves plainly; an unknown name is an error. + fn parse(p: &Value, op: ToolOp, cmd: &str) -> Result { + let Some(raw) = str_p(p, "mode") else { + return Ok(match op { + ToolOp::Dolly(_) => ToolMode::Plain, + _ => ToolMode::Target, + }); + }; + let k: String = raw.chars().filter(char::is_ascii_alphanumeric).collect::().to_ascii_lowercase(); + let mode = match (op, k.as_str()) { + (ToolOp::Orbit(..), "aroundcursor" | "cursor") => ToolMode::Cursor, + (ToolOp::Orbit(..), "aroundscene" | "scene") => ToolMode::Scene, + (ToolOp::Orbit(..), "aroundcamerapoi" | "camerapoi" | "aroundcameratarget" | "aroundtarget" | "cameratarget" | "target" | "poi") => { + ToolMode::Target + } + (ToolOp::Pan(..), "undercursor" | "cursor") => ToolMode::Cursor, + (ToolOp::Pan(..), "camerapoi" | "tocamerapoi" | "tocameratarget" | "totarget" | "cameratarget" | "target" | "poi") => ToolMode::Target, + (ToolOp::Dolly(_), "towardscursor" | "cursor") => ToolMode::Cursor, + (ToolOp::Dolly(_), "tocursor") => ToolMode::ToCursor, + (ToolOp::Dolly(_), "tocamerapoi" | "camerapoi" | "tocameratarget" | "totarget" | "cameratarget" | "target" | "poi") => ToolMode::Target, + _ => return Err(bad(cmd, format!("unknown mode `{raw}`"))), + }; + Ok(mode) + } +} + +/// The 3D layers that make up the scene at comp time `t`: active, visible (Video on, not a guide) +/// and with pixels (no cameras, lights or nulls). Solo applies as the renderer's +/// `Renderer::visible_layers` does (`Comp::any_solo`): with a layer soloed, only soloed layers count. +fn scene_layers(comp: &Comp, t: Tick) -> Vec { + let any_solo = comp.any_solo(); + comp.layers + .iter() + .filter(|l| l.is_active_at(t) && l.switches.three_d && l.switches.video && !l.switches.guide && l.source.is_av() && (!any_solo || l.switches.solo)) + .map(|l| l.id) + .collect() +} + +/// World-space rectangles of the layers' content at comp time `t` (for picking the point under +/// the cursor); layers without content bounds are left out. +fn layer_quads(s: &Session, cid: ItemId, ids: &[LayerId], t: Tick) -> Vec<[Vec3; 4]> { + let Some(comp) = s.project.comp(cid) else { return vec![] }; + let ctx = EvalCtx { + project: &s.project, + comp_id: cid, + comp, + time: t, + expr: s.expr.as_deref(), + footage: None, + property_overrides: &[], + media_overrides: &[], + reads: None, + }; + comp.layers + .iter() + .filter(|l| ids.contains(&l.id)) + .filter_map(|l| { + let m = ctx.world_matrix(l); + let [x0, y0, x1, y1] = effectcraft_render::content_bounds(&ctx, l)?; + Some([m.apply(vec3(x0, y0, 0.0)), m.apply(vec3(x1, y0, 0.0)), m.apply(vec3(x1, y1, 0.0)), m.apply(vec3(x0, y1, 0.0))]) + }) + .collect() +} + +/// The world point a camera tool turns about, pans at or dollies towards, for the modes that +/// need one: `point` when given (the UI resolves it once at mouse-down and sends it with every +/// step of the drag), else the scene's centre, or the point under `cursor` (comp pixels; default +/// the comp's centre) as `cam` sees it, falling back to the depth of `poi`. +fn tool_pivot(s: &Session, cid: ItemId, p: &Value, mode: ToolMode, cam: &camera::CameraState, poi: Vec3, t: Tick) -> Option { + if matches!(mode, ToolMode::Plain | ToolMode::Target) { + return None; + } + if let Some(pt) = v3_p(p, "point").map(Vec3::from).filter(|v| v.x.is_finite() && v.y.is_finite() && v.z.is_finite()) { + return Some(pt); + } + let comp = s.project.comp(cid)?; + let (w, h) = (comp.width as f64, comp.height as f64); + let ids = scene_layers(comp, t); + if mode == ToolMode::Scene { + let pts = layer_points(s, cid, &ids, t); + return Some(camera::bounds_center(&pts).unwrap_or(vec3(w / 2.0, h / 2.0, 0.0))); + } + let px = v3_p(p, "cursor").map(|c| [c[0], c[1]]).filter(|c| c[0].is_finite() && c[1].is_finite()).unwrap_or([w / 2.0, h / 2.0]); + Some(camera::point_under(cam, w, h, px, &layer_quads(s, cid, &ids, t), poi)) +} + +/// Applies one orbit, pan or dolly step to the active camera, or to the current custom view, about the pivot its mode picks. +/// A step that would leave a non-finite camera is dropped; returns the layer and the view it came from. fn camera_tool(s: &mut Session, p: &Value, op: ToolOp, cmd: &str, label: &str) -> Result { let cid = comp_id(s, p)?; let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone(); let (w, h) = (comp.width as f64, comp.height as f64); let cur = s.state.views3d.get(&cid).map(|v| v.current).unwrap_or_default(); - let apply = |r: &mut Rig, layer: bool| match op { - ToolOp::Orbit(yaw, pitch) => r.orbit(yaw, pitch), - ToolOp::Pan(dx, dy) => r.pan(dx, dy), - ToolOp::Dolly(a) => r.dolly(a, layer), - }; - if cur != View3D::ActiveCamera { - let vs = views(s, cid); - let vc = vs.cam(cur, w, h); - let mut r = Rig::from_view(&vc); - apply(&mut r, false); - let nc = ViewCam { eye: camera::arr(r.eye), poi: camera::arr(r.poi), zoom: r.zoom, ..vc }; - vs.cams.insert(cur, nc); - return Ok(json!({"view": cur.id(), "eye": nc.eye, "poi": nc.poi, "zoom": nc.zoom})); - } + let mode = ToolMode::parse(p, op, cmd)?; let t = s.state.times.get(&cid).copied().unwrap_or(Tick::ZERO); + // One step of the tool; a step that would leave a non-finite camera is dropped. + let apply = |r: &mut Rig, layer: bool, pivot: Option, mode: ToolMode| { + let before = *r; + let at = pivot.unwrap_or(r.poi); + match (op, mode) { + (ToolOp::Orbit(yaw, pitch), ToolMode::Cursor | ToolMode::Scene | ToolMode::ToCursor) => r.orbit_about(at, yaw, pitch), + (ToolOp::Orbit(yaw, pitch), _) => r.orbit(yaw, pitch), + (ToolOp::Pan(dx, dy), ToolMode::Cursor | ToolMode::Scene | ToolMode::ToCursor) => r.pan_at(dx, dy, at), + (ToolOp::Pan(dx, dy), _) => r.pan(dx, dy), + (ToolOp::Dolly(a), ToolMode::Plain) => r.dolly(a, layer), + (ToolOp::Dolly(a), ToolMode::Target) => r.dolly(a, false), + (ToolOp::Dolly(a), ToolMode::Cursor | ToolMode::Scene) => r.dolly_towards(a, at, false), + (ToolOp::Dolly(a), ToolMode::ToCursor) => r.dolly_towards(a, at, true), + } + if !r.is_finite() { + *r = before; + } + }; + let pivot_json = |pv: Option| pv.map(camera::arr).map_or(Value::Null, |a| json!(a)); + if cur != View3D::ActiveCamera { + let vc = views(s, cid).cam(cur, w, h); + let mut r = Rig::from_view(&vc); + let pivot = tool_pivot(s, cid, p, mode, &vc.state(), r.poi, t); + apply(&mut r, false, pivot, mode); + let nc = ViewCam { eye: camera::arr(r.eye), poi: camera::arr(r.poi), zoom: r.zoom, ..vc }; + views(s, cid).cams.insert(cur, nc); + return Ok(json!({"view": cur.id(), "eye": nc.eye, "poi": nc.poi, "zoom": nc.zoom, "pivot": pivot_json(pivot)})); + } let cam = match p.get("layer") { Some(v) => super::resolve_layer(&comp, v).filter(|id| comp.layer(*id).is_some_and(|l| l.is_camera())), None => comp.active_camera(t).map(|l| l.id), } .ok_or_else(|| bad(cmd, "the comp has no active camera layer (Layer ▸ New ▸ Camera), or switch to a custom 3D view"))?; + // The point under the cursor as the camera layer shows it, in world space (returned, and + // sent back by the viewer as `point`) and in the camera's parent space (what the rig edits). + let (pivot, local_pivot, pw) = match comp.layer(cam) { + Some(l) if !matches!(mode, ToolMode::Plain | ToolMode::Target) => { + let ctx = EvalCtx { + project: &s.project, + comp_id: cid, + comp: &comp, + time: t, + expr: s.expr.as_deref(), + footage: None, + property_overrides: &[], + media_overrides: &[], + reads: None, + }; + let state = camera::layer_camera(&ctx, l); + let pw = camera::parent_world(&ctx, l); + let poi = match get_at(l, "transform/poi", t) { + Some(v) if camera::is_two_node(l) => pw.apply(Vec3::from(v.as_vec3())), + _ => state.eye + state.forward() * state.zoom, + }; + let world = tool_pivot(s, cid, p, mode, &state, poi, t); + let local = world.and_then(|w| pw.inverse().map(|m| m.apply(w))).filter(|v| v.x.is_finite() && v.y.is_finite() && v.z.is_finite()); + (world, local, pw) + } + _ => (None, None, Mat4::IDENTITY), + }; + // A parent that cannot be inverted leaves no pivot in the camera's space: work about its + // point of interest instead, and report that point (the rig's, through the parent) as the one + // used; sent back as `point`, it lands here again. + let fallback = pivot.is_some() && local_pivot.is_none(); + let mode = if fallback { ToolMode::Target } else { mode }; let merge = merge_p(p).map(str::to_string); let r = s.edit(label, merge.as_deref(), |proj, _| { let l = layer_mut(proj, cid, cam)?; @@ -505,8 +660,9 @@ fn camera_tool(s: &mut Session, p: &Value, op: ToolOp, cmd: &str, label: &str) - let fwd = (Mat4::orientation(Vec3::from(o)) * Mat4::rotation_xyz(rx, ry, 0.0)).apply_vec(vec3(0.0, 0.0, 1.0)); pos + fwd * zoom }; + let used = if fallback { Some(pw.apply(poi)).filter(|v| v.x.is_finite() && v.y.is_finite() && v.z.is_finite()) } else { pivot }; let mut rig = Rig { eye: pos, poi, zoom, ortho: false }; - apply(&mut rig, true); + apply(&mut rig, true, local_pivot, mode); set_at(l, "transform/position", t, KV::Vec3(camera::arr(rig.eye))); if two { set_at(l, "transform/poi", t, KV::Vec3(camera::arr(rig.poi))); @@ -515,7 +671,7 @@ fn camera_tool(s: &mut Session, p: &Value, op: ToolOp, cmd: &str, label: &str) - set_at(l, "transform/rotationX", t, KV::Scalar(0.0)); set_at(l, "transform/rotationY", t, KV::Scalar(0.0)); } - Ok(json!({"layer": cam.0, "position": camera::arr(rig.eye), "poi": camera::arr(rig.poi)})) + Ok(json!({"layer": cam.0, "position": camera::arr(rig.eye), "poi": camera::arr(rig.poi), "pivot": pivot_json(used)})) })?; Ok(r) } @@ -697,6 +853,7 @@ fn camera_from_view(s: &mut Session, p: &Value) -> Result { Ok(json!({"layer": id.0, "from": cur.id()})) } +/// Returns the command specs of the 3D commands, including the eight camera tools. pub fn specs() -> Vec { vec![ cmd!( @@ -786,12 +943,28 @@ pub fn specs() -> Vec { "Orbit Camera", [], None, - "{yaw|dx deg, pitch|dy deg, layer?, merge?} — current 3D view (camera layer in Active Camera)", + "{yaw|dx deg, pitch|dy deg, mode?: aroundCursor|aroundScene|aroundCameraPoi (default; alias aroundCameraTarget), cursor? [x,y] comp px, point? [x,y,z] pivot, layer?, merge?} — current 3D view (camera layer in Active Camera); returns `pivot`, the world point used (null when the tool works about the point of interest)", has_comp, orbit ), - cmd!("camera.pan", "Pan Camera", [], None, "{dx, dy (comp px), layer?, merge?}", has_comp, pan), - cmd!("camera.dolly", "Dolly Camera", [], None, "{amount (px, + = forward), layer?, merge?}", has_comp, dolly), + cmd!( + "camera.pan", + "Pan Camera", + [], + None, + "{dx, dy (comp px), mode?: underCursor|cameraPoi (default; alias toCameraTarget), cursor? [x,y], point? [x,y,z], layer?, merge?} — returns `pivot` (null: the point of interest)", + has_comp, + pan + ), + cmd!( + "camera.dolly", + "Dolly Camera", + [], + None, + "{amount (px, + = forward), mode?: towardsCursor|toCursor|toCameraPoi (alias toCameraTarget; default: along the view axis), cursor? [x,y], point? [x,y,z], layer?, merge?} — returns `pivot` (null: the point of interest or, without mode, the view axis)", + has_comp, + dolly + ), query!("view.get3D", "3D View State", "{comp?} → current 3D view, view camera, active camera layer, lights", get_3d), ] } diff --git a/crates/engine/src/tests/three_d.rs b/crates/engine/src/tests/three_d.rs index 5b5af594d..67d6ee6b6 100644 --- a/crates/engine/src/tests/three_d.rs +++ b/crates/engine/src/tests/three_d.rs @@ -325,6 +325,263 @@ fn camera_tools_edit_active_camera_with_undo() { assert!(o[1].abs() > 1.0, "{o:?}"); } +/// Returns the Euclidean distance between two 3D points. +fn dist3(a: [f64; 3], b: [f64; 3]) -> f64 { + ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt() +} + +/// Reads a JSON array of three numbers as a point; panics on anything else. +fn arr3(v: &serde_json::Value) -> [f64; 3] { + let a = v.as_array().unwrap_or_else(|| panic!("not a point: {v}")); + [a[0].as_f64().unwrap(), a[1].as_f64().unwrap(), a[2].as_f64().unwrap()] +} + +/// Orbit Around Scene (#2586) turns a 3D view about the centre of the comp's 3D layers, not +/// about the view's point of interest. +#[test] +fn orbit_around_scene_turns_the_view_about_the_layers_centre() { + let mut s = session(); + let cid = s.active_comp_id().unwrap(); + let id = s.execute("layer.newSolid", json!({"width": 100, "height": 100})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setSwitch", json!({"layer": id, "switch": "threeD", "value": true})).unwrap(); + s.execute("prop.set", json!({"layer": id, "path": "transform/position", "value": [500, 100, 300]})).unwrap(); + s.execute("view.3d.custom1", json!({})).unwrap(); + let cam0 = s.state.views3d[&cid].cam(View3D::Custom1, 640.0, 360.0); + let r = s.execute("camera.orbit", json!({"yaw": 25, "mode": "aroundScene"})).unwrap(); + let pivot = arr3(&r["pivot"]); + assert!(dist3(pivot, [500.0, 100.0, 300.0]) < 1e-6, "{pivot:?}"); + let cam1 = s.state.views3d[&cid].cam(View3D::Custom1, 640.0, 360.0); + assert!(dist3(cam1.poi, cam0.poi) > 1.0, "the point of interest goes round the scene too"); + assert!((dist3(cam1.eye, pivot) - dist3(cam0.eye, pivot)).abs() < 1e-6); + // Around Camera POI (the default; the old mode name still works) keeps the point of interest. + s.execute("camera.orbit", json!({"yaw": 25, "mode": "aroundCameraTarget"})).unwrap(); + assert!(dist3(s.state.views3d[&cid].cam(View3D::Custom1, 640.0, 360.0).poi, cam1.poi) < 1e-9); + assert!(s.execute("camera.orbit", json!({"yaw": 5, "mode": "sideways"})).is_err()); + assert!(s.execute("camera.pan", json!({"dx": 5, "mode": "aroundScene"})).is_err(), "Pan has no scene variant"); +} + +/// The cursor variants on a camera layer pick the point under the cursor on a 3D layer; +/// Dolly to Cursor and Dolly to Camera POI stop short of their point (#2586). +#[test] +fn cursor_and_target_camera_tools_on_a_camera_layer() { + let mut s = session(); + let id = s.execute("layer.newSolid", json!({"width": 640, "height": 360})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setSwitch", json!({"layer": id, "switch": "threeD", "value": true})).unwrap(); + let cam = s.execute("layer.newCamera", json!({})).unwrap()["layer"].as_u64().unwrap(); + let poi0 = prop(&s, cam, "transform/poi").as_vec3(); + // The cursor off centre picks a point on the solid (z = 0), not the point of interest. + let r = s.execute("camera.pan", json!({"dx": 0, "dy": 0, "mode": "underCursor", "cursor": [100, 60]})).unwrap(); + let pivot = arr3(&r["pivot"]); + assert!(pivot[2].abs() < 1e-6, "{pivot:?}"); + assert!(dist3(pivot, poi0) > 50.0, "{pivot:?}"); + // Dolly to Cursor: a long dolly ends just short of the point, with the aim kept. + let aim0 = { + let (p, q) = (prop(&s, cam, "transform/position").as_vec3(), prop(&s, cam, "transform/poi").as_vec3()); + [q[0] - p[0], q[1] - p[1], q[2] - p[2]] + }; + s.execute("camera.dolly", json!({"amount": 1.0e7, "mode": "toCursor", "point": pivot})).unwrap(); + let (p1, q1) = (prop(&s, cam, "transform/position").as_vec3(), prop(&s, cam, "transform/poi").as_vec3()); + assert!((dist3(p1, pivot) - 1.0).abs() < 1e-6, "{p1:?}"); + assert!(dist3([q1[0] - p1[0], q1[1] - p1[1], q1[2] - p1[2]], aim0) < 1e-6); + s.undo(); + // Dolly to Camera POI: the point of interest stays and the camera stops 1 px from it. + s.execute("camera.dolly", json!({"amount": 1.0e7, "mode": "toCameraTarget"})).unwrap(); + assert_eq!(prop(&s, cam, "transform/poi").as_vec3(), poi0); + assert!((dist3(prop(&s, cam, "transform/position").as_vec3(), poi0) - 1.0).abs() < 1e-6); + s.undo(); + // Orbit Around Cursor keeps both distances to the picked point. + let p0 = prop(&s, cam, "transform/position").as_vec3(); + s.execute("camera.orbit", json!({"yaw": 20, "pitch": -5, "mode": "aroundCursor", "point": pivot})).unwrap(); + let p2 = prop(&s, cam, "transform/position").as_vec3(); + assert!((dist3(p2, pivot) - dist3(p0, pivot)).abs() < 1e-6); + assert!(dist3(prop(&s, cam, "transform/poi").as_vec3(), poi0) > 1.0); +} + +/// A camera parented to a moved and turned null: the tools pick their point in world space and +/// move the camera about it, converting into the camera's parent space (#2586). +#[test] +fn camera_tools_on_a_parented_camera_use_the_world_point() { + let mut s = session(); + let id = s.execute("layer.newSolid", json!({"width": 100, "height": 100})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setSwitch", json!({"layer": id, "switch": "threeD", "value": true})).unwrap(); + s.execute("prop.set", json!({"layer": id, "path": "transform/position", "value": [400, 120, 200]})).unwrap(); + let parent = s.execute("layer.newNull", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setSwitch", json!({"layer": parent, "switch": "threeD", "value": true})).unwrap(); + s.execute("prop.set", json!({"layer": parent, "path": "transform/position", "value": [150, -60, 250]})).unwrap(); + s.execute("prop.set", json!({"layer": parent, "path": "transform/rotationY", "value": 30})).unwrap(); + s.execute("prop.set", json!({"layer": parent, "path": "transform/rotationX", "value": 15})).unwrap(); + let cam = s.execute("layer.newCamera", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setParent", json!({"layers": [cam], "parent": parent})).unwrap(); + let world_eye = |s: &mut Session| arr3(&s.execute("view.get3D", json!({})).unwrap()["camera"]["eye"]); + let e0 = world_eye(&mut s); + let r = s.execute("camera.orbit", json!({"yaw": 25, "pitch": -10, "mode": "aroundScene"})).unwrap(); + let pivot = arr3(&r["pivot"]); + assert!(dist3(pivot, [400.0, 120.0, 200.0]) < 1e-6, "the scene centre is a world point: {pivot:?}"); + let e1 = world_eye(&mut s); + assert!(dist3(e1, e0) > 10.0); + assert!((dist3(e1, pivot) - dist3(e0, pivot)).abs() < 1e-6, "{e0:?} → {e1:?} about {pivot:?}"); + s.undo(); + s.execute("camera.dolly", json!({"amount": 1.0e7, "mode": "toCursor", "point": pivot})).unwrap(); + assert!((dist3(world_eye(&mut s), pivot) - 1.0).abs() < 1e-6); +} + +/// The comp's active camera as rendered (world space). +fn active_cam(s: &Session) -> effectcraft_render::three_d::CameraState { + let cid = s.active_comp_id().unwrap(); + let comp = s.project.comp(cid).unwrap(); + let ctx = effectcraft_render::EvalCtx { + project: &s.project, + comp_id: cid, + comp, + time: s.time(), + expr: s.expr.as_deref(), + footage: None, + property_overrides: &[], + media_overrides: &[], + reads: None, + }; + effectcraft_render::three_d::camera::active_camera(&ctx) +} + +fn solid3d(s: &mut Session, w: u32, h: u32, pos: [f64; 3]) -> u64 { + let id = s.execute("layer.newSolid", json!({"width": w, "height": h})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setSwitch", json!({"layer": id, "switch": "threeD", "value": true})).unwrap(); + s.execute("prop.set", json!({"layer": id, "path": "transform/position", "value": pos})).unwrap(); + id +} + +/// Pan Under Cursor on a camera layer: the grabbed point, nearer than the point of interest, +/// follows the drag exactly (#2586). +#[test] +fn pan_under_cursor_moves_the_grabbed_point_by_the_drag() { + let mut s = session(); + solid3d(&mut s, 640, 360, [320.0, 180.0, -300.0]); + s.execute("layer.newCamera", json!({})).unwrap(); + let r = s.execute("camera.pan", json!({"dx": 0, "dy": 0, "mode": "underCursor", "cursor": [200, 100]})).unwrap(); + let pivot = arr3(&r["pivot"]); + assert!((pivot[2] + 300.0).abs() < 1e-6, "on the nearer solid: {pivot:?}"); + let at = effectcraft_geom::Vec3::from(pivot); + let before = active_cam(&s).project(640.0, 360.0, at).unwrap(); + s.execute("camera.pan", json!({"dx": 30, "dy": -12, "mode": "underCursor", "point": pivot})).unwrap(); + let after = active_cam(&s).project(640.0, 360.0, at).unwrap(); + assert!((after.x - before.x - 30.0).abs() < 1e-6 && (after.y - before.y + 12.0).abs() < 1e-6, "{before:?} → {after:?}"); +} + +/// The point under the cursor is on a visible 3D layer: guides, layers with Video off, nulls, +/// cameras and lights in front of it are not picked (#2586). +#[test] +fn the_point_under_the_cursor_skips_hidden_and_guide_layers() { + let mut s = session(); + solid3d(&mut s, 640, 360, [320.0, 180.0, 0.0]); + let guide = solid3d(&mut s, 640, 360, [320.0, 180.0, -200.0]); + s.execute("layer.setSwitch", json!({"layer": guide, "switch": "guide", "value": true})).unwrap(); + let hidden = solid3d(&mut s, 640, 360, [320.0, 180.0, -300.0]); + s.execute("layer.setSwitch", json!({"layer": hidden, "switch": "video", "value": false})).unwrap(); + let nul = s.execute("layer.newNull", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setSwitch", json!({"layer": nul, "switch": "threeD", "value": true})).unwrap(); + s.execute("prop.set", json!({"layer": nul, "path": "transform/position", "value": [320, 180, -400]})).unwrap(); + s.execute("layer.newCamera", json!({})).unwrap(); + let r = s.execute("camera.orbit", json!({"yaw": 0, "mode": "aroundCursor", "cursor": [300, 170]})).unwrap(); + let pivot = arr3(&r["pivot"]); + assert!(pivot[2].abs() < 1e-6, "the visible solid at z = 0: {pivot:?}"); + // The scene's centre counts only that solid too. + let r = s.execute("camera.orbit", json!({"yaw": 0, "mode": "aroundScene"})).unwrap(); + assert!(dist3(arr3(&r["pivot"]), [320.0, 180.0, 0.0]) < 1e-6, "{}", r["pivot"]); +} + +/// With a layer soloed, a nearer non-solo plane is not drawn and so not picked: the cursor modes +/// take the soloed plane's depth, and Orbit Around Scene's centre ignores the hidden plane (#2586). +#[test] +fn the_camera_tool_pivot_respects_solo() { + let mut s = session(); + let far = solid3d(&mut s, 640, 360, [320.0, 180.0, 0.0]); + let near = solid3d(&mut s, 200, 200, [320.0, 180.0, -300.0]); + s.execute("layer.newCamera", json!({})).unwrap(); + // Nothing soloed: the nearer plane under the cursor is picked. + let r = s.execute("camera.orbit", json!({"yaw": 0, "mode": "aroundCursor", "cursor": [320, 180]})).unwrap(); + assert!((arr3(&r["pivot"])[2] + 300.0).abs() < 1e-6, "{}", r["pivot"]); + s.execute("layer.setSwitch", json!({"layer": far, "switch": "solo", "value": true})).unwrap(); + assert_ne!(far, near); + for (cmd, mode) in [("camera.orbit", "aroundCursor"), ("camera.pan", "underCursor"), ("camera.dolly", "towardsCursor")] { + let r = s.execute(cmd, json!({"yaw": 0, "dx": 0, "dy": 0, "amount": 0, "mode": mode, "cursor": [320, 180]})).unwrap(); + let pivot = arr3(&r["pivot"]); + assert!(pivot[2].abs() < 1e-6, "{cmd}: the soloed plane's depth, not the hidden one's: {pivot:?}"); + } + // The scene centre is the soloed plane's, not the middle of both. + let r = s.execute("camera.orbit", json!({"yaw": 0, "mode": "aroundScene"})).unwrap(); + assert!(dist3(arr3(&r["pivot"]), [320.0, 180.0, 0.0]) < 1e-6, "{}", r["pivot"]); +} + +/// Orbit Around Scene without 3D layers turns about the comp's centre (#2586). +#[test] +fn orbit_around_scene_without_3d_layers_uses_the_comp_centre() { + let mut s = session(); + s.execute("layer.newSolid", json!({"width": 100, "height": 100})).unwrap(); + s.execute("layer.newCamera", json!({})).unwrap(); + let r = s.execute("camera.orbit", json!({"yaw": 10, "mode": "aroundScene"})).unwrap(); + assert!(dist3(arr3(&r["pivot"]), [320.0, 180.0, 0.0]) < 1e-9, "{}", r["pivot"]); +} + +/// A camera whose parent cannot be inverted (scale 0) works about its point of interest, stays +/// finite, and reports that point as the one used (#2586). +#[test] +fn a_parent_that_cannot_be_inverted_falls_back_to_the_point_of_interest() { + let mut s = session(); + solid3d(&mut s, 100, 100, [400.0, 120.0, 200.0]); + let parent = s.execute("layer.newNull", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setSwitch", json!({"layer": parent, "switch": "threeD", "value": true})).unwrap(); + let cam = s.execute("layer.newCamera", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setParent", json!({"layers": [cam], "parent": parent, "compensate": false})).unwrap(); + s.execute("prop.set", json!({"layer": parent, "path": "transform/scale", "value": [0, 0, 0]})).unwrap(); + let poi0 = prop(&s, cam, "transform/poi").as_vec3(); + // Through a scale-0 parent every point of the camera lands on the parent's position. + let world_poi = prop(&s, parent, "transform/position").as_vec3(); + let r = s.execute("camera.orbit", json!({"yaw": 20, "pitch": -5, "mode": "aroundScene"})).unwrap(); + let pivot = arr3(&r["pivot"]); + assert!(dist3(pivot, world_poi) < 1e-9, "the point of interest, not the scene's centre: {pivot:?}"); + assert_eq!(prop(&s, cam, "transform/poi").as_vec3(), poi0, "Orbit Around Camera POI keeps the point of interest"); + let pos = prop(&s, cam, "transform/position").as_vec3(); + assert!(pos.iter().all(|v| v.is_finite()), "{pos:?}"); + // Sent back as `point`, it falls back the same way. + let r2 = s.execute("camera.orbit", json!({"yaw": 5, "mode": "aroundScene", "point": pivot})).unwrap(); + assert!(dist3(arr3(&r2["pivot"]), pivot) < 1e-9); +} + +/// A one-node camera under a scale-0 parent: Pan Under Cursor and Dolly to Cursor work as their +/// Camera POI variants, and report the rig's point of interest through the parent, which is +/// where the parent puts every point (#2586). +#[test] +fn a_one_node_camera_under_a_scale_0_parent_pans_and_dollies_about_its_poi() { + let setup = || { + let mut s = session(); + solid3d(&mut s, 100, 100, [400.0, 120.0, 200.0]); + let parent = s.execute("layer.newNull", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setSwitch", json!({"layer": parent, "switch": "threeD", "value": true})).unwrap(); + s.execute("prop.set", json!({"layer": parent, "path": "transform/position", "value": [100, 50, 30]})).unwrap(); + let cam = s.execute("layer.newCamera", json!({"type": "oneNode"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setParent", json!({"layers": [cam], "parent": parent, "compensate": false})).unwrap(); + s.execute("prop.set", json!({"layer": parent, "path": "transform/scale", "value": [0, 0, 0]})).unwrap(); + (s, cam) + }; + for (cmd, params, poi_mode) in [ + ("camera.pan", json!({"dx": 30, "dy": -12, "mode": "underCursor", "cursor": [200, 100]}), "cameraPoi"), + ("camera.dolly", json!({"amount": 80, "mode": "toCursor", "cursor": [200, 100]}), "toCameraPoi"), + ] { + let (mut s, cam) = setup(); + let r = s.execute(cmd, params.clone()).unwrap(); + let pivot = arr3(&r["pivot"]); + assert!(dist3(pivot, [100.0, 50.0, 30.0]) < 1e-9, "{cmd}: {pivot:?}"); + let moved = (prop(&s, cam, "transform/position").as_vec3(), prop(&s, cam, "transform/orientation").as_vec3()); + assert!(moved.0.iter().chain(moved.1.iter()).all(|v| v.is_finite()), "{cmd}: {moved:?}"); + let (mut t, cam_t) = setup(); + let mut poi_params = params; + poi_params["mode"] = json!(poi_mode); + t.execute(cmd, poi_params).unwrap(); + let want = (prop(&t, cam_t, "transform/position").as_vec3(), prop(&t, cam_t, "transform/orientation").as_vec3()); + assert!(dist3(moved.0, want.0) < 1e-9 && dist3(moved.1, want.1) < 1e-9, "{cmd}: {moved:?} vs {want:?}"); + } +} + #[test] fn demo_has_3d_showcase() { let mut s = Session::default(); diff --git a/crates/render/src/three_d/camera.rs b/crates/render/src/three_d/camera.rs index 18f6dfe8a..fae868ccd 100644 --- a/crates/render/src/three_d/camera.rs +++ b/crates/render/src/three_d/camera.rs @@ -603,11 +603,20 @@ impl Rig { pub fn from_view(v: &ViewCam) -> Rig { Rig { eye: Vec3::from(v.eye), poi: Vec3::from(v.poi), zoom: v.zoom, ortho: v.ortho } } + /// The camera this rig looks through (screen-down hint world Y, as the tools use). + pub fn state(&self) -> CameraState { + CameraState { view: basis_view(self.eye, self.poi - self.eye, vec3(0.0, 1.0, 0.0)), eye: self.eye, zoom: self.zoom, ortho: self.ortho, dof: None } + } + /// Returns the camera's forward, right and down unit vectors. fn frame(&self) -> (Vec3, Vec3, Vec3) { - let s = - CameraState { view: basis_view(self.eye, self.poi - self.eye, vec3(0.0, 1.0, 0.0)), eye: self.eye, zoom: self.zoom, ortho: self.ortho, dof: None }; + let s = self.state(); (s.forward(), s.right(), s.down()) } + /// Every coordinate and the zoom are finite numbers (a tool step that would leave NaN or + /// infinity behind is dropped instead of written into the camera). + pub fn is_finite(&self) -> bool { + [self.eye, self.poi].iter().all(|v| v.x.is_finite() && v.y.is_finite() && v.z.is_finite()) && self.zoom.is_finite() + } /// Orbit the eye around the point of interest: `yaw` about world Y, `pitch` about the /// camera's right axis (degrees). Pitch is limited short of straight up/down. pub fn orbit(&mut self, yaw: f64, pitch: f64) { @@ -647,8 +656,138 @@ impl Rig { self.poi += f * amount; } else { let dist = (self.poi - self.eye).length(); - let d = amount.min(dist - 1.0); + let d = amount.min((dist - 1.0).max(0.0)); self.eye += f * d; } } + /// Orbit Around Cursor / Orbit Around Scene: turn the whole camera (eye and point of + /// interest together) about `pivot`: `yaw` about world Y, `pitch` about the camera's + /// horizontal right axis (degrees, same senses as [`Rig::orbit`]). The pivot keeps its place + /// on screen and both distances to it; the view is limited short of straight up/down. + pub fn orbit_about(&mut self, pivot: Vec3, yaw: f64, pitch: f64) { + if self.ortho || !(pivot.x.is_finite() && pivot.y.is_finite() && pivot.z.is_finite()) { + return; + } + let off = self.eye - self.poi; + let dist = off.length(); + if !(dist.is_finite() && dist > 1e-9) { + return; + } + let cur = (off.y / dist).clamp(-1.0, 1.0).asin().to_degrees(); + let pitch = (cur + pitch).clamp(-89.0, 89.0) - cur; + let up = vec3(0.0, 1.0, 0.0); + let horiz = vec3(off.x, 0.0, off.z); + // Rotating about (horizontal offset × up) raises the eye's offset, as `orbit` does. + let axis = if horiz.length() > 1e-9 { horiz.normalize().cross(up).normalize() } else { self.frame().1 }; + let turn = |v: Vec3| rotate_about(rotate_about(v, axis, pitch), up, -yaw); + self.eye = pivot + turn(self.eye - pivot); + self.poi = pivot + turn(self.poi - pivot); + } + /// Pan Under Cursor: move the camera in its image plane so the world point `at` (the point + /// under the cursor) follows the drag of (`dx`, `dy`) comp pixels. Falls back to [`Rig::pan`] + /// (the point of interest's depth) when `at` is not in front of the camera. + pub fn pan_at(&mut self, dx: f64, dy: f64, at: Vec3) { + let (f, r, d) = self.frame(); + let depth = (at - self.eye).dot(f); + if self.ortho || !(depth.is_finite() && depth > 1e-6) { + self.pan(dx, dy); + return; + } + let k = depth / self.zoom.max(1e-9); + let delta = r * (-dx * k) + d * (-dy * k); + self.eye += delta; + self.poi += delta; + } + /// Dolly Towards Cursor (`stop_short` false) / Dolly to Cursor (`stop_short` true): move the + /// camera (eye and point of interest together, so its aim is kept) by `amount` pixels along + /// the line from the eye through `target`, the point under the cursor, which therefore keeps + /// its place on screen. Dolly to Cursor stops 1 px short of the target instead of passing it. + /// Orthographic views scale, as [`Rig::dolly`]. + pub fn dolly_towards(&mut self, amount: f64, target: Vec3, stop_short: bool) { + if self.ortho { + self.dolly(amount, false); + return; + } + let to = target - self.eye; + let dist = to.length(); + if !(dist.is_finite() && dist > 1e-9) { + // The eye sits on the target: nothing to approach (Towards Cursor goes straight on). + if !stop_short { + self.dolly(amount, true); + } + return; + } + // Once Dolly Towards Cursor has passed the point, the line through it still runs the same + // way: keep moving along the view, never back towards the point. + let dir = to / dist; + let dir = if !stop_short && dir.dot(self.frame().0) < 0.0 { -dir } else { dir }; + let d = if stop_short { amount.min((dist - 1.0).max(0.0)) } else { amount }; + self.eye += dir * d; + self.poi += dir * d; + } +} + +/// `v` turned by `deg` degrees about the unit `axis` (right-handed, Rodrigues). +fn rotate_about(v: Vec3, axis: Vec3, deg: f64) -> Vec3 { + let (s, c) = deg.to_radians().sin_cos(); + v * c + axis.cross(v) * s + axis * (axis.dot(v) * (1.0 - c)) +} + +/// The ray through comp pixel `px` of a `w`×`h` comp seen by `cam`: origin and direction. The +/// direction's component along the view axis is 1, so `origin + dir * z` is the ray's point at +/// view depth `z` (perspective and orthographic alike). +pub fn pixel_ray(cam: &CameraState, w: f64, h: f64, px: [f64; 2]) -> (Vec3, Vec3) { + let zoom = if cam.zoom.is_finite() && cam.zoom.abs() > 1e-9 { cam.zoom } else { 1e-9 }; + let (x, y) = ((px[0] - w * 0.5) / zoom, (px[1] - h * 0.5) / zoom); + let (f, r, d) = (cam.forward(), cam.right(), cam.down()); + if cam.ortho { (cam.eye + r * x + d * y, f) } else { (cam.eye, r * x + d * y + f) } +} + +/// The world point under comp pixel `px`: the nearest place the ray hits one of `quads` (planar +/// layer rectangles, four corners in order), else the ray's point at the view depth of +/// `fallback` (the point of interest), else `fallback` itself. +pub fn point_under(cam: &CameraState, w: f64, h: f64, px: [f64; 2], quads: &[[Vec3; 4]], fallback: Vec3) -> Vec3 { + let (o, dir) = pixel_ray(cam, w, h, px); + let finite = |v: Vec3| v.x.is_finite() && v.y.is_finite() && v.z.is_finite(); + let mut best: Option = None; + for q in quads { + let n = (q[1] - q[0]).cross(q[3] - q[0]); + let den = n.dot(dir); + if !(den.is_finite() && den.abs() > 1e-12) { + continue; + } + let t = n.dot(q[0] - o) / den; + if !(t.is_finite() && t > 1e-6) || best.is_some_and(|b| b <= t) { + continue; + } + // (a perspective camera sees nothing nearer than its near plane: such a layer is not under + // the cursor; `t` is the view depth, as the direction's part along the view is 1) + if !cam.ortho && t < NEAR { + continue; + } + let hit = o + dir * t; + let side = |i: usize| { + let (a, b) = (q[i % 4], q[(i + 1) % 4]); + (b - a).cross(hit - a).dot(n) + }; + let s = [side(0), side(1), side(2), side(3)]; + if s.iter().all(|v| *v >= -1e-9) || s.iter().all(|v| *v <= 1e-9) { + best = Some(t); + } + } + let at_depth = || { + let z = (fallback - o).dot(cam.forward()); + (z.is_finite() && z > 1e-6).then(|| o + dir * z) + }; + best.map(|t| o + dir * t).or_else(at_depth).filter(|p| finite(*p)).unwrap_or(fallback) +} + +/// The centre of the box around `points` (Orbit Around Scene's pivot); None without points. +pub fn bounds_center(points: &[Vec3]) -> Option { + let first = *points.first()?; + let (lo, hi) = points + .iter() + .fold((first, first), |(lo, hi), q| (vec3(lo.x.min(q.x), lo.y.min(q.y), lo.z.min(q.z)), vec3(hi.x.max(q.x), hi.y.max(q.y), hi.z.max(q.z)))); + let c = (lo + hi) * 0.5; + (c.x.is_finite() && c.y.is_finite() && c.z.is_finite()).then_some(c) } diff --git a/crates/render/src/three_d/tests.rs b/crates/render/src/three_d/tests.rs index 699f7d79d..ea8044cc9 100644 --- a/crates/render/src/three_d/tests.rs +++ b/crates/render/src/three_d/tests.rs @@ -765,3 +765,198 @@ fn rig_orbit_keeps_distance_and_pan_moves_both() { let off = r.eye - r.poi; assert!(off.y.abs() / off.length() < 0.9999); } + +// ---- the eight camera tools (#2586): pivots of the Cursor / Scene / Camera POI variants + +const CW: f64 = 1920.0; +const CH: f64 = 1080.0; + +/// Returns the rig of the default Custom View 1 camera in a comp of size `CW` by `CH`. +fn custom_rig() -> Rig { + Rig::from_view(&default_view_cam(View3D::Custom1, CW, CH)) +} + +/// Projects the world point `p` through the rig's camera to comp pixels; panics when the point is behind the camera. +fn screen(r: &Rig, p: Vec3) -> effectcraft_geom::Vec2 { + r.state().project(CW, CH, p).expect("in front of the camera") +} + +/// Checks that orbiting about the point of interest equals the plain orbit step. +#[test] +fn orbit_around_camera_poi_is_orbit_about_the_poi() { + let (mut a, mut b) = (custom_rig(), custom_rig()); + a.orbit(25.0, -10.0); + b.orbit_about(b.poi, 25.0, -10.0); + assert!((a.eye - b.eye).length() < 1e-6, "{:?} vs {:?}", a.eye, b.eye); + assert!((a.poi - b.poi).length() < 1e-9); +} + +/// Checks that orbiting about a pivot keeps the pivot's distance and screen position while the point of interest turns too, and that a NaN pivot is ignored. +#[test] +fn orbit_around_a_pivot_keeps_it_on_screen_and_turns_the_whole_camera() { + let mut r = custom_rig(); + // A pivot well off the point of interest (the cursor over a layer, or the scene's centre). + let pivot = r.poi + vec3(300.0, -120.0, 400.0); + let (s0, de, dp, poi0) = (screen(&r, pivot), (r.eye - pivot).length(), (r.poi - pivot).length(), r.poi); + r.orbit_about(pivot, 30.0, -12.0); + let s1 = screen(&r, pivot); + assert!((s1.x - s0.x).abs() < 1e-6 && (s1.y - s0.y).abs() < 1e-6, "{s0:?} → {s1:?}"); + assert!(((r.eye - pivot).length() - de).abs() < 1e-6); + assert!(((r.poi - pivot).length() - dp).abs() < 1e-6); + // Unlike Orbit Around Camera POI, the point of interest goes round too. + assert!((r.poi - poi0).length() > 10.0); + // Pitch stops short of the poles; a pivot that is not a number leaves the camera alone. + r.orbit_about(pivot, 0.0, 500.0); + let off = r.eye - r.poi; + assert!(off.y.abs() / off.length() < 0.9999); + let before = r; + r.orbit_about(vec3(f64::NAN, 0.0, 0.0), 10.0, 10.0); + assert_eq!(r, before); +} + +/// Checks that Pan Under Cursor moves a point by exactly the drag, unlike Pan Camera POI, and falls back to the POI depth behind the camera. +#[test] +fn pan_under_cursor_keeps_the_grabbed_point_under_the_pointer() { + // A point nearer than the point of interest: Pan Camera POI moves it by less + // than the drag, Pan Under Cursor by exactly the drag. + let r0 = custom_rig(); + let at = r0.eye + (r0.poi - r0.eye) * 0.3 + vec3(40.0, 25.0, 0.0); + let s0 = screen(&r0, at); + let mut r = r0; + r.pan_at(30.0, -12.0, at); + let s1 = screen(&r, at); + assert!((s1.x - s0.x - 30.0).abs() < 1e-6 && (s1.y - s0.y + 12.0).abs() < 1e-6, "{s0:?} → {s1:?}"); + assert!(((r.eye - r.poi) - (r0.eye - r0.poi)).length() < 1e-9, "the aim is kept"); + let mut target = r0; + target.pan(30.0, -12.0); + let st = screen(&target, at); + assert!((st.x - s0.x - 30.0).abs() > 1.0, "Pan Camera POI scales by the POI depth"); + // A point behind the camera falls back to the point of interest's depth. + let mut back = r0; + back.pan_at(30.0, -12.0, r0.eye - (r0.poi - r0.eye)); + assert!((back.eye - target.eye).length() < 1e-9); +} + +/// Checks that both cursor dollies keep the point under the cursor fixed and that Dolly to Cursor stops short of it. +#[test] +fn dolly_towards_and_to_cursor_move_along_the_cursor_ray() { + let r0 = custom_rig(); + let target = r0.poi + vec3(-200.0, 90.0, 150.0); + let (s0, d0) = (screen(&r0, target), (r0.eye - target).length()); + let mut r = r0; + r.dolly_towards(150.0, target, false); + let s1 = screen(&r, target); + assert!((s1.x - s0.x).abs() < 1e-6 && (s1.y - s0.y).abs() < 1e-6, "the point under the cursor stays put"); + assert!(((r.eye - target).length() - (d0 - 150.0)).abs() < 1e-6); + assert!(((r.eye - r.poi) - (r0.eye - r0.poi)).length() < 1e-9, "the aim is kept"); + // Dolly Towards Cursor goes on past the point; Dolly to Cursor stops just short of it. + let mut past = r0; + past.dolly_towards(d0 + 500.0, target, false); + assert!(((past.eye - target).length() - 500.0).abs() < 1e-6); + let mut to = r0; + to.dolly_towards(d0 + 500.0, target, true); + assert!(((to.eye - target).length() - 1.0).abs() < 1e-6); + to.dolly_towards(50.0, target, true); + assert!(((to.eye - target).length() - 1.0).abs() < 1e-6, "no further"); + // Backwards is not limited. + to.dolly_towards(-100.0, target, true); + assert!(((to.eye - target).length() - 101.0).abs() < 1e-6); +} + +/// A Dolly Towards Cursor drag is many small steps towards one point: past the point it keeps +/// going forward instead of turning back towards it. +#[test] +fn dolly_towards_cursor_keeps_going_past_the_point() { + let r0 = custom_rig(); + let target = r0.poi + vec3(-200.0, 90.0, 150.0); + let f = (r0.poi - r0.eye).normalize(); + let d0 = (r0.eye - target).length(); + let mut r = r0; + let mut last = r.eye.dot(f); + let steps = (d0 / 50.0) as usize + 40; + for _ in 0..steps { + r.dolly_towards(50.0, target, false); + let now = r.eye.dot(f); + assert!(now > last + 1.0, "the drag turned back at {:?}", r.eye); + last = now; + } + assert!((r.eye - target).length() > 1000.0, "well past the point"); +} + +/// Checks that Dolly to Camera POI leaves the camera in place when it is already within a pixel of the point. +#[test] +fn dolly_to_camera_poi_never_backs_off_when_closer_than_a_pixel() { + let mut r = custom_rig(); + let f = (r.poi - r.eye).normalize(); + r.eye = r.poi - f * 0.5; + let eye = r.eye; + r.dolly(10.0, false); + assert!((r.eye - eye).length() < 1e-12, "{:?}", r.eye); +} + +/// Checks that every camera tool keeps the rig finite for degenerate cameras, pivots and targets. +#[test] +fn camera_tools_never_produce_nan_cameras() { + let nan_free = |r: &Rig| assert!(r.is_finite(), "{r:?}"); + // Eye on the point of interest, zero zoom, and pivots / targets on the eye. + let mut r = Rig { eye: vec3(10.0, 20.0, 30.0), poi: vec3(10.0, 20.0, 30.0), zoom: 0.0, ortho: false }; + r.orbit(10.0, 10.0); + nan_free(&r); + r.orbit_about(r.eye, 10.0, 10.0); + nan_free(&r); + r.pan_at(5.0, 5.0, r.eye); + nan_free(&r); + r.dolly_towards(10.0, r.eye, false); + nan_free(&r); + r.dolly_towards(10.0, r.eye, true); + nan_free(&r); + r.dolly(10.0, false); + nan_free(&r); + // Looking straight down: orbiting about a pivot still has an axis to pitch about. + let mut down = Rig { eye: vec3(0.0, -500.0, 0.0), poi: Vec3::ZERO, zoom: 800.0, ortho: false }; + down.orbit_about(vec3(50.0, 0.0, 50.0), 20.0, -30.0); + nan_free(&down); + let cam = down.state(); + nan_free(&Rig { eye: super::camera::point_under(&cam, CW, CH, [10.0, 10.0], &[], down.poi), ..down }); +} + +/// #3259 review: a layer between the eye and the near plane is not on screen, so it is not under +/// the cursor; the layer behind it is. An orthographic camera has no such cut. +#[test] +fn a_layer_nearer_than_the_near_plane_is_not_under_the_cursor() { + let r = Rig::from_view(&default_view_cam(View3D::Default, CW, CH)); + let cam = r.state(); + let quad = [vec3(0.0, 0.0, 0.0), vec3(CW, 0.0, 0.0), vec3(CW, CH, 0.0), vec3(0.0, CH, 0.0)]; + // A big plane 0.5 in front of the eye (the near plane is 1). + let (f, rt, dn) = (cam.forward(), cam.right(), cam.down()); + let c = cam.eye + f * 0.5; + let inside = [c - rt * 1e5 - dn * 1e5, c + rt * 1e5 - dn * 1e5, c + rt * 1e5 + dn * 1e5, c - rt * 1e5 + dn * 1e5]; + let p = super::camera::point_under(&cam, CW, CH, [960.0, 540.0], &[quad, inside], r.poi); + assert!(cam.depth(p) > 1.0 && (p - vec3(960.0, 540.0, 0.0)).length() < 1e-6, "the layer behind it is picked: {p:?}"); +} + +/// Checks that the point under the cursor lies on the nearest layer it hits, else at the POI depth. +#[test] +fn the_point_under_the_cursor_is_on_the_layer_it_hits() { + let r = Rig::from_view(&default_view_cam(View3D::Default, CW, CH)); + let cam = r.state(); + // A comp-sized layer at z = 0 maps 1:1 to the default camera's pixels. + let quad = [vec3(0.0, 0.0, 0.0), vec3(CW, 0.0, 0.0), vec3(CW, CH, 0.0), vec3(0.0, CH, 0.0)]; + let p = super::camera::point_under(&cam, CW, CH, [100.0, 200.0], &[quad], r.poi); + assert!((p - vec3(100.0, 200.0, 0.0)).length() < 1e-6, "{p:?}"); + // The nearer of two layers wins. + let near: [Vec3; 4] = quad.map(|c| c + vec3(0.0, 0.0, -300.0)); + let p = super::camera::point_under(&cam, CW, CH, [960.0, 540.0], &[quad, near], r.poi); + assert!((p.z + 300.0).abs() < 1e-6, "{p:?}"); + // Off every layer: the cursor's point at the depth of the point of interest. + let small = [vec3(0.0, 0.0, 0.0), vec3(10.0, 0.0, 0.0), vec3(10.0, 10.0, 0.0), vec3(0.0, 10.0, 0.0)]; + let off = r.poi + vec3(0.0, 0.0, 200.0); + let p = super::camera::point_under(&cam, CW, CH, [1500.0, 700.0], &[small], off); + assert!((cam.depth(p) - cam.depth(off)).abs() < 1e-6); + let s = cam.project(CW, CH, p).unwrap(); + assert!((s.x - 1500.0).abs() < 1e-6 && (s.y - 700.0).abs() < 1e-6, "{s:?}"); + // The scene's centre is the middle of the box around the points. + let c = super::camera::bounds_center(&[vec3(0.0, 0.0, 0.0), vec3(100.0, 50.0, -40.0), vec3(20.0, 10.0, 60.0)]).unwrap(); + assert!((c - vec3(50.0, 25.0, 10.0)).length() < 1e-12); + assert!(super::camera::bounds_center(&[]).is_none()); +} diff --git a/crates/ui-egui/src/header.rs b/crates/ui-egui/src/header.rs index 140a0bbaf..205c6b114 100644 --- a/crates/ui-egui/src/header.rs +++ b/crates/ui-egui/src/header.rs @@ -975,6 +975,50 @@ mod tests { assert!(!app.auto.elements.iter().any(|w| w.id == "tools.select.TypeVertical")); } + /// The Orbit, Pan and Dolly slots carry After Effects' variants of each camera tool, each + /// picked from the slot's flyout by its automation id (#2586). + #[test] + fn every_camera_tool_is_picked_from_its_flyout() { + let mut app = EffectcraftApp::new(effectcraft_engine::Session::default()); + let ctx = egui::Context::default(); + crate::theme::install(&ctx, &app.tokens, crate::i18n::language(&app)); + frame(&mut app, &ctx, 0.0, vec![]); + frame(&mut app, &ctx, 0.1, vec![]); + let center = |element: &crate::automation::Element| { + let [x, y, w, h] = element.rect; + egui::pos2(x + w / 2.0, y + h / 2.0) + }; + let pointer = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let picks = [ + (3, Tool::OrbitScene), + (3, Tool::OrbitTarget), + (3, Tool::Orbit), + (4, Tool::PanTarget), + (4, Tool::PanCamera), + (5, Tool::DollyToCursor), + (5, Tool::DollyTarget), + (5, Tool::Dolly), + ]; + let mut time = 1.0; + for (slot, tool) in picks { + let shown = app.ui.slot_tools[slot]; + let at = center(app.auto.elements.iter().find(|w| w.id == format!("tools.{shown:?}")).unwrap_or_else(|| panic!("no slot tools.{shown:?}"))); + // Press and hold opens the flyout. + frame(&mut app, &ctx, time, vec![egui::Event::PointerMoved(at), pointer(at, true)]); + frame(&mut app, &ctx, time + 0.36, vec![]); + frame(&mut app, &ctx, time + 0.4, vec![pointer(at, false)]); + frame(&mut app, &ctx, time + 0.45, vec![]); + let id = format!("tools.select.{tool:?}"); + let row = center(app.auto.elements.iter().find(|w| w.id == id).unwrap_or_else(|| panic!("no {id}"))); + frame(&mut app, &ctx, time + 0.6, vec![egui::Event::PointerMoved(row), pointer(row, true)]); + frame(&mut app, &ctx, time + 0.65, vec![pointer(row, false)]); + assert_eq!(app.ui.tool, tool, "{id}"); + assert_eq!(app.ui.slot_tools[slot], tool); + frame(&mut app, &ctx, time + 0.7, vec![]); + time += 1.0; + } + } + /// Alt/Option-click cycles a Tools-bar flyout slot without opening the menu. #[test] fn alt_click_cycles_the_type_slot() { diff --git a/crates/ui-egui/src/i18n/ui.rs b/crates/ui-egui/src/i18n/ui.rs index e964037e3..5d3b5f9f0 100644 --- a/crates/ui-egui/src/i18n/ui.rs +++ b/crates/ui-egui/src/i18n/ui.rs @@ -957,6 +957,11 @@ const JAPANESE: &[(&str, &str)] = &[ ("Orbit Around Cursor Tool", "カーソルのまわりを周回ツール"), ("Pan Under Cursor Tool", "カーソルの下でパンツール"), ("Dolly Towards Cursor Tool", "カーソルに向かってドリーツール"), + ("Orbit Around Scene Tool", "シーンのまわりを周回ツール"), + ("Orbit Around Camera POI Tool", "カメラ目標点のまわりを周回ツール"), + ("Pan Camera POI Tool", "カメラの目標点にパンツール"), + ("Dolly to Cursor Tool", "カーソルにドリーツール"), + ("Dolly to Camera POI Tool", "カメラの目標点にドリーツール"), ("Rotation Tool", "回転ツール"), ("Pan Behind (Anchor Point) Tool", "アンカーポイントツール"), ("Rectangle Tool", "長方形ツール"), @@ -3279,6 +3284,11 @@ const SWEDISH: &[(&str, &str)] = &[ ("Orbit Around Cursor Tool", "Verktyg för att kretsa kring pekaren"), ("Pan Under Cursor Tool", "Verktyg för att panorera under pekaren"), ("Dolly Towards Cursor Tool", "Verktyget Dolly mot pekaren"), + ("Orbit Around Scene Tool", "Verktyg för att kretsa kring scenen"), + ("Orbit Around Camera POI Tool", "Verktyg för att kretsa kring kamerans intressepunkt"), + ("Pan Camera POI Tool", "Verktyg för att panorera kamerans intressepunkt"), + ("Dolly to Cursor Tool", "Verktyget Dolly till pekaren"), + ("Dolly to Camera POI Tool", "Verktyget Dolly till kamerans intressepunkt"), ("Rotation Tool", "Rotationsverktyg"), ("Pan Behind (Anchor Point) Tool", "Verktyg för att panorera bakom (ankarpunkt)"), ("Rectangle Tool", "Rektangelverktyg"), @@ -10093,6 +10103,11 @@ const FRENCH: &[(&str, &str)] = &[ ("Orbit Around Cursor Tool", "Outil Orbite autour du curseur"), ("Pan Under Cursor Tool", "Outil Panoramique sous le curseur"), ("Dolly Towards Cursor Tool", "Outil Travelling vers le curseur"), + ("Orbit Around Scene Tool", "Outil Orbite autour de la scène"), + ("Orbit Around Camera POI Tool", "Outil Orbite autour du point ciblé de la caméra"), + ("Pan Camera POI Tool", "Outil Panoramique du point ciblé de la caméra"), + ("Dolly to Cursor Tool", "Outil Travelling jusqu'au curseur"), + ("Dolly to Camera POI Tool", "Outil Travelling jusqu'au point ciblé de la caméra"), ("Rotation Tool", "Outil Rotation"), ("Pan Behind (Anchor Point) Tool", "Outil Déplacement derrière (point d’ancrage)"), ("Rectangle Tool", "Outil Rectangle"), diff --git a/crates/ui-egui/src/menus/commands.rs b/crates/ui-egui/src/menus/commands.rs index c162bbd3a..8817b94d6 100644 --- a/crates/ui-egui/src/menus/commands.rs +++ b/crates/ui-egui/src/menus/commands.rs @@ -92,6 +92,7 @@ pub const UI_COMMANDS: &[UiCommand] = &[ uic!("tool.selection", "Selection Tool", [], Some("V")), uic!("tool.hand", "Hand Tool", [], Some("H")), uic!("tool.zoom", "Zoom Tool", [], Some("Z")), + // 1, 2 and 3 select the Orbit, Pan and Dolly slots' variant as the slot last showed it. uic!("tool.orbit", "Orbit Tool", [], Some("1")), uic!("tool.panCamera", "Pan Camera Tool", [], Some("2")), uic!("tool.dolly", "Dolly Tool", [], Some("3")), diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index bcd0f7481..419c85a03 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -348,13 +348,23 @@ pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: V return frontend(app, ctx, "window.workspace", json!({"name": ws})); } if let Some(t) = id.strip_prefix("tool.") { - // C cycles through the camera tools. - if t == "camera" { - let tools = [Tool::Orbit, Tool::PanCamera, Tool::Dolly]; - let next = match tools.iter().position(|x| *x == app.ui.tool) { - Some(i) => tools[(i + 1) % tools.len()], - None => Tool::Orbit, - }; + // The camera tools: the Orbit, Pan and Dolly slots, each showing the variant last picked + // from its flyout. C cycles the three; 1, 2 and 3 pick one. + let camera_tool = |g: usize| { + let lead = [Tool::Orbit, Tool::PanCamera, Tool::Dolly].get(g).copied().unwrap_or(Tool::Orbit); + let Some(si) = Tool::SLOTS.iter().position(|s| s.contains(&lead)) else { return lead }; + let slot = Tool::SLOTS.get(si).copied().unwrap_or(&[]); + app.ui.slot_tools.get(si).copied().filter(|x| slot.contains(x)).unwrap_or(lead) + }; + let group = match t { + "camera" => Some(app.ui.tool.camera_group().map_or(0, |g| (g + 1) % 3)), + "orbit" => Some(0), + "panCamera" => Some(1), + "dolly" => Some(2), + _ => None, + }; + if let Some(g) = group { + let next = camera_tool(g); app.ui.tool = next; return Ok(json!({"tool": next})); } diff --git a/crates/ui-egui/src/menus/shortcuts.rs b/crates/ui-egui/src/menus/shortcuts.rs index 703a9cd7c..7af870add 100644 --- a/crates/ui-egui/src/menus/shortcuts.rs +++ b/crates/ui-egui/src/menus/shortcuts.rs @@ -189,7 +189,7 @@ pub fn active_contexts(app: &EffectcraftApp) -> Vec<&'static str> { } match app.ui.tool { Tool::Brush | Tool::Clone | Tool::Eraser => out.push("Paint"), - Tool::Orbit | Tool::PanCamera | Tool::Dolly => out.push("Camera"), + t if t.is_camera() => out.push("Camera"), _ => {} } if app.session.selected_mask().is_some() { diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 88d936f49..e06979243 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -230,6 +230,100 @@ fn c_cycles_the_camera_tools() { assert_eq!(seen, [Tool::Orbit, Tool::PanCamera, Tool::Dolly, Tool::Orbit]); } +/// Each camera tool's command and `mode` (what the viewer sends while dragging) run in the +/// engine and move a 3D view as the tool's name says (#2586). +#[test] +fn every_camera_tool_runs_its_engine_variant() { + use effectcraft_render::three_d::View3D; + let d = |a: [f64; 3], b: [f64; 3]| ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt(); + let tools: Vec = Tool::ALL.into_iter().filter(|t| t.is_camera()).collect(); + assert_eq!(tools.len(), 8); + for tool in tools { + let mut s = effectcraft_engine::Session::default(); + s.execute("comp.new", json!({"name": "C", "width": 640, "height": 360, "duration": 2})).unwrap(); + let cid = s.active_comp_id().unwrap(); + let id = s.execute("layer.newSolid", json!({"width": 100, "height": 100})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setSwitch", json!({"layer": id, "switch": "threeD", "value": true})).unwrap(); + s.execute("prop.set", json!({"layer": id, "path": "transform/position", "value": [400, 120, 200]})).unwrap(); + s.execute("view.3d.custom1", json!({})).unwrap(); + let cam = |s: &effectcraft_engine::Session| s.state.views3d[&cid].cam(View3D::Custom1, 640.0, 360.0); + let c0 = cam(&s); + let (id, mode) = tool.camera_command().unwrap(); + let mut p = match id { + "camera.orbit" => json!({"yaw": 20, "pitch": -5}), + "camera.pan" => json!({"dx": 30, "dy": 10}), + _ => json!({"amount": 1.0e7}), + }; + p["mode"] = json!(mode); + p["cursor"] = json!([400.0, 120.0]); + let r = s.execute(id, p).unwrap_or_else(|e| panic!("{tool:?}: {e}")); + let c1 = cam(&s); + let pivot = r["pivot"].as_array().map(|a| [a[0].as_f64().unwrap(), a[1].as_f64().unwrap(), a[2].as_f64().unwrap()]); + match tool { + Tool::OrbitTarget => { + assert!(pivot.is_none(), "{tool:?}"); + assert!(d(c1.poi, c0.poi) < 1e-9 && d(c1.eye, c0.eye) > 1.0, "{tool:?}"); + } + Tool::PanTarget => { + assert!(pivot.is_none(), "{tool:?}"); + assert!(d(c1.poi, c0.poi) > 1.0, "{tool:?}"); + } + Tool::DollyTarget => { + assert!(pivot.is_none(), "{tool:?}"); + assert!(d(c1.poi, c0.poi) < 1e-9 && (d(c1.eye, c1.poi) - 1.0).abs() < 1e-6, "{tool:?}"); + } + Tool::Orbit | Tool::OrbitScene => { + let pv = pivot.unwrap_or_else(|| panic!("{tool:?}: no pivot")); + if tool == Tool::OrbitScene { + assert!(d(pv, [400.0, 120.0, 200.0]) < 1e-6, "{pv:?}"); + } + assert!(d(c1.poi, c0.poi) > 1.0, "{tool:?}"); + assert!((d(c1.eye, pv) - d(c0.eye, pv)).abs() < 1e-6, "{tool:?}"); + } + Tool::PanCamera => { + assert!(pivot.is_some(), "{tool:?}"); + assert!(d(c1.poi, c0.poi) > 1.0, "{tool:?}"); + } + Tool::Dolly => { + let pv = pivot.unwrap_or_else(|| panic!("{tool:?}: no pivot")); + assert!(d(c1.eye, pv) > 1.0e6, "Dolly Towards Cursor goes on past the point"); + } + Tool::DollyToCursor => { + let pv = pivot.unwrap_or_else(|| panic!("{tool:?}: no pivot")); + assert!((d(c1.eye, pv) - 1.0).abs() < 1e-6, "Dolly to Cursor stops short of the point"); + } + other => panic!("not a camera tool: {other:?}"), + } + } +} + +/// C and 1 / 2 / 3 pick each camera slot's variant as its flyout last left it (#2586). +#[test] +fn camera_keys_keep_each_slots_variant() { + let ctx = egui::Context::default(); + let mut app = EffectcraftApp::new(effectcraft_engine::Session::default()); + app.ui.tool = Tool::Selection; + app.ui.slot_tools[3] = Tool::OrbitScene; + app.ui.slot_tools[4] = Tool::PanTarget; + app.ui.slot_tools[5] = Tool::DollyToCursor; + let mut seen = vec![]; + for _ in 0..4 { + invoke(&mut app, &ctx, "tool.camera", json!({})).unwrap(); + seen.push(app.ui.tool); + } + assert_eq!(seen, [Tool::OrbitScene, Tool::PanTarget, Tool::DollyToCursor, Tool::OrbitScene]); + app.ui.slot_tools[5] = Tool::DollyTarget; + for (id, tool) in [("tool.dolly", Tool::DollyTarget), ("tool.panCamera", Tool::PanTarget), ("tool.orbit", Tool::OrbitScene)] { + invoke(&mut app, &ctx, id, json!({})).unwrap(); + assert_eq!(app.ui.tool, tool, "{id}"); + } + // Every variant is reachable by name, as the control channel selects tools. + for tool in [Tool::OrbitScene, Tool::OrbitTarget, Tool::PanTarget, Tool::DollyToCursor, Tool::DollyTarget] { + invoke(&mut app, &ctx, &format!("tool.{tool:?}"), json!({})).unwrap(); + assert_eq!(app.ui.tool, tool); + } +} + #[test] fn dispatch_uses_the_active_custom_preset() { let mut app = EffectcraftApp::new(effectcraft_engine::Session::default()); diff --git a/crates/ui-egui/src/panels/viewer.rs b/crates/ui-egui/src/panels/viewer.rs index 45abbc049..810334f8b 100644 --- a/crates/ui-egui/src/panels/viewer.rs +++ b/crates/ui-egui/src/panels/viewer.rs @@ -975,6 +975,7 @@ fn wheel_scrub_frames(ctx: &egui::Context, pref: bool, scroll: &super::ViewerScr scrub.then_some((scroll.wheel_lines.round() as i64).clamp(-30, 30)) } +/// Handles the pointer moving over the viewer without a drag: hover feedback, cursors and tool hints. fn phase_hover(app: &mut EffectcraftApp, ui: &mut egui::Ui, ectx: &EvalCtx, resp: &egui::Response, v: &mut Vw<'_>) { let area = v.area; let zoom = v.zoom; @@ -1009,9 +1010,9 @@ fn phase_hover(app: &mut EffectcraftApp, ui: &mut egui::Ui, ectx: &EvalCtx, resp 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, + Tool::Orbit | Tool::OrbitScene | Tool::OrbitTarget => egui::CursorIcon::Alias, + Tool::PanCamera | Tool::PanTarget => egui::CursorIcon::Move, + Tool::Dolly | Tool::DollyToCursor | Tool::DollyTarget => egui::CursorIcon::ResizeVertical, t if t.is_pen() => { pen_cursor( &ctx, @@ -1328,7 +1329,9 @@ fn phase_dragstart(app: &mut EffectcraftApp, ui: &mut egui::Ui, ectx: &EvalCtx, } Some(Gesture::PuppetPin { layer: h.layer, pin: h.pin, inv }) }), - Tool::Orbit | Tool::PanCamera | Tool::Dolly => Some(Gesture::Camera { tool }), + // The cursor variants turn about / pan at / dolly towards the point under the press; + // the engine resolves it on the first step and the drag keeps it (`pivot`). + t if t.is_camera() => Some(Gesture::Camera { tool, cursor: map.to_comp(press), pivot: None }), Tool::Selection if super::tracker::hit_at(&track_hits, press).is_some() => { let hit = super::tracker::hit_at(&track_hits, press); track_cur.zip(hit).and_then(|((tl, tu), hit)| { @@ -1493,6 +1496,37 @@ fn edge_pan_speed(area: Rect, pos: Pos2) -> egui::Vec2 { vec2(axis(pos.x, area.min.x, area.max.x), axis(pos.y, area.min.y, area.max.y)) } +/// One step of a camera tool's drag: the tool's command with its `mode`, the press point and, once +/// known, the point it works about. Returns the point the first step found, for the drag to keep. +fn camera_drag(app: &mut EffectcraftApp, tool: Tool, cursor: [f64; 2], pivot: Option<[f64; 3]>, d: egui::Vec2, zoom: f32, merge: String) -> Option<[f64; 3]> { + let (id, mode) = tool.camera_command()?; + if d == egui::Vec2::ZERO { + return None; + } + let (dx, dy) = ((d.x / zoom) as f64, (d.y / zoom) as f64); + let mut params = match id { + "camera.orbit" => json!({"yaw": -d.x as f64 * 0.4, "pitch": d.y as f64 * 0.4}), + "camera.pan" => json!({"dx": dx, "dy": dy}), + _ => json!({"amount": -dy * 2.0}), + }; + params["mode"] = json!(mode); + params["merge"] = json!(merge); + params["cursor"] = json!(cursor); + if let Some(pv) = pivot { + params["point"] = json!(pv); + } + match app.session.execute(id, params) { + // Keep the point the first step found for the rest of the drag. + Ok(r) if pivot.is_none() => r["pivot"].as_array().and_then(|a| Some([a.first()?.as_f64()?, a.get(1)?.as_f64()?, a.get(2)?.as_f64()?])), + Ok(_) => None, + Err(e) => { + app.ui.status = e.to_string(); + None + } + } +} + +/// Continues the viewer gesture that `phase_dragstart` began, applying the pointer's movement to it. fn phase_drag(app: &mut EffectcraftApp, ui: &mut egui::Ui, ectx: &EvalCtx, resp: &egui::Response, v: &mut Vw<'_>) { let t = v.t; let zoom = v.zoom; @@ -1579,18 +1613,9 @@ fn phase_drag(app: &mut EffectcraftApp, ui: &mut egui::Ui, ectx: &EvalCtx, resp: 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::Camera { tool, cursor, pivot } => { + if let Some(found) = camera_drag(app, tool, cursor, pivot, resp.drag_delta(), zoom, merge) { + ui.data_mut(|dd| dd.insert_temp(gid, Gesture::Camera { tool, cursor, pivot: Some(found) })); } } Gesture::Create { tool, start } => { diff --git a/crates/ui-egui/src/panels/viewer/gesture.rs b/crates/ui-egui/src/panels/viewer/gesture.rs index 72ef22a84..0b59172e4 100644 --- a/crates/ui-egui/src/panels/viewer/gesture.rs +++ b/crates/ui-egui/src/panels/viewer/gesture.rs @@ -12,6 +12,10 @@ pub(super) enum Gesture { }, Camera { tool: Tool, + /// Where the drag began (comp pixels): the cursor variants' point is under it. + cursor: [f64; 2], + /// The world point the tool turns about / pans at / dollies towards, once resolved. + pivot: Option<[f64; 3]>, }, /// A bounding-box handle: scales about the anchor point so the grabbed point follows the /// pointer (corners both axes, edges one), relative to the layer as the drag began; the diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 5a7df800b..9bd583ef4 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -13,9 +13,22 @@ pub enum Tool { Selection, Hand, Zoom, + /// Orbit Around Cursor. Orbit, + /// Pan Under Cursor. PanCamera, + /// Dolly Towards Cursor. Dolly, + /// Orbit Around Scene (the centre of the comp's 3D layers). + OrbitScene, + /// Orbit Around Camera POI (the camera's point of interest). + OrbitTarget, + /// Pan Camera POI (moves as far as the point of interest's depth asks). + PanTarget, + /// Dolly to Cursor (stops short of the point under the cursor). + DollyToCursor, + /// Dolly to Camera POI (approaches the point of interest, which stays). + DollyTarget, Rotate, PanBehind, Rectangle, @@ -50,9 +63,9 @@ impl Tool { &[Tool::Selection], &[Tool::Hand], &[Tool::Zoom], - &[Tool::Orbit], - &[Tool::PanCamera], - &[Tool::Dolly], + &[Tool::Orbit, Tool::OrbitScene, Tool::OrbitTarget], + &[Tool::PanCamera, Tool::PanTarget], + &[Tool::Dolly, Tool::DollyToCursor, Tool::DollyTarget], &[Tool::Rotate], &[Tool::PanBehind], &[Tool::Rectangle, Tool::RoundedRect, Tool::Ellipse, Tool::Polygon, Tool::Star], @@ -64,13 +77,20 @@ impl Tool { &[Tool::RotoBrush, Tool::RefineEdge, Tool::ObjectMatte], &[Tool::Puppet, Tool::PuppetStarch, Tool::PuppetBend, Tool::PuppetAdvanced, Tool::PuppetOverlap], ]; - pub const ALL: [Tool; 31] = [ + /// Each slot's first tool comes before its variants: [`Tool::from_name`] matches labels by + /// prefix, so `orbit` stays Orbit Around Cursor. + pub const ALL: [Tool; 36] = [ Tool::Selection, Tool::Hand, Tool::Zoom, Tool::Orbit, Tool::PanCamera, Tool::Dolly, + Tool::OrbitScene, + Tool::OrbitTarget, + Tool::PanTarget, + Tool::DollyToCursor, + Tool::DollyTarget, Tool::Rotate, Tool::PanBehind, Tool::Rectangle, @@ -97,6 +117,7 @@ impl Tool { Tool::PuppetAdvanced, Tool::PuppetOverlap, ]; + /// Returns the tool's name as After Effects shows it, e.g. `Orbit Around Cursor Tool`. pub fn label(self) -> &'static str { match self { Tool::Selection => "Selection Tool", @@ -105,6 +126,11 @@ impl Tool { Tool::Orbit => "Orbit Around Cursor Tool", Tool::PanCamera => "Pan Under Cursor Tool", Tool::Dolly => "Dolly Towards Cursor Tool", + Tool::OrbitScene => "Orbit Around Scene Tool", + Tool::OrbitTarget => "Orbit Around Camera POI Tool", + Tool::PanTarget => "Pan Camera POI Tool", + Tool::DollyToCursor => "Dolly to Cursor Tool", + Tool::DollyTarget => "Dolly to Camera POI Tool", Tool::Rotate => "Rotation Tool", Tool::PanBehind => "Pan Behind (Anchor Point) Tool", Tool::Rectangle => "Rectangle Tool", @@ -132,14 +158,15 @@ impl Tool { Tool::PuppetOverlap => "Puppet Overlap Pin Tool", } } + /// Returns the tool's key, shared by the variants in one toolbar slot, or `None` when it has none. pub fn shortcut(self) -> Option<&'static str> { match self { Tool::Selection => Some("V"), Tool::Hand => Some("H"), Tool::Zoom => Some("Z"), - Tool::Orbit => Some("1"), - Tool::PanCamera => Some("2"), - Tool::Dolly => Some("3"), + Tool::Orbit | Tool::OrbitScene | Tool::OrbitTarget => Some("1"), + Tool::PanCamera | Tool::PanTarget => Some("2"), + Tool::Dolly | Tool::DollyToCursor | Tool::DollyTarget => Some("3"), Tool::Rotate => Some("W"), Tool::PanBehind => Some("Y"), Tool::Rectangle | Tool::RoundedRect | Tool::Ellipse | Tool::Polygon | Tool::Star => Some("Q"), @@ -150,14 +177,15 @@ impl Tool { Tool::Puppet | Tool::PuppetStarch | Tool::PuppetBend | Tool::PuppetAdvanced | Tool::PuppetOverlap => Some("Cmd+P"), } } + /// Returns the toolbar icon of the tool; the variants of one slot share an icon. pub fn icon(self) -> Icon { match self { Tool::Selection => Icon::Selection, Tool::Hand => Icon::Hand, Tool::Zoom => Icon::Zoom, - Tool::Orbit => Icon::Orbit, - Tool::PanCamera => Icon::PanCamera, - Tool::Dolly => Icon::Dolly, + Tool::Orbit | Tool::OrbitScene | Tool::OrbitTarget => Icon::Orbit, + Tool::PanCamera | Tool::PanTarget => Icon::PanCamera, + Tool::Dolly | Tool::DollyToCursor | Tool::DollyTarget => Icon::Dolly, Tool::Rotate => Icon::Rotate, Tool::PanBehind => Icon::PanBehind, Tool::Rectangle => Icon::Rectangle, @@ -189,6 +217,33 @@ impl Tool { let n = s.to_ascii_lowercase().replace([' ', '_', '-'], ""); Tool::ALL.into_iter().find(|t| format!("{t:?}").to_ascii_lowercase() == n || t.label().to_ascii_lowercase().replace(' ', "").starts_with(&n)) } + /// The camera tools' toolbar slot (0 = the Orbit tools, 1 = Pan, 2 = Dolly); None for other tools. + pub fn camera_group(self) -> Option { + match self { + Tool::Orbit | Tool::OrbitScene | Tool::OrbitTarget => Some(0), + Tool::PanCamera | Tool::PanTarget => Some(1), + Tool::Dolly | Tool::DollyToCursor | Tool::DollyTarget => Some(2), + _ => None, + } + } + /// Returns whether the tool is one of the orbit, pan or dolly camera tools. + pub fn is_camera(self) -> bool { + self.camera_group().is_some() + } + /// A camera tool's engine command and its `mode` (After Effects' variant of the tool). + pub fn camera_command(self) -> Option<(&'static str, &'static str)> { + Some(match self { + Tool::Orbit => ("camera.orbit", "aroundCursor"), + Tool::OrbitScene => ("camera.orbit", "aroundScene"), + Tool::OrbitTarget => ("camera.orbit", "aroundCameraPoi"), + Tool::PanCamera => ("camera.pan", "underCursor"), + Tool::PanTarget => ("camera.pan", "cameraPoi"), + Tool::Dolly => ("camera.dolly", "towardsCursor"), + Tool::DollyToCursor => ("camera.dolly", "toCursor"), + Tool::DollyTarget => ("camera.dolly", "toCameraPoi"), + _ => return None, + }) + } /// Puppet pin tools, with the pin kind they place (`puppet.addPin` kind). pub fn puppet_kind(self) -> Option<&'static str> { Some(match self { diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 1505e268b..aef83e77b 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -196,6 +196,16 @@ step; `ui.set {viewer: {res}}` sets the active comp's, and `ui.inspect` reports shape paths by uid), `keys.setSpatialTangents` (motion-path handles) and `keys.transform` (Graph Editor transform box, timeline Alt-drag scaling). +Camera tools: the Tools bar's Orbit, Pan and Dolly slots hold After Effects' variants +(`tools.Orbit|OrbitScene|OrbitTarget`, `tools.PanCamera|PanTarget`, +`tools.Dolly|DollyToCursor|DollyTarget`; flyout rows `tools.select.`). `tool.orbit`, +`tool.panCamera` and `tool.dolly` (1, 2, 3) select the variant the slot last showed, `tool.camera` +(C) cycles the three slots, and `tool.` (e.g. `tool.OrbitScene`) selects one directly. A drag +runs `camera.orbit` / `camera.pan` / `camera.dolly` with the tool's `mode` and the press point as +`cursor`; the result's `pivot` is the world point used, sent back as `point` for the rest of the drag +(null when the tool works about the camera's point of interest: the POI variants, and `camera.dolly` +without `mode`). + The MCP server's bridge mode (`effectcraft-cli mcp --bridge 9877`) is a thin client of this protocol; see [agents.md](agents.md).