mirror of
https://github.com/storytold/AniCraft.git
synced 2026-11-28 17:19:31 +01:00
Merge pull request #274 from storytold/m7/camera-depth
feat(camera): layer depth in perspective, attaching layers and camera colour (M7)
This commit is contained in:
26 files changed
+1300
-179
No files matched your search
@@ -2,6 +2,29 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
* **Camera, second slice: layer depth, attaching layers and colour** (ADR 0082, M7).
|
||||
* **Layer depth in perspective**: through the camera, a pinhole with a fixed focal length
|
||||
(1,000 px), a deeper layer moves less when the camera pans and grows less when it zooms;
|
||||
deeper layers draw behind nearer ones (ties in timeline order). The camera at rest shows
|
||||
every layer as drawn, and depth 0 is bit-for-bit what it was. A layer the camera has passed
|
||||
isn't drawn.
|
||||
* **Depth over time**: key a layer's depth on any frame; it tweens linearly between keys.
|
||||
* **Window › Layer Depth**: the layers by depth, nearest first, each with a track to drag
|
||||
nearer or farther, its value, a key diamond and Attach.
|
||||
* **Attach Layer to Camera**: a camera toggle on each layer's timeline row; an attached layer
|
||||
stays where it is on screen while the camera moves (titles, HUDs).
|
||||
* **Camera colour effects**: Brightness, Tint and Advanced (no alpha), in Properties and
|
||||
`camera.set`, tweened, in every export.
|
||||
* **Editing while previewing**: with View › Preview Through Camera the Selection tool picks
|
||||
and moves artwork where the movie shows it, mapped back through the camera and the layer's
|
||||
depth.
|
||||
* Every export (PNG, sequences, GIF, video, SVG, Lottie, HTML canvas), Test Movie and the GPU
|
||||
stage see the same picture. Headless: `layer.set_depth {key, frame}`,
|
||||
`layer.remove_depth_key`, `layer.set_attached`, `layer.depths`, `element.pick {view:
|
||||
camera}`; `camera.info` reports `color_effect`.
|
||||
* Changed: depth now also scales under the camera's zoom (it was pan-only); files with a
|
||||
depth and a zoomed camera look different.
|
||||
|
||||
* **Drawing parity leftovers** (ADR 0080, M1).
|
||||
* **PolyStar options**: Shape (**Polygon** or **Star**), **Sides**/**Points** (3 to 32) and
|
||||
**Point size** (0 to 1; at 1 a star is the polygon through its tips) in the tool's options.
|
||||
|
||||
+263
-46
@@ -1,18 +1,22 @@
|
||||
//! The camera layer (ADR 0027): a special layer at the top of a scene's timeline whose camera
|
||||
//! views the stage. Its keyframes hold one [`ElementKind::Camera`] element, so the camera
|
||||
//! The camera layer (ADR 0027, 0082): a special layer at the top of a scene's timeline whose
|
||||
//! camera views the stage. Its keyframes hold one [`ElementKind::Camera`] element, so the camera
|
||||
//! tweens like any instance (classic tweens and motion tweens): the element's transform is the
|
||||
//! camera on the stage, `T(x, y) · R(rotation) · S(zoom)`, with the camera's centre at `(x, y)`,
|
||||
//! and its colour effect's tint colours the whole view.
|
||||
//! and its colour effect (None, Brightness, Tint or Advanced) colours the whole view.
|
||||
//!
|
||||
//! What the movie shows is the stage seen through the camera: every layer is drawn through
|
||||
//! [`Camera::view`], which puts the camera's centre at the middle of the output, zoomed and
|
||||
//! turned the other way. A layer's **depth** (Animate's Layer Depth) gives parallax: a layer
|
||||
//! `depth` pixels behind the stage moves `FOCAL / (FOCAL + depth)` as far when the camera pans,
|
||||
//! keeping its size (so a layer at depth 0 moves with the stage, a far background barely moves).
|
||||
//! Everything here is pure: the camera at a frame is a function of the document.
|
||||
//! turned the other way. A layer's **depth** (Animate's Layer Depth, keyable over time,
|
||||
//! [`Layer::depth_at`]) places it in a pinhole perspective with a fixed focal length
|
||||
//! ([`FOCAL`]): the camera at rest shows every layer as drawn, and its pans and zooms move and
|
||||
//! scale a deeper layer less (ADR 0082). A layer at depth 0 is the stage plane, exactly as
|
||||
//! before; a layer **attached** to the camera ignores it (titles, HUDs). Layers are drawn
|
||||
//! deepest first, ties in timeline order ([`Timeline::draw_order`]). Everything here is pure:
|
||||
//! the camera at a frame is a function of the document.
|
||||
|
||||
use crate::{ColorEffect, ColorTransform, Element, ElementId, ElementKind, Layer, LayerKind, Rgba, Stage, Timeline, evaluate_layer_elements};
|
||||
use anicraft_geom::{Affine, Decomposed, Vec2};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Smallest and largest camera zoom (5 % to 2,000 %).
|
||||
pub const MIN_ZOOM: f32 = 0.05;
|
||||
@@ -20,9 +24,29 @@ pub const MAX_ZOOM: f32 = 20.0;
|
||||
/// Layer depth range, in pixels behind (positive) or in front of (negative) the stage.
|
||||
pub const MIN_DEPTH: f32 = -500.0;
|
||||
pub const MAX_DEPTH: f32 = 10_000.0;
|
||||
/// Distance from the camera to the stage plane, in pixels: a layer this far behind the stage
|
||||
/// moves half as much as the stage when the camera pans.
|
||||
/// Distance from the camera to the stage plane at zoom 100 %, in pixels (the pinhole's focal
|
||||
/// length): a layer this far behind the stage moves half as much as the stage when the camera
|
||||
/// pans. Zooming moves the camera towards the stage: at zoom `z` it is `FOCAL / z` away.
|
||||
pub const FOCAL: f32 = 1_000.0;
|
||||
/// Nearest a layer may be to the camera and still show (pixels): a layer the camera has
|
||||
/// reached or passed (a near layer under a strong zoom) isn't drawn.
|
||||
pub const NEAR: f32 = FOCAL / 100.0;
|
||||
/// Most depth keys one layer keeps.
|
||||
pub const MAX_DEPTH_KEYS: usize = 4_096;
|
||||
|
||||
/// A layer's depth at one frame (ADR 0082): between two keys the depth travels linearly; before
|
||||
/// the first and after the last it holds.
|
||||
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
|
||||
pub struct DepthKey {
|
||||
pub frame: u32,
|
||||
pub depth: f32,
|
||||
}
|
||||
|
||||
impl PartialEq for DepthKey {
|
||||
fn eq(&self, o: &DepthKey) -> bool {
|
||||
self.frame == o.frame && self.depth.to_bits() == o.depth.to_bits()
|
||||
}
|
||||
}
|
||||
|
||||
/// The camera at one frame, resolved and sanitized.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
@@ -33,16 +57,16 @@ pub struct Camera {
|
||||
pub zoom: f32,
|
||||
/// Radians, clockwise on the stage (the view turns the other way).
|
||||
pub rotation: f32,
|
||||
/// The tint colouring the whole view (`tint_amount` 0: none).
|
||||
pub tint: Rgba,
|
||||
pub tint_amount: f32,
|
||||
/// The colour effect on everything the camera shows: None, Brightness, Tint or Advanced
|
||||
/// (the camera has no opacity: Alpha reads as None and Advanced keeps alpha as it is).
|
||||
pub color: ColorEffect,
|
||||
}
|
||||
|
||||
impl Camera {
|
||||
/// The camera at rest on `stage`: its centre at the stage's, zoom 100 %, no turn, no tint.
|
||||
/// The view through it is the stage itself.
|
||||
/// The camera at rest on `stage`: its centre at the stage's, zoom 100 %, no turn, no colour
|
||||
/// effect. The view through it is the stage itself.
|
||||
pub fn rest(stage: &Stage) -> Camera {
|
||||
Camera { center: stage_center(stage), zoom: 1.0, rotation: 0.0, tint: Rgba::WHITE, tint_amount: 0.0 }
|
||||
Camera { center: stage_center(stage), zoom: 1.0, rotation: 0.0, color: ColorEffect::Tint { color: Rgba::WHITE, amount: 0.0 } }
|
||||
}
|
||||
|
||||
/// The camera a camera element describes (any element: its transform and colour effect).
|
||||
@@ -55,17 +79,12 @@ impl Camera {
|
||||
let center = Vec2::new(fin(d.tx, rest.center.x), fin(d.ty, rest.center.y));
|
||||
let zoom = fin(d.sx.abs(), 1.0).clamp(MIN_ZOOM, MAX_ZOOM);
|
||||
let rotation = fin(d.rotation, 0.0);
|
||||
// The camera's colour effect is a tint (ADR 0027); other styles leave the view as it is.
|
||||
let (tint, amount) = match el.color {
|
||||
ColorEffect::Tint { color, amount } => (color.sanitized(), fin(amount, 0.0).clamp(0.0, 1.0)),
|
||||
_ => (Rgba::WHITE, 0.0),
|
||||
};
|
||||
Camera { center, zoom, rotation, tint, tint_amount: amount }
|
||||
Camera { center, zoom, rotation, color: camera_effect(&el.color) }
|
||||
}
|
||||
|
||||
/// The camera element holding this camera (for commands).
|
||||
pub fn to_element(&self, id: ElementId) -> Element {
|
||||
Element { id, name: String::new(), transform: self.transform(), color: ColorEffect::Tint { color: self.tint, amount: self.tint_amount }, kind: ElementKind::Camera }
|
||||
Element { id, name: String::new(), transform: self.transform(), color: camera_effect(&self.color), kind: ElementKind::Camera }
|
||||
}
|
||||
|
||||
/// The camera on the stage: `T(centre) · R(rotation) · S(zoom)`.
|
||||
@@ -75,34 +94,77 @@ impl Camera {
|
||||
|
||||
/// The colour effect the camera puts on everything it shows.
|
||||
pub fn color(&self) -> ColorTransform {
|
||||
ColorTransform::tint(self.tint, self.tint_amount)
|
||||
camera_effect(&self.color).transform()
|
||||
}
|
||||
|
||||
/// Stage space → output space for a layer `depth` pixels behind the stage: the camera's
|
||||
/// centre (moved by the layer's parallax) lands at the middle of the output, zoomed, and
|
||||
/// turned against the camera's rotation.
|
||||
pub fn view(&self, stage: &Stage, depth: f32) -> Affine {
|
||||
/// Stage space → output space for the stage plane (a layer at depth 0): the camera's centre
|
||||
/// lands at the middle of the output, zoomed, and turned against the camera's rotation.
|
||||
pub fn stage_view(&self, stage: &Stage) -> Affine {
|
||||
let mid = stage_center(stage);
|
||||
let c = mid + (self.center - mid) * parallax(depth);
|
||||
let c = self.center;
|
||||
let m = Affine::translate(mid.x, mid.y).mul(&Affine::scale(self.zoom, self.zoom)).mul(&Affine::rotate(-self.rotation)).mul(&Affine::translate(-c.x, -c.y));
|
||||
if m.is_finite() { m } else { Affine::IDENTITY }
|
||||
}
|
||||
|
||||
/// Stage space → output space for a layer `depth` pixels behind the stage, by a pinhole
|
||||
/// camera `FOCAL / zoom` from the stage plane (ADR 0082). The layer is drawn as it would be
|
||||
/// seen if it stood that far back, enlarged so that the camera at rest shows it exactly as
|
||||
/// drawn: for a stage point `p`, with `d = FOCAL / zoom + depth`,
|
||||
/// `out = mid + R(−rotation) · ((FOCAL + depth) / d · (p − mid) − FOCAL / d · (centre − mid))`.
|
||||
/// Depth 0 is [`Camera::stage_view`] exactly. `None` when the layer is at or behind the
|
||||
/// camera (nearer than [`NEAR`]): it isn't drawn.
|
||||
pub fn view(&self, stage: &Stage, depth: f32) -> Option<Affine> {
|
||||
let depth = clamp_depth(depth);
|
||||
if depth == 0.0 {
|
||||
return Some(self.stage_view(stage));
|
||||
}
|
||||
let dist = FOCAL / self.zoom + depth;
|
||||
if dist.is_nan() || dist < NEAR {
|
||||
return None;
|
||||
}
|
||||
let mid = stage_center(stage);
|
||||
let size = (FOCAL + depth) / dist;
|
||||
let pan = (self.center - mid) * (FOCAL / dist);
|
||||
let m = Affine::translate(mid.x, mid.y).mul(&Affine::rotate(-self.rotation)).mul(&Affine::translate(-pan.x, -pan.y)).mul(&Affine::scale(size, size)).mul(&Affine::translate(-mid.x, -mid.y));
|
||||
Some(if m.is_finite() { m } else { Affine::IDENTITY })
|
||||
}
|
||||
|
||||
/// How `layer` is placed at `frame` through this camera: by its depth then, or not at all
|
||||
/// when attached (it stays on screen as drawn). `None`: the camera has passed it.
|
||||
pub fn layer_view(&self, stage: &Stage, layer: &Layer, frame: u32) -> Option<Affine> {
|
||||
if layer.attached { Some(Affine::IDENTITY) } else { self.view(stage, layer.depth_at(frame)) }
|
||||
}
|
||||
|
||||
/// The camera's frame on the stage (what it sees), corners clockwise from the top left.
|
||||
pub fn frame(&self, stage: &Stage) -> [Vec2; 4] {
|
||||
let (w, h) = (stage.width as f32, stage.height as f32);
|
||||
let inv = self.view(stage, 0.0).inverse().unwrap_or(Affine::IDENTITY);
|
||||
let inv = self.stage_view(stage).inverse().unwrap_or(Affine::IDENTITY);
|
||||
[Vec2::new(0.0, 0.0), Vec2::new(w, 0.0), Vec2::new(w, h), Vec2::new(0.0, h)].map(|p| inv.apply(p))
|
||||
}
|
||||
|
||||
/// The stage point under output point `p` (layers at depth 0).
|
||||
pub fn to_stage(&self, stage: &Stage, p: Vec2) -> Vec2 {
|
||||
self.view(stage, 0.0).inverse().map_or(p, |m| m.apply(p))
|
||||
self.stage_view(stage).inverse().map_or(p, |m| m.apply(p))
|
||||
}
|
||||
|
||||
/// Whether the view is the stage as it is (nothing to apply).
|
||||
pub fn is_rest(&self, stage: &Stage) -> bool {
|
||||
*self == Camera::rest(stage) || (self.view(stage, 0.0) == Affine::IDENTITY && self.tint_amount <= 0.0)
|
||||
let still = (self.center, self.zoom, self.rotation) == (stage_center(stage), 1.0, 0.0) || self.stage_view(stage) == Affine::IDENTITY;
|
||||
still && self.color().is_identity()
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour effect a camera can have: Alpha reads as None, and Advanced keeps alpha as it is
|
||||
/// (the movie never fades out through its camera).
|
||||
pub fn camera_effect(fx: &ColorEffect) -> ColorEffect {
|
||||
match fx.sanitized() {
|
||||
ColorEffect::Alpha(_) => ColorEffect::None,
|
||||
ColorEffect::Advanced(mut t) => {
|
||||
t.mul[3] = 1.0;
|
||||
t.add[3] = 0.0;
|
||||
ColorEffect::Advanced(t)
|
||||
}
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,8 +173,8 @@ pub fn stage_center(stage: &Stage) -> Vec2 {
|
||||
Vec2::new(stage.width as f32 * 0.5, stage.height as f32 * 0.5)
|
||||
}
|
||||
|
||||
/// How far a layer `depth` pixels behind the stage moves when the camera pans, as a fraction
|
||||
/// of the stage's movement (1 at depth 0).
|
||||
/// How far a layer `depth` pixels behind the stage moves when the camera pans at zoom 100 %,
|
||||
/// as a fraction of the stage's movement (1 at depth 0).
|
||||
pub fn parallax(depth: f32) -> f32 {
|
||||
FOCAL / (FOCAL + clamp_depth(depth))
|
||||
}
|
||||
@@ -122,6 +184,68 @@ pub fn clamp_depth(depth: f32) -> f32 {
|
||||
if depth.is_finite() { depth.clamp(MIN_DEPTH, MAX_DEPTH) } else { 0.0 }
|
||||
}
|
||||
|
||||
impl Layer {
|
||||
/// The layer's depth at `frame` (ADR 0082): its keys' when it has any (linear between two,
|
||||
/// held outside them), else its one depth. Always in range.
|
||||
pub fn depth_at(&self, frame: u32) -> f32 {
|
||||
let keys = &self.depth_keys;
|
||||
let Some(first) = keys.first() else { return clamp_depth(self.depth) };
|
||||
// The first key after `frame` (keys are sorted by frame).
|
||||
let next = keys.partition_point(|k| k.frame <= frame);
|
||||
let d = match (next.checked_sub(1).and_then(|i| keys.get(i)), keys.get(next)) {
|
||||
(Some(a), Some(b)) if b.frame > a.frame => {
|
||||
let t = (frame - a.frame) as f32 / (b.frame - a.frame) as f32;
|
||||
a.depth + (b.depth - a.depth) * t
|
||||
}
|
||||
(Some(a), _) => a.depth,
|
||||
(None, _) => first.depth,
|
||||
};
|
||||
clamp_depth(d)
|
||||
}
|
||||
|
||||
/// Whether the layer has a depth anywhere (a key or its one depth off the stage plane).
|
||||
pub fn has_depth(&self) -> bool {
|
||||
self.depth != 0.0 || self.depth_keys.iter().any(|k| k.depth != 0.0)
|
||||
}
|
||||
|
||||
/// Whether the depth keys are sorted, one per frame, in range and not too many.
|
||||
pub fn depth_keys_clean(&self) -> bool {
|
||||
let keys = &self.depth_keys;
|
||||
keys.len() <= MAX_DEPTH_KEYS && keys.windows(2).all(|w| w[0].frame < w[1].frame) && keys.iter().all(|k| clamp_depth(k.depth).to_bits() == k.depth.to_bits())
|
||||
}
|
||||
|
||||
/// Keeps the depth keys sorted, one per frame, finite and in range, and at most
|
||||
/// [`MAX_DEPTH_KEYS`]. Returns whether anything changed.
|
||||
pub fn sanitize_depth_keys(&mut self) -> bool {
|
||||
if self.depth_keys_clean() {
|
||||
return false;
|
||||
}
|
||||
let keys = &mut self.depth_keys;
|
||||
keys.truncate(MAX_DEPTH_KEYS);
|
||||
for k in keys.iter_mut() {
|
||||
k.depth = clamp_depth(k.depth);
|
||||
}
|
||||
// The last key given for a frame wins.
|
||||
keys.reverse();
|
||||
keys.sort_by_key(|k| k.frame);
|
||||
keys.dedup_by_key(|k| k.frame);
|
||||
true
|
||||
}
|
||||
|
||||
/// Sets the depth at `frame` as a key (replacing one there), keeping the keys sorted.
|
||||
pub fn set_depth_key(&mut self, frame: u32, depth: f32) {
|
||||
let depth = clamp_depth(depth);
|
||||
match self.depth_keys.binary_search_by_key(&frame, |k| k.frame) {
|
||||
Ok(i) => {
|
||||
if let Some(k) = self.depth_keys.get_mut(i) {
|
||||
k.depth = depth;
|
||||
}
|
||||
}
|
||||
Err(i) => self.depth_keys.insert(i, DepthKey { frame, depth }),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Timeline {
|
||||
/// The camera layer, if the timeline has one (it is always the top layer).
|
||||
pub fn camera_layer(&self) -> Option<&Layer> {
|
||||
@@ -147,6 +271,27 @@ impl Timeline {
|
||||
}
|
||||
}
|
||||
|
||||
/// The order the layers are drawn in at `frame`, bottom first, as indices into `layers`
|
||||
/// (ADR 0082): the deepest first, ties in timeline order (lower layers first). A masked
|
||||
/// layer goes with its mask's depth, so a mask stays with the layers it masks. With every
|
||||
/// layer on the stage plane this is the timeline order, bottom up.
|
||||
pub fn draw_order(&self, frame: u32) -> Vec<usize> {
|
||||
let n = self.layers.len();
|
||||
let mut order: Vec<usize> = (0..n).rev().collect();
|
||||
if !self.layers.iter().any(|l| l.has_depth()) {
|
||||
return order;
|
||||
}
|
||||
let depth = |l: &Layer| -> f32 {
|
||||
let mask = l.parent.and_then(|p| self.layer(p)).filter(|p| p.kind == LayerKind::Mask);
|
||||
mask.unwrap_or(l).depth_at(frame)
|
||||
};
|
||||
let depths: Vec<f32> = self.layers.iter().map(|l| depth(l)).collect();
|
||||
let at = |i: usize| depths.get(i).copied().unwrap_or(0.0);
|
||||
// Stable: equal depths keep the bottom-up order. Depths are finite (clamped).
|
||||
order.sort_by(|&a, &b| at(b).total_cmp(&at(a)));
|
||||
order
|
||||
}
|
||||
|
||||
/// The camera at `frame`, when the timeline has a visible camera layer with a camera on that
|
||||
/// frame. A hidden camera layer is a camera turned off; a keyframe with no camera element is
|
||||
/// the camera at rest.
|
||||
@@ -178,8 +323,9 @@ mod tests {
|
||||
#[test]
|
||||
fn the_rest_camera_shows_the_stage_as_it_is() {
|
||||
let c = Camera::rest(&stage());
|
||||
assert_eq!(c.view(&stage(), 0.0), Affine::IDENTITY);
|
||||
assert_eq!(c.view(&stage(), 5000.0), Affine::IDENTITY, "depth only matters when the camera moves");
|
||||
assert_eq!(c.stage_view(&stage()), Affine::IDENTITY);
|
||||
assert_eq!(c.view(&stage(), 5000.0), Some(Affine::IDENTITY), "depth only matters when the camera moves");
|
||||
assert_eq!(c.view(&stage(), -400.0), Some(Affine::IDENTITY));
|
||||
assert!(c.is_rest(&stage()));
|
||||
let f = c.frame(&stage());
|
||||
assert!(close(f[2], Vec2::new(200.0, 100.0)));
|
||||
@@ -188,7 +334,7 @@ mod tests {
|
||||
#[test]
|
||||
fn zoom_doubles_sizes_about_the_camera_centre() {
|
||||
let c = Camera { center: Vec2::new(60.0, 40.0), zoom: 2.0, ..Camera::rest(&stage()) };
|
||||
let v = c.view(&stage(), 0.0);
|
||||
let v = c.stage_view(&stage());
|
||||
assert!(close(v.apply(Vec2::new(60.0, 40.0)), Vec2::new(100.0, 50.0)), "the centre lands mid-output");
|
||||
assert!(close(v.apply(Vec2::new(70.0, 40.0)), Vec2::new(120.0, 50.0)), "10 px become 20");
|
||||
// The frame sees half the stage's width.
|
||||
@@ -199,7 +345,7 @@ mod tests {
|
||||
#[test]
|
||||
fn rotation_turns_the_view_the_other_way() {
|
||||
let c = Camera { rotation: std::f32::consts::FRAC_PI_2, ..Camera::rest(&stage()) };
|
||||
let v = c.view(&stage(), 0.0);
|
||||
let v = c.stage_view(&stage());
|
||||
// A point right of the centre ends up above it (the world turns counter-clockwise).
|
||||
assert!(close(v.apply(Vec2::new(110.0, 50.0)), Vec2::new(100.0, 40.0)), "{:?}", v.apply(Vec2::new(110.0, 50.0)));
|
||||
// Round trip through the element.
|
||||
@@ -208,15 +354,83 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn depth_scales_the_pan_only() {
|
||||
let c = Camera { center: Vec2::new(150.0, 50.0), zoom: 1.5, ..Camera::rest(&stage()) };
|
||||
fn depth_zero_is_the_stage_view_bit_for_bit() {
|
||||
let c = Camera { center: Vec2::new(131.7, 12.3), zoom: 1.37, rotation: 0.41, ..Camera::rest(&stage()) };
|
||||
assert_eq!(c.view(&stage(), 0.0), Some(c.stage_view(&stage())));
|
||||
assert_eq!(c.view(&stage(), -0.0), Some(c.stage_view(&stage())));
|
||||
assert_eq!(c.view(&stage(), f32::NAN), Some(c.stage_view(&stage())), "a NaN depth is the stage plane");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pans_move_a_layer_by_the_pinhole_ratio() {
|
||||
// Analytic: a pan of 40 px at zoom 1 moves a layer at depth d by 40 · F / (F + d).
|
||||
let c = Camera { center: Vec2::new(140.0, 50.0), ..Camera::rest(&stage()) };
|
||||
for d in [-500.0_f32, -250.0, 0.0, 250.0, 1000.0, 3000.0, 10_000.0] {
|
||||
let v = c.view(&stage(), d).unwrap_or(Affine::IDENTITY);
|
||||
let moved = 100.0 - v.apply(Vec2::new(100.0, 50.0)).x;
|
||||
let want = 40.0 * FOCAL / (FOCAL + d);
|
||||
assert!((moved - want).abs() < 1e-3, "depth {d}: moved {moved}, want {want}");
|
||||
assert!((v.mean_scale() - 1.0).abs() < 1e-5, "a pan keeps sizes at every depth");
|
||||
}
|
||||
assert!((parallax(FOCAL) - 0.5).abs() < 1e-6);
|
||||
let near = c.view(&stage(), 0.0).apply(Vec2::new(150.0, 50.0));
|
||||
let far = c.view(&stage(), FOCAL).apply(Vec2::new(125.0, 50.0));
|
||||
assert!(close(near, Vec2::new(100.0, 50.0)) && close(far, Vec2::new(100.0, 50.0)), "a far layer moved half as far");
|
||||
assert!((c.view(&stage(), FOCAL).mean_scale() - 1.5).abs() < 1e-4, "zoom is the same at every depth");
|
||||
assert_eq!(clamp_depth(f32::NAN), 0.0);
|
||||
assert_eq!(clamp_depth(-1e9), MIN_DEPTH);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zooms_scale_a_deeper_layer_less() {
|
||||
// Zoom 2: the camera is F / 2 from the stage. A layer F back is 1.5 F away: it grows by
|
||||
// 2F / 1.5F = 4/3, the stage plane by 2.
|
||||
let c = Camera { zoom: 2.0, ..Camera::rest(&stage()) };
|
||||
let s = |d: f32| c.view(&stage(), d).map_or(0.0, |v| v.mean_scale());
|
||||
assert!((s(0.0) - 2.0).abs() < 1e-5);
|
||||
assert!((s(FOCAL) - 4.0 / 3.0).abs() < 1e-4, "{}", s(FOCAL));
|
||||
assert!(s(MAX_DEPTH) > 1.0 && s(MAX_DEPTH) < s(FOCAL));
|
||||
assert!(s(-250.0) > 2.0, "a nearer layer grows more");
|
||||
// The centre stays put at every depth (the zoom is about the camera's axis).
|
||||
let v = c.view(&stage(), 600.0).unwrap_or(Affine::IDENTITY);
|
||||
assert!(close(v.apply(Vec2::new(100.0, 50.0)), Vec2::new(100.0, 50.0)));
|
||||
// A layer the camera has passed isn't drawn: zoom 4 puts the camera 250 px from the
|
||||
// stage, past a layer 400 px in front.
|
||||
let past = Camera { zoom: 4.0, ..Camera::rest(&stage()) };
|
||||
assert_eq!(past.view(&stage(), -400.0), None);
|
||||
assert!(past.view(&stage(), -200.0).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn depth_keys_travel_linearly_and_hold_outside() {
|
||||
let mut l = Layer::new(crate::LayerId(1), "x");
|
||||
l.depth = 50.0;
|
||||
assert_eq!(l.depth_at(7), 50.0, "no keys: the one depth");
|
||||
l.set_depth_key(10, 100.0);
|
||||
l.set_depth_key(20, 300.0);
|
||||
assert_eq!(l.depth_at(0), 100.0);
|
||||
assert_eq!(l.depth_at(15), 200.0, "the midpoint");
|
||||
assert_eq!(l.depth_at(20), 300.0);
|
||||
assert_eq!(l.depth_at(u32::MAX), 300.0);
|
||||
l.set_depth_key(20, 1e30);
|
||||
assert_eq!(l.depth_at(20), MAX_DEPTH);
|
||||
// Hostile keys: unsorted, repeated, NaN, too many.
|
||||
l.depth_keys = vec![DepthKey { frame: 5, depth: f32::NAN }, DepthKey { frame: 1, depth: -1e9 }, DepthKey { frame: 5, depth: 7.0 }];
|
||||
assert!(l.sanitize_depth_keys());
|
||||
assert_eq!(l.depth_keys, vec![DepthKey { frame: 1, depth: MIN_DEPTH }, DepthKey { frame: 5, depth: 7.0 }]);
|
||||
assert!(!l.sanitize_depth_keys(), "already clean");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn camera_colour_effects_have_no_opacity() {
|
||||
let mut c = Camera::rest(&stage());
|
||||
c.color = ColorEffect::Brightness(0.5);
|
||||
assert_eq!(c.color(), ColorTransform::brightness(0.5));
|
||||
assert!(!c.is_rest(&stage()));
|
||||
c.color = ColorEffect::Alpha(0.2);
|
||||
assert!(c.color().is_identity() && c.is_rest(&stage()), "a camera never fades");
|
||||
let mut t = ColorTransform::IDENTITY;
|
||||
t.mul = [0.5, 1.0, 1.0, 0.1];
|
||||
t.add = [0.2, 0.0, 0.0, -0.5];
|
||||
c.color = ColorEffect::Advanced(t);
|
||||
let got = c.color();
|
||||
assert_eq!((got.mul[0], got.add[0], got.mul[3], got.add[3]), (0.5, 0.2, 1.0, 0.0));
|
||||
let back = Camera::of_element(&c.to_element(ElementId(1)), &stage());
|
||||
assert_eq!(back.color(), got);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -225,7 +439,10 @@ mod tests {
|
||||
el.transform = Affine { m: [f32::NAN, 0.0, 0.0, f32::INFINITY, f32::NAN, 1e30] };
|
||||
el.color = ColorEffect::Tint { color: Rgba::WHITE, amount: f32::NAN };
|
||||
let c = Camera::of_element(&el, &stage());
|
||||
assert!(c.view(&stage(), 0.0).is_finite());
|
||||
assert!(c.stage_view(&stage()).is_finite());
|
||||
for d in [f32::NAN, f32::INFINITY, -1e30, 1e30, MIN_DEPTH, MAX_DEPTH] {
|
||||
assert!(c.view(&stage(), d).is_none_or(|v| v.is_finite()));
|
||||
}
|
||||
assert!((MIN_ZOOM..=MAX_ZOOM).contains(&c.zoom));
|
||||
el.transform = Affine::scale(0.0, 0.0);
|
||||
assert_eq!(Camera::of_element(&el, &stage()).zoom, MIN_ZOOM);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Evaluation through the camera layer (ADR 0027).
|
||||
|
||||
use crate::camera::{Camera, FOCAL, MAX_DEPTH};
|
||||
use crate::camera::{Camera, DepthKey, FOCAL, MAX_DEPTH};
|
||||
use crate::{ColorEffect, Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, LayerKind, MotionTween, Paint, Property, Rgba, Shape, Symbol, SymbolId, SymbolKind, Timeline, Tween, evaluate, evaluate_scene};
|
||||
use anicraft_geom::{Affine, Path, Vec2};
|
||||
use std::sync::Arc;
|
||||
@@ -64,7 +64,7 @@ fn a_camera_zoom_doubles_sizes_about_its_centre_and_editing_keeps_stage_space()
|
||||
#[test]
|
||||
fn camera_rotation_and_tint_apply_to_the_whole_view() {
|
||||
let mut d = one_square();
|
||||
let cam = Camera { rotation: std::f32::consts::FRAC_PI_2, tint: Rgba::hex(0xff0000), tint_amount: 0.5, ..Camera::rest(&d.stage) };
|
||||
let cam = Camera { rotation: std::f32::consts::FRAC_PI_2, color: ColorEffect::Tint { color: Rgba::hex(0xff0000), amount: 0.5 }, ..Camera::rest(&d.stage) };
|
||||
with_camera(&mut d, &[(0, 20, cam, false)]);
|
||||
let i = &evaluate(&d, 0).items[0];
|
||||
// Stage point (105, 50) is right of the centre; the camera turned clockwise, so it shows
|
||||
@@ -171,3 +171,113 @@ fn a_keyframe_without_a_camera_is_the_camera_at_rest() {
|
||||
assert!(d.timeline(0).camera_at(0, &d.stage).is_none());
|
||||
assert_eq!(evaluate(&d, 0).items[0].transform, Affine::translate(95.0, 0.0));
|
||||
}
|
||||
|
||||
/// Each item's x translation by element id.
|
||||
fn xs(dl: &crate::DisplayList, id: u64) -> f32 {
|
||||
dl.items.iter().find(|i| i.element == ElementId(id)).map_or(f32::NAN, |i| i.transform.translation().x)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layers_at_depth_zero_are_bit_exact_through_any_camera() {
|
||||
// The same scene with and without a deep layer elsewhere: the stage-plane layer's item is
|
||||
// identical, bit for bit, to what the camera's stage view gives it.
|
||||
let mut d = one_square();
|
||||
let cam = Camera { center: Vec2::new(123.4, 56.7), zoom: 1.7, rotation: 0.3, ..Camera::rest(&d.stage) };
|
||||
with_camera(&mut d, &[(0, 20, cam, false)]);
|
||||
let before = evaluate(&d, 0).items[0].transform;
|
||||
let want = cam.stage_view(&d.stage).mul(&Affine::translate(95.0, 0.0));
|
||||
assert!(before.m.iter().zip(want.m).all(|(a, b)| (a - b).abs() < 1e-3), "the stage view: {before:?}");
|
||||
let mut back = art_layer(50, square(11, 0.0));
|
||||
back.depth = 400.0;
|
||||
d.timeline_mut(0).layers.push(Arc::new(back));
|
||||
let after = evaluate(&d, 0);
|
||||
let it = after.items.iter().find(|i| i.element == ElementId(10)).unwrap();
|
||||
assert_eq!(it.transform.m, before.m);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pan_moves_layers_by_their_parallax_and_attached_layers_stay() {
|
||||
let mut d = one_square();
|
||||
let mut mid = art_layer(40, square(11, 95.0));
|
||||
mid.depth = 250.0;
|
||||
let mut far = art_layer(50, square(12, 95.0));
|
||||
far.depth = 3000.0;
|
||||
let mut hud = art_layer(60, square(13, 95.0));
|
||||
hud.attached = true;
|
||||
hud.depth = 900.0;
|
||||
d.timeline_mut(0).layers.extend([Arc::new(mid), Arc::new(far)]);
|
||||
d.timeline_mut(0).layers.insert(0, Arc::new(hud));
|
||||
let cam = Camera { center: Vec2::new(150.0, 50.0), ..Camera::rest(&d.stage) };
|
||||
with_camera(&mut d, &[(0, 20, cam, false)]);
|
||||
let dl = evaluate(&d, 0);
|
||||
// A pan of 50 px moves a layer at depth d by 50 · F / (F + d).
|
||||
for (id, depth) in [(10, 0.0), (11, 250.0), (12, 3000.0)] {
|
||||
let moved = 95.0 - xs(&dl, id);
|
||||
let want = 50.0 * FOCAL / (FOCAL + depth);
|
||||
assert!((moved - want).abs() < 1e-3, "{id}: moved {moved}, want {want}");
|
||||
}
|
||||
assert_eq!(xs(&dl, 13), 95.0, "the attached layer stays where it is on screen");
|
||||
// While editing, every layer is in stage space.
|
||||
let edit = evaluate_scene(&d, 0, 0);
|
||||
assert!([10, 11, 12, 13].iter().all(|&id| xs(&edit, id) == 95.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deeper_layers_draw_first_ties_in_timeline_order() {
|
||||
let mut d = one_square();
|
||||
// Top to bottom: 10 (depth 0), 11 (depth 500), 12 (depth 0), 13 (depth 500).
|
||||
let deep = |id, el| {
|
||||
let mut l = art_layer(id, el);
|
||||
l.depth = 500.0;
|
||||
Arc::new(l)
|
||||
};
|
||||
d.timeline_mut(0).layers.extend([deep(40, square(11, 0.0)), Arc::new(art_layer(50, square(12, 0.0))), deep(60, square(13, 0.0))]);
|
||||
let ids = |dl: &crate::DisplayList| dl.items.iter().map(|i| i.element.0).collect::<Vec<_>>();
|
||||
assert_eq!(ids(&evaluate_scene(&d, 0, 0)), [13, 11, 12, 10], "the deep pair first, each pair bottom-up");
|
||||
assert_eq!(ids(&evaluate(&d, 0)), [13, 11, 12, 10], "the movie stacks as the stage does");
|
||||
// All at depth 0: the timeline order, as always.
|
||||
for l in &mut d.timeline_mut(0).layers {
|
||||
Arc::make_mut(l).depth = 0.0;
|
||||
}
|
||||
assert_eq!(ids(&evaluate_scene(&d, 0, 0)), [13, 12, 11, 10]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_depth_tween_is_halfway_at_its_midpoint() {
|
||||
let mut d = one_square();
|
||||
let l = Arc::make_mut(&mut d.timeline_mut(0).layers[0]);
|
||||
l.depth_keys = vec![DepthKey { frame: 0, depth: 0.0 }, DepthKey { frame: 10, depth: 2000.0 }];
|
||||
let cam = Camera { center: Vec2::new(140.0, 50.0), ..Camera::rest(&d.stage) };
|
||||
with_camera(&mut d, &[(0, 20, cam, false)]);
|
||||
assert_eq!(d.timeline(0).layers[1].depth_at(5), 1000.0);
|
||||
// At frame 5 the layer is 1,000 px back: the 40 px pan moves it 20.
|
||||
assert!((xs(&evaluate(&d, 5), 10) - 75.0).abs() < 1e-3);
|
||||
assert!((xs(&evaluate(&d, 0), 10) - 55.0).abs() < 1e-3);
|
||||
// Keys and attachment round-trip; older files read without them, and they are left out
|
||||
// when unused.
|
||||
let mut l = Layer::new(LayerId(5), "x");
|
||||
let plain = serde_json::to_string(&l).unwrap();
|
||||
assert!(!plain.contains("depth_keys") && !plain.contains("attached"));
|
||||
l.depth_keys = vec![DepthKey { frame: 3, depth: 120.5 }];
|
||||
l.attached = true;
|
||||
let back: Layer = serde_json::from_str(&serde_json::to_string(&l).unwrap()).unwrap();
|
||||
assert_eq!(back, l);
|
||||
let old: Layer = serde_json::from_str(r#"{"id":5,"name":"x","depth":40}"#).unwrap();
|
||||
assert!(old.depth_keys.is_empty() && !old.attached && old.depth_at(9) == 40.0);
|
||||
// Hostile keys on load are sorted and clamped.
|
||||
let mut d2 = Document::default();
|
||||
Arc::make_mut(&mut d2.timeline_mut(0).layers[0]).depth_keys = vec![DepthKey { frame: 9, depth: f32::NAN }, DepthKey { frame: 2, depth: 1e20 }];
|
||||
d2.sanitize();
|
||||
assert_eq!(d2.timeline(0).layers[0].depth_keys, vec![DepthKey { frame: 2, depth: MAX_DEPTH }, DepthKey { frame: 9, depth: 0.0 }]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_camera_brightness_colours_the_whole_view() {
|
||||
let mut d = one_square();
|
||||
let cam = Camera { color: ColorEffect::Brightness(-0.5), ..Camera::rest(&d.stage) };
|
||||
with_camera(&mut d, &[(0, 20, cam, false)]);
|
||||
assert!(d.timeline(0).camera_at(0, &d.stage).is_some(), "a colour alone is a camera that does something");
|
||||
let i = &evaluate(&d, 0).items[0];
|
||||
assert_eq!(i.transform, Affine::translate(95.0, 0.0), "nothing moved");
|
||||
assert_eq!(i.color, crate::ColorTransform::brightness(-0.5));
|
||||
}
|
||||
+16
-3
@@ -465,7 +465,13 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut
|
||||
let clip_of = |id: LayerId| clips.iter().find(|(l, _)| *l == id).map(|(_, c)| *c);
|
||||
// Folders draw nothing, and a hidden folder hides everything in it.
|
||||
let has_folders = tl.layers.iter().any(|l| l.kind == LayerKind::Folder);
|
||||
for (index, layer) in tl.layers.iter().enumerate().rev() {
|
||||
// Deepest first, ties in timeline order (ADR 0082); depth belongs to a scene's own layers.
|
||||
// (Only sorted when some layer has a depth: nested timelines allocate nothing.)
|
||||
let sorted = (cx.depth == 0 && tl.layers.iter().any(|l| l.has_depth())).then(|| tl.draw_order(frame));
|
||||
let n = tl.layers.len();
|
||||
for k in 0..n {
|
||||
let index = sorted.as_ref().map_or(n - 1 - k, |o| o.get(k).copied().unwrap_or(n));
|
||||
let Some(layer) = tl.layers.get(index) else { continue };
|
||||
// Guide artwork is listed (marked, for editing) but never drawn; inside mask artwork
|
||||
// it plays no part at all.
|
||||
let is_guide = layer.kind == LayerKind::Guide;
|
||||
@@ -484,8 +490,15 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut
|
||||
let walk = layer.parent.and_then(|p| tl.layer(p)).filter(|g| g.kind == LayerKind::Guide).and_then(|g| guide_walk(g, frame));
|
||||
let Some((kf_start, elements)) = evaluate_guided(layer, frame, walk.as_ref()) else { continue };
|
||||
let layer_outline = cx.outline.or(if layer.outline && cx.stage { Some(layer.color) } else { None });
|
||||
// Through a camera, each layer is placed by the camera and its own depth.
|
||||
let layer_xf = cx.camera.map_or(cx.xf, |c| c.view(&doc.stage, layer.depth));
|
||||
// Through a camera, each layer is placed by the camera and its own depth (an attached
|
||||
// layer stays put); a layer the camera has passed isn't drawn.
|
||||
let layer_xf = match cx.camera {
|
||||
Some(c) => match c.layer_view(&doc.stage, layer, frame) {
|
||||
Some(v) => v,
|
||||
None => continue,
|
||||
},
|
||||
None => cx.xf,
|
||||
};
|
||||
let lc = LayerCtx { layer, frame, kf_start, clip, masks, guide, outline: layer_outline, xf: layer_xf };
|
||||
for el in elements.iter() {
|
||||
eval_element(doc, cx, &lc, el, out, play);
|
||||
|
||||
+18
-2
@@ -42,7 +42,7 @@ pub use motion::{MotionTween, OnPath, PROPERTIES, Pin, PinError, Property, Prope
|
||||
pub use sound::{EnvelopePoint, FrameSound, Sound, SoundEffect, SoundFormat, SoundId, SoundSync};
|
||||
pub use width::{MAX_WIDTH_FACTOR, MAX_WIDTH_POINTS, ProfilePreset, WidthPoint, WidthProfile};
|
||||
pub use stroke_style::{Cap, Dash, DashKind, Join, StrokeStyle};
|
||||
pub use camera::Camera;
|
||||
pub use camera::{Camera, DepthKey};
|
||||
pub use swatch::{MAX_SWATCHES, Swatch, SwatchPaint};
|
||||
pub use aids::{Aids, GUIDE_REACH, Grid, Guide, GuideAxis, MAX_GUIDES};
|
||||
pub use nine_slice::symbol_box;
|
||||
@@ -1138,6 +1138,14 @@ pub struct Layer {
|
||||
/// move a deeper layer less (parallax). Not the nesting depth ([`Timeline::depth`]).
|
||||
#[serde(default, skip_serializing_if = "is_zero")]
|
||||
pub depth: f32,
|
||||
/// Depth over time (ADR 0082): with keys, the depth at a frame is theirs
|
||||
/// ([`Layer::depth_at`]) and `depth` plays no part. Sorted by frame, one per frame.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub depth_keys: Vec<camera::DepthKey>,
|
||||
/// Attached to the camera (ADR 0082): the camera's moves leave the layer where it is on
|
||||
/// screen (titles, HUDs); its coordinates are the output's.
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub attached: bool,
|
||||
/// Volume of the sounds on this layer (and in the symbols on it), `0..=1` (ADR 0039).
|
||||
#[serde(default = "full", skip_serializing_if = "is_full")]
|
||||
pub volume: f32,
|
||||
@@ -1235,6 +1243,8 @@ impl PartialEq for Layer {
|
||||
&& self.onion == o.onion
|
||||
&& self.height_rows == o.height_rows
|
||||
&& self.depth.to_bits() == o.depth.to_bits()
|
||||
&& self.depth_keys == o.depth_keys
|
||||
&& self.attached == o.attached
|
||||
&& self.volume.to_bits() == o.volume.to_bits()
|
||||
&& self.muted == o.muted
|
||||
&& self.mask_mode == o.mask_mode
|
||||
@@ -1268,6 +1278,8 @@ impl Layer {
|
||||
height_rows: 1,
|
||||
keyframes: vec![Arc::new(Keyframe::new(0, 1))],
|
||||
depth: 0.0,
|
||||
depth_keys: Vec::new(),
|
||||
attached: false,
|
||||
volume: 1.0,
|
||||
muted: false,
|
||||
armature: None,
|
||||
@@ -2039,12 +2051,16 @@ fn sanitize_warps(layer: &mut Arc<Layer>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps a loaded layer's depth finite and in range (touching it only if it isn't).
|
||||
/// Keeps a loaded layer's depth and depth keys finite and in range (touching it only if they
|
||||
/// aren't).
|
||||
fn sanitize_depth(layer: &mut Arc<Layer>) {
|
||||
let d = camera::clamp_depth(layer.depth);
|
||||
if d.to_bits() != layer.depth.to_bits() {
|
||||
Arc::make_mut(layer).depth = d;
|
||||
}
|
||||
if !layer.depth_keys_clean() {
|
||||
Arc::make_mut(layer).sanitize_depth_keys();
|
||||
}
|
||||
}
|
||||
|
||||
/// Repairs a loaded layer's armature (ADR 0043): only an armature layer has one, its bones are
|
||||
|
||||
@@ -560,7 +560,13 @@ fn walk(doc: &Document, st: &PlayerState, tl: &Timeline, frame: u32, parent: usi
|
||||
}
|
||||
let base: InstancePath = out.get(parent).map(|n| n.path.clone()).unwrap_or_default();
|
||||
let parent_gain = out.get(parent).map_or(1.0, |n| n.gain);
|
||||
for (index, layer) in tl.layers.iter().enumerate().rev() {
|
||||
// Drawn deepest first (ADR 0082), so the topmost hit is the one drawn last.
|
||||
// (Only sorted when some layer has a depth: nested timelines allocate nothing.)
|
||||
let sorted = (depth == 1 && tl.layers.iter().any(|l| l.has_depth())).then(|| tl.draw_order(frame));
|
||||
let n = tl.layers.len();
|
||||
for k in 0..n {
|
||||
let index = sorted.as_ref().map_or(n - 1 - k, |o| o.get(k).copied().unwrap_or(n));
|
||||
let Some(layer) = tl.layers.get(index) else { continue };
|
||||
if !plays(tl, index) {
|
||||
continue;
|
||||
}
|
||||
@@ -568,7 +574,13 @@ fn walk(doc: &Document, st: &PlayerState, tl: &Timeline, frame: u32, parent: usi
|
||||
let hit = hittable && layer.kind != LayerKind::Mask;
|
||||
let path_walk = layer.parent.and_then(|p| tl.layer(p)).filter(|g| g.kind == LayerKind::Guide).and_then(|g| guide_walk(g, frame));
|
||||
let Some((kf_start, els)) = evaluate_guided(layer, frame, path_walk.as_ref()) else { continue };
|
||||
let layer_xf = camera.map_or(xf, |c| c.view(&doc.stage, layer.depth));
|
||||
let layer_xf = match camera {
|
||||
Some(c) => match c.layer_view(&doc.stage, layer, frame) {
|
||||
Some(v) => v,
|
||||
None => continue,
|
||||
},
|
||||
None => xf,
|
||||
};
|
||||
// Instances inside a group belong to the group's timeline (ADR 0073).
|
||||
let els = crate::expand_groups(&els).into_owned();
|
||||
for el in els.iter() {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Camera commands (ADR 0027): add and remove the scene's camera layer, set the camera at a
|
||||
//! frame (pan, zoom, rotation, tint), read it back, and give layers a depth for parallax.
|
||||
//! frame (pan, zoom, rotation, colour effect), read it back, give layers a depth (keyable over
|
||||
//! time) for perspective, and attach layers to the camera (ADR 0027, 0082).
|
||||
//!
|
||||
//! `camera.set` edits the camera like any instance: through [`Session::editable_keyframe`], so
|
||||
//! inside a classic tween it keys the playhead and inside a motion tween it becomes property
|
||||
@@ -23,12 +24,23 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Camera",
|
||||
"",
|
||||
None,
|
||||
"{x?, y? (camera centre, stage px), dx?, dy? (pan by), zoom? (%, 5–2000), zoom_by? (factor), rotation? (°), rotate_by? (°), tint? (#rrggbb), tint_amount? (%), reset?: bool, frame?}",
|
||||
"{x?, y? (camera centre, stage px), dx?, dy? (pan by), zoom? (%, 5–2000), zoom_by? (factor), rotation? (°), rotate_by? (°), reset?: bool, frame?, and the colour effect as element.set_color_effect takes it: style?: none|brightness|tint|advanced, brightness? (%), tint? (#rrggbb), tint_amount? (%), red_multiplier? … blue_offset? (the camera has no opacity: no alpha values)}",
|
||||
true,
|
||||
set,
|
||||
),
|
||||
c("camera.info", "Camera Info", "", None, "{frame?} → the camera at the frame (x, y, zoom %, rotation °, tint) and its frame on the stage", false, info),
|
||||
c("layer.set_depth", "Layer Depth", "", None, "{depth (px behind the stage, −500…10000; deeper layers move less when the camera pans), layer?}", true, set_depth),
|
||||
c(
|
||||
"layer.set_depth",
|
||||
"Layer Depth",
|
||||
"",
|
||||
None,
|
||||
"{depth (px behind the stage, −500…10000; through the camera a deeper layer moves and scales less, and draws behind nearer ones), layer?, key?: bool (default: whether the layer's depth is keyed), frame? (default: the playhead)} with `key` sets a depth key at the frame (the first key away from frame 0 also keys frame 0 with the depth it had), so the depth tweens linearly between keys; `key: false` makes the depth one value again (ADR 0082)",
|
||||
true,
|
||||
set_depth,
|
||||
),
|
||||
c("layer.remove_depth_key", "Remove Depth Key", "", None, "{layer?, frame? (default: the playhead)} removes the layer's depth key at the frame; removing the last one leaves the depth it had there", true, remove_depth_key),
|
||||
c("layer.set_attached", "Attach Layer to Camera", "", None, "{attached?: bool (default: toggles), layer?} an attached layer stays where it is on screen while the camera moves (titles, HUDs); its depth plays no part (ADR 0082)", true, set_attached),
|
||||
c("layer.depths", "Layer Depths", "", None, "{frame?} → {camera: bool, layers: [{layer, name, depth, keyed, key_here, attached}]} the layers that can have a depth, nearest first (ties in timeline order), at the frame", false, depths),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -113,8 +125,10 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let num = |k: &str| opt_f32(p, k);
|
||||
let (x, y, dx, dy) = (num("x")?, num("y")?, num("dx")?, num("dy")?);
|
||||
let (zoom, zoom_by, rotation, rotate_by) = (num("zoom")?, num("zoom_by")?, num("rotation")?, num("rotate_by")?);
|
||||
let tint = opt_color(p, "tint")?;
|
||||
let tint_amount = num("tint_amount")?;
|
||||
let effect = crate::cmds_draw::EffectEdit::parse(p)?;
|
||||
if effect.as_ref().is_some_and(|e| e.touches_alpha()) {
|
||||
return Err(EngineError::Param("the camera has no opacity: give brightness, tint or advanced colour values (no alpha)".into()));
|
||||
}
|
||||
let reset = opt_bool(p, "reset")?.unwrap_or(false);
|
||||
if let Some(z) = zoom
|
||||
&& !(MIN_ZOOM * 100.0..=MAX_ZOOM * 100.0).contains(&z)
|
||||
@@ -124,9 +138,6 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if zoom_by.is_some_and(|f| f <= 0.0) {
|
||||
return Err(EngineError::Param("param 'zoom_by' must be above 0".into()));
|
||||
}
|
||||
if tint_amount.is_some_and(|a| !(0.0..=100.0).contains(&a)) {
|
||||
return Err(EngineError::Param("param 'tint_amount' must be between 0 and 100 (%)".into()));
|
||||
}
|
||||
let stage = s.doc.stage;
|
||||
// A camera is created on a keyframe that has none (a blank camera keyframe is at rest).
|
||||
// (Its id is taken only when it is used, so a no-op leaves the document unchanged.)
|
||||
@@ -157,11 +168,8 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
c.rotation = r.to_radians();
|
||||
}
|
||||
c.rotation += rotate_by.unwrap_or(0.0).to_radians();
|
||||
if let Some(t) = tint {
|
||||
c.tint = t.with_alpha(1.0);
|
||||
}
|
||||
if let Some(a) = tint_amount {
|
||||
c.tint_amount = a / 100.0;
|
||||
if let Some(e) = &effect {
|
||||
c.color = camera::camera_effect(&e.apply(&c.color));
|
||||
}
|
||||
// Keep the centre on a sane plane (a long drag can't fling it to infinity).
|
||||
let lim = 1_000_000.0;
|
||||
@@ -183,7 +191,7 @@ fn camera_json(c: &Camera, stage: &anicraft_doc::Stage) -> Value {
|
||||
let f = c.frame(stage);
|
||||
json!({
|
||||
"x": c.center.x, "y": c.center.y, "zoom": c.zoom * 100.0, "rotation": c.rotation.to_degrees(),
|
||||
"tint": c.tint.to_hex(), "tint_amount": c.tint_amount * 100.0,
|
||||
"color_effect": crate::color_effect_json(&c.color),
|
||||
"frame": f.iter().map(|p| json!([p.x, p.y])).collect::<Vec<_>>(),
|
||||
})
|
||||
}
|
||||
@@ -200,16 +208,86 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// The layer a depth or attachment command acts on: a scene's layer with artwork.
|
||||
fn depth_layer<'a>(s: &'a mut Session, p: &Value) -> Result<&'a mut Layer> {
|
||||
// Depth belongs to a scene's own layers; artwork inside a symbol moves with its instance.
|
||||
if !s.editing.is_empty() {
|
||||
return Err(EngineError::State("layer depth belongs to a scene's layers: close the symbol you are editing first (Edit › Edit Document)".into()));
|
||||
}
|
||||
let lid = opt_u64(p, "layer")?.map(LayerId);
|
||||
let layer = s.layer_mut(lid)?;
|
||||
if !has_depth_kind(layer.kind) {
|
||||
return Err(EngineError::State(format!("'{}' has no depth of its own (only layers with artwork do)", layer.name)));
|
||||
}
|
||||
Ok(layer)
|
||||
}
|
||||
|
||||
/// Whether a layer of this kind has a depth (and can be attached to the camera).
|
||||
fn has_depth_kind(kind: LayerKind) -> bool {
|
||||
!matches!(kind, LayerKind::Camera | LayerKind::Folder | LayerKind::Guide)
|
||||
}
|
||||
|
||||
fn set_depth(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let depth = f32_req(p, "depth")?;
|
||||
if !(camera::MIN_DEPTH..=camera::MAX_DEPTH).contains(&depth) {
|
||||
return Err(EngineError::Param(format!("param 'depth' must be between {} and {}", camera::MIN_DEPTH, camera::MAX_DEPTH)));
|
||||
}
|
||||
let lid = opt_u64(p, "layer")?.map(LayerId);
|
||||
let layer = s.layer_mut(lid)?;
|
||||
if matches!(layer.kind, LayerKind::Camera | LayerKind::Folder) {
|
||||
return Err(EngineError::State(format!("'{}' has no depth of its own (only layers with artwork do)", layer.name)));
|
||||
let key = opt_bool(p, "key")?;
|
||||
let frame = opt_u32(p, "frame")?.unwrap_or(s.frame);
|
||||
if frame > MAX_FRAME {
|
||||
return Err(EngineError::Param(format!("param 'frame' must be at most {MAX_FRAME}")));
|
||||
}
|
||||
layer.depth = depth;
|
||||
Ok(json!({"layer": layer.id.0, "depth": depth}))
|
||||
let layer = depth_layer(s, p)?;
|
||||
let keyed = key.unwrap_or(!layer.depth_keys.is_empty());
|
||||
if keyed {
|
||||
if layer.depth_keys.len() >= camera::MAX_DEPTH_KEYS && layer.depth_keys.binary_search_by_key(&frame, |k| k.frame).is_err() {
|
||||
return Err(EngineError::State(format!("a layer keeps at most {} depth keys", camera::MAX_DEPTH_KEYS)));
|
||||
}
|
||||
// The first key: what came before keeps the depth the layer had.
|
||||
if layer.depth_keys.is_empty() && frame > 0 && layer.depth != depth {
|
||||
let was = layer.depth;
|
||||
layer.set_depth_key(0, was);
|
||||
}
|
||||
layer.set_depth_key(frame, depth);
|
||||
layer.depth = 0.0;
|
||||
} else {
|
||||
layer.depth_keys.clear();
|
||||
layer.depth = depth;
|
||||
}
|
||||
Ok(json!({"layer": layer.id.0, "depth": depth, "keyed": keyed, "keys": layer.depth_keys.len()}))
|
||||
}
|
||||
|
||||
fn remove_depth_key(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let frame = opt_u32(p, "frame")?.unwrap_or(s.frame);
|
||||
let layer = depth_layer(s, p)?;
|
||||
let i = layer.depth_keys.binary_search_by_key(&frame, |k| k.frame).map_err(|_| EngineError::State(format!("'{}' has no depth key on frame {}", layer.name, frame.saturating_add(1))))?;
|
||||
let here = layer.depth_at(frame);
|
||||
layer.depth_keys.remove(i);
|
||||
if layer.depth_keys.is_empty() {
|
||||
layer.depth = here;
|
||||
}
|
||||
Ok(json!({"layer": layer.id.0, "keys": layer.depth_keys.len(), "depth": layer.depth_at(frame)}))
|
||||
}
|
||||
|
||||
fn set_attached(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let on = opt_bool(p, "attached")?;
|
||||
let layer = depth_layer(s, p)?;
|
||||
layer.attached = on.unwrap_or(!layer.attached);
|
||||
Ok(json!({"layer": layer.id.0, "attached": layer.attached}))
|
||||
}
|
||||
|
||||
fn depths(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let frame = opt_u32(p, "frame")?.unwrap_or(s.frame).min(MAX_FRAME);
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
let mut rows: Vec<(usize, &Layer)> = tl.layers.iter().enumerate().filter(|(_, l)| has_depth_kind(l.kind)).map(|(i, l)| (i, &**l)).collect();
|
||||
// Nearest first; ties in timeline order (top first).
|
||||
rows.sort_by(|a, b| a.1.depth_at(frame).total_cmp(&b.1.depth_at(frame)).then(a.0.cmp(&b.0)));
|
||||
let layers: Vec<Value> = rows
|
||||
.iter()
|
||||
.map(|(_, l)| {
|
||||
let key_here = l.depth_keys.iter().any(|k| k.frame == frame);
|
||||
json!({"layer": l.id.0, "name": l.name, "depth": l.depth_at(frame), "keyed": !l.depth_keys.is_empty(), "key_here": key_here, "attached": l.attached})
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({"camera": tl.camera_layer().is_some(), "layers": layers}))
|
||||
}
|
||||
@@ -24,13 +24,13 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
c("edit.delete", "Clear", "Edit", Some("Delete"), "{} (on every layer with selected items)", true, delete_selection),
|
||||
c("edit.duplicate", "Duplicate", "Edit", Some("Ctrl+D"), "{dx?, dy?} (each copy on its original's layer)", true, |s, p| s.each_layer(true, |s| duplicate(s, p))),
|
||||
c("element.select", "Select Elements", "", None, "{ids: [..], add?: bool, toggle?: bool, layer?} selects elements on any visible, unlocked layer at the playhead (ids are unique; `layer` looks only there); `toggle` takes each one that is selected out of the selection and adds the others (Shift+Space on a stage element); the active layer becomes the first one's unless it has some of them", false, select),
|
||||
c("element.pick", "Select at Point", "", None, "{x, y, add?: bool} the topmost element there on a visible, unlocked layer; `add` (Shift) adds it to the selection, or lets go of it, on any layer", false, pick),
|
||||
c("element.pick", "Select at Point", "", None, "{x, y, add?: bool, view?: stage|camera} the topmost element there on a visible, unlocked layer; `add` (Shift) adds it to the selection, or lets go of it, on any layer; with `view: camera` the point is on the movie's picture as the camera shows it (each layer through its depth)", false, pick),
|
||||
c("element.translate", "Move", "", None, "{dx, dy, snap?, from?: [x, y]} moves the selection, on every layer; with `snap` (a distance) one of its corners or ends, or its box's corners or centre (the nearest to `from`), then snaps within that distance by the snap engine's priority (ADR 0076): a point, guide, line or fill edge of the rest, the grid, a whole pixel", true, translate),
|
||||
c("element.set_transform", "Transform", "", None, "{x?, y?, sx?, sy?, rotation? (degrees)}", true, |s, p| s.each_layer(true, |s| set_transform(s, p))),
|
||||
c("element.set_fill", "Fill Colour", "", None, "{color: \"#rrggbb\" | null}", true, |s, p| s.each_layer(false, |s| set_fill(s, p))),
|
||||
c("element.set_stroke", "Stroke", "", None, "{color?: \"#rrggbb\" | null, width?, profile?: uniform|taper_both|taper_start|taper_end|bulge|pinch | [[t, left, right], ..], cap?, join?, miter?, style?, dash?, dash_offset?, dot_spacing? (as stroke.set_style)}", true, |s, p| s.each_layer(false, |s| set_stroke(s, p))),
|
||||
c("element.set_alpha", "Alpha", "", None, "{alpha: 0..1} sets the alpha multiplier and keeps the rest of the colour effect (None becomes Alpha; Brightness and Tint become Advanced below 1)", true, |s, p| s.each_layer(true, |s| set_alpha(s, p))),
|
||||
c("element.set_color_effect", "Colour Effect", "", None, "{style?: none|brightness|tint|advanced|alpha (default: the style the values belong to, else each element's own), alpha? (%, 0..100), brightness? (%, -100..100), tint? (#rrggbb), tint_amount? (%, 0..100), red_multiplier?, green_multiplier?, blue_multiplier?, alpha_multiplier? (%, -100..100), red_offset?, green_offset?, blue_offset?, alpha_offset? (-255..255)} on every selected element (ADR 0056); values not given keep each element's own. A new style starts from the look it can keep: Advanced is exactly the effect before, Alpha keeps the opacity, Brightness and Tint start at 0 %. The camera's effect is a tint", true, |s, p| s.each_layer(true, |s| set_color_effect(s, p))),
|
||||
c("element.set_color_effect", "Colour Effect", "", None, "{style?: none|brightness|tint|advanced|alpha (default: the style the values belong to, else each element's own), alpha? (%, 0..100), brightness? (%, -100..100), tint? (#rrggbb), tint_amount? (%, 0..100), red_multiplier?, green_multiplier?, blue_multiplier?, alpha_multiplier? (%, -100..100), red_offset?, green_offset?, blue_offset?, alpha_offset? (-255..255)} on every selected element (ADR 0056); values not given keep each element's own. A new style starts from the look it can keep: Advanced is exactly the effect before, Alpha keeps the opacity, Brightness and Tint start at 0 %. The camera has no opacity (no Alpha style, alpha multiplier or offset)", true, |s, p| s.each_layer(true, |s| set_color_effect(s, p))),
|
||||
c("element.set_blend", "Blending", "", None, "{mode: normal|layer|darken|multiply|lighten|screen|overlay|hardlight|add|subtract|difference|invert|alpha|erase} on the selected movie clip and button instances", true, |s, p| s.each_layer(false, |s| set_blend(s, p))),
|
||||
c("element.set_filters", "Filters", "", None, "{filters: [{type: blur|drop_shadow|glow|bevel|gradient_glow|gradient_bevel|adjust_color, …values}]} replaces the selected movie clip and button instances' filters (in order; [] removes them). Bevel: shadow_color, highlight_color, side: inner|outer|full, knockout; gradient filters: stops: [{offset 0..1, color \"#rrggbbaa\"}] (Gradient Glow's start and Gradient Bevel's middle stay transparent)", true, |s, p| s.each_layer(false, |s| set_filters(s, p))),
|
||||
c("element.set_loop", "Looping", "", None, "{loop?: loop|play_once|single_frame, first_frame?}", true, |s, p| s.each_layer(false, |s| set_loop(s, p))),
|
||||
@@ -282,7 +282,13 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn pick(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let pt = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?);
|
||||
let add = opt_bool(p, "add")?.unwrap_or(false);
|
||||
match s.hit_test(pt, 2.0) {
|
||||
// `view: "camera"`: the point is on the movie's picture, seen through the camera (ADR 0082).
|
||||
let through = match opt_str(p, "view")? {
|
||||
None | Some("stage") => false,
|
||||
Some("camera") => true,
|
||||
Some(v) => return Err(EngineError::Param(format!("unknown view '{v}' (stage or camera)"))),
|
||||
};
|
||||
match if through { s.hit_test_camera(pt, 2.0) } else { s.hit_test(pt, 2.0) } {
|
||||
Some((layer, el)) => {
|
||||
// Shift adds it to (or takes it from) the selection, whichever layers that is on.
|
||||
if add {
|
||||
@@ -462,45 +468,60 @@ const EFFECT_VALUES: [(&str, ColorStyle, f32, f32, f32); 11] = [
|
||||
("alpha_offset", ColorStyle::Advanced, -255.0, 255.0, 255.0),
|
||||
];
|
||||
|
||||
fn set_color_effect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let style = match opt_str(p, "style")? {
|
||||
Some(k) => Some(ColorStyle::from_key(k).ok_or_else(|| EngineError::Param(format!("unknown style '{k}' (none, brightness, tint, advanced or alpha)")))?),
|
||||
None => None,
|
||||
};
|
||||
let tint = opt_color(p, "tint")?;
|
||||
let mut values: Vec<(usize, f32)> = Vec::new();
|
||||
let mut families: Vec<ColorStyle> = tint.map(|_| ColorStyle::Tint).into_iter().collect();
|
||||
for (i, (key, fam, lo, hi, scale)) in EFFECT_VALUES.iter().enumerate() {
|
||||
if let Some(v) = opt_f32(p, key)? {
|
||||
if !(*lo..=*hi).contains(&v) {
|
||||
return Err(EngineError::Param(format!("param '{key}' must be between {lo} and {hi}")));
|
||||
}
|
||||
values.push((i, v / scale));
|
||||
if !families.contains(fam) {
|
||||
families.push(*fam);
|
||||
/// A colour effect change as `element.set_color_effect` and `camera.set` take it (ADR 0056):
|
||||
/// a style, values in percent (or −255..255 for offsets), or both.
|
||||
pub(crate) struct EffectEdit {
|
||||
style: Option<ColorStyle>,
|
||||
tint: Option<anicraft_doc::Rgba>,
|
||||
values: Vec<(usize, f32)>,
|
||||
}
|
||||
|
||||
impl EffectEdit {
|
||||
/// The change `p` asks for; `None` when it names no style and no value.
|
||||
pub(crate) fn parse(p: &Value) -> Result<Option<EffectEdit>> {
|
||||
let style = match opt_str(p, "style")? {
|
||||
Some(k) => Some(ColorStyle::from_key(k).ok_or_else(|| EngineError::Param(format!("unknown style '{k}' (none, brightness, tint, advanced or alpha)")))?),
|
||||
None => None,
|
||||
};
|
||||
let tint = opt_color(p, "tint")?;
|
||||
let mut values: Vec<(usize, f32)> = Vec::new();
|
||||
let mut families: Vec<ColorStyle> = tint.map(|_| ColorStyle::Tint).into_iter().collect();
|
||||
for (i, (key, fam, lo, hi, scale)) in EFFECT_VALUES.iter().enumerate() {
|
||||
if let Some(v) = opt_f32(p, key)? {
|
||||
if !(*lo..=*hi).contains(&v) {
|
||||
return Err(EngineError::Param(format!("param '{key}' must be between {lo} and {hi}")));
|
||||
}
|
||||
values.push((i, v / scale));
|
||||
if !families.contains(fam) {
|
||||
families.push(*fam);
|
||||
}
|
||||
}
|
||||
}
|
||||
let style = match (style, families.as_slice()) {
|
||||
(Some(st), f) if f.iter().any(|x| *x != st) => return Err(EngineError::Param(format!("the {} style has none of these values: give only its own", st.key()))),
|
||||
(Some(st), _) => Some(st),
|
||||
(None, []) => return Ok(None),
|
||||
(None, [one]) => Some(*one),
|
||||
(None, _) => return Err(EngineError::Param("these values belong to different styles: give one style's values".into())),
|
||||
};
|
||||
Ok(Some(EffectEdit { style, tint, values }))
|
||||
}
|
||||
let style = match (style, families.as_slice()) {
|
||||
(Some(st), f) if f.iter().any(|x| *x != st) => return Err(EngineError::Param(format!("the {} style has none of these values: give only its own", st.key()))),
|
||||
(Some(st), _) => Some(st),
|
||||
(None, []) => return Err(EngineError::Param("give a style, or a value to set".into())),
|
||||
(None, [one]) => Some(*one),
|
||||
(None, _) => return Err(EngineError::Param("these values belong to different styles: give one style's values".into())),
|
||||
};
|
||||
let mut first = None;
|
||||
for e in s.selected_elements_mut()? {
|
||||
let target = style.unwrap_or(e.color.style());
|
||||
if matches!(e.kind, ElementKind::Camera) && !matches!(target, ColorStyle::Tint | ColorStyle::None) {
|
||||
return Err(EngineError::State("the camera's colour effect is a tint".into()));
|
||||
}
|
||||
let mut fx = e.color.to_style(target);
|
||||
|
||||
/// Whether it sets an alpha value (the Alpha style, or an alpha multiplier or offset).
|
||||
pub(crate) fn touches_alpha(&self) -> bool {
|
||||
self.style == Some(ColorStyle::Alpha) || self.values.iter().any(|(i, _)| matches!(i, 0 | 6 | 10))
|
||||
}
|
||||
|
||||
/// `fx` changed: into the style (a new one starting from the look it can keep), with the
|
||||
/// values given set and the rest kept.
|
||||
pub(crate) fn apply(&self, fx: &ColorEffect) -> ColorEffect {
|
||||
let mut fx = fx.to_style(self.style.unwrap_or(fx.style()));
|
||||
if let ColorEffect::Tint { color, .. } = &mut fx
|
||||
&& let Some(t) = tint
|
||||
&& let Some(t) = self.tint
|
||||
{
|
||||
*color = t.with_alpha(1.0);
|
||||
}
|
||||
for &(i, v) in &values {
|
||||
for &(i, v) in &self.values {
|
||||
match &mut fx {
|
||||
ColorEffect::Alpha(a) if i == 0 => *a = v,
|
||||
ColorEffect::Brightness(b) if i == 1 => *b = v,
|
||||
@@ -515,7 +536,21 @@ fn set_color_effect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
e.color = fx.sanitized();
|
||||
fx.sanitized()
|
||||
}
|
||||
}
|
||||
|
||||
fn set_color_effect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let edit = EffectEdit::parse(p)?.ok_or_else(|| EngineError::Param("give a style, or a value to set".into()))?;
|
||||
let mut first = None;
|
||||
for e in s.selected_elements_mut()? {
|
||||
if matches!(e.kind, ElementKind::Camera) && edit.touches_alpha() {
|
||||
return Err(EngineError::State("the camera has no opacity: its colour effect is None, Brightness, Tint or Advanced (without alpha)".into()));
|
||||
}
|
||||
e.color = edit.apply(&e.color);
|
||||
if matches!(e.kind, ElementKind::Camera) {
|
||||
e.color = anicraft_doc::camera::camera_effect(&e.color);
|
||||
}
|
||||
first.get_or_insert(e.color);
|
||||
}
|
||||
Ok(first.map_or(Value::Null, |fx| crate::color_effect_json(&fx)))
|
||||
|
||||
@@ -61,7 +61,7 @@ pub mod publish;
|
||||
pub mod vfs;
|
||||
|
||||
use anicraft_doc::{DisplayList, Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, LayerKind, evaluate_layer_elements, evaluate_scene};
|
||||
use anicraft_geom::{Rect, Vec2};
|
||||
use anicraft_geom::{Affine, Rect, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
use history::History;
|
||||
use std::cell::RefCell;
|
||||
@@ -846,6 +846,32 @@ impl Session {
|
||||
dl.items.get(i).map(|it| (it.layer, it.element))
|
||||
}
|
||||
|
||||
/// Stage → output for layer `id` at the playhead as the camera shows it (ADR 0082): the
|
||||
/// camera and the layer's depth then, the identity for an attached layer. `None` without a
|
||||
/// camera that does something, while a symbol is open, or when the camera has passed the
|
||||
/// layer. What editing through the camera maps the pointer back with.
|
||||
pub fn camera_view(&self, id: LayerId) -> Option<Affine> {
|
||||
if !self.editing.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let tl = self.doc.timeline(self.scene);
|
||||
let cam = tl.camera_at(self.frame, &self.doc.stage)?;
|
||||
cam.layer_view(&self.doc.stage, tl.layer(id)?, self.frame)
|
||||
}
|
||||
|
||||
/// [`Session::hit_test`] through the scene's camera: the topmost element under output
|
||||
/// point `p` (the movie's pixels) on a visible, unlocked layer, `slop` in output pixels.
|
||||
/// Without a camera that does something this is the stage's hit test.
|
||||
pub fn hit_test_camera(&self, p: Vec2, slop: f32) -> Option<(LayerId, ElementId)> {
|
||||
if !self.editing.is_empty() || self.doc.timeline(self.scene).camera_at(self.frame, &self.doc.stage).is_none() {
|
||||
return self.hit_test(p, slop);
|
||||
}
|
||||
let tl = self.timeline();
|
||||
let dl = anicraft_doc::evaluate_scene_camera(&self.doc, self.scene, self.frame);
|
||||
let i = pick_index(&dl, p, slop, |_, it| tl.layer(it.layer).is_some_and(|layer| !layer.locked && !tl.locked_by_folder(layer.id)))?;
|
||||
dl.items.get(i).map(|it| (it.layer, it.element))
|
||||
}
|
||||
|
||||
/// Stage-space bounds of a top-level element at the playhead.
|
||||
pub fn element_bounds(&self, id: ElementId) -> Rect {
|
||||
let mut r = Rect::EMPTY;
|
||||
|
||||
@@ -228,6 +228,9 @@ fn plugins_may_drive_the_camera() {
|
||||
assert!(crate::cmds_plugin::plugin_may_call("camera.set").is_ok());
|
||||
assert!(crate::cmds_plugin::plugin_may_call("camera.add").is_ok());
|
||||
assert!(crate::cmds_plugin::plugin_may_call("layer.set_depth").is_ok());
|
||||
for id in ["layer.remove_depth_key", "layer.set_attached", "layer.depths"] {
|
||||
assert!(crate::cmds_plugin::plugin_may_call(id).is_ok(), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Every command with hostile params while the scene has an animated camera: Ok or Err, never
|
||||
@@ -242,6 +245,11 @@ fn panic_hunt_with_a_camera() {
|
||||
json!({"x": 1e7, "y": -1e7, "zoom": 5, "zoom_by": 1e7, "reset": true, "frame": 99_999, "layer": 1}),
|
||||
json!({"layers": [1, 2, 3], "from": 0, "to": 100, "by": 1, "layer_by": 1, "frame": 0}),
|
||||
json!({"layer": 2, "type": "camera", "depth": 10000, "count": 50}),
|
||||
// Depth keys and attachment (ADR 0082): huge, negative, overflowing and wrong-typed.
|
||||
json!({"depth": -1e39, "key": true, "frame": 4_000_000_000u64, "attached": "x"}),
|
||||
json!({"depth": 1e39, "key": "yes", "layer": u64::MAX, "view": "camera", "x": 1e30, "y": -1e30}),
|
||||
json!({"depth": -500, "key": true, "frame": 0, "attached": true, "style": "advanced", "red_multiplier": -100, "blue_offset": 255}),
|
||||
json!({"depth": 10000, "key": true, "frame": 19, "style": "alpha", "alpha": 0, "brightness": 1e9, "view": "nowhere"}),
|
||||
];
|
||||
let mut base = stage_with(&[(95.0, 45.0, 10.0, 10.0)]);
|
||||
run(&mut base, "camera.add", json!({}));
|
||||
@@ -262,3 +270,158 @@ fn panic_hunt_with_a_camera() {
|
||||
let tl = s.doc.timeline(0);
|
||||
assert!(tl.layers.iter().skip(1).all(|l| l.kind != LayerKind::Camera), "at most one camera, on top");
|
||||
}
|
||||
|
||||
// ----- ADR 0082: depth over time, perspective, attaching layers, colour, editing through it ---
|
||||
|
||||
/// A stage with a 10 × 10 square on a layer behind (depth `far`) and one on the stage plane,
|
||||
/// both at (95, 45), and a camera. Returns (session, far layer, near layer).
|
||||
fn two_planes(far: f32) -> (Session, anicraft_doc::LayerId, anicraft_doc::LayerId) {
|
||||
let mut s = stage_with(&[(95.0, 45.0, 10.0, 10.0)]);
|
||||
let back = s.layer;
|
||||
run(&mut s, "layer.set_depth", json!({"depth": far}));
|
||||
run(&mut s, "layer.new", json!({}));
|
||||
let near = s.layer;
|
||||
run(&mut s, "draw.rect", json!({"x": 95, "y": 45, "w": 10, "h": 10, "fill": "#000000", "stroke": null}));
|
||||
run(&mut s, "camera.add", json!({}));
|
||||
(s, back, near)
|
||||
}
|
||||
|
||||
/// The x of the left edge of the black run on row `y` starting the search at `from`.
|
||||
fn left_edge(s: &Session, frame: u32, y: u32, from: u32) -> Option<u32> {
|
||||
(from..200).find(|&x| black(s, frame, x, y))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn depth_keys_tween_the_parallax_and_undo_in_one_step() {
|
||||
let (mut s, back, _) = two_planes(0.0);
|
||||
run(&mut s, "layer.set_depth", json!({"layer": back.0, "depth": 1000, "key": true, "frame": 10}));
|
||||
let l = s.doc.timeline(0).layer(back).unwrap().clone();
|
||||
assert_eq!(l.depth_keys.len(), 2, "frame 0 keeps the depth it had");
|
||||
assert_eq!(l.depth_at(5), 500.0, "the midpoint");
|
||||
// Keyed from now on: a plain set at the playhead adds a key there.
|
||||
s.set_frame(15);
|
||||
run(&mut s, "layer.set_depth", json!({"layer": back.0, "depth": 3000}));
|
||||
assert_eq!(s.doc.timeline(0).layer(back).unwrap().depth_keys.len(), 3);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(s.doc.timeline(0).layer(back).unwrap().depth_keys.len(), 2);
|
||||
// A 40 px pan: at frame 10 the far square moves 20 px (75..85); the near one 40 (55..65).
|
||||
let cam = camera_id(&s);
|
||||
run(&mut s, "timeline.insert_keyframe", json!({"layer": cam.0, "frame": 10}));
|
||||
run(&mut s, "camera.set", json!({"frame": 0, "dx": 40}));
|
||||
run(&mut s, "camera.set", json!({"frame": 10, "dx": 40}));
|
||||
assert_eq!(left_edge(&s, 10, 50, 0), Some(55));
|
||||
assert_eq!(left_edge(&s, 10, 50, 66), Some(75));
|
||||
// Frame 5 (depth 500): moved 40 · 1000 / 1500 = 26.67 px, to 68.33: pixel 69 is fully in.
|
||||
assert!(black(&s, 5, 69, 50) && !black(&s, 5, 67, 50));
|
||||
// Removing keys: the last leaves the depth it had there.
|
||||
run(&mut s, "layer.remove_depth_key", json!({"layer": back.0, "frame": 10}));
|
||||
assert!(s.execute("layer.remove_depth_key", &json!({"layer": back.0, "frame": 10})).is_err());
|
||||
run(&mut s, "layer.remove_depth_key", json!({"layer": back.0, "frame": 0}));
|
||||
let l = s.doc.timeline(0).layer(back).unwrap();
|
||||
assert!(l.depth_keys.is_empty() && l.depth == 0.0);
|
||||
// `key: false` makes it one value again.
|
||||
run(&mut s, "layer.set_depth", json!({"layer": back.0, "depth": 200, "key": true, "frame": 3}));
|
||||
run(&mut s, "layer.set_depth", json!({"layer": back.0, "depth": 50, "key": false}));
|
||||
let l = s.doc.timeline(0).layer(back).unwrap();
|
||||
assert!(l.depth_keys.is_empty() && l.depth == 50.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_camera_zoom_scales_deeper_layers_less() {
|
||||
// Zoom 200 % about the centre (100, 50): the stage-plane square doubles (90..110); one
|
||||
// 1000 px back grows by 4/3 (93.33..106.67).
|
||||
let (mut s, _, _) = two_planes(1000.0);
|
||||
run(&mut s, "camera.set", json!({"zoom": 200}));
|
||||
let dl = anicraft_doc::evaluate(&s.doc, 0);
|
||||
let scales: Vec<f32> = dl.items.iter().map(|i| i.transform.mean_scale()).collect();
|
||||
assert!((scales[0] - 4.0 / 3.0).abs() < 1e-4 && (scales[1] - 2.0).abs() < 1e-5, "{scales:?}");
|
||||
assert_eq!(left_edge(&s, 0, 50, 0), Some(90));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attached_layers_stay_on_screen_while_the_camera_moves() {
|
||||
let (mut s, back, near) = two_planes(0.0);
|
||||
assert_eq!(run(&mut s, "layer.set_attached", json!({"layer": near.0}))["attached"], true, "toggles on");
|
||||
run(&mut s, "camera.set", json!({"dx": 40, "zoom": 150, "rotation": 20}));
|
||||
// The attached square is exactly where it was drawn.
|
||||
let dl = anicraft_doc::evaluate(&s.doc, 0);
|
||||
let it = dl.items.iter().find(|i| i.layer == near).unwrap();
|
||||
assert_eq!(it.transform, anicraft_doc::evaluate_scene(&s.doc, 0, 0).items.iter().find(|i| i.layer == near).unwrap().transform);
|
||||
assert!(black(&s, 0, 96, 46) && black(&s, 0, 104, 54));
|
||||
assert!(dl.items.iter().find(|i| i.layer == back).unwrap().transform != it.transform);
|
||||
// Listed, and refused on the camera layer and inside a symbol.
|
||||
let v = run(&mut s, "layer.depths", json!({}));
|
||||
assert_eq!(v["camera"], true);
|
||||
assert!(v["layers"].as_array().unwrap().iter().any(|r| r["layer"] == near.0 && r["attached"] == true));
|
||||
assert!(s.execute("layer.set_attached", &json!({"layer": camera_id(&s).0})).is_err());
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert!(!s.doc.timeline(0).layer(near).unwrap().attached);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_depths_list_nearest_first_ties_in_timeline_order() {
|
||||
let mut s = stage_with(&[(0.0, 0.0, 5.0, 5.0)]);
|
||||
let a = s.layer;
|
||||
run(&mut s, "layer.new", json!({}));
|
||||
let b = s.layer;
|
||||
run(&mut s, "layer.new", json!({}));
|
||||
let c = s.layer;
|
||||
run(&mut s, "layer.set_depth", json!({"layer": a.0, "depth": -100}));
|
||||
run(&mut s, "layer.set_depth", json!({"layer": c.0, "depth": 400}));
|
||||
let v = run(&mut s, "layer.depths", json!({}));
|
||||
let ids: Vec<u64> = v["layers"].as_array().unwrap().iter().map(|r| r["layer"].as_u64().unwrap()).collect();
|
||||
assert_eq!(ids, [a.0, b.0, c.0]);
|
||||
// Ties: b and a at 0 go top first (b is above a).
|
||||
run(&mut s, "layer.set_depth", json!({"layer": a.0, "depth": 0}));
|
||||
let v = run(&mut s, "layer.depths", json!({}));
|
||||
let ids: Vec<u64> = v["layers"].as_array().unwrap().iter().map(|r| r["layer"].as_u64().unwrap()).collect();
|
||||
assert_eq!(ids, [b.0, a.0, c.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn camera_colour_effects_reach_the_pixels() {
|
||||
let mut s = stage_with(&[(95.0, 45.0, 10.0, 10.0)]);
|
||||
run(&mut s, "camera.add", json!({}));
|
||||
// Brightness +50 %: white stays white, black becomes mid grey (0.5).
|
||||
let v = run(&mut s, "camera.set", json!({"brightness": 50}));
|
||||
assert_eq!(v["color_effect"]["style"], "brightness");
|
||||
let px = render_frame(&s.doc, 0, 1.0).unwrap();
|
||||
let p = px.pixel(100, 50).unwrap();
|
||||
assert!((p[0] - 0.5).abs() < 0.01 && (p[2] - 0.5).abs() < 0.01, "{p:?}");
|
||||
// Advanced: red × 0 and blue + 255 turn white blue-ish and black blue.
|
||||
run(&mut s, "camera.set", json!({"style": "none"}));
|
||||
run(&mut s, "camera.set", json!({"style": "advanced", "red_multiplier": 0, "blue_offset": 255}));
|
||||
let px = render_frame(&s.doc, 0, 1.0).unwrap();
|
||||
let sq = px.pixel(100, 50).unwrap();
|
||||
assert!(sq[0] < 0.01 && sq[1] < 0.01 && sq[2] > 0.99, "the square: {sq:?}");
|
||||
// The camera has no opacity.
|
||||
assert!(s.execute("camera.set", &json!({"alpha_multiplier": 50})).is_err());
|
||||
assert!(s.execute("camera.set", &json!({"style": "alpha"})).is_err());
|
||||
let info = run(&mut s, "camera.info", json!({}));
|
||||
assert_eq!(info["color_effect"]["style"], "advanced");
|
||||
// A colour change alone keys inside a camera tween like any other edit, and round-trips.
|
||||
let back = crate::format::from_json(&crate::format::to_json(&s.doc).unwrap()).unwrap();
|
||||
assert_eq!(back, s.doc);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picking_through_the_camera_finds_what_the_movie_shows() {
|
||||
// The far square (depth 1000) and the near one start together; a 40 px pan puts the near
|
||||
// one at 55..65 on the picture and the far one at 75..85.
|
||||
let (mut s, back, near) = two_planes(1000.0);
|
||||
run(&mut s, "camera.set", json!({"dx": 40}));
|
||||
assert_eq!(run(&mut s, "element.pick", json!({"x": 80, "y": 50, "view": "camera"}))["layer"], back.0);
|
||||
assert_eq!(run(&mut s, "element.pick", json!({"x": 60, "y": 50, "view": "camera"}))["layer"], near.0);
|
||||
assert!(run(&mut s, "element.pick", json!({"x": 100, "y": 50, "view": "camera"}))["element"].is_null(), "nothing shows there");
|
||||
assert!(s.execute("element.pick", &json!({"x": 1, "y": 1, "view": "sideways"})).is_err());
|
||||
// Dragging maps the pointer back through the layer's view: 10 picture px on the far layer
|
||||
// are 10 stage px at zoom 100 % (a pan keeps sizes).
|
||||
let v = s.camera_view(back).unwrap();
|
||||
let d = v.inverse().unwrap().apply_vector(anicraft_geom::Vec2::new(10.0, 0.0));
|
||||
assert!((d.x - 10.0).abs() < 1e-4);
|
||||
run(&mut s, "camera.set", json!({"zoom": 200}));
|
||||
let v = s.camera_view(near).unwrap();
|
||||
let d = v.inverse().unwrap().apply_vector(anicraft_geom::Vec2::new(10.0, 0.0));
|
||||
assert!((d.x - 5.0).abs() < 1e-4, "{d:?}");
|
||||
}
|
||||
@@ -500,7 +500,7 @@ fn f32_diff(a: &[Premul], b: &[Premul]) -> (f64, f32) {
|
||||
/// deep, so every transform the camera adds reaches the GPU's fills.
|
||||
fn camera_sample() -> anicraft_doc::Document {
|
||||
let mut doc = sample::demo();
|
||||
let cam = anicraft_doc::Camera { center: Vec2::new(700.0, 380.0), zoom: 1.6, rotation: -0.15, tint: Rgba::hex(0x3366ff), tint_amount: 0.3 };
|
||||
let cam = anicraft_doc::Camera { center: Vec2::new(700.0, 380.0), zoom: 1.6, rotation: -0.15, color: anicraft_doc::ColorEffect::Tint { color: Rgba::hex(0x3366ff), amount: 0.3 } };
|
||||
let mut layer = anicraft_doc::Layer::new(LayerId(9_000), "Camera");
|
||||
layer.kind = anicraft_doc::LayerKind::Camera;
|
||||
let mut k = anicraft_doc::Keyframe::new(0, doc.frame_count());
|
||||
|
||||
@@ -724,11 +724,18 @@ impl<'a> Bake<'a> {
|
||||
for f in 0..n {
|
||||
let camera = if scene { tl.camera_at(f, &stage) } else { None };
|
||||
let mut layers = Vec::new();
|
||||
for &index in playing.iter().rev() {
|
||||
// Drawn deepest first, ties in timeline order, as the evaluator does (ADR 0082).
|
||||
let order = if scene { tl.draw_order(f) } else { (0..tl.layers.len()).rev().collect() };
|
||||
for index in order.into_iter().filter(|i| playing.contains(i)) {
|
||||
let Some(layer) = tl.layers.get(index).filter(|l| l.kind != LayerKind::Camera) else { continue };
|
||||
let mut entry = Map::new();
|
||||
if let Some(v) = camera.and_then(|c| matrix(&c.view(&stage, layer.depth))) {
|
||||
entry.insert("v".into(), v);
|
||||
// Each layer's view: the camera and its depth then (none when attached); a
|
||||
// layer the camera has passed isn't drawn.
|
||||
if let Some(c) = camera {
|
||||
let Some(view) = c.layer_view(&stage, layer, f) else { continue };
|
||||
if let Some(v) = matrix(&view) {
|
||||
entry.insert("v".into(), v);
|
||||
}
|
||||
}
|
||||
// The layer's volume, for the sounds inside the symbols on it.
|
||||
if layer.sound_gain() != 1.0 {
|
||||
|
||||
@@ -408,8 +408,7 @@ fn the_camera_and_layer_depth_come_across_and_buttons_answer_through_them() {
|
||||
far.center = Vec2::new(260.0, 150.0);
|
||||
far.zoom = 1.5;
|
||||
far.rotation = 0.2;
|
||||
far.tint = Rgba::hex(0x3366ff);
|
||||
far.tint_amount = 0.3;
|
||||
far.color = anicraft_doc::ColorEffect::Tint { color: Rgba::hex(0x3366ff), amount: 0.3 };
|
||||
let rest = anicraft_doc::Camera::rest(&stage).to_element(ElementId(7001));
|
||||
let near = far.to_element(ElementId(7001));
|
||||
let mut cam = Layer::new(LayerId(70), "Camera");
|
||||
@@ -424,7 +423,7 @@ fn the_camera_and_layer_depth_come_across_and_buttons_answer_through_them() {
|
||||
assert!(m.json["contents"].as_array().unwrap().iter().any(|c| c["cc"].is_array()), "the camera's tint is baked");
|
||||
assert!(first["f"].as_array().unwrap().len() > 15, "the camera moves every frame");
|
||||
// Where the knob is on screen once the camera has arrived.
|
||||
let knob = far.view(&stage, 0.0).apply(Vec2::new(100.0, 100.0));
|
||||
let knob = far.stage_view(&stage).apply(Vec2::new(100.0, 100.0));
|
||||
let mut script: Vec<(Vec<Event>, Vec<Event>)> = vec![(vec![], vec![]); 22];
|
||||
script.push((vec![Event::Move(knob), Event::Down(knob)], vec![Event::Up(knob)]));
|
||||
script.extend(vec![(vec![], vec![]); 6]);
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
# ADR 0082: Camera, second slice: layer depth in perspective, attaching layers, colour
|
||||
|
||||
* Status: accepted (2026-11-12)
|
||||
* Relates to: ADR 0027 (camera layer), ADR 0056 (colour effects), ADR 0016 (motion tweens),
|
||||
ADR 0024 (player), ADR 0004 (destructive actions), roadmap M7
|
||||
|
||||
## Context
|
||||
|
||||
ADR 0027 shipped one camera per scene with pan-only parallax ("maintain size"): a layer's depth
|
||||
scaled how far a pan moved it, while zoom and rotation were the same at every depth. Its "not
|
||||
yet" list: perspective depth, a Layer Depth panel, depth over time, attaching layers to the camera
|
||||
(HUDs), camera colour effects beyond tint, editing while previewing, and XFL import. Behaviour was
|
||||
learned from Adobe's public help pages on the camera and Layer Depth panel and from observation;
|
||||
nothing was copied.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **A pinhole camera with a fixed focal length.** At zoom `z` the camera is `FOCAL / z` from the
|
||||
stage plane (`FOCAL` = 1,000 px). A layer `depth` px behind the stage is drawn as a pinhole
|
||||
would see it, enlarged so that **the camera at rest shows every layer as drawn**: with
|
||||
`d = FOCAL / z + depth`, a stage point `p` lands at
|
||||
`mid + R(−rotation) · ((FOCAL + depth) / d · (p − mid) − FOCAL / d · (centre − mid))`.
|
||||
* A pan by `Δ` at zoom 1 moves a layer by `Δ · FOCAL / (FOCAL + depth)`: exactly ADR 0027's
|
||||
parallax, so files without zoom look the same.
|
||||
* A zoom grows the stage plane by `z` and a deeper layer by less (a far sky barely changes),
|
||||
a nearer one by more.
|
||||
* **Depth 0 is the stage view bit for bit**: `Camera::view` returns `stage_view` for depth 0
|
||||
before any perspective arithmetic, so artists who never touch depth see no change.
|
||||
* A layer the camera has reached or passed (`d < NEAR` = 10 px, a near layer under a strong
|
||||
zoom) isn't drawn; every view is finite for any depth, NaN depths read as 0.
|
||||
* We keep the rest-normalisation (Animate's "maintain size") rather than shrinking deep
|
||||
layers at rest: depth then never changes the composition the artist drew, only how the
|
||||
camera's moves affect it. That is the behaviour that lets depth be set late without
|
||||
re-scaling artwork.
|
||||
* **Changed behaviour:** ADR 0027 kept zoom equal at every depth. A file that has both a
|
||||
depth and a zoomed camera now renders differently. ADR 0027 shipped one day earlier in
|
||||
the same unreleased alpha, so we take the one behaviour now rather than carry a
|
||||
"pan-only" mode.
|
||||
2. **Depth draws in order.** `Timeline::draw_order(frame)`: deepest first, a stable sort, so
|
||||
ties (and every layer at 0) keep the timeline order. A masked layer sorts with its mask, so a
|
||||
mask stays with what it masks. The stage while editing, every export, the player's hit
|
||||
testing and the HTML canvas export use the same order, so stacking matches everywhere.
|
||||
Nested timelines aren't sorted (depth belongs to a scene's layers) and allocate nothing.
|
||||
3. **Depth over time.** `Layer.depth_keys: Vec<DepthKey { frame, depth }>` (sorted, one per
|
||||
frame, at most 4,096, clamped on load; `#[serde(default, skip_serializing_if = empty)]`).
|
||||
With keys, `Layer::depth_at(frame)` is linear between keys and held outside them; without,
|
||||
it is `Layer.depth`. Keys live on the layer by frame number, not on keyframes: depth is a
|
||||
property of the layer's place in the scene, it must tween across keyframe boundaries, and
|
||||
it must not be lost when artwork keyframes are cut and pasted. The cost: inserting frames
|
||||
doesn't move depth keys yet (listed below).
|
||||
4. **Attach to camera.** `Layer.attached` (`skip_serializing_if = false`): through the camera,
|
||||
the layer's view is the identity, so it stays where it was drawn on screen; depth plays no
|
||||
part in placing it (it still sorts by it). While editing (stage space) it is drawn where its
|
||||
coordinates say, which is where it will appear with the camera at rest: the artist designs
|
||||
a HUD in the frame. The camera's colour effect still colours it (the whole picture is seen
|
||||
through the camera).
|
||||
5. **Camera colour effects.** `Camera.color` is a `ColorEffect` (ADR 0056) instead of a tint:
|
||||
None, Brightness, Tint or Advanced. The camera has no opacity (`camera_effect`: Alpha reads as
|
||||
None, Advanced keeps alpha untouched), so the movie never fades to transparent through its
|
||||
camera. Classic and motion tweens of the camera element already interpolate colour effects;
|
||||
every renderer already composes the camera's transform around everything.
|
||||
6. **Editing while previewing.** The model allows it for moves: `Session::camera_view(layer)`
|
||||
is each layer's stage → picture transform, and `Session::hit_test_camera` picks in the
|
||||
camera's display list. With View › Preview Through Camera, the Selection tool's click runs
|
||||
`element.pick {view: camera}`, a drag maps each pointer step back through the inverse of the
|
||||
active layer's view and runs the ordinary `element.translate`, and selection boxes are drawn
|
||||
through the view. The other tools still pause there: they draw or reshape in stage space and
|
||||
would each need their geometry mapped per layer (proposed below).
|
||||
7. **Commands.** `layer.set_depth {depth, layer?, key?, frame?}` (with `key`, a key at the frame;
|
||||
the first key away from frame 0 also keys frame 0 with the depth it had, so the past doesn't
|
||||
change; `key: false` makes the depth one value again), `layer.remove_depth_key`,
|
||||
`layer.set_attached {attached?}` (toggles), `layer.depths {frame?}` (nearest first, ties in
|
||||
timeline order), `element.pick {view: stage|camera}`, and `camera.set` takes
|
||||
`element.set_color_effect`'s colour params except alpha. The parsing is shared
|
||||
(`EffectEdit`). Depth commands are refused on camera, folder and guide layers and while a
|
||||
symbol is open. All live in existing namespaces (`layer`, `camera`, `element`), which plug-ins
|
||||
may call. Every change is routine and undoable (ADR 0004 tier 3).
|
||||
8. **The shell.** **Window › Layer Depth** (docked beside the Library): the layers nearest
|
||||
first, each with its colour, name, value, a key diamond, Attach, and a full-width track laid
|
||||
out by parallax (`FOCAL / (FOCAL + depth)`), so the busy range near the stage gets the room;
|
||||
a drag is one undo step. Properties › Frame's Depth row gains the key diamond and Attach.
|
||||
The timeline shows a camera toggle on each layer row once the scene has a camera.
|
||||
|
||||
## XFL
|
||||
|
||||
Animate's public documentation describes the camera and the Layer Depth panel as features but
|
||||
not how XFL stores them (the camera layer, layer depth, attachment). Without a public format
|
||||
description we don't import them; documents keep importing as before. Reported, not guessed.
|
||||
|
||||
## Consequences
|
||||
|
||||
* Every export draws the evaluated display list (PNG, sequences, GIF, video, SVG, Lottie) or
|
||||
bakes each layer's view per frame (HTML canvas, now through `Camera::layer_view`), so all of
|
||||
them match the stage; parity is covered by the existing export tests through the shared paths.
|
||||
* Files without depth keys or attached layers are written exactly as before.
|
||||
* Measured: no per-item work is added; a scene's draw order is computed once per evaluation, and
|
||||
only when some layer has a depth.
|
||||
|
||||
## Not yet
|
||||
|
||||
* Tools other than Selection while previewing (drawing and reshaping through the camera need
|
||||
per-layer pointer mapping in every tool).
|
||||
* Depth inside symbols; depth keys moving with inserted and removed frames; easing on depth keys.
|
||||
* XFL import of cameras, layer depth and attachment (no public format description).
|
||||
@@ -106,8 +106,10 @@ With the Camera tool:
|
||||
* use the mouse wheel to zoom.
|
||||
|
||||
Each drag is one undo step. For exact values, use **Properties › Camera**: **Position**,
|
||||
**Zoom** (5 to 2,000 %), **Rotation**, and a **Tint** over the whole view with its amount.
|
||||
**Reset** puts the camera back to the plain stage: centred, 100 %, no turn and no tint.
|
||||
**Zoom** (5 to 2,000 %), **Rotation**, and a **Colour effect** over the whole view: **Brightness**,
|
||||
**Tint** or **Advanced** (red, green and blue multipliers and offsets), as on a symbol instance.
|
||||
The camera has no opacity, so there is no Alpha style. Colour effects tween with the camera.
|
||||
**Reset** puts the camera back to the plain stage: centred, 100 %, no turn and no colour effect.
|
||||
|
||||
### Animating the camera
|
||||
|
||||
@@ -117,17 +119,37 @@ is **Scale X**.
|
||||
|
||||
The Camera layer holds only the camera. Draw your artwork on other layers.
|
||||
|
||||
### Depth and parallax
|
||||
### Layer depth
|
||||
|
||||
Once the scene has a camera, each layer can have a **Depth** in **Properties › Frame**. A layer
|
||||
with more depth sits farther behind the stage and moves less as the camera pans, which gives a
|
||||
sense of distance (parallax). A negative depth puts the layer in front.
|
||||
Once the scene has a camera, each layer can have a **depth**: how far behind the stage it sits,
|
||||
in pixels (a negative depth puts it in front, down to −500). The camera sees the layers as a real
|
||||
camera would (a pinhole camera 1,000 px from the stage): when it pans, a deeper layer moves less;
|
||||
when it zooms in, a deeper layer grows less. Deeper layers are drawn behind nearer ones; layers at
|
||||
the same depth keep their timeline order. With the camera at rest, every layer looks just as you
|
||||
drew it, and a layer at depth 0 behaves exactly as it always did.
|
||||
|
||||
Open **Window › Layer Depth** to see the layers listed by depth, nearest first. Drag a layer's
|
||||
handle along its track (left is nearer, right is farther) or type its depth. Each drag is one
|
||||
undo step. The **Depth** row in **Properties › Frame** sets the active layer's depth too.
|
||||
|
||||
**Animating depth.** Click the diamond beside a depth to key it on the current frame. The depth
|
||||
then tweens evenly between keys and holds before the first and after the last. Click a filled
|
||||
diamond to remove that key.
|
||||
|
||||
### Attaching a layer to the camera
|
||||
|
||||
Titles, captions and HUDs should stay put while the camera moves. Click the camera icon on a
|
||||
layer's row in the timeline (or **Attach** in the Layer Depth panel) to attach the layer to the
|
||||
camera: it then stays exactly where you drew it on screen, whatever the camera does. Draw it as
|
||||
it should look in the frame, with the camera at rest.
|
||||
|
||||
### Preview Through Camera
|
||||
|
||||
Choose **View › Preview Through Camera** (also in the Camera layer's right-click menu and in
|
||||
**Properties › Camera**) to see the stage just as the movie will look. While you preview, the
|
||||
drawing tools pause; turn the preview off to edit artwork again.
|
||||
**Selection** tool still works: click artwork where you see it to select it, and drag it to move
|
||||
it. It follows the pointer at any depth and zoom. The drawing tools pause; turn the preview off to
|
||||
draw.
|
||||
|
||||
While you're editing, the stage otherwise stays in stage space, so your artwork doesn't jump
|
||||
around as the camera moves. Test Movie and every export always see through the camera.
|
||||
@@ -140,8 +162,8 @@ around as the camera moves. Test Movie and every export always see through the c
|
||||
**Modify › Timeline › Remove Camera**. If the camera is animated, AniCraft asks first. Undo
|
||||
brings it back.
|
||||
|
||||
Not there yet: editing artwork while previewing through the camera, a perspective mode where
|
||||
depth scales layers, depth inside symbols, and cameras from Animate files.
|
||||
Not there yet: tools other than Selection while previewing, depth inside symbols, depth keys that
|
||||
move with inserted frames, and cameras or layer depth from Animate files.
|
||||
|
||||
## Bones and inverse kinematics
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Command reference
|
||||
|
||||
Everything you can do in AniCraft is a command: the menus, the shortcuts, the command palette (**Ctrl+K**, macOS **⌘K**), `anicraft-cli` and AI assistants over MCP all run the same 308 commands, listed here by menu. The id is what scripts and [working headless](../working-headless.md) use; the parameters are what a command takes as JSON. Commands that change the document are one undo step each. Your own shortcuts (**F1**) replace the defaults shown here; see the [shortcut reference](shortcuts.md).
|
||||
Everything you can do in AniCraft is a command: the menus, the shortcuts, the command palette (**Ctrl+K**, macOS **⌘K**), `anicraft-cli` and AI assistants over MCP all run the same 311 commands, listed here by menu. The id is what scripts and [working headless](../working-headless.md) use; the parameters are what a command takes as JSON. Commands that change the document are one undo step each. Your own shortcuts (**F1**) replace the defaults shown here; see the [shortcut reference](shortcuts.md).
|
||||
|
||||
This page is generated from the command registry, so it always matches the version of AniCraft it came with.
|
||||
|
||||
@@ -330,11 +330,17 @@ These commands have no menu item: the panels, the stage and the timeline use the
|
||||
- **Get Layer Properties** `layer.properties`
|
||||
Parameters: `{layer?} the layer's name, type, mask type (mask layers), colour, outline, height (percent), visible, locked and onion`
|
||||
- **Camera** `camera.set` · changes the document
|
||||
Parameters: `{x?, y? (camera centre, stage px), dx?, dy? (pan by), zoom? (%, 5–2000), zoom_by? (factor), rotation? (°), rotate_by? (°), tint? (#rrggbb), tint_amount? (%), reset?: bool, frame?}`
|
||||
Parameters: `{x?, y? (camera centre, stage px), dx?, dy? (pan by), zoom? (%, 5–2000), zoom_by? (factor), rotation? (°), rotate_by? (°), reset?: bool, frame?, and the colour effect as element.set_color_effect takes it: style?: none|brightness|tint|advanced, brightness? (%), tint? (#rrggbb), tint_amount? (%), red_multiplier? … blue_offset? (the camera has no opacity: no alpha values)}`
|
||||
- **Camera Info** `camera.info`
|
||||
Parameters: `{frame?} → the camera at the frame (x, y, zoom %, rotation °, tint) and its frame on the stage`
|
||||
- **Layer Depth** `layer.set_depth` · changes the document
|
||||
Parameters: `{depth (px behind the stage, −500…10000; deeper layers move less when the camera pans), layer?}`
|
||||
Parameters: ``{depth (px behind the stage, −500…10000; through the camera a deeper layer moves and scales less, and draws behind nearer ones), layer?, key?: bool (default: whether the layer's depth is keyed), frame? (default: the playhead)} with `key` sets a depth key at the frame (the first key away from frame 0 also keys frame 0 with the depth it had), so the depth tweens linearly between keys; `key: false` makes the depth one value again (ADR 0082)``
|
||||
- **Remove Depth Key** `layer.remove_depth_key` · changes the document
|
||||
Parameters: `{layer?, frame? (default: the playhead)} removes the layer's depth key at the frame; removing the last one leaves the depth it had there`
|
||||
- **Attach Layer to Camera** `layer.set_attached` · changes the document
|
||||
Parameters: `{attached?: bool (default: toggles), layer?} an attached layer stays where it is on screen while the camera moves (titles, HUDs); its depth plays no part (ADR 0082)`
|
||||
- **Layer Depths** `layer.depths`
|
||||
Parameters: `{frame?} → {camera: bool, layers: [{layer, name, depth, keyed, key_here, attached}]} the layers that can have a depth, nearest first (ties in timeline order), at the frame`
|
||||
- **Add Bone** `bone.add` · changes the document
|
||||
Parameters: ``{from (instance id: the bone starts on it), to (instance id: the bone moves it), head?: [x, y] (the joint on a root instance, stage px, default its registration point; from an instance that hangs from a bone the joint is always that bone's end, so chains stay joined), tail?: [x, y] (default `to`'s registration point), name?} → {bone, layer}. Both instances go to an armature layer (made for the first bone)``
|
||||
- **Add Bone in Shape** `bone.add_in_shape` · changes the document
|
||||
@@ -426,7 +432,7 @@ These commands have no menu item: the panels, the stage and the timeline use the
|
||||
- **Select Elements** `element.select`
|
||||
Parameters: ``{ids: [..], add?: bool, toggle?: bool, layer?} selects elements on any visible, unlocked layer at the playhead (ids are unique; `layer` looks only there); `toggle` takes each one that is selected out of the selection and adds the others (Shift+Space on a stage element); the active layer becomes the first one's unless it has some of them``
|
||||
- **Select at Point** `element.pick`
|
||||
Parameters: ``{x, y, add?: bool} the topmost element there on a visible, unlocked layer; `add` (Shift) adds it to the selection, or lets go of it, on any layer``
|
||||
Parameters: ``{x, y, add?: bool, view?: stage|camera} the topmost element there on a visible, unlocked layer; `add` (Shift) adds it to the selection, or lets go of it, on any layer; with `view: camera` the point is on the movie's picture as the camera shows it (each layer through its depth)``
|
||||
- **Move** `element.translate` · changes the document
|
||||
Parameters: ``{dx, dy, snap?, from?: [x, y]} moves the selection, on every layer; with `snap` (a distance) one of its corners or ends, or its box's corners or centre (the nearest to `from`), then snaps within that distance by the snap engine's priority (ADR 0076): a point, guide, line or fill edge of the rest, the grid, a whole pixel``
|
||||
- **Transform** `element.set_transform` · changes the document
|
||||
@@ -438,7 +444,7 @@ These commands have no menu item: the panels, the stage and the timeline use the
|
||||
- **Alpha** `element.set_alpha` · changes the document
|
||||
Parameters: `{alpha: 0..1} sets the alpha multiplier and keeps the rest of the colour effect (None becomes Alpha; Brightness and Tint become Advanced below 1)`
|
||||
- **Colour Effect** `element.set_color_effect` · changes the document
|
||||
Parameters: `{style?: none|brightness|tint|advanced|alpha (default: the style the values belong to, else each element's own), alpha? (%, 0..100), brightness? (%, -100..100), tint? (#rrggbb), tint_amount? (%, 0..100), red_multiplier?, green_multiplier?, blue_multiplier?, alpha_multiplier? (%, -100..100), red_offset?, green_offset?, blue_offset?, alpha_offset? (-255..255)} on every selected element (ADR 0056); values not given keep each element's own. A new style starts from the look it can keep: Advanced is exactly the effect before, Alpha keeps the opacity, Brightness and Tint start at 0 %. The camera's effect is a tint`
|
||||
Parameters: `{style?: none|brightness|tint|advanced|alpha (default: the style the values belong to, else each element's own), alpha? (%, 0..100), brightness? (%, -100..100), tint? (#rrggbb), tint_amount? (%, 0..100), red_multiplier?, green_multiplier?, blue_multiplier?, alpha_multiplier? (%, -100..100), red_offset?, green_offset?, blue_offset?, alpha_offset? (-255..255)} on every selected element (ADR 0056); values not given keep each element's own. A new style starts from the look it can keep: Advanced is exactly the effect before, Alpha keeps the opacity, Brightness and Tint start at 0 %. The camera has no opacity (no Alpha style, alpha multiplier or offset)`
|
||||
- **Blending** `element.set_blend` · changes the document
|
||||
Parameters: `{mode: normal|layer|darken|multiply|lighten|screen|overlay|hardlight|add|subtract|difference|invert|alpha|erase} on the selected movie clip and button instances`
|
||||
- **Filters** `element.set_filters` · changes the document
|
||||
|
||||
+4
-4
@@ -10,7 +10,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a
|
||||
|---|---|
|
||||
| Architecture | M0 skeleton in place: geom → doc → render → engine → cli → shell, layering enforced by `cargo test` (`src/architecture_tests.rs`: lower layers only, no UI crates below the shell, and the AGENTS.md map must match). |
|
||||
| Rendering | CPU oracle with analytic AA, non-zero/even-odd, solid + linear/radial gradients (with reflect/repeat, focal points, elliptical radials and linear RGB, ADR 0074), round-join strokes. **Mask clipping**: the display list carries nested clips; a clip is the anti-aliased union of its mask fills (strokes and opacity ignored), intersected with any enclosing clip, computed once per render band; an empty mask hides everything under it. **Soft masks** (ADR 0070): a mask layer's mask type is Shape (coverage), Alpha (its artwork's opacity as drawn: gradients, faded shapes, strokes, bitmaps) or Luminance (brightness × opacity, SVG's coefficients), in the CPU oracle (analytic tests), the GPU stage (parity: mean 0.00006, worst 1 step of 255), SVG export (`<mask>` with `mask-type`), Lottie (alpha and luma track mattes) and the HTML canvas; Layer Properties › Mask type. **Group alpha**: a symbol instance below full opacity is a group in the display list; each render band composites the group's run of ops into its own buffer (nested groups stack) and blends it once at the group's alpha, so overlaps don't show through; SVG export writes `<g opacity>`. **Blend modes** (Animate's 14, on movie clip and button instances): an instance with one is an isolated group that blends at its close with the W3C separable formulas on premultiplied colour (Alpha and Erase keep or clear the backdrop); SVG gets CSS `mix-blend-mode`, Lottie the layer `bm`. **Bitmaps**: `Paint::Bitmap` fills (once or tiled) with bilinear sampling in premultiplied space, colour effects per sample; PNG/JPEG import to stage (a rectangle of the image's size); stored in the document as PNG (base64 in `.anicraft`), decoded once on first use; SVG export embeds each image once as a pattern. **Filters**: a filtered group is drawn on its own (by the same renderer, recursively, so nested filters work) into a buffer over its artwork grown by the filters' reach, filtered (box-blur passes; shadow and glow from the blurred, offset opacity; **bevel and gradient bevel** from the difference of the blurred opacity offset towards and away from the light, **gradient glow** from the glow's intensity, both through a colour ramp whose rest stop is pinned transparent, inner/outer/full and knockout, ADR 0025; colour matrix), and composited back as one image in its group, so alpha and blend apply; clips from inside the symbol apply before filtering and the instance's own clip after. **GPU stage, first slice** (M3, ADR 0019; `--features gpu-stage`, off by default): Preferences › Stage › Renderer *GPU (preview)* draws the stage with wgpu compute from the oracle's own prepared fills (tile binning with per-row backdrops on the CPU, exact area coverage and src-over per pixel on the GPU): solid and gradient fills and strokes, non-zero and even-odd; masks, group opacity, blend modes, filters and bitmaps fall back to the CPU per tile, and the status bar says so. Parity with the oracle: max 1/255, mean < 0.0001/255 on the sample, stress and analytic scenes (tests skip without an adapter). 4K with 1,000 shapes: 8.8–9.0 ms vs the CPU's 17.4–17.8 ms. **Second slice** (ADR 0029): on the window's wgpu device the stage tiles are drawn straight into textures egui shows (no readback; a headless device with readback when the window is on OpenGL); **masks** (nested, united artwork), **group opacity** and **all 14 blend modes** on the GPU, same parity (max 1/255, mean ≤ 0.0011/255); 4K: 1,000 shapes in 2.1–2.4 ms, 10k shapes in 10.2 ms as stage tiles, masked scenes 7× the CPU. **Third slice** (ADR 0032): **bitmap fills** (textures uploaded once per image and cached under a 256 MB budget, sampled with the oracle's own bilinear filter, colour effect and repeat rules: byte-identical) and **all seven filters** (each filtered symbol drawn into a layer of its own and filtered by compute passes that run the oracle's resolved steps: max 1/255, mean ≤ 0.007/255) on the GPU; the shaders now build with Direct3D's FXC, so DX12 windows get the GPU stage too (parity suite green on Vulkan and DX12); software adapters are refused (the CPU is faster), the start-up self-test compares with the oracle. **The GPU is the default stage renderer**: the shell's `gpu-stage` feature is on by default, Preferences › Stage › Renderer defaults to *Graphics card (GPU)*, and the CPU draws whenever there is no usable card, a tile is past the GPU's limits (more than 16 images, filters nested deeper than 4) or anything fails. 4K: the filtered sample in 3.9 ms (CPU 31.5), 200 bitmap fills in 4.4 ms (CPU 37.2). **Fourth slice** (ADR 0048): **tile binning on the GPU** for heavy frames without masks or groups (count, prefix sum, scatter and tile-list passes, no atomics, no readback; the CPU binning stays the reference and does the rest; one tile format for both: an integer backdrop per tile and steps on the tiles' left edges): on Vulkan, 10k shapes at 4K in one texture 21.7 → 4.7 ms, 50k shapes 122 → 22.5 msLine truncated
|
||||
| Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, icon buttons and right-click menu) act on the whole selection; with no frame selection F5 extends every layer with frames at or after the playhead, and F5/F6/F7 move the playhead on as in Animate (F6/F7 on a keyframe key the next frame; `all_layers`/`advance` headless); drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), **timeline polish** (ADR 0061): a per-layer **onion skin toggle** column (Alt-click solos; left-out layers aren't onion-skinned; Edit Multiple Frames unaffected), the colour square toggles **View as Outlines** in the layer colour **on the stage only** (exports, Test Movie and the player draw the artwork as it is), the **colour chip** opens the layer colour (swatches, hex, More…), **onion frames of the parent timeline** dimmed around a symbol edited in place, **Layer Height** 100/200/300 %, **Layer Properties** (double-click the layer icon; name, show/lock, type, outline colour, outlines, onion, height; one undo step), **Frame View** (Tiny/Small/Normal/Medium/Large, Short rows) with the frame zoom in the timeline's bottom bar (the header fits at the default window size, tested); headless `layer.set_onion/set_color/set_height/set_properties/properties`; XFL `heightMultiplier`. Not yet: folder onion toggles, onion of deeper parent timelines, multi-layer Layer Properties and layer transparency, frame thumbnails (Preview). Keyframes, blank keyframes, insert/remove frames, classic tweens with 8 easing presets + curve preview, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, looping playback. **Onion skin and Edit Multiple Frames** (ADR 0047): onion markers on the frame ruler (drag the start and end brackets; Always Show Markers, Anchor Markers, Onion 2 / Onion 5 / Onion All, also on a right-click on the ruler), frames before and after the playhead tinted in their own colours (theme blue and green, changeable in the onion menu, Reset) and fading with distance, Outlines, Keyframes Only, locked layers left out as in Animate, each layer's onion frames under its own artwork and over the layers below; options saved in the preferences; the stage's frame cache keys every look apart. **Edit Multiple Frames** shows every keyframe within the markers at full strength and selects (click, Shift-click, marquee, Select All) and moves (drag, arrow keys) artwork across them, one undo step, motion tween paths moving with their objects. Headless: `frames.artwork`, `frames.edit_multiple`. **Edit Multiple Frames, complete** (ADR 0051): Cut, Copy, Paste (current frame), Paste in Place (back keyframe by keyframe, or a one-frame copy onto every keyframe between the markers), Clear, Align (Ctrl+Alt+1…6, To Stage), Rotate 90° and Flip, and **Free Transform** of the selection on every keyframe about one shared pivot (one box, one undo step per drag); raw shapes moved, transformed or pasted merge again on their own keyframe; **onion skin and Edit Multiple Frames inside a symbol edited in place**, on its own timeline and markLine truncated
|
||||
| Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, icon buttons and right-click menu) act on the whole selection; with no frame selection F5 extends every layer with frames at or after the playhead, and F5/F6/F7 move the playhead on as in Animate (F6/F7 on a keyframe key the next frame; `all_layers`/`advance` headless); drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), **timeline polish** (ADR 0061): a per-layer **onion skin toggle** column (Alt-click solos; left-out layers aren't onion-skinned; Edit Multiple Frames unaffected), the colour square toggles **View as Outlines** in the layer colour **on the stage only** (exports, Test Movie and the player draw the artwork as it is), the **colour chip** opens the layer colour (swatches, hex, More…), **onion frames of the parent timeline** dimmed around a symbol edited in place, **Layer Height** 100/200/300 %, **Layer Properties** (double-click the layer icon; name, show/lock, type, outline colour, outlines, onion, height; one undo step), **Frame View** (Tiny/Small/Normal/Medium/Large, Short rows) with the frame zoom in the timeline's bottom bar (the header fits at the default window size, tested); headless `layer.set_onion/set_color/set_height/set_properties/properties`; XFL `heightMultiplier`. Not yet: folder onion toggles, onion of deeper parent timelines, multi-layer Layer Properties and layer transparency, frame thumbnails (Preview). Keyframes, blank keyframes, insert/remove frames, classic tweens with 8 easing presets + curve preview, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, looping playback. **Onion skin and Edit Multiple Frames** (ADR 0047): onion markers on the frame ruler (drag the start and end brackets; Always Show Markers, Anchor Markers, Onion 2 / Onion 5 / Onion All, also on a right-click on the ruler), frames before and after the playhead tinted in their own colours (theme blue and green, changeable in the onion menu, Reset) and fading with distance, Outlines, Keyframes Only, locked layers left out as in Animate, each layer's onion frames under its own artwork and over the layers below; options saved in the preferences; the stage's frame cache keys every look apart. **Edit Multiple Frames** shows every keyframe within the markers at full strength and selects (click, Shift-click, marquee, Select All) and moves (drag, arrow keys) artwork across them, one undo step, motion tween paths moving with their objects. Headless: `frames.artwork`, `frames.edit_multiple`. **Edit Multiple Frames, complete** (ADR 0051): Cut, Copy, Paste (current frame), Paste in Place (back keyframe by keyframe, or a one-frame copy onto every keyframe between the markers), Clear, Align (Ctrl+Alt+1…6, To Stage), Rotate 90° and Flip, and **Free Transform** of the selection on every keyframe about one shared pivot (one box, one undo step per drag); raw shapes moved, transformed or pasted merge again on their own keyframe; **onion skin and Edit Multiple Frames inside a symbol edited in place**, on its own timeline and markLine truncated
|
||||
| Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, under or over the artwork, snap accuracy up to Always); Snap to Pixels; one snap engine for every drawing tool, the Selection tool's moves and Free Transform's handles (point › guide › line › grid › pixel, guides and grid per axis); stage only, never exported, on the CPU and GPU stage. Headless: `view.rulers`, `view.grid_show/grid_snap/grid_set`, `view.guides_show/guides_lock/guides_snap/guides_set`, `view.guide_add/guide_move/guide_delete/guides_clear`, `view.snap_pixels`, `view.aids`, `moving` on `draw.snap`. *Not yet:* units other than px, a movable ruler origin, a symbol's own guides, guides and grid from Animate files, Snap Align and Edit Snapping, snapping while rotating. bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing Line truncated
|
||||
| Plug-ins | **WebAssembly plug-ins** (ADR 0017, `docs/plugins.md`): sandboxed modules run by `wasmi` with no imports but the AniCraft ABI (`anicraft.call`/`anicraft.response`: JSON requests that run registry commands, read a compact document view or the active layer's elements, and log); fuel (10⁹ instructions), memory (256 MiB), wall-clock (5 s), request, size and log limits, a fresh instance per run; file, plug-in, undo and clipboard commands refused. `plugin.install/list/run/remove/reload`; a run is atomic and one undo step named after the plug-in. App: **Commands** menu (Plug-ins, Install, Manage, Reload), palette entries, a dialog generated from the manifest's parameters with a live preview; plug-ins load from `<settings>/plugins` or `ANICRAFT_PLUGINS`; CLI `--plugins`. Samples in Rust (Star Field, Jitter Selection, guest SDK) in `examples/plugins`. Frame scripts: see Interactivity. Not yet: exporter and easing kinds, background runs with cancel, a binary document view. |
|
||||
| Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. **A window of its own on the desktop** (ADR 0062): sized to the stage at 100 % (smaller to fit the screen), titled with the document, back where it was last (not on Wayland, where the desktop places windows), with the keyboard when it opens; Esc or Ctrl+W (⌘W) closes it, Ctrl+Enter restarts it in place, and the editor's Ctrl/Alt shortcuts work from it; floating inside the editor in the web build, where the system can't open windows (it says so), or by choice in Preferences › Test Movie. Not yet: full screen, zoom in the movie window, remembering its size. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; **filters and Subtract/Invert in the page** (ADR 0072: `filters.js`, a port of the renderer's filters run over the group's pixels on a layer that reaches past the canvas by the filters' reach, Subtract and Invert composited per pixel, results kept while the group is unchanged; equal to the oracle's pixels within 9.3e-4 in Boa; 3.4 ms a frame for the demo's filters at 1080p while they change); Web Audio for Event/Start/Stop/Stream sounds; bitmap tints, 9-slice scaling and plug-in frame scripts reported. Not yet: 9-slice in the page, keeping a moving filtered group's pixels, filters off the main thread. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). **ActionScript small logic** (ADR 0052): scripts compile to a small typed script IR evaluated by the player with fuel (100,000 per script or listener call, 1,000,000 per step; an endless loop or a run-time error stops its script with an Output line and the movie plays on): typed variables (Number, int, uint, Boolean, String, untyped) kept per timeline instance across its frame scripts, expressions as ECMA-262 has them, `if`/`else`, `for`/`while`/`do`, functions with parameters, results and recursion, called from any frame of the same timeline (a timeline-level link step; names that aren't there keep the script from running, said in place), property reads of instances and timelines (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`, `tLine truncated
|
||||
@@ -35,12 +35,12 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a
|
||||
|---|---|---|
|
||||
| **M0** | Foundations *(this version)* | Workspace + layering; document model; timeline evaluation with classic tweens and easing; CPU oracle renderer; command registry with undo; `.anicraft`; CLI render + JSON-lines; egui shell with stage, tools, timeline, properties, library; `--screenshot`. |
|
||||
| **M1** | Authoring core ✅ *(v0.1.0)* | ~~Free transform tool with handles~~ ✅; ~~subselection and Bézier point editing~~ ✅; ~~Pen and Pencil~~ ✅; ~~Paint bucket / Ink bottle~~ ✅; ~~copy/paste~~ ✅, ~~duplicate, arrange~~ ✅, ~~align~~ ✅ (commands and menus; and the dock's Align panel ✅); ~~onion skin~~ ✅ (markers, tint, fade, outlines, keyframes only, Edit Multiple Frames: ADR 0047; its delete, copy/paste, Free Transform, align and re-merge, and both inside symbols: ADR 0051); ~~frame selection ranges in the timeline (multi-frame insert/remove/move keyframes by drag)~~ ✅ (including between layers); ~~PNG sequence + animated GIF export~~ ✅; ~~keyboard shortcut map editor~~ ✅; ~~groups, Combine Objects, Selection-tool modifiers~~ ✅ first slice (ADR 0073); ~~gradient editor, Gradient Transform tool and Lock Fill~~ ✅ (ADR 0074: the colour picker sets a fill's type, with a keyboard-operable stop bar, overflow, Linear RGB, focal point and bitmap fills; the Gradient Transform tool (F)); ~~rulers, grid and guides with one snap engine~~ ✅ first slice (ADR 0076). |
|
||||
| **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅, ~~shape hints~~ ✅ (ADR 0023); ~~motion tween + Motion Editor curves~~ ✅ first slice (ADR 0016); ~~motion paths on the stage with orient to path~~ ✅ first slice (ADR 0030), ~~path point add/delete/convert and moving the whole path~~ ✅ (ADR 0038), ~~anchors pinned to frames~~ ✅ (ADR 0049; 3D and XFL import later); ~~library management~~ ✅ first slice (ADR 0050: folders, rename, duplicate, Swap Symbol, use counts and unused items, sort, search, preview, Allow Smoothing), ~~Library and Properties polish~~ ✅ (ADR 0053: drag onto the stage, Swap Bitmap, Convert to Symbol folders, mixed on every Properties row), ~~9-slice scaling~~ ✅ first slice (ADR 0055); ~~colour effects, complete~~ ✅ (ADR 0056: Properties' Style menu with None, Brightness, Tint, Advanced and Alpha, one exact colour transform in the CPU oracle, the GPU stage, SVG `feColorMatrix`, HTML canvas and Lottie, XFL `Color` import with a corpus package, classic tweens across styles, motion tween tint colour, brightness and Advanced tracks; not yet: camera colour effects beyond tint, a colour picker for the Motion Editor's tint colour); ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). |
|
||||
| **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅, ~~shape hints~~ ✅ (ADR 0023); ~~motion tween + Motion Editor curves~~ ✅ first slice (ADR 0016); ~~motion paths on the stage with orient to path~~ ✅ first slice (ADR 0030), ~~path point add/delete/convert and moving the whole path~~ ✅ (ADR 0038), ~~anchors pinned to frames~~ ✅ (ADR 0049; 3D and XFL import later); ~~library management~~ ✅ first slice (ADR 0050: folders, rename, duplicate, Swap Symbol, use counts and unused items, sort, search, preview, Allow Smoothing), ~~Library and Properties polish~~ ✅ (ADR 0053: drag onto the stage, Swap Bitmap, Convert to Symbol folders, mixed on every Properties row), ~~9-slice scaling~~ ✅ first slice (ADR 0055); ~~colour effects, complete~~ ✅ (ADR 0056: Properties' Style menu with None, Brightness, Tint, Advanced and Alpha, one exact colour transform in the CPU oracle, the GPU stage, SVG `feColorMatrix`, HTML canvas and Lottie, XFL `Color` import with a corpus package, classic tweens across styles, motion tween tint colour, brightness and Advanced tracks; not yet: a colour picker for the Motion Editor's tint colour); ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). |
|
||||
| **M3** | GPU stage *(in progress; the default stage renderer since ADR 0032)* | ~~wgpu renderer behind a feature flag~~ ✅ first slice (ADR 0019: the oracle's fills, CPU tile binning with backdrops, compute coverage; gradient tables in a storage buffer); ~~per-pixel parity tests vs the CPU oracle~~ ✅ (max 1/255, mean < 0.0001/255); ~~4K at 60 fps for 1,000 shapes~~ ✅ (8.8–9.0 ms); ~~no-readback textures, masks/groups/blend modes on the GPU~~ ✅ second slice (ADR 0029: window's device, 4K 10k shapes in 10.2 ms as tiles); ~~GPU binning~~ ✅ fourth slice (ADR 0048: heavy frames without masks or groups binned on the GPU, 50k shapes at 4K 122 → 22.5 ms in one texture; outline mode's hairlines as fast as tinted onion skin); ~~bitmaps and filters on the GPU~~ ✅ third slice (ADR 0032: bitmaps byte-identical, filters max 1/255; 4K filtered sample 3.9 ms, 200 bitmaps 4.4 ms); ~~hardware breadth~~ ✅ Vulkan and DX12 (FXC), software adapters refused, oracle-checked self-test; ~~GPU as the default stage renderer~~ ✅ (`gpu-stage` on by default for the app, automatic CPU fallback); next: GPU binning inside masks and groups, shared filtered layers across tiles, an image atlas, GPU exports. |
|
||||
| **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~larger self-authored corpus with golden render tests~~ ✅ (ADR 0035: twelve packages covering every mapped feature, exact report expectations, hostile variants, CPU-oracle goldens); ~~`.fla` variants of the corpus and a hardened zip reader~~ ✅ (ADR 0054: nine zip layouts imported identically to the folder, ZIP64, CP437 names, a 9,664-archive hostile fuzz; a 54.6 MB `.fla` imports in 0.31 s); not yet: sound and video items, self-extracting and top-folder `.fla` archives; ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (frame-accurate; easing curves instead of per-frame keys later); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅; ~~animated PNG and WebP~~ ✅ (ADR 0063; lossless WebP; lossy WebP not yet). |
|
||||
| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles later); ~~text on a path~~ ✅ first slice (ADR 0070: a copy of a shape's outline in the block, glyphs set by arc length and stored as outlines, offset, flip and alignment, Attach to Path by picking a shape, SVG `textPath`; editing the path in place and several lines on a path later); ~~dynamic and input text fields~~ ✅ first slice (ADR 0066: Text type in Properties, instance names, `field.text`/`appendText`/`length` in scripts, typing with caret, selection, max chars and passwords in Test Movie, native inputs in the HTML export, XFL fields kept; `htmlText`, change events, embedded fonts in HTML and other `TextField` API later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039); ~~button sounds and hit-area editing~~ ✅ (ADR 0057: state sounds in Test Movie and HTML, state names on the timeline, the Hit area over the other states, Show hit areas in Test Movie, XFL sounds in the package); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import; filter presets, reordering, on/off and tweened filter values later) and ~~blend modes~~ ✅ on Movie Clips. |
|
||||
| **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017; exporter and easing kinds later); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it; ~~filters, Subtract and Invert in the page~~ ✅, ADR 0072); command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); ~~tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts~~ ✅; ~~tier 2.5 small logic (typed variables, expressions, `if` and loops, property reads, functions across frames, enter-frame and keyboard listeners, seeded random, ADR 0052)~~ ✅. The full language, the `flash.*` API and SWF bytecode are not planned. |
|
||||
| **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: spring, joint translation, runtime armatures, XFL armature import, editing member instances' properties in place); ~~shape armatures~~ ✅ first slice (ADR 0071: bones inside one shape, automatic binding, linear blend skinning, Bind tool; not yet: instances and shapes in one armature, reshaping a bound shape, painted weights); ~~asset warp~~ ✅ first slice (ADR 0079: warp meshes on shapes and bitmaps, pins, rigid MLS, pin poses tweened, Asset Warp tool, every export; not yet: outline-following ARAP meshes, symbols, pins bound to bones, a GPU textured path, bent bitmaps in HTML/Lottie); ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export; not yet: editing while previewing, perspective depth, brightness/advanced colour, attaching layers to the camera, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~brush library, pressure curves and the Paint Brush~~ ✅ first slice (ADR 0068: parameter presets, user brushes and brush sets, curve editor, velocity, stroke mode; not yet: tilt, textured brushes); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles; not yet: erasing inside symbols, gradients and width profiles in the merge) and brush library; graph-based easing presets library. |
|
||||
| **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: outline-following ARAP meshes, symbols, pins bound to bones, a GPU textured path, bent bitmaps in HTML/Lottie); not yet: spring, joint translation, runtime armatures, XFL armature import, editing member instances' properties in place); ~~shape armatures~~ ✅ first slice (ADR 0071: bones inside one shape, automatic binding, linear blend skinning, Bind tool; not yet: instances and shapes in one armature, reshaping a bound shape, painted weights); ~~asset warp~~ ✅ first slice (ADR 0079: warp meshes on shapes and bitmaps, pins, rigid MLS, pin poses tweened, Asset Warp tool, ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export); ~~layer depth in perspective, keyed over time, Layer Depth panel, attaching layers, camera colour effects, editing while previewing~~ ✅ second slice (ADR 0082; not yet: tools other than Selection while previewing, depth inside symbols, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~brush library, pressure curves and the Paint Brush~~ ✅ first slice (ADR 0068: parameter presets, user brushes and brush sets, curve editor, velocity, stroke mode; not yet: tilt, textured brushes); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles; not yet: erasing inside symbols, gradients and width profiles in the merge) and brush library; graph-based easing presets library. |
|
||||
| **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; ~~opening documents from Finder~~ ✅ (ADR 0062, to be checked on a Mac); next: AppImage desktop integration, portable mode, store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node, the release zip made by `packaging/web/package.sh` and checked in CI (#210); next: releases carrying it and a hosted copy, once the team decides where, Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), second pass ✅ (ADR 0064: stage elements and timeline frames for screen readers, keyboard selection on the stage, keyboard menu bar, following the system's contrast setting), ~~a light theme~~ ✅ (ADR 0077: Light palette, Follow system for light or dark, #227), next: live screen-reader passes on each platform, a light high-contrast palette; ~~crash-recovery autosave~~ ✅ (ADR 0015); ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058: `find.search`/`find.replace`/`find.goto` over text, fonts, colours, symbols, sounds and bitmaps, scene or document, linear-time patterns, Replace All as one undo step asking above 100 places, going there opens symbols in place; `explorer.tree` paged, Show filters and search, the Movie Explorer tab beside the Library, lists drawing only the rows in view; not yet: action parameters and ActionScript strings apart from code, font size and style, colour tolerance, renaming in the Movie Explorer); ~~files from the desktop, recent files and a start screen~~ ✅ first slice (ADR 0059: drops route by type and target in one undo step, Open Recent with pins and missing files, start screen with presets and thumbnails); ~~templates, SVG into the Library, drops on the timeline~~ ✅ first slice (ADR 0065: six built-in templates built in code, Save as Template with category and picture, SVG as a graphic symbol, sounds onto a frame's keyframe and media into a keyframe made there; next: exact desktop drop positions once eframe moves to winit 0.31, user template descriptions and renaming); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060: the publish profile in the document, every format with its export options and an output relative to the document's folder with `{name}`, Shift+F12 publishing in the background with progress, Cancel and one report, overwriting asked once per session, presets in Preferences, the browser's downloads as one ZIP; not yet: Animate's PublishSettings.xml from XFL, more placeholders, outputs outside the document's folder, progress inside HTML, Lottie and audio); ~~documentation book~~ ✅ first slice (ADR 0069: the user guide in `docs/guide/`, generated command and shortcut references, Help › User Guide offline; next: translated guides, search, PDF, context help); ~~dockable panels and workspaces~~ ✅ first slice (ADR 0075, #249: every panel docks on any side of the stage, stacks as tabs, resizes, folds, floats in a window of its own with ADR 0062's fallback, closes and reopens where it was from the Window menu; Essentials, Animator, Designer and your own workspaces with Reset, kept in the preferences; new Colour and Output panels; Ctrl+F6 follows the layout; not yet: moving the tools, dragging a floating window back into a dock, several tabs in one floating window, deleting and renaming workspaces, docks collapsed to icons). |
|
||||
|
||||
## Releases
|
||||
@@ -61,7 +61,7 @@ titled with its milestone.
|
||||
| M4 | Text from Animate files | XFL import, text engine (M5 first slice) |
|
||||
| M5 | Audio layers: import, waveform, playback sync | timeline, layers |
|
||||
| M6 | ~~WebAssembly plug-ins (U2)~~ ✅ first slice (ADR 0017); ~~frame scripts and Test Movie on the plug-in host~~ ✅ first slice (ADR 0024); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028); ~~ActionScript tier 1: keep scripts~~ ✅ (ADR 0013); ~~ActionScript tier 2: run the timeline subset~~ ✅ (ADR 0013); ~~ActionScript tier 2.5: small logic~~ ✅ (ADR 0052); next: command macros, or growing the ActionScript subset (`switch`, arrays, event bubbling) | command registry, plug-in host, action IR and player |
|
||||
| M7 | ~~Variable-width strokes~~ ✅ (ADR 0018), ~~camera layer with depth~~ ✅ first slice (ADR 0027), ~~Bone tool and IK~~ ✅ first slice (ADR 0043), ~~shape armatures and the Bind tool~~ ✅ first slice (ADR 0071), ~~Asset Warp~~ ✅ first slice (ADR 0079), ~~Brush tool~~ ✅ first slice (ADR 0033), ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034); ~~brush library and pressure curves~~ ✅ first slice (ADR 0068); next: Paint Selection/Inside, tilt | strokes, Pen and Pencil, width profiles, timeline evaluation |
|
||||
| M7 | ~~Variable-width strokes~~ ✅ (ADR 0018), ~~camera layer with depth~~ ✅ first slice (ADR 0027), ~~camera depth, attaching and colour~~ ✅ (ADR 0082), ~~Bone tool and IK~~ ✅ first slice (ADR 0043), ~~shape armatures and the Bind tool~~ ✅ first slice (ADR 0071), ~~Asset Warp~~ ✅ first slice (ADR 0079), ~~Brush tool~~ ✅ first slice (ADR 0033), ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034); ~~brush library and pressure curves~~ ✅ first slice (ADR 0068); next: Paint Selection/Inside, tilt | strokes, Pen and Pencil, width profiles, timeline evaluation |
|
||||
| M8 | ~~Crash-recovery autosave~~ ✅, ~~accessibility first pass~~ ✅ (ADR 0022), ~~installers and signing~~ ✅ first slice (ADR 0026), ~~web build~~ ✅ first slice (ADR 0036), ~~localisation~~ ✅ first slice (ADR 0040), ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058), ~~drops, recent files and the start screen~~ ✅ first slice (ADR 0059); ~~templates and drops on the timeline~~ ✅ first slice (ADR 0065); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060); ~~Test Movie in its own window and macOS document opening~~ ✅ first slice (ADR 0062); ~~accessibility second pass~~ ✅ (ADR 0064); ~~a light theme~~ ✅ (ADR 0077); ~~CI on macOS and Windows~~ ✅ (ADR 0067); ~~dockable panels and workspaces~~ ✅ first slice (ADR 0075); next: live screen-reader passes | `.anicraft` format, session, AccessKit in eframe |
|
||||
|
||||
Tasks that wait on an open track: XFL motion tweens (on M2's motion tweens); frame scripts and
|
||||
|
||||
+26
@@ -192,6 +192,10 @@ pub struct StageView {
|
||||
pub enum Drag {
|
||||
None,
|
||||
Move { last: egui::Pos2 },
|
||||
/// Selection tool on the camera preview (ADR 0082): moving the selection with the pointer,
|
||||
/// which was at picture point `last`; each move maps back through the camera and the
|
||||
/// active layer's depth.
|
||||
CameraMove { last: anicraft_engine::geom::Vec2 },
|
||||
/// Selection tool: moving the selection, snapping as it goes (ADR 0041): from stage point
|
||||
/// `start`, `applied` moved so far.
|
||||
SnapMove { start: egui::Pos2, applied: egui::Vec2 },
|
||||
@@ -2031,6 +2035,28 @@ impl App {
|
||||
self.last_tool = Tool::Camera;
|
||||
self.camera_preview = which == "cameraview";
|
||||
}
|
||||
Some(which @ ("layerdepth" | "layerdepthview")) => {
|
||||
// A parallax scene mid-pan (ADR 0082): the camera pans right and pushes in over
|
||||
// the first second; the sky is far back, the sun and hills between, the star
|
||||
// attached to the camera like a title; the Layer Depth panel open, frame 12.
|
||||
self.run("camera.add", json!({}));
|
||||
self.run("timeline.insert_keyframe", json!({"frame": 23}));
|
||||
self.run("camera.set", json!({"frame": 23, "dx": 100, "zoom": 125}));
|
||||
self.run("timeline.create_tween", json!({"frame": 0}));
|
||||
let id = |app: &App, name: &str| app.s.doc.timeline(0).layers.iter().find(|l| l.name.eq_ignore_ascii_case(name)).map(|l| l.id.0);
|
||||
for (name, depth) in [("sky", 900), ("sun", 450), ("hills", 200)] {
|
||||
if let Some(l) = id(self, name) {
|
||||
self.run("layer.set_depth", json!({"layer": l, "depth": depth}));
|
||||
}
|
||||
}
|
||||
if let Some(l) = id(self, "star") {
|
||||
self.run("layer.set_attached", json!({"layer": l, "attached": true}));
|
||||
}
|
||||
self.run("timeline.goto", json!({"frame": 12}));
|
||||
self.tool = Tool::Select;
|
||||
self.camera_preview = which == "layerdepthview";
|
||||
self.show_panel(crate::dock::Panel::LayerDepth);
|
||||
}
|
||||
Some("bones") => {
|
||||
// A three-limb arm on an armature (ADR 0043): bent by IK at frame 1, the elbow
|
||||
// limited, a second pose at frame 24, the elbow's bone selected.
|
||||
|
||||
+32
-1
@@ -5,7 +5,11 @@
|
||||
//! Camera tool, a drag pans the camera, the round handle above the frame turns it, and the
|
||||
//! wheel zooms it; each drag (or burst of wheel turns) is one undo step. With View › Preview
|
||||
//! Through Camera the stage shows the movie's picture instead: there a drag moves the picture
|
||||
//! under the pointer (the camera the other way), as panning a view does.
|
||||
//! under the pointer (the camera the other way), as panning a view does, and the Selection
|
||||
//! tool picks and drags artwork where the movie shows it (ADR 0082): the press picks through
|
||||
//! the camera (`element.pick {view: camera}`), and each move is mapped back to the stage
|
||||
//! through the inverse of the picked layer's view (camera and depth), so the artwork follows
|
||||
//! the pointer on the picture.
|
||||
|
||||
use crate::app::{App, Drag, Tool};
|
||||
use crate::theme::to_color32;
|
||||
@@ -172,3 +176,30 @@ pub fn draw(app: &App, painter: &egui::Painter, g: &Geo, hot: Option<Pos2>) {
|
||||
painter.circle(knob, if hot { 6.5 } else { 5.5 }, Color32::WHITE, Stroke::new(1.5, color));
|
||||
}
|
||||
}
|
||||
|
||||
/// A Selection tool press on the camera preview at picture point `at`: picks what the movie
|
||||
/// shows there and, on artwork, starts moving the selection (one undo step).
|
||||
pub fn select_press(app: &mut App, at: Vec2, add: bool) -> Drag {
|
||||
app.bone_sel = None;
|
||||
let hit = app.run("element.pick", json!({"x": at.x, "y": at.y, "add": add, "view": "camera"}));
|
||||
if hit.is_none_or(|v| v["element"].is_null()) || app.s.selection.is_empty() {
|
||||
return Drag::None;
|
||||
}
|
||||
app.s.begin_gesture(tr_noop!("Move"));
|
||||
Drag::CameraMove { last: at }
|
||||
}
|
||||
|
||||
/// Continues a move on the preview to picture point `cur`: the picture's step mapped back to
|
||||
/// the stage through the active layer's view, so the artwork stays under the pointer.
|
||||
pub fn move_to(app: &mut App, last: &mut Vec2, cur: Vec2) {
|
||||
let d = cur - *last;
|
||||
if d.length() <= 0.0 {
|
||||
return;
|
||||
}
|
||||
*last = cur;
|
||||
let back = app.s.camera_view(app.s.layer).and_then(|v| v.inverse()).unwrap_or(Affine::IDENTITY);
|
||||
let s = back.apply_vector(d);
|
||||
if s.x.is_finite() && s.y.is_finite() {
|
||||
app.run("element.translate", json!({"dx": s.x, "dy": s.y}));
|
||||
}
|
||||
}
|
||||
+8
-1
@@ -23,6 +23,7 @@ pub enum Panel {
|
||||
Library,
|
||||
MovieExplorer,
|
||||
History,
|
||||
LayerDepth,
|
||||
Timeline,
|
||||
MotionEditor,
|
||||
Actions,
|
||||
@@ -32,7 +33,7 @@ pub enum Panel {
|
||||
|
||||
impl Panel {
|
||||
/// In the Window menu's order.
|
||||
pub const ALL: [Panel; 11] = [Panel::Actions, Panel::Align, Panel::Colour, Panel::History, Panel::Library, Panel::MotionEditor, Panel::MovieExplorer, Panel::Output, Panel::Properties, Panel::Swatches, Panel::Timeline];
|
||||
pub const ALL: [Panel; 12] = [Panel::Actions, Panel::Align, Panel::Colour, Panel::History, Panel::LayerDepth, Panel::Library, Panel::MotionEditor, Panel::MovieExplorer, Panel::Output, Panel::Properties, Panel::Swatches, Panel::Timeline];
|
||||
|
||||
/// Its machine name, in the preferences (English, never translated).
|
||||
pub fn id(self) -> &'static str {
|
||||
@@ -43,6 +44,7 @@ impl Panel {
|
||||
Panel::Library => "library",
|
||||
Panel::MovieExplorer => "movie_explorer",
|
||||
Panel::History => "history",
|
||||
Panel::LayerDepth => "layer_depth",
|
||||
Panel::Timeline => "timeline",
|
||||
Panel::MotionEditor => "motion_editor",
|
||||
Panel::Actions => "actions",
|
||||
@@ -64,6 +66,7 @@ impl Panel {
|
||||
Panel::Library => tr_noop!("Library"),
|
||||
Panel::MovieExplorer => tr_noop!("Movie Explorer"),
|
||||
Panel::History => tr_noop!("History"),
|
||||
Panel::LayerDepth => tr_noop!("Layer Depth"),
|
||||
Panel::Timeline => tr_noop!("Timeline"),
|
||||
Panel::MotionEditor => tr_noop!("Motion Editor"),
|
||||
Panel::Actions => tr_noop!("Actions"),
|
||||
@@ -80,6 +83,7 @@ impl Panel {
|
||||
Panel::Output => [520.0, 300.0],
|
||||
Panel::Align => [300.0, 140.0],
|
||||
Panel::Swatches => [300.0, 300.0],
|
||||
Panel::LayerDepth => [440.0, 260.0],
|
||||
_ => [320.0, 460.0],
|
||||
}
|
||||
}
|
||||
@@ -457,6 +461,9 @@ fn default_home(p: Panel) -> Home {
|
||||
Panel::History => (Side::Right, None),
|
||||
Panel::Timeline | Panel::MotionEditor | Panel::Output => (Side::Bottom, Some(Panel::Timeline)),
|
||||
Panel::Actions => (Side::Right, None),
|
||||
// Layer Depth opens as a tab beside the Library, under Properties, where it has the
|
||||
// width for its tracks.
|
||||
Panel::LayerDepth => (Side::Right, Some(Panel::Library)),
|
||||
};
|
||||
Home { side, near, floating: p == Panel::Actions }
|
||||
}
|
||||
|
||||
@@ -505,6 +505,9 @@ pub fn panel_body(app: &mut App, ui: &mut egui::Ui, p: Panel) {
|
||||
Panel::History => {
|
||||
pad(12, 8).show(ui, |ui| crate::panels::history(app, ui));
|
||||
}
|
||||
Panel::LayerDepth => {
|
||||
scroll("layer_depth").show(ui, |ui| pad(12, 8).show(ui, |ui| crate::layer_depth::panel(app, ui)));
|
||||
}
|
||||
Panel::Timeline => crate::timeline::show(app, ui),
|
||||
Panel::MotionEditor => crate::motion_editor::show(app, ui),
|
||||
Panel::Actions => {
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
//! Window › Layer Depth (ADR 0082): the scene's layers listed by depth, nearest first, each with
|
||||
//! a track to drag it nearer (left) or farther (right), its depth in pixels, a key toggle that
|
||||
//! animates the depth over time, and Attach to Camera. The track is laid out by how far a layer
|
||||
//! moves when the camera pans (`FOCAL / (FOCAL + depth)`), so equal distances on it look like
|
||||
//! equal steps in parallax, and the busy range near the stage gets the room. Each drag is one
|
||||
//! undo step; edits show on the stage in the same frame.
|
||||
|
||||
use crate::a11y::{self, Named};
|
||||
use crate::app::App;
|
||||
use crate::theme::{T, TARGET, Type, text, to_color32};
|
||||
use anicraft_engine::doc::camera::{FOCAL, MAX_DEPTH, MIN_DEPTH, parallax};
|
||||
use anicraft_engine::doc::{Layer, LayerKind};
|
||||
use egui::{Sense, Stroke, StrokeKind, pos2, vec2};
|
||||
use serde_json::json;
|
||||
|
||||
/// Whether a layer of this kind has a depth (the camera, folders and guides don't).
|
||||
pub fn has_depth(kind: LayerKind) -> bool {
|
||||
!matches!(kind, LayerKind::Camera | LayerKind::Folder | LayerKind::Guide)
|
||||
}
|
||||
|
||||
/// Where depth `d` sits on the track, `0` (nearest) to `1` (farthest).
|
||||
pub fn track_pos(d: f32) -> f32 {
|
||||
let (near, far) = (parallax(MIN_DEPTH), parallax(MAX_DEPTH));
|
||||
((near - parallax(d)) / (near - far)).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
/// The depth at track position `u` (the inverse of [`track_pos`]), rounded to whole pixels.
|
||||
pub fn track_depth(u: f32) -> f32 {
|
||||
let (near, far) = (parallax(MIN_DEPTH), parallax(MAX_DEPTH));
|
||||
let u = if u.is_finite() { u.clamp(0.0, 1.0) } else { 0.0 };
|
||||
let p = near - u * (near - far);
|
||||
(FOCAL / p - FOCAL).round().clamp(MIN_DEPTH, MAX_DEPTH)
|
||||
}
|
||||
|
||||
/// The Depth row in Properties for the active layer: the value at the playhead, a key toggle,
|
||||
/// and Attach to Camera.
|
||||
pub fn depth_row(app: &mut App, ui: &mut egui::Ui, layer: &Layer, frame: u32) {
|
||||
let mut depth = layer.depth_at(frame);
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_sized(vec2(84.0, TARGET * 0.8), egui::Label::new(text(Type::Label, tr!("Depth"))));
|
||||
let r = ui.add(egui::DragValue::new(&mut depth).suffix(" px").speed(2.0).range(MIN_DEPTH..=MAX_DEPTH).max_decimals(0)).named(tr!("Layer depth"));
|
||||
if r.on_hover_text(tr!("How far behind the stage this layer is: through the camera a deeper layer moves and zooms less, and draws behind nearer ones. Negative is in front.")).changed() {
|
||||
crate::panels::live(app, tr_noop!("Layer Depth"), "layer.set_depth", json!({"layer": layer.id.0, "depth": depth}));
|
||||
}
|
||||
key_button(app, ui, layer, frame);
|
||||
});
|
||||
let mut attached = layer.attached;
|
||||
if crate::theme::checkbox(ui, &mut attached, tr!("Attach layer to camera")).on_hover_text(tr!("The layer stays where it is on screen while the camera moves: for titles and HUDs")).changed() {
|
||||
app.run("layer.set_attached", json!({"layer": layer.id.0, "attached": attached}));
|
||||
}
|
||||
}
|
||||
|
||||
/// The diamond that keys the layer's depth at the playhead (filled: a key here), or removes it.
|
||||
fn key_button(app: &mut App, ui: &mut egui::Ui, layer: &Layer, frame: u32) {
|
||||
let here = layer.depth_keys.iter().any(|k| k.frame == frame);
|
||||
let keyed = !layer.depth_keys.is_empty();
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(TARGET * 0.8, TARGET * 0.8), Sense::click());
|
||||
let c = rect.center();
|
||||
let r = rect.height() * 0.28;
|
||||
let pts = vec![c - vec2(0.0, r), c + vec2(r, 0.0), c + vec2(0.0, r), c - vec2(r, 0.0)];
|
||||
let color = if resp.hovered() { T.icon_hot } else if keyed { T.accent } else { T.icon };
|
||||
let fill = if here { color } else { egui::Color32::TRANSPARENT };
|
||||
ui.painter().add(egui::Shape::convex_polygon(pts, fill, Stroke::new(1.5, color)));
|
||||
let tip = if here { tr!("Remove the depth key on this frame") } else { tr!("Key the depth on this frame: the depth then tweens between keys") };
|
||||
a11y::control(ui, &resp, egui::WidgetType::Button, tr!("Depth key"), Some(here));
|
||||
if resp.on_hover_text(tip).clicked() {
|
||||
if here {
|
||||
app.run("layer.remove_depth_key", json!({"layer": layer.id.0, "frame": frame}));
|
||||
} else {
|
||||
app.run("layer.set_depth", json!({"layer": layer.id.0, "depth": layer.depth_at(frame), "key": true, "frame": frame}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The panel.
|
||||
pub fn panel(app: &mut App, ui: &mut egui::Ui) {
|
||||
if !app.s.editing.is_empty() {
|
||||
ui.label(text(Type::Caption, tr!("Layer depth belongs to a scene's layers. Edit the document (Edit › Edit Document) to set it.")));
|
||||
return;
|
||||
}
|
||||
let frame = app.s.frame;
|
||||
let tl = app.s.doc.timeline(app.s.scene).clone();
|
||||
if tl.camera_layer().is_none() {
|
||||
ui.label(text(Type::Caption, tr!("Depth works through the camera: deeper layers move and zoom less as it moves.")));
|
||||
if ui.button(tr!("Add Camera")).named(tr!("Add camera")).clicked() {
|
||||
app.run("camera.add", json!({}));
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Nearest first; ties in timeline order (top first), as `layer.depths` lists them.
|
||||
let mut rows: Vec<(usize, &Layer)> = tl.layers.iter().enumerate().filter(|(_, l)| has_depth(l.kind)).map(|(i, l)| (i, &**l)).collect();
|
||||
rows.sort_by(|a, b| a.1.depth_at(frame).total_cmp(&b.1.depth_at(frame)).then(a.0.cmp(&b.0)));
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(text(Type::Caption, tr!("Nearer")));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| ui.label(text(Type::Caption, tr!("Farther"))));
|
||||
});
|
||||
for (_, layer) in rows {
|
||||
ui.push_id(layer.id.0, |ui| layer_row(app, ui, layer, frame));
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
ui.label(text(Type::Caption, tr!("Drag a layer along its track, or type its depth. The diamond keys the depth on this frame.")));
|
||||
}
|
||||
|
||||
/// One layer: its colour and name, the track with its handle, the value, the key and Attach.
|
||||
fn layer_row(app: &mut App, ui: &mut egui::Ui, layer: &Layer, frame: u32) {
|
||||
let depth = layer.depth_at(frame);
|
||||
let active = app.s.layer == layer.id;
|
||||
let label = tr!("Depth of {layer}", layer = layer.name);
|
||||
// First line: the layer's colour and name; its value, key and Attach on the right.
|
||||
ui.horizontal(|ui| {
|
||||
let (chip, _) = ui.allocate_exact_size(vec2(10.0, TARGET * 0.8), Sense::hover());
|
||||
ui.painter().rect_filled(egui::Rect::from_center_size(chip.center(), vec2(8.0, 8.0)), 2.0, to_color32(layer.color));
|
||||
let name = ui.add(egui::Label::new(text(Type::Body, layer.name.clone()).color(if active { T.text } else { T.text_dim })).truncate().sense(Sense::click()));
|
||||
if name.clicked() {
|
||||
app.run("layer.select", json!({"layer": layer.id.0}));
|
||||
}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let mut attached = layer.attached;
|
||||
if ui.toggle_value(&mut attached, text(Type::Label, tr!("Attach"))).named(&tr!("Attach {layer} to camera", layer = layer.name)).on_hover_text(tr!("Attach Layer to Camera: the layer stays where it is on screen while the camera moves")).changed() {
|
||||
app.run("layer.set_attached", json!({"layer": layer.id.0, "attached": attached}));
|
||||
}
|
||||
key_button(app, ui, layer, frame);
|
||||
let mut v = depth;
|
||||
if ui.add(egui::DragValue::new(&mut v).suffix(" px").speed(2.0).range(MIN_DEPTH..=MAX_DEPTH).max_decimals(0)).named(&label).changed() {
|
||||
crate::panels::live(app, tr_noop!("Layer Depth"), "layer.set_depth", json!({"layer": layer.id.0, "depth": v}));
|
||||
}
|
||||
});
|
||||
});
|
||||
// Second line: the track, the panel's width. Drag the handle (or click on the track).
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(14.0);
|
||||
let width = (ui.available_width() - 4.0).max(48.0);
|
||||
let (track, resp) = ui.allocate_exact_size(vec2(width, TARGET * 0.6), Sense::click_and_drag());
|
||||
let p = ui.painter();
|
||||
let y = track.center().y;
|
||||
p.line_segment([pos2(track.left(), y), pos2(track.right(), y)], Stroke::new(2.0, T.border));
|
||||
// The stage plane, marked.
|
||||
let x0 = track.left() + track_pos(0.0) * track.width();
|
||||
p.line_segment([pos2(x0, y - 5.0), pos2(x0, y + 5.0)], Stroke::new(1.0, T.text_faint));
|
||||
let hx = track.left() + track_pos(depth) * track.width();
|
||||
let hot = resp.hovered() || resp.dragged();
|
||||
let handle = egui::Rect::from_center_size(pos2(hx, y), vec2(8.0, track.height() * 0.8));
|
||||
let fill = if layer.attached { T.text_faint } else { to_color32(layer.color) };
|
||||
p.rect(handle, 2.0, fill, Stroke::new(if hot { 1.5 } else { 1.0 }, if hot { T.icon_hot } else { T.border }), StrokeKind::Inside);
|
||||
a11y::control(ui, &resp, egui::WidgetType::Slider, &label, None);
|
||||
if (resp.dragged() || resp.clicked())
|
||||
&& let Some(at) = resp.interact_pointer_pos()
|
||||
{
|
||||
let d = track_depth((at.x - track.left()) / track.width().max(1.0));
|
||||
if d != depth {
|
||||
crate::panels::live(app, tr_noop!("Layer Depth"), "layer.set_depth", json!({"layer": layer.id.0, "depth": d}));
|
||||
}
|
||||
}
|
||||
if resp.drag_stopped() {
|
||||
app.s.end_gesture();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_track_runs_nearest_to_farthest_and_back() {
|
||||
assert_eq!(track_pos(MIN_DEPTH), 0.0);
|
||||
assert_eq!(track_pos(MAX_DEPTH), 1.0);
|
||||
assert!(track_pos(0.0) > 0.4 && track_pos(0.0) < 0.6, "the stage plane is mid-track: {}", track_pos(0.0));
|
||||
for d in [-500.0, -120.0, 0.0, 37.0, 1000.0, 4321.0, 10_000.0] {
|
||||
assert!((track_depth(track_pos(d)) - d).abs() <= 1.0, "{d}");
|
||||
}
|
||||
assert_eq!(track_depth(f32::NAN), MIN_DEPTH);
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -39,6 +39,7 @@ mod warp_tool;
|
||||
mod bone_tool;
|
||||
mod camera_tool;
|
||||
mod convert_symbol;
|
||||
mod layer_depth;
|
||||
mod layer_props;
|
||||
mod dialogs;
|
||||
mod dock;
|
||||
@@ -254,7 +255,7 @@ fn parse_args(args: impl IntoIterator<Item = String>) -> Result<Args, String> {
|
||||
/// `--help` (the console's text, in English).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
// i18n-exempt: the --help console text
|
||||
const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width <px>]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme graphite|high-contrast] [--scale <percent>] [--lang <code>|auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|rulers|editguides|editgrid|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|polystar|paintinside|drawingedit|shapeenvelope|brushlibrary|brushcurve|paintbrush|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|library|librarymenu|colour|layerprops|frameview|layercolour|timelinepolish|dock|animator|designer|gradient|gradientbucket|swatches|swatchpanel]\n\
|
||||
const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width <px>]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme graphite|high-contrast] [--scale <percent>] [--lang <code>|auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|rulers|editguides|editgrid|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|polystar|paintinside|drawingedit|shapeenvelope|brushlibrary|brushcurve|paintbrush|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|layerdepth|layerdepthview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|library|librarymenu|colour|layerprops|frameview|layercolour|timelinepolish|dock|animator|designer|gradient|gradientbucket|swatches|swatchpanel]\n\
|
||||
--renderer the window's graphics (also ANICRAFT_RENDERER); default automatic, falling back to OpenGL\n\
|
||||
--open shows a panel at start (handy with --screenshot for visual checks)\n\
|
||||
--shot-width scales the screenshot down to this width (the user guide's pictures)\n\
|
||||
|
||||
+40
-31
@@ -670,24 +670,44 @@ fn mixed(ui: &mut egui::Ui, differs: bool) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whose colour effect the rows edit: the selected elements' (every style), or the camera's
|
||||
/// (ADR 0082: no opacity, so no Alpha style and no alpha channel in Advanced).
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum EffectOf {
|
||||
Selection,
|
||||
Camera,
|
||||
}
|
||||
|
||||
impl EffectOf {
|
||||
fn command(self) -> &'static str {
|
||||
match self {
|
||||
EffectOf::Selection => "element.set_color_effect",
|
||||
EffectOf::Camera => "camera.set",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour effect (ADR 0056): Animate's Style menu, then the chosen style's controls. Each
|
||||
/// change sets that value on every selected element (ADR 0053), as one undo step per drag.
|
||||
fn colour_effect_rows(app: &mut App, ui: &mut egui::Ui, fx: &ColorEffect, m: crate::mixed::ColorMixed) {
|
||||
/// change sets that value on every selected element (ADR 0053), or on the camera, as one undo
|
||||
/// step per drag.
|
||||
fn colour_effect_rows(app: &mut App, ui: &mut egui::Ui, fx: &ColorEffect, m: crate::mixed::ColorMixed, of: EffectOf) {
|
||||
let current = fx.style();
|
||||
let cmd = of.command();
|
||||
let camera = of == EffectOf::Camera;
|
||||
row_prose(ui, tr!("Colour effect"), |ui| {
|
||||
egui::ComboBox::from_id_salt("prop_color_style").selected_text(crate::i18n::t(current.label())).show_ui(ui, |ui| {
|
||||
for st in ColorStyle::ALL {
|
||||
egui::ComboBox::from_id_salt(if camera { "prop_camera_color_style" } else { "prop_color_style" }).selected_text(crate::i18n::t(current.label())).show_ui(ui, |ui| {
|
||||
for st in ColorStyle::ALL.into_iter().filter(|st| !camera || *st != ColorStyle::Alpha) {
|
||||
if ui.selectable_label(st == current, crate::i18n::t(st.label())).clicked() && (st != current || m.style) {
|
||||
app.run("element.set_color_effect", json!({"style": st.key()}));
|
||||
app.run(cmd, json!({"style": st.key()}));
|
||||
}
|
||||
}
|
||||
})
|
||||
.response
|
||||
.set_name(tr!("Colour effect style"));
|
||||
.set_name(if camera { tr!("Camera colour effect style") } else { tr!("Colour effect style") });
|
||||
mixed(ui, m.style);
|
||||
});
|
||||
let pct = a11y::SliderLook { suffix: " %", max_decimals: Some(0), ..Default::default() };
|
||||
let set = |app: &mut App, p: Value| live(app, tr_noop!("Colour Effect"), "element.set_color_effect", p);
|
||||
let set = |app: &mut App, p: Value| live(app, if camera { tr_noop!("Camera Colour Effect") } else { tr_noop!("Colour Effect") }, cmd, p);
|
||||
match *fx {
|
||||
ColorEffect::None => {}
|
||||
ColorEffect::Alpha(a) => {
|
||||
@@ -728,7 +748,8 @@ fn colour_effect_rows(app: &mut App, ui: &mut egui::Ui, fx: &ColorEffect, m: cra
|
||||
ColorEffect::Advanced(t) => {
|
||||
// Each channel: its multiplier in percent, then the offset added (−255..255).
|
||||
let channels = [(tr!("Red"), tr!("Red multiplier"), tr!("Red offset"), "red"), (tr!("Green"), tr!("Green multiplier"), tr!("Green offset"), "green"), (tr!("Blue"), tr!("Blue multiplier"), tr!("Blue offset"), "blue"), (tr!("Alpha"), tr!("Alpha multiplier"), tr!("Alpha offset"), "alpha")];
|
||||
for (i, (label, mul_name, off_name, key)) in channels.into_iter().enumerate() {
|
||||
// The camera has no opacity: its Advanced effect has no alpha channel.
|
||||
for (i, (label, mul_name, off_name, key)) in channels.into_iter().enumerate().take(if camera { 3 } else { 4 }) {
|
||||
let mut mv = t.mul.get(i).copied().unwrap_or(1.0) * 100.0;
|
||||
let mut ov = t.add.get(i).copied().unwrap_or(0.0) * 255.0;
|
||||
row(ui, label, |ui| {
|
||||
@@ -795,7 +816,7 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E
|
||||
mixed(ui, m.rotation);
|
||||
});
|
||||
if !matches!(e.kind, ElementKind::Camera) {
|
||||
colour_effect_rows(app, ui, &e.color, m.color);
|
||||
colour_effect_rows(app, ui, &e.color, m.color, EffectOf::Selection);
|
||||
}
|
||||
// Blending and filters, on movie clips and buttons as in Animate.
|
||||
if let ElementKind::Symbol { symbol, filters, .. } = &e.kind
|
||||
@@ -1595,7 +1616,8 @@ pub fn text_style_rows(app: &mut App, ui: &mut egui::Ui, st: &mut anicraft_engin
|
||||
out
|
||||
}
|
||||
|
||||
/// The camera at the playhead: where it looks, its zoom, turn and tint, and the preview switch.
|
||||
/// The camera at the playhead: where it looks, its zoom, turn and colour effect, and the
|
||||
/// preview switch.
|
||||
/// Edits key the playhead like any edit of a tweened object.
|
||||
fn camera_props(app: &mut App, ui: &mut egui::Ui) {
|
||||
let Some(cam) = crate::camera_tool::camera(app) else { return };
|
||||
@@ -1621,26 +1643,19 @@ fn camera_props(app: &mut App, ui: &mut egui::Ui) {
|
||||
live(app, tr_noop!("Rotate Camera"), "camera.set", json!({"rotation": rot}));
|
||||
}
|
||||
});
|
||||
let mut tint = rgb(cam.tint);
|
||||
let mut amount = cam.tint_amount * 100.0;
|
||||
row(ui, tr!("Tint"), |ui| {
|
||||
let a = crate::colour::button(ui, &mut tint).named(tr!("Camera tint colour"));
|
||||
let b = ui.add(egui::DragValue::new(&mut amount).suffix(" %").speed(0.5).range(0.0..=100.0).max_decimals(0)).named(tr!("Camera tint amount"));
|
||||
if a.changed() || b.changed() {
|
||||
live(app, tr_noop!("Camera Tint"), "camera.set", json!({"tint": hex(tint), "tint_amount": amount}));
|
||||
}
|
||||
});
|
||||
// Brightness, Tint or Advanced over the whole view, as on an instance (ADR 0082).
|
||||
colour_effect_rows(app, ui, &cam.color, crate::mixed::ColorMixed::default(), EffectOf::Camera);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let mut on = app.camera_preview;
|
||||
if crate::theme::checkbox(ui, &mut on, tr!("Preview through camera")).on_hover_text(tr!("Show the stage as the movie shows it (View › Preview Through Camera)")).changed() {
|
||||
app.toggle_camera_preview();
|
||||
}
|
||||
if ui.button(tr!("Reset")).named(tr!("Reset camera")).on_hover_text(tr!("Back to the stage as it is: centred, 100 %, no turn, no tint")).clicked() {
|
||||
if ui.button(tr!("Reset")).named(tr!("Reset camera")).on_hover_text(tr!("Back to the stage as it is: centred, 100 %, no turn, no colour effect")).clicked() {
|
||||
app.run("camera.set", json!({"reset": true}));
|
||||
}
|
||||
});
|
||||
let hidden = app.s.timeline().camera_layer().is_some_and(|l| !l.visible);
|
||||
ui.label(text(Type::Caption, if hidden { tr!("The camera layer is hidden: the movie shows the stage as it is.") } else { tr!("The movie shows what the frame on the stage shows. Layer depth (in Frame, per layer) moves far layers less.") }));
|
||||
ui.label(text(Type::Caption, if hidden { tr!("The camera layer is hidden: the movie shows the stage as it is.") } else { tr!("The movie shows what the frame on the stage shows. Deeper layers (Window › Layer Depth) move and zoom less.") }));
|
||||
}
|
||||
|
||||
/// The selected bone: its joint angle at the playhead (editing it keys the pose), the joint's
|
||||
@@ -1790,16 +1805,10 @@ fn frame_props(app: &mut App, ui: &mut egui::Ui, layer: &anicraft_engine::doc::L
|
||||
ui.label(text(Type::Caption, tr!("Folders hold layers, not frames. Hiding or locking the folder hides or locks everything in it; move layers in under it with Up and Down.")));
|
||||
return;
|
||||
}
|
||||
// Layer depth matters once the scene has a camera: deeper layers move less as it pans.
|
||||
if layer.kind != anicraft_engine::doc::LayerKind::Camera && app.s.timeline().camera_layer().is_some() {
|
||||
let mut depth = layer.depth;
|
||||
let (lo, hi) = (anicraft_engine::doc::camera::MIN_DEPTH, anicraft_engine::doc::camera::MAX_DEPTH);
|
||||
row(ui, tr!("Depth"), |ui| {
|
||||
let r = ui.add(egui::DragValue::new(&mut depth).suffix(" px").speed(2.0).range(lo..=hi).max_decimals(0)).named(tr!("Layer depth"));
|
||||
if r.on_hover_text(tr!("How far behind the stage this layer is: when the camera pans, a deeper layer moves less (parallax). Negative is in front.")).changed() {
|
||||
live(app, tr_noop!("Layer Depth"), "layer.set_depth", json!({"depth": depth}));
|
||||
}
|
||||
});
|
||||
// Layer depth matters once the scene has a camera (ADR 0082): deeper layers move and zoom
|
||||
// less, and draw behind nearer ones.
|
||||
if crate::layer_depth::has_depth(layer.kind) && app.s.timeline().camera_layer().is_some() && app.s.editing.is_empty() {
|
||||
crate::layer_depth::depth_row(app, ui, layer, frame);
|
||||
}
|
||||
{
|
||||
match layer.keyframe_at(frame) {
|
||||
|
||||
+31
-6
@@ -296,8 +296,10 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
let to_screen = |p: Vec2| pos2(origin.x + p.x * zoom, origin.y + p.y * zoom);
|
||||
let to_stage = |p: Pos2| pos2((p.x - origin.x) / zoom, (p.y - origin.y) / zoom);
|
||||
let painter = ui.painter_at(canvas);
|
||||
// View > Preview Through Camera: the stage shows the movie's picture (ADR 0027). Artwork
|
||||
// tools pause meanwhile (what they'd edit is in stage space, not where it shows).
|
||||
// View > Preview Through Camera: the stage shows the movie's picture (ADR 0027). The
|
||||
// Selection tool picks and moves artwork there, the pointer mapped back through the camera
|
||||
// and each layer's depth (ADR 0082); the other artwork tools pause (what they'd edit is in
|
||||
// stage space, not where it shows).
|
||||
let preview = crate::camera_tool::previewing(app);
|
||||
let cam_geo = crate::camera_tool::Geo { origin: st_origin, zoom: st_zoom, stage_rect, preview };
|
||||
// Library items dragged onto the stage land at the pointer (ADR 0053).
|
||||
@@ -311,12 +313,14 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
let pointer = resp.hover_pos().or_else(|| resp.interact_pointer_pos());
|
||||
app.cursor_stage = pointer.filter(|p| canvas.contains(*p)).map(to_stage);
|
||||
let panning = app.tool == Tool::Hand || space || resp.dragged_by(egui::PointerButton::Middle);
|
||||
let paused = preview && !panning && !matches!(app.tool, Tool::Camera | Tool::Hand | Tool::Zoom);
|
||||
let paused = preview && !panning && !matches!(app.tool, Tool::Camera | Tool::Hand | Tool::Zoom | Tool::Select);
|
||||
// The Selection tool on the movie's picture: points there are the picture's (ADR 0082).
|
||||
let through = preview && !panning && app.tool == Tool::Select;
|
||||
// A drag from a ruler makes a guide (ADR 0076).
|
||||
crate::rulers::input(app, ui, &bars, geo, preview);
|
||||
let guide_hot = if app.drag == Drag::None && !panning && !preview { pointer.and_then(|p| crate::rulers::guide_at(app, geo, p)) } else { None };
|
||||
if paused && (resp.drag_started() || resp.clicked()) {
|
||||
app.status_ok(tr!("Previewing through the camera: artwork edits are paused. Turn off View › Preview Through Camera to edit."));
|
||||
app.status_ok(tr!("Previewing through the camera: the Selection tool picks and moves artwork here; other tools wait. Turn off View › Preview Through Camera to draw."));
|
||||
}
|
||||
// Selection box in screen space (free transform handles live on it).
|
||||
// Edit Multiple Frames takes the Selection and Free Transform tools' input (ADR 0047); Free
|
||||
@@ -415,6 +419,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
Drag::Pan
|
||||
} else if paused {
|
||||
Drag::None
|
||||
} else if through {
|
||||
crate::camera_tool::select_press(app, to_v(sp), shift)
|
||||
} else if let Some(i) = crate::rulers::guide_at(app, geo, press) {
|
||||
// The Selection tool on a guide moves it; onto a ruler, deletes it (ADR 0076).
|
||||
crate::rulers::drag_start(app, i)
|
||||
@@ -521,6 +527,11 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
}
|
||||
match (&mut app.drag, cur) {
|
||||
(Drag::Pan, _) => app.view.pan += resp.drag_delta(),
|
||||
(Drag::CameraMove { last }, Some(c)) => {
|
||||
let mut l = *last;
|
||||
crate::camera_tool::move_to(app, &mut l, to_v(c));
|
||||
app.drag = Drag::CameraMove { last: l };
|
||||
}
|
||||
(Drag::Move { last }, Some(c)) => {
|
||||
let d = c - *last;
|
||||
if d.length_sq() > 0.0 {
|
||||
@@ -644,7 +655,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
|
||||
if resp.drag_stopped() {
|
||||
match app.drag {
|
||||
Drag::Move { .. } | Drag::SnapMove { .. } => {
|
||||
Drag::Move { .. } | Drag::SnapMove { .. } | Drag::CameraMove { .. } => {
|
||||
app.drop_raw();
|
||||
app.s.end_gesture();
|
||||
}
|
||||
@@ -686,6 +697,11 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
&& let Some(p) = resp.interact_pointer_pos() {
|
||||
let sp = to_stage(p);
|
||||
match app.tool {
|
||||
// Previewing: pick what the movie shows there (ADR 0082).
|
||||
Tool::Select if through => {
|
||||
app.bone_sel = None;
|
||||
app.run("element.pick", json!({"x": sp.x, "y": sp.y, "add": shift, "view": "camera"}));
|
||||
}
|
||||
_ if !panning && let Some(text) = app.path_pick.take() => {
|
||||
app.s.selection = anicraft_engine::Selection::only(app.s.layer, [text]);
|
||||
if app.run("text.attach_path", json!({"x": sp.x, "y": sp.y})).is_some() {
|
||||
@@ -1051,6 +1067,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
let raw = raw_ids(app);
|
||||
if app.tool == Tool::Select && app.drag == Drag::None
|
||||
&& !multi
|
||||
&& !preview
|
||||
&& app.palette.is_none()
|
||||
&& !app.modal_open()
|
||||
&& let Some(sp) = app.cursor_stage
|
||||
@@ -1066,7 +1083,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
// An open envelope (ADR 0080) shows its mesh instead of boxes.
|
||||
let enveloped = crate::shape_envelope::shown(app).is_some();
|
||||
// Selected raw shapes (ADR 0031) show Animate's dot pattern over themselves, with no box.
|
||||
if app.tool == Tool::Select {
|
||||
if app.tool == Tool::Select && !preview {
|
||||
let to_px = Affine::translate(origin.x, origin.y).mul(&Affine::scale(zoom, zoom));
|
||||
let (mut spans, mut dots) = (Vec::new(), egui::Mesh::default());
|
||||
let mut budget = MAX_DOTS;
|
||||
@@ -1092,6 +1109,14 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
if b.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// Previewing: the box where the movie shows it, through the camera and the layer's
|
||||
// depth (ADR 0082).
|
||||
if preview {
|
||||
let v = app.s.camera_view(layer).unwrap_or(Affine::IDENTITY);
|
||||
let q = [b.min, Vec2::new(b.max.x, b.min.y), b.max, Vec2::new(b.min.x, b.max.y)].map(|p| to_screen(v.apply(p)));
|
||||
painter.add(egui::Shape::closed_line(q.to_vec(), sel_stroke));
|
||||
continue;
|
||||
}
|
||||
let r = Rect::from_min_max(to_screen(b.min), to_screen(b.max)).expand(1.0);
|
||||
if matches!(app.tool, Tool::Subselect | Tool::Width | Tool::GradientTransform) {
|
||||
// Subselection and Width show outlines and points instead (below); Gradient
|
||||
|
||||
+16
-2
@@ -516,8 +516,11 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
let onion_t = (!is_camera && !is_folder).then(|| toggle(3.0));
|
||||
// A layer with sounds has a speaker before the others: Mute (ADR 0039).
|
||||
let speaker = layer.has_sounds().then(|| toggle(if onion_t.is_some() { 4.0 } else { 3.0 }));
|
||||
// With a camera in the scene, layers with artwork can be attached to it (ADR 0082):
|
||||
// they then stay put on screen while it moves.
|
||||
let attach_t = (tl_now.camera_layer().is_some() && app.s.editing.is_empty() && crate::layer_depth::has_depth(layer.kind)).then(|| toggle(3.0 + f32::from(u8::from(onion_t.is_some())) + f32::from(u8::from(speaker.is_some()))));
|
||||
let hover = ui.input(|inp| inp.pointer.hover_pos());
|
||||
for r in [eye, lock, outl].into_iter().take(if is_camera { 2 } else { 3 }).chain(onion_t).chain(speaker) {
|
||||
for r in [eye, lock, outl].into_iter().take(if is_camera { 2 } else { 3 }).chain(onion_t).chain(speaker).chain(attach_t) {
|
||||
if hover.is_some_and(|h| r.contains(h)) {
|
||||
painter.rect_filled(r, T.rc(), T.hover);
|
||||
}
|
||||
@@ -543,6 +546,10 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
painter.line_segment([g.left_bottom(), g.right_top()], Stroke::new(1.5, c_off));
|
||||
}
|
||||
}
|
||||
// Attached to the camera: the camera glyph, bright when attached.
|
||||
if let Some(at) = attach_t {
|
||||
icons::paint(&painter, glyph(at), Icon::Camera, if layer.attached { T.accent_text } else { c_off });
|
||||
}
|
||||
// outline swatch
|
||||
let sw = Rect::from_center_size(outl.center(), vec2(10.0, 10.0));
|
||||
if is_camera {
|
||||
@@ -553,7 +560,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
} else {
|
||||
painter.rect_filled(sw, 0.0, to_color32(layer.color));
|
||||
}
|
||||
let name_rect = Rect::from_min_max(left.left_top(), pos2(speaker.or(onion_t).unwrap_or(eye).left() - 4.0, left.bottom()));
|
||||
let name_rect = Rect::from_min_max(left.left_top(), pos2(attach_t.or(speaker).or(onion_t).unwrap_or(eye).left() - 4.0, left.bottom()));
|
||||
let nr = ui.interact(name_rect, ui.id().with(("lname", layer.id.0)), Sense::click());
|
||||
// Screen readers hear the row as a selectable item, "Ball · layer", then its toggles.
|
||||
let name = &layer.name;
|
||||
@@ -588,6 +595,13 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
app.run(id, json!({"layer": layer.id.0}));
|
||||
}
|
||||
}
|
||||
if let Some(at) = attach_t {
|
||||
let rr = ui.interact(at, ui.id().with(("attach", layer.id.0)), Sense::click());
|
||||
a11y::control(ui, &rr, WidgetType::Checkbox, &tr!("Attach {name} to camera", name = name), Some(layer.attached));
|
||||
if rr.on_hover_text(tr!("Attach Layer to Camera: the layer stays where it is on screen while the camera moves (titles, HUDs)")).clicked() {
|
||||
app.run("layer.set_attached", json!({"layer": layer.id.0}));
|
||||
}
|
||||
}
|
||||
if let Some(ot) = onion_t {
|
||||
let rr = ui.interact(ot, ui.id().with(("onion", layer.id.0)), Sense::click());
|
||||
a11y::control(ui, &rr, WidgetType::Checkbox, &tr!("Onion skin {name}", name = name), Some(layer.onion));
|
||||
|
||||
Reference in new issue
Block a user