mirror of
https://github.com/storytold/AniCraft.git
synced 2026-11-23 19:12:08 +01:00
Merge pull request #458 from storytold/m6/data-tables
feat(data): data tables that drive animation (M6)
This commit is contained in:
46 files changed
+4003
-57
No files matched your search
+2
-1
@@ -25,7 +25,7 @@ shaders or SDK code).
|
||||
| `assets/icons/*.svg` except `anicraft-*` (37 files: tools, transport, layer toggles, folders, guide, image, text, sound, chevrons, plus, trash, copy, ellipsis) | UI icons, stroked by `src/icons.rs` | Lucide Icons and Contributors (some derived from Feather by Cole Bemis) | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`), copied unchanged from the PhotoCraft sibling project's set (`volume-2.svg` from Lucide 0.512.0; `plus.svg`, `trash.svg`, `copy.svg` and `ellipsis.svg` from Lucide's `main` branch, 2026-11) | ISC (Lucide) and MIT (Feather), [`licenses/icons/LICENSE-lucide.txt`](licenses/icons/LICENSE-lucide.txt) |
|
||||
| `assets/app-icon/` (`anicraft.svg`, `anicraft-small.svg` and every render: PNGs, `anicraft.ico`, `hicolor/`) | App icon (engraved rabbit): window, Dock, taskbar, `anicraft.exe`, Help › About | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for AniCraft, vectorised by `assets/app-icon/trace.py` and rendered by `scripts/icons.sh` | MIT OR Apache-2.0 ([`assets/app-icon/LICENSE.txt`](assets/app-icon/LICENSE.txt)) |
|
||||
| `packaging/macos/dmg/` (`background.tiff`, `dmg-layout.DS_Store`) | macOS DMG window background and Finder layout | AniCraft contributors | Original work drawn by `packaging/macos/dmg/generate.py` in the app icon's colours; layout approach as in the PhotoCraft sibling project | MIT OR Apache-2.0 |
|
||||
| `docs/guide/images/` (11 screenshots) | User guide (Help › User Guide) | AniCraft contributors | Original work: AniCraft's own screenshots, taken by `scripts/guide-shots.sh` | MIT OR Apache-2.0 |
|
||||
| `docs/guide/images/` (13 screenshots) | User guide (Help › User Guide) | AniCraft contributors | Original work: AniCraft's own screenshots, taken by `scripts/guide-shots.sh` | MIT OR Apache-2.0 |
|
||||
| `docs/images/` (screenshots and `sample-animation.gif`) | README | AniCraft contributors | Original work: AniCraft's own screenshots (`--screenshot`) and sample animation (`anicraft-cli gif`) | MIT OR Apache-2.0 |
|
||||
| Library symbol-kind marks, selection handles, timeline marks | UI | AniCraft contributors | Original work, drawn in code (`src/panels.rs`, `src/timeline.rs`, `src/stage.rs`) | MIT OR Apache-2.0 |
|
||||
| Sample animation (ball, star, sun, hills, sky) | First launch, tests, CLI `--sample` | AniCraft contributors | Original work, generated in code (`crates/doc/src/sample.rs`) | MIT OR Apache-2.0 |
|
||||
@@ -92,6 +92,7 @@ OR Apache-2.0) is noted in the table.
|
||||
| Plural categories for whole numbers (zero, one, two, few, many, other) | `src/i18n/plural.rs` | Unicode CLDR, *Language Plural Rules* (`common/supplemental/plurals.xml`), <https://cldr.unicode.org>, Unicode License v3 (Unicode-3.0) | The integer rules rewritten as Rust `match`es from the published rules; no CLDR data file is bundled. |
|
||||
| Stage elements as a multi-select list box; menu bar keyboard model (Alt/F10, arrows, access keys) | `src/stage_a11y.rs`, `src/menus.rs` | W3C *WAI-ARIA Authoring Practices Guide*, Listbox and Menubar patterns, <https://www.w3.org/WAI/ARIA/apg/> (W3C Software and Document License) | Keyboard behaviour learned from the published patterns; no code or text copied. |
|
||||
| Superscript and subscript size and offset; underline position and thickness | `crates/text/src/rich.rs` | Microsoft and Adobe, *OpenType specification*, `OS/2` table (`ySuperscriptYSize`, `ySuperscriptYOffset`, `ySubscriptYSize`, `ySubscriptYOffset`) and `post` table (`underlinePosition`, `underlineThickness`), <https://learn.microsoft.com/typography/opentype/spec/> | Metrics read from the font as the specification describes them; no code copied. |
|
||||
| Data tables read from delimited text and JSON (ADR 0118) | `crates/engine/src/data_import.rs` (CSV and TSV records through `craft-csv`) | RFC 4180 *Common Format and MIME Type for Comma-Separated Values (CSV) Files*; RFC 8259 *The JavaScript Object Notation (JSON) Data Interchange Format* (public specifications) | Written from the specifications; no code copied. |
|
||||
| Desktop integration of an AppImage: desktop entry `Exec` quoting and string escapes, MIME packages, hicolor icons, the user's data folder | `crates/engine/src/cmds_desktop.rs`, `src/platform.rs` | freedesktop.org *Desktop Entry Specification* 1.5, *Shared MIME-info Database*, *Icon Theme Specification*, *XDG Base Directory Specification*, <https://specifications.freedesktop.org/>; AppImage documentation on `$APPIMAGE` (public docs) | Written from the specifications (ADR 0094); no code copied. |
|
||||
| Reading the desktop's contrast setting | `src/platform.rs` | *XDG Desktop Portal*, Settings interface, `org.freedesktop.appearance` `contrast` key, <https://flatpak.github.io/xdg-desktop-portal/> (LGPL documentation, read only; nothing bundled or linked) | One value read through the `gdbus` tool. |
|
||||
| Interface catalog format (TSV keyed by English, `@plural`/`@id` rows, fallback order) | `src/i18n/catalog.rs`, `build.rs` | storytold/craft-i18n `docs/catalog-format.md` and `docs/integration.md` (MIT OR Apache-2.0, same project family) | Our own parser written from those documents; the craft-libs `craft-i18n` crate is not used (ADR 0040). |
|
||||
|
||||
@@ -2,6 +2,29 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
* **Data-driven animation** (#416, #417, #418, ADR 0118, M6): keep the numbers behind an
|
||||
animation in the document and let them drive it.
|
||||
* **Data tables in the Library.** **File › Import › Import Data Table…** reads CSV, TSV or
|
||||
JSON: the first line names the columns, cells that aren't numbers become gaps, and columns
|
||||
with no numbers are left out (the status bar says which). A table is looked up by row
|
||||
number, a row per frame, or by a **key column** such as an age or a time. **View Table**
|
||||
shows every row and column. Tables are saved in the `.anicraft` file.
|
||||
* **Bind to Data** (Modify › Data, or the Data section of a symbol instance's Properties): a
|
||||
column drives the instance's **X**, **Y**, **Scale X**, **Scale Y**, **Rotation**, **Alpha**
|
||||
or **the frame a graphic symbol shows**, over a span of frames. Set the frames, the rows or
|
||||
keys the span runs between (backwards too), a scale and an offset, and **Linear** or
|
||||
**Step** between rows; the stage follows as you change them. The stage, Test Movie and
|
||||
every export that draws frames show the same thing.
|
||||
* **Import Again** replaces a table's values from a revised file, and everything bound to it
|
||||
follows with no keyframes to redo.
|
||||
* **Bake to Keyframes** writes what the bindings show as ordinary keyframes; every frame
|
||||
looks as it did. Use it before Lottie export, which writes keys.
|
||||
* Headless: `data.import_table`, `data.set_table`, `data.list`, `data.get`, `data.set_cell`,
|
||||
`data.set_key`, `data.remove`, `data.bind`, `data.unbind`, `data.bindings` and `data.bake`,
|
||||
over the CLI and MCP; plug-ins may use all but reading a file.
|
||||
* Not yet: bindings don't follow copy, paste or duplicate; cells aren't edited in the viewer;
|
||||
baking inside a motion tween.
|
||||
|
||||
* **Import Video** (#369, ADR 0116, M5): **File › Import › Import Video…** brings in MP4, MOV,
|
||||
WebM and any other video the ffmpeg on your computer reads, for reference and rotoscoping.
|
||||
* **Frames in the document**: the video's frames become bitmaps on a new layer from the
|
||||
|
||||
Generated
+9
@@ -318,6 +318,7 @@ dependencies = [
|
||||
"anicraft-text",
|
||||
"anicraft-xfl",
|
||||
"craft-anicraft-format",
|
||||
"craft-csv",
|
||||
"craft-gif",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=55b1d7f3c598b600a130ae63f4a40334a230ae7b)",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18)",
|
||||
@@ -1243,6 +1244,14 @@ name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18"
|
||||
|
||||
[[package]]
|
||||
name = "craft-csv"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-gif"
|
||||
version = "0.1.0"
|
||||
|
||||
@@ -41,6 +41,9 @@ craft-apng-container = { package = "craft-image-codecs", version = "0.1.0", git
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" }
|
||||
craft-webp = { git = "https://github.com/storytold/craft-libs", rev = "0c144b7d983899d4b5b281046dd03a8b1ab35fbb" }
|
||||
craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "b67b9f90c50091a3090f93fa054c34e409edba11" }
|
||||
# Delimited text (CSV, TSV) for data tables (ADR 0118): encoding and delimiter detection and a
|
||||
# bounded record parser. The same reviewed commit as craft-mime and craft-gif.
|
||||
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "b67b9f90c50091a3090f93fa054c34e409edba11" }
|
||||
# The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same
|
||||
# (default) features, so the tree keeps one wgpu build.
|
||||
|
||||
@@ -0,0 +1,688 @@
|
||||
//! Data tables that drive animation (ADR 0118).
|
||||
//!
|
||||
//! A document keeps **tables** of numbers ([`DataTable`]: named columns, one row per frame or,
|
||||
//! with a key column, one row per keyed time such as an age or a depth) and **bindings**
|
||||
//! ([`Binding`]): a column of a table drives one property of one symbol instance over a span
|
||||
//! of frames. Both live in [`Document::data`], apart from the timelines: a binding names its
|
||||
//! instance by id, so it follows the instance through keyframes and tweens without touching
|
||||
//! either, and editing or re-importing a table changes what every frame shows with no keyframe
|
||||
//! to rebuild.
|
||||
//!
|
||||
//! Bindings are applied inside [`crate::evaluate`] (time stays a function): after tweens and
|
||||
//! poses have placed a layer's elements, each bound instance gets the bound properties' values
|
||||
//! for the frame. A binding whose table or column is missing, or whose column has no number,
|
||||
//! leaves the instance as it is. Everything here is pure and bounded; nothing panics on any
|
||||
//! table, binding or frame.
|
||||
|
||||
use crate::library::FolderId;
|
||||
use crate::motion::{Property, Props};
|
||||
use crate::{Document, Element, ElementId, ElementKind, LoopMode};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::borrow::Cow;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Unique id of a data table (from the document's id counter).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub struct DataId(pub u64);
|
||||
|
||||
/// Most tables in a document.
|
||||
pub const MAX_TABLES: usize = 256;
|
||||
/// Most columns in a table.
|
||||
pub const MAX_COLUMNS: usize = 256;
|
||||
/// Most rows in a table.
|
||||
pub const MAX_ROWS: usize = 100_000;
|
||||
/// Most cells (rows × columns) in a table.
|
||||
pub const MAX_CELLS: usize = 1_000_000;
|
||||
/// Longest column name (characters).
|
||||
pub const MAX_COLUMN_NAME: usize = 64;
|
||||
/// Longest note of where a table came from (characters).
|
||||
pub const MAX_SOURCE: usize = 256;
|
||||
/// Most bindings in a document.
|
||||
pub const MAX_BINDINGS: usize = 10_000;
|
||||
/// Longest frame span a binding maps (and the last frame it may start on).
|
||||
pub const MAX_SPAN: u32 = 100_000;
|
||||
/// Largest scale or offset of a binding, and the largest value it gives.
|
||||
pub const MAX_VALUE: f64 = 1.0e9;
|
||||
|
||||
/// One named column of numbers. `None` is a gap: a cell with no number.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct DataColumn {
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub values: Vec<Option<f64>>,
|
||||
}
|
||||
|
||||
/// A table of numbers kept in the document: a Library item (ADR 0118).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct DataTable {
|
||||
pub id: DataId,
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub columns: Vec<DataColumn>,
|
||||
/// The column rows are looked up by (an age, a depth, a time). `None`: by row number, the
|
||||
/// first row being 0, so a binding of as many frames as rows shows one row per frame. A
|
||||
/// table with a key keeps its rows in the key's ascending order, rows without a key last.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub key: Option<String>,
|
||||
/// The name of the file it was imported from (the name only, never a folder), shown in the
|
||||
/// viewer and offered when importing again.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub source: String,
|
||||
/// The Library folder it is in (`None`: the top level). Kept here, not in the Library
|
||||
/// tree's placements, so builds from before data tables still open the file.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub folder: Option<FolderId>,
|
||||
}
|
||||
|
||||
fn same_name(a: &str, b: &str) -> bool {
|
||||
a == b || a.to_lowercase() == b.to_lowercase()
|
||||
}
|
||||
|
||||
/// A column name as tables keep it: trimmed, without control characters, at most
|
||||
/// [`MAX_COLUMN_NAME`] characters. Empty when nothing is left.
|
||||
pub fn clean_column_name(name: &str) -> String {
|
||||
name.trim().chars().filter(|c| !c.is_control()).take(MAX_COLUMN_NAME).collect::<String>().trim().to_string()
|
||||
}
|
||||
|
||||
impl DataTable {
|
||||
/// A table of `columns`, repaired to the rules ([`DataTable::normalize`]).
|
||||
pub fn new(id: DataId, name: impl Into<String>, columns: Vec<DataColumn>, key: Option<String>) -> DataTable {
|
||||
let mut t = DataTable { id, name: name.into(), columns, key, source: String::new(), folder: None };
|
||||
t.normalize();
|
||||
t
|
||||
}
|
||||
|
||||
/// How many rows the table has (every column has as many).
|
||||
pub fn rows(&self) -> usize {
|
||||
self.columns.iter().map(|c| c.values.len()).max().unwrap_or(0)
|
||||
}
|
||||
|
||||
/// The column called `name`: exactly, else without case.
|
||||
pub fn column_index(&self, name: &str) -> Option<usize> {
|
||||
self.columns.iter().position(|c| c.name == name).or_else(|| self.columns.iter().position(|c| same_name(&c.name, name)))
|
||||
}
|
||||
|
||||
pub fn column(&self, name: &str) -> Option<&DataColumn> {
|
||||
self.column_index(name).and_then(|i| self.columns.get(i))
|
||||
}
|
||||
|
||||
/// The key column, when the table has one.
|
||||
pub fn key_column(&self) -> Option<&DataColumn> {
|
||||
self.key.as_deref().and_then(|k| self.column(k))
|
||||
}
|
||||
|
||||
/// Whether the table breaks none of the rules [`DataTable::normalize`] repairs.
|
||||
pub fn is_normal(&self) -> bool {
|
||||
let rows = self.rows();
|
||||
let cols = self.columns.len();
|
||||
let names_ok = self.columns.iter().enumerate().all(|(i, c)| !c.name.is_empty() && clean_column_name(&c.name) == c.name && !self.columns.iter().take(i).any(|o| same_name(&o.name, &c.name)));
|
||||
let sizes_ok = cols <= MAX_COLUMNS && rows <= MAX_ROWS && rows.saturating_mul(cols) <= MAX_CELLS && self.columns.iter().all(|c| c.values.len() == rows);
|
||||
let cells_ok = self.columns.iter().all(|c| c.values.iter().all(|v| v.is_none_or(f64::is_finite)));
|
||||
let key_ok = match &self.key {
|
||||
None => true,
|
||||
Some(k) => self.columns.iter().any(|c| c.name == *k) && self.key_column().is_some_and(|c| keys_sorted(&c.values)),
|
||||
};
|
||||
names_ok && sizes_ok && cells_ok && key_ok && self.source.chars().count() <= MAX_SOURCE && !self.source.contains(['/', '\\'])
|
||||
}
|
||||
|
||||
/// Repairs the table: column names cleaned and made unique (a nameless one is `Column n`),
|
||||
/// at most [`MAX_COLUMNS`] columns, [`MAX_ROWS`] rows and [`MAX_CELLS`] cells, short columns
|
||||
/// padded with gaps, cells that aren't finite turned into gaps, a key that names no column
|
||||
/// dropped, and with a key the rows put in its ascending order (stable; rows without a key
|
||||
/// last). Idempotent.
|
||||
pub fn normalize(&mut self) {
|
||||
if self.is_normal() {
|
||||
return;
|
||||
}
|
||||
self.columns.truncate(MAX_COLUMNS);
|
||||
let mut names: Vec<String> = Vec::with_capacity(self.columns.len());
|
||||
for (i, c) in self.columns.iter_mut().enumerate() {
|
||||
let mut base = clean_column_name(&c.name);
|
||||
if base.is_empty() {
|
||||
base = format!("Column {}", i + 1);
|
||||
}
|
||||
let mut name = base.clone();
|
||||
let mut n = 2usize;
|
||||
// Bounded: at most as many names are taken as there are columns.
|
||||
while names.iter().any(|o| same_name(o, &name)) && n <= MAX_COLUMNS + 2 {
|
||||
let stem: String = base.chars().take(MAX_COLUMN_NAME.saturating_sub(5)).collect();
|
||||
name = format!("{stem} {n}");
|
||||
n += 1;
|
||||
}
|
||||
c.name = name.clone();
|
||||
names.push(name);
|
||||
}
|
||||
let cols = self.columns.len().max(1);
|
||||
let rows = self.rows().min(MAX_ROWS).min(MAX_CELLS / cols);
|
||||
for c in &mut self.columns {
|
||||
c.values.resize(rows, None);
|
||||
for v in &mut c.values {
|
||||
if v.is_some_and(|x| !x.is_finite()) {
|
||||
*v = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
self.source = self.source.rsplit(['/', '\\']).next().unwrap_or("").chars().filter(|c| !c.is_control()).take(MAX_SOURCE).collect();
|
||||
self.key = self.key.as_deref().and_then(|k| self.column_index(k)).and_then(|i| self.columns.get(i)).map(|c| c.name.clone());
|
||||
if let Some(keys) = self.key_column().map(|c| c.values.clone())
|
||||
&& !keys_sorted(&keys)
|
||||
{
|
||||
let mut order: Vec<usize> = (0..rows).collect();
|
||||
let key = |i: usize| keys.get(i).copied().flatten();
|
||||
order.sort_by(|&a, &b| match (key(a), key(b)) {
|
||||
(Some(x), Some(y)) => x.total_cmp(&y),
|
||||
(Some(_), None) => std::cmp::Ordering::Less,
|
||||
(None, Some(_)) => std::cmp::Ordering::Greater,
|
||||
(None, None) => std::cmp::Ordering::Equal,
|
||||
});
|
||||
for c in &mut self.columns {
|
||||
c.values = order.iter().map(|&i| c.values.get(i).copied().flatten()).collect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The first and last key a binding maps a span onto by default: the key column's lowest
|
||||
/// and highest, or the first and last row numbers. `None` for a table with no rows (or no
|
||||
/// keyed row).
|
||||
pub fn key_range(&self) -> Option<(f64, f64)> {
|
||||
match self.key_column() {
|
||||
Some(k) => {
|
||||
let n = k.values.partition_point(Option::is_some);
|
||||
let first = k.values.first().copied().flatten()?;
|
||||
let last = n.checked_sub(1).and_then(|i| k.values.get(i)).copied().flatten()?;
|
||||
Some((first, last))
|
||||
}
|
||||
None => self.rows().checked_sub(1).map(|last| (0.0, last as f64)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Column `column`'s value at `key` (a row number when the table has no key column):
|
||||
/// between the nearest rows with a number on either side, straight across ([`Interp::Linear`])
|
||||
/// or held from the earlier one ([`Interp::Step`]). Before the first such row and after the
|
||||
/// last, theirs. Gaps are skipped. `None` when the column has no number at all.
|
||||
pub fn sample(&self, column: usize, key: f64, interp: Interp) -> Option<f64> {
|
||||
let vals = &self.columns.get(column)?.values;
|
||||
if !key.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let keys = self.key_column().map(|c| c.values.as_slice());
|
||||
// The rows that have a key, and the first of them whose key is past `key`.
|
||||
let (n, i) = match keys {
|
||||
Some(k) => {
|
||||
let n = k.partition_point(Option::is_some).min(vals.len());
|
||||
(n, k.get(..n)?.partition_point(|x| x.is_some_and(|x| x <= key)))
|
||||
}
|
||||
None => {
|
||||
let n = vals.len();
|
||||
(n, if key < 0.0 { 0 } else if key >= n as f64 { n } else { (key.floor() as usize + 1).min(n) })
|
||||
}
|
||||
};
|
||||
let key_of = |j: usize| match keys {
|
||||
Some(k) => k.get(j).copied().flatten(),
|
||||
None => Some(j as f64),
|
||||
};
|
||||
let value = |j: usize| vals.get(j).copied().flatten();
|
||||
let lo = (0..i).rev().find(|&j| value(j).is_some());
|
||||
let hi = (i..n).find(|&j| value(j).is_some());
|
||||
match (lo, hi) {
|
||||
(None, None) => None,
|
||||
(Some(a), None) => value(a),
|
||||
(None, Some(b)) => value(b),
|
||||
(Some(a), Some(b)) => match interp {
|
||||
Interp::Step => value(a),
|
||||
Interp::Linear => {
|
||||
let (va, vb, ka, kb) = (value(a)?, value(b)?, key_of(a)?, key_of(b)?);
|
||||
let span = kb - ka;
|
||||
let v = if span > 0.0 { va + (vb - va) * ((key - ka) / span).clamp(0.0, 1.0) } else { va };
|
||||
v.is_finite().then_some(v)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether keys are in ascending order with the rows that have none last.
|
||||
fn keys_sorted(keys: &[Option<f64>]) -> bool {
|
||||
keys.windows(2).all(|w| match (w.first().copied().flatten(), w.get(1).copied().flatten()) {
|
||||
(Some(a), Some(b)) => a <= b,
|
||||
(None, Some(_)) => false,
|
||||
_ => true,
|
||||
})
|
||||
}
|
||||
|
||||
/// How a binding reads a column between two rows.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Interp {
|
||||
/// Straight from one row's value to the next.
|
||||
#[default]
|
||||
Linear,
|
||||
/// Each row's value is held until the next row.
|
||||
Step,
|
||||
}
|
||||
|
||||
impl Interp {
|
||||
pub const ALL: [Interp; 2] = [Interp::Linear, Interp::Step];
|
||||
|
||||
pub fn key(self) -> &'static str {
|
||||
match self {
|
||||
Interp::Linear => "linear",
|
||||
Interp::Step => "step",
|
||||
}
|
||||
}
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Interp::Linear => "Linear",
|
||||
Interp::Step => "Step",
|
||||
}
|
||||
}
|
||||
pub fn from_key(s: &str) -> Option<Interp> {
|
||||
match s.trim().to_ascii_lowercase().as_str() {
|
||||
"linear" | "smooth" => Some(Interp::Linear),
|
||||
"step" | "hold" | "stepped" => Some(Interp::Step),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn is_linear(&self) -> bool {
|
||||
*self == Interp::Linear
|
||||
}
|
||||
}
|
||||
|
||||
/// A property of an instance a column can drive.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum BoundProperty {
|
||||
/// Registration point, pixels in the layer's space.
|
||||
X,
|
||||
Y,
|
||||
/// Percent (100 = natural size).
|
||||
ScaleX,
|
||||
ScaleY,
|
||||
/// Degrees, clockwise on screen.
|
||||
Rotation,
|
||||
/// Opacity, percent.
|
||||
Alpha,
|
||||
/// The frame of its symbol a graphic instance shows, counted from 0 (0 is the symbol's
|
||||
/// first frame) and held as a single frame.
|
||||
Frame,
|
||||
}
|
||||
|
||||
impl BoundProperty {
|
||||
pub const ALL: [BoundProperty; 7] = [BoundProperty::X, BoundProperty::Y, BoundProperty::ScaleX, BoundProperty::ScaleY, BoundProperty::Rotation, BoundProperty::Alpha, BoundProperty::Frame];
|
||||
|
||||
/// The name used in files and commands.
|
||||
pub fn key(self) -> &'static str {
|
||||
match self {
|
||||
BoundProperty::X => "x",
|
||||
BoundProperty::Y => "y",
|
||||
BoundProperty::ScaleX => "scale_x",
|
||||
BoundProperty::ScaleY => "scale_y",
|
||||
BoundProperty::Rotation => "rotation",
|
||||
BoundProperty::Alpha => "alpha",
|
||||
BoundProperty::Frame => "frame",
|
||||
}
|
||||
}
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
BoundProperty::X => "X",
|
||||
BoundProperty::Y => "Y",
|
||||
BoundProperty::ScaleX => "Scale X",
|
||||
BoundProperty::ScaleY => "Scale Y",
|
||||
BoundProperty::Rotation => "Rotation",
|
||||
BoundProperty::Alpha => "Alpha",
|
||||
BoundProperty::Frame => "Frame shown",
|
||||
}
|
||||
}
|
||||
pub fn unit(self) -> &'static str {
|
||||
match self {
|
||||
BoundProperty::X | BoundProperty::Y => "px",
|
||||
BoundProperty::ScaleX | BoundProperty::ScaleY | BoundProperty::Alpha => "%",
|
||||
BoundProperty::Rotation => "°",
|
||||
BoundProperty::Frame => "",
|
||||
}
|
||||
}
|
||||
pub fn from_key(s: &str) -> Option<BoundProperty> {
|
||||
let s = s.trim().to_ascii_lowercase().replace([' ', '-'], "_");
|
||||
let s = match s.as_str() {
|
||||
"opacity" => "alpha",
|
||||
"scalex" => "scale_x",
|
||||
"scaley" => "scale_y",
|
||||
"rotate" => "rotation",
|
||||
"first_frame" | "firstframe" => "frame",
|
||||
other => other,
|
||||
};
|
||||
BoundProperty::ALL.into_iter().find(|p| p.key() == s)
|
||||
}
|
||||
/// The motion property this is (`None` for the frame shown).
|
||||
fn property(self) -> Option<Property> {
|
||||
match self {
|
||||
BoundProperty::X => Some(Property::X),
|
||||
BoundProperty::Y => Some(Property::Y),
|
||||
BoundProperty::ScaleX => Some(Property::ScaleX),
|
||||
BoundProperty::ScaleY => Some(Property::ScaleY),
|
||||
BoundProperty::Rotation => Some(Property::Rotation),
|
||||
BoundProperty::Alpha => Some(Property::Alpha),
|
||||
BoundProperty::Frame => None,
|
||||
}
|
||||
}
|
||||
/// `v` kept within what the property takes (as a motion tween's curve is).
|
||||
pub fn clamp(self, v: f32) -> f32 {
|
||||
match self.property() {
|
||||
Some(p) => {
|
||||
let r = p.range();
|
||||
v.clamp(*r.start(), *r.end())
|
||||
}
|
||||
None => v.round().clamp(0.0, MAX_SPAN as f32),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn one() -> f64 {
|
||||
1.0
|
||||
}
|
||||
fn is_one(v: &f64) -> bool {
|
||||
*v == 1.0
|
||||
}
|
||||
fn is_zero(v: &f64) -> bool {
|
||||
*v == 0.0
|
||||
}
|
||||
|
||||
/// A column of a table driving one property of one instance over a span of frames.
|
||||
///
|
||||
/// The span's first frame shows the key `from`, its last the key `to`, the frames between keys
|
||||
/// in a straight line between the two; the column read there ([`DataTable::sample`]) times
|
||||
/// `scale` plus `offset` is the property's value. Before the span the instance shows the first
|
||||
/// frame's value and after it the last's, so a chart doesn't snap back when its data ends.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Binding {
|
||||
pub element: ElementId,
|
||||
pub property: BoundProperty,
|
||||
pub table: DataId,
|
||||
pub column: String,
|
||||
/// The span's first frame, on the timeline the instance is on.
|
||||
#[serde(default)]
|
||||
pub start: u32,
|
||||
/// How many frames the span has (at least 1).
|
||||
#[serde(default = "one_frame")]
|
||||
pub frames: u32,
|
||||
/// The key the first frame shows. `None`: the table's first ([`DataTable::key_range`]).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub from: Option<f64>,
|
||||
/// The key the last frame shows. `None`: the table's last. May be before `from`, to play a
|
||||
/// record backwards (ages run from old to young).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub to: Option<f64>,
|
||||
#[serde(default, skip_serializing_if = "Interp::is_linear")]
|
||||
pub interp: Interp,
|
||||
#[serde(default = "one", skip_serializing_if = "is_one")]
|
||||
pub scale: f64,
|
||||
#[serde(default, skip_serializing_if = "is_zero")]
|
||||
pub offset: f64,
|
||||
}
|
||||
|
||||
fn one_frame() -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
impl Binding {
|
||||
/// The key frame `frame` shows in `table`: exact at the span's ends, and exact on every
|
||||
/// frame of a span with one frame per row.
|
||||
pub fn key_at(&self, table: &DataTable, frame: u32) -> Option<f64> {
|
||||
let (first, last) = table.key_range()?;
|
||||
let (from, to) = (self.from.unwrap_or(first), self.to.unwrap_or(last));
|
||||
let den = self.frames.max(1) - 1;
|
||||
let num = frame.saturating_sub(self.start).min(den);
|
||||
let key = if num == 0 {
|
||||
from
|
||||
} else if num >= den {
|
||||
to
|
||||
} else {
|
||||
// Multiplied before dividing: with one frame per row this is the row number exactly.
|
||||
from + (to - from) * f64::from(num) / f64::from(den)
|
||||
};
|
||||
key.is_finite().then_some(key)
|
||||
}
|
||||
|
||||
/// The property's value at `frame`, in the property's units and range. `None` when the
|
||||
/// table or column is missing or has no number: the instance stays as placed.
|
||||
pub fn value_at(&self, data: &DataSet, frame: u32) -> Option<f32> {
|
||||
let table = data.table(self.table)?;
|
||||
let column = table.column_index(&self.column)?;
|
||||
let v = table.sample(column, self.key_at(table, frame)?, self.interp)? * self.scale + self.offset;
|
||||
v.is_finite().then(|| self.property.clamp(v.clamp(-MAX_VALUE, MAX_VALUE) as f32))
|
||||
}
|
||||
|
||||
/// Whether the binding breaks none of the rules [`Binding::sanitize`] repairs.
|
||||
fn is_sane(&self) -> bool {
|
||||
let fin = |v: f64| v.is_finite() && v.abs() <= MAX_VALUE;
|
||||
self.start <= MAX_SPAN && (1..=MAX_SPAN).contains(&self.frames) && fin(self.scale) && fin(self.offset) && self.from.is_none_or(fin) && self.to.is_none_or(fin) && clean_column_name(&self.column) == self.column
|
||||
}
|
||||
|
||||
/// Repairs the binding's numbers and name.
|
||||
pub fn sanitize(&mut self) {
|
||||
let fin = |v: f64, or: f64| if v.is_finite() { v.clamp(-MAX_VALUE, MAX_VALUE) } else { or };
|
||||
self.start = self.start.min(MAX_SPAN);
|
||||
self.frames = self.frames.clamp(1, MAX_SPAN);
|
||||
self.scale = fin(self.scale, 1.0);
|
||||
self.offset = fin(self.offset, 0.0);
|
||||
self.from = self.from.filter(|v| v.is_finite()).map(|v| fin(v, 0.0));
|
||||
self.to = self.to.filter(|v| v.is_finite()).map(|v| fin(v, 0.0));
|
||||
self.column = clean_column_name(&self.column);
|
||||
}
|
||||
}
|
||||
|
||||
/// The document's data: its tables and what they drive.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct DataSet {
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub tables: Vec<Arc<DataTable>>,
|
||||
/// Sorted by instance, then property: one binding per property of an instance.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub bindings: Vec<Binding>,
|
||||
}
|
||||
|
||||
impl DataSet {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.tables.is_empty() && self.bindings.is_empty()
|
||||
}
|
||||
|
||||
pub fn table(&self, id: DataId) -> Option<&DataTable> {
|
||||
self.tables.iter().find(|t| t.id == id).map(|t| &**t)
|
||||
}
|
||||
|
||||
/// The bindings of instance `id`, in property order.
|
||||
pub fn bindings_of(&self, id: ElementId) -> &[Binding] {
|
||||
let a = self.bindings.partition_point(|b| b.element < id);
|
||||
let n = self.bindings.get(a..).map_or(0, |rest| rest.partition_point(|b| b.element == id));
|
||||
self.bindings.get(a..a + n).unwrap_or(&[])
|
||||
}
|
||||
|
||||
/// Adds `b`, replacing the binding of the same property of the same instance. `false`
|
||||
/// when the document can't hold another.
|
||||
pub fn bind(&mut self, mut b: Binding) -> bool {
|
||||
b.sanitize();
|
||||
let at = self.bindings.partition_point(|o| (o.element, o.property) < (b.element, b.property));
|
||||
let full = self.bindings.len() >= MAX_BINDINGS;
|
||||
match self.bindings.get_mut(at) {
|
||||
Some(o) if o.element == b.element && o.property == b.property => *o = b,
|
||||
_ if full => return false,
|
||||
_ => self.bindings.insert(at, b),
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Removes instance `id`'s binding of `property` (every binding of it for `None`). How many
|
||||
/// went.
|
||||
pub fn unbind(&mut self, id: ElementId, property: Option<BoundProperty>) -> usize {
|
||||
let before = self.bindings.len();
|
||||
self.bindings.retain(|b| b.element != id || property.is_some_and(|p| p != b.property));
|
||||
before - self.bindings.len()
|
||||
}
|
||||
|
||||
/// How many bindings read table `id`.
|
||||
pub fn uses(&self, id: DataId) -> usize {
|
||||
self.bindings.iter().filter(|b| b.table == id).count()
|
||||
}
|
||||
|
||||
/// Whether the set breaks none of the rules [`DataSet::sanitize`] repairs.
|
||||
fn is_sane(&self) -> bool {
|
||||
let tables_ok = self.tables.len() <= MAX_TABLES && self.tables.iter().enumerate().all(|(i, t)| t.is_normal() && !self.tables.iter().take(i).any(|o| o.id == t.id));
|
||||
let sorted = self.bindings.windows(2).all(|w| match (w.first(), w.get(1)) {
|
||||
(Some(a), Some(b)) => (a.element, a.property) < (b.element, b.property),
|
||||
_ => true,
|
||||
});
|
||||
tables_ok && sorted && self.bindings.len() <= MAX_BINDINGS && self.bindings.iter().all(Binding::is_sane)
|
||||
}
|
||||
|
||||
/// Repairs loaded data: tables with unique ids, each normal; bindings sane, sorted, one
|
||||
/// per property of an instance, at most [`MAX_BINDINGS`]. `true` when something changed.
|
||||
pub fn sanitize(&mut self) -> bool {
|
||||
if self.is_sane() {
|
||||
return false;
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
self.tables.retain(|t| seen.insert(t.id));
|
||||
self.tables.truncate(MAX_TABLES);
|
||||
for t in &mut self.tables {
|
||||
if !t.is_normal() {
|
||||
Arc::make_mut(t).normalize();
|
||||
}
|
||||
}
|
||||
for b in &mut self.bindings {
|
||||
b.sanitize();
|
||||
}
|
||||
self.bindings.sort_by_key(|b| (b.element, b.property));
|
||||
self.bindings.dedup_by_key(|b| (b.element, b.property));
|
||||
self.bindings.truncate(MAX_BINDINGS);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// `el` with `values` (each a property and its value, in the property's units) in place of its
|
||||
/// own: scaled and turned about its transformation point when it has one (ADR 0111), as a motion
|
||||
/// tween's curves do; alpha keeps the rest of its colour effect; a frame makes a graphic
|
||||
/// instance show that frame of its symbol and hold it.
|
||||
pub fn with_values(el: &Element, values: &[(BoundProperty, f32)]) -> Element {
|
||||
let mut out = el.clone();
|
||||
let base = Props::of(el);
|
||||
let mut props = base;
|
||||
let mut moved = false;
|
||||
for &(p, v) in values {
|
||||
let v = p.clamp(v);
|
||||
match p {
|
||||
BoundProperty::Alpha => out.color = el.color.with_alpha((v / 100.0).clamp(0.0, 1.0)).sanitized(),
|
||||
BoundProperty::Frame => {
|
||||
if let ElementKind::Symbol { loop_mode, first_frame, .. } = &mut out.kind {
|
||||
*loop_mode = LoopMode::SingleFrame;
|
||||
*first_frame = v as u32;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if let Some(q) = p.property() {
|
||||
props.set(q, v);
|
||||
moved = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if moved {
|
||||
let m = crate::motion::placed(el, &base, &props);
|
||||
if m.is_finite() {
|
||||
out.transform = m;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
impl Document {
|
||||
pub fn data_table(&self, id: DataId) -> Option<&DataTable> {
|
||||
self.data.table(id)
|
||||
}
|
||||
|
||||
/// The table called `name` (without case), the first in Library order.
|
||||
pub fn data_table_named(&self, name: &str) -> Option<&DataTable> {
|
||||
self.data.tables.iter().find(|t| t.name == name).or_else(|| self.data.tables.iter().find(|t| same_name(&t.name, name))).map(|t| &**t)
|
||||
}
|
||||
|
||||
/// What `el`'s bindings make of it at `frame` of the timeline it is on: `None` when it has
|
||||
/// none, or none of them has a value there.
|
||||
pub fn bound_element(&self, el: &Element, frame: u32) -> Option<Element> {
|
||||
let bindings = self.data.bindings_of(el.id);
|
||||
if bindings.is_empty() || !matches!(el.kind, ElementKind::Symbol { .. }) {
|
||||
return None;
|
||||
}
|
||||
let mut values = [(BoundProperty::X, 0.0f32); BoundProperty::ALL.len()];
|
||||
let mut n = 0;
|
||||
for b in bindings {
|
||||
if let (Some(v), Some(slot)) = (b.value_at(&self.data, frame), values.get_mut(n)) {
|
||||
*slot = (b.property, v);
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
(n > 0).then(|| with_values(el, values.get(..n).unwrap_or(&[])))
|
||||
}
|
||||
|
||||
/// A layer's elements at `frame` with the document's bindings applied (see
|
||||
/// [`Document::bound_element`]). Costs one check when the document binds nothing.
|
||||
pub fn bound_elements<'a>(&self, els: Cow<'a, [Arc<Element>]>, frame: u32) -> Cow<'a, [Arc<Element>]> {
|
||||
if self.data.bindings.is_empty() {
|
||||
return els;
|
||||
}
|
||||
let mut els = els;
|
||||
for i in 0..els.len() {
|
||||
let Some(bound) = els.get(i).and_then(|e| self.bound_element(e, frame)) else { continue };
|
||||
if let Some(slot) = els.to_mut().get_mut(i) {
|
||||
*slot = Arc::new(bound);
|
||||
}
|
||||
}
|
||||
els
|
||||
}
|
||||
|
||||
/// Repairs loaded data (see [`DataSet::sanitize`]); tables also get usable, unique Library
|
||||
/// names and folders that exist, and bindings of instances that are nowhere in the document
|
||||
/// are dropped. Ids count towards `max_id`. Touches the data only if something needs it.
|
||||
pub(crate) fn sanitize_data(&mut self, max_id: &mut u64) {
|
||||
if self.data.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut data = (*self.data).clone();
|
||||
let mut changed = data.sanitize();
|
||||
let mut names: Vec<String> = Vec::new();
|
||||
for (i, t) in data.tables.iter_mut().enumerate() {
|
||||
*max_id = (*max_id).max(t.id.0);
|
||||
let cleaned = crate::library::clean_name(&t.name).unwrap_or_else(|_| format!("Table {}", i + 1));
|
||||
let mut name = cleaned.clone();
|
||||
let mut n = 2usize;
|
||||
while names.iter().any(|o| same_name(o, &name)) && n <= MAX_TABLES + 2 {
|
||||
name = format!("{} {n}", cleaned.chars().take(crate::library::MAX_NAME_CHARS - 8).collect::<String>());
|
||||
n += 1;
|
||||
}
|
||||
let folder = t.folder.filter(|f| self.folder(*f).is_some());
|
||||
if name != t.name || folder != t.folder {
|
||||
let t = Arc::make_mut(t);
|
||||
t.name = name.clone();
|
||||
t.folder = folder;
|
||||
changed = true;
|
||||
}
|
||||
names.push(name);
|
||||
}
|
||||
if !data.bindings.is_empty() {
|
||||
let mut live = std::collections::HashSet::new();
|
||||
for tl in self.scenes.iter().map(|s| &s.timeline).chain(self.library.iter().map(|s| &s.timeline)) {
|
||||
for e in tl.layers.iter().flat_map(|l| l.keyframes.iter()).flat_map(|k| k.elements.iter()) {
|
||||
live.insert(e.id);
|
||||
}
|
||||
}
|
||||
let before = data.bindings.len();
|
||||
data.bindings.retain(|b| live.contains(&b.element));
|
||||
changed |= data.bindings.len() != before;
|
||||
}
|
||||
if changed {
|
||||
self.data = Arc::new(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "data_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,377 @@
|
||||
use super::*;
|
||||
use crate::{ColorEffect, Keyframe, Layer, LayerId, Paint, Rgba, Shape, Symbol, SymbolId, SymbolKind, Timeline, Tween, evaluate};
|
||||
use anicraft_geom::{Affine, Path, Vec2};
|
||||
|
||||
fn col(name: &str, v: &[Option<f64>]) -> DataColumn {
|
||||
DataColumn { name: name.into(), values: v.to_vec() }
|
||||
}
|
||||
|
||||
fn nums(name: &str, v: &[f64]) -> DataColumn {
|
||||
DataColumn { name: name.into(), values: v.iter().copied().map(Some).collect() }
|
||||
}
|
||||
|
||||
/// A document with a graphic symbol (three frames: a 10, 20 and 30 pixel square) and one
|
||||
/// instance of it (element 50) at (100, 200) on frames 0..40.
|
||||
fn doc() -> Document {
|
||||
let mut d = Document::default();
|
||||
let sid = SymbolId(40);
|
||||
let mut inner = Layer::new(LayerId(41), "art");
|
||||
inner.keyframes = (0..3u32)
|
||||
.map(|f| {
|
||||
let mut k = Keyframe::new(f, 1);
|
||||
let side = 10.0 * (f + 1) as f32;
|
||||
k.elements.push(Arc::new(Element { id: ElementId(42 + u64::from(f)), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, side, side), Paint::Solid(Rgba::BLACK))) }));
|
||||
Arc::new(k)
|
||||
})
|
||||
.collect();
|
||||
d.library.push(Arc::new(Symbol { id: sid, name: "Bar".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(inner)] } }));
|
||||
let mut k = Keyframe::new(0, 40);
|
||||
k.elements.push(Arc::new(instance(50, sid, 100.0, 200.0)));
|
||||
Arc::make_mut(&mut d.timeline_mut(0).layers[0]).keyframes = vec![Arc::new(k)];
|
||||
d.next_id = 100;
|
||||
d
|
||||
}
|
||||
|
||||
fn instance(id: u64, sid: SymbolId, x: f32, y: f32) -> Element {
|
||||
Element {
|
||||
id: ElementId(id),
|
||||
name: String::new(),
|
||||
transform: Affine::translate(x, y),
|
||||
color: ColorEffect::default(),
|
||||
kind: ElementKind::Symbol { symbol: sid, loop_mode: LoopMode::SingleFrame, first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new(), pivot: None },
|
||||
}
|
||||
}
|
||||
|
||||
fn add_table(d: &mut Document, t: DataTable) {
|
||||
Arc::make_mut(&mut d.data).tables.push(Arc::new(t));
|
||||
}
|
||||
|
||||
fn binding(property: BoundProperty, column: &str, frames: u32) -> Binding {
|
||||
Binding { element: ElementId(50), property, table: DataId(90), column: column.into(), start: 0, frames, from: None, to: None, interp: Interp::Linear, scale: 1.0, offset: 0.0 }
|
||||
}
|
||||
|
||||
fn bind(d: &mut Document, b: Binding) {
|
||||
assert!(Arc::make_mut(&mut d.data).bind(b));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_table_is_repaired_to_the_rules() {
|
||||
let t = DataTable::new(DataId(1), "t", vec![col(" a ", &[Some(1.0), Some(f64::NAN), Some(f64::INFINITY)]), col("A", &[Some(2.0)]), col("", &[]), col("\u{7}", &[])], Some("nope".into()));
|
||||
assert_eq!(t.columns.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["a", "A 2", "Column 3", "Column 4"]);
|
||||
assert_eq!(t.rows(), 3);
|
||||
assert_eq!(t.columns[0].values, [Some(1.0), None, None], "cells that aren't finite are gaps");
|
||||
assert_eq!(t.columns[1].values, [Some(2.0), None, None], "a short column is padded with gaps");
|
||||
assert_eq!(t.key, None, "a key that names no column is dropped");
|
||||
assert!(t.is_normal());
|
||||
let mut again = t.clone();
|
||||
again.normalize();
|
||||
assert_eq!(again, t, "normalize is idempotent");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_table_is_cut_to_its_limits() {
|
||||
let wide = DataTable::new(DataId(1), "t", (0..MAX_COLUMNS + 20).map(|i| nums(&format!("c{i}"), &[1.0])).collect(), None);
|
||||
assert_eq!(wide.columns.len(), MAX_COLUMNS);
|
||||
let long = DataTable::new(DataId(1), "t", vec![DataColumn { name: "a".into(), values: vec![Some(1.0); MAX_ROWS + 5] }], None);
|
||||
assert_eq!(long.rows(), MAX_ROWS);
|
||||
let big = DataTable::new(DataId(1), "t", (0..100).map(|i| DataColumn { name: format!("c{i}"), values: vec![Some(1.0); 20_000] }).collect(), None);
|
||||
assert!(big.rows() * big.columns.len() <= MAX_CELLS);
|
||||
assert_eq!(big.rows(), MAX_CELLS / 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_keyed_table_keeps_its_rows_in_key_order() {
|
||||
let t = DataTable::new(DataId(1), "t", vec![col("age", &[Some(30.0), None, Some(10.0), Some(20.0)]), nums("v", &[3.0, 9.0, 1.0, 2.0])], Some("AGE".into()));
|
||||
assert_eq!(t.key.as_deref(), Some("age"), "the key takes the column's own spelling");
|
||||
assert_eq!(t.columns[0].values, [Some(10.0), Some(20.0), Some(30.0), None]);
|
||||
assert_eq!(t.columns[1].values, [Some(1.0), Some(2.0), Some(3.0), Some(9.0)]);
|
||||
assert_eq!(t.key_range(), Some((10.0, 30.0)));
|
||||
// The row without a key plays no part.
|
||||
assert_eq!(t.sample(1, 1_000.0, Interp::Linear), Some(3.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sampling_by_row_number() {
|
||||
let t = DataTable::new(DataId(1), "t", vec![nums("v", &[10.0, 20.0, 40.0])], None);
|
||||
let s = |k, i| t.sample(0, k, i);
|
||||
assert_eq!(s(0.0, Interp::Linear), Some(10.0));
|
||||
assert_eq!(s(0.5, Interp::Linear), Some(15.0));
|
||||
assert_eq!(s(1.0, Interp::Linear), Some(20.0));
|
||||
assert_eq!(s(1.75, Interp::Linear), Some(35.0));
|
||||
assert_eq!(s(2.0, Interp::Linear), Some(40.0));
|
||||
assert_eq!(s(0.99, Interp::Step), Some(10.0));
|
||||
assert_eq!(s(1.0, Interp::Step), Some(20.0));
|
||||
assert_eq!(s(1.99, Interp::Step), Some(20.0));
|
||||
// Outside the rows: the nearest end's value.
|
||||
assert_eq!(s(-5.0, Interp::Linear), Some(10.0));
|
||||
assert_eq!(s(1e12, Interp::Step), Some(40.0));
|
||||
assert_eq!(s(f64::NAN, Interp::Linear), None);
|
||||
assert_eq!(t.sample(7, 0.0, Interp::Linear), None, "no such column");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sampling_skips_gaps() {
|
||||
let t = DataTable::new(DataId(1), "t", vec![col("v", &[None, Some(10.0), None, None, Some(40.0), None]), col("none", &[None; 6])], None);
|
||||
assert_eq!(t.sample(0, 0.0, Interp::Linear), Some(10.0), "before the first number: it");
|
||||
assert_eq!(t.sample(0, 2.0, Interp::Linear), Some(20.0), "across a gap, by row number");
|
||||
assert_eq!(t.sample(0, 3.0, Interp::Step), Some(10.0));
|
||||
assert_eq!(t.sample(0, 5.0, Interp::Linear), Some(40.0));
|
||||
assert_eq!(t.sample(1, 2.0, Interp::Linear), None, "a column of gaps has no value");
|
||||
let empty = DataTable::new(DataId(2), "e", vec![col("v", &[])], None);
|
||||
assert_eq!(empty.sample(0, 0.0, Interp::Linear), None);
|
||||
assert_eq!(empty.key_range(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sampling_by_key() {
|
||||
let t = DataTable::new(DataId(1), "t", vec![nums("depth", &[0.0, 10.0, 10.0, 30.0]), nums("v", &[1.0, 2.0, 5.0, 9.0])], Some("depth".into()));
|
||||
assert_eq!(t.sample(1, 5.0, Interp::Linear), Some(1.5));
|
||||
assert_eq!(t.sample(1, 10.0, Interp::Linear), Some(5.0), "the last row of a repeated key wins");
|
||||
assert_eq!(t.sample(1, 20.0, Interp::Linear), Some(7.0));
|
||||
assert_eq!(t.sample(1, 29.0, Interp::Step), Some(5.0));
|
||||
assert_eq!(t.sample(1, -1.0, Interp::Step), Some(1.0));
|
||||
assert_eq!(t.sample(1, 31.0, Interp::Linear), Some(9.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_frame_per_row_is_exact() {
|
||||
// 997 rows, a prime, so row/(rows - 1) is rarely exact in binary.
|
||||
let rows: Vec<f64> = (0..997).map(|i| f64::from(i) * 3.0).collect();
|
||||
let mut d = doc();
|
||||
add_table(&mut d, DataTable::new(DataId(90), "t", vec![nums("v", &rows)], None));
|
||||
let b = Binding { interp: Interp::Step, ..binding(BoundProperty::X, "v", 997) };
|
||||
for f in 0..997u32 {
|
||||
assert_eq!(b.key_at(d.data_table(DataId(90)).unwrap(), f), Some(f64::from(f)), "frame {f}");
|
||||
assert_eq!(b.value_at(&d.data, f), Some(f as f32 * 3.0), "frame {f}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_span_maps_onto_keys_forwards_and_backwards_and_holds_outside() {
|
||||
let mut d = doc();
|
||||
add_table(&mut d, DataTable::new(DataId(90), "t", vec![nums("age", &[100.0, 200.0, 300.0]), nums("v", &[1.0, 2.0, 3.0])], Some("age".into())));
|
||||
let fwd = Binding { start: 10, ..binding(BoundProperty::X, "v", 21) };
|
||||
let v = |b: &Binding, f| b.value_at(&d.data, f).unwrap();
|
||||
assert_eq!(v(&fwd, 0), 1.0, "before the span: its first frame's value");
|
||||
assert_eq!(v(&fwd, 10), 1.0);
|
||||
assert_eq!(v(&fwd, 20), 2.0);
|
||||
assert_eq!(v(&fwd, 25), 2.5);
|
||||
assert_eq!(v(&fwd, 30), 3.0);
|
||||
assert_eq!(v(&fwd, 5_000), 3.0, "after the span: its last frame's value");
|
||||
let back = Binding { from: Some(300.0), to: Some(100.0), ..fwd.clone() };
|
||||
assert_eq!(v(&back, 10), 3.0);
|
||||
assert_eq!(v(&back, 20), 2.0);
|
||||
assert_eq!(v(&back, 30), 1.0);
|
||||
let part = Binding { from: Some(150.0), to: Some(250.0), scale: 10.0, offset: -1.0, ..fwd.clone() };
|
||||
assert_eq!(v(&part, 10), 14.0);
|
||||
assert_eq!(v(&part, 30), 24.0);
|
||||
let one = Binding { frames: 1, ..fwd };
|
||||
assert_eq!(v(&one, 0), 1.0);
|
||||
assert_eq!(v(&one, 99), 1.0, "a one-frame span shows its first key");
|
||||
}
|
||||
|
||||
fn placed(d: &Document, frame: u32) -> Affine {
|
||||
evaluate(d, frame).items[0].transform
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bindings_place_the_instance_in_evaluate() {
|
||||
let mut d = doc();
|
||||
add_table(&mut d, DataTable::new(DataId(90), "t", vec![nums("x", &[0.0, 300.0]), nums("s", &[100.0, 300.0]), nums("r", &[0.0, 90.0])], None));
|
||||
assert_eq!(placed(&d, 5).translation(), Vec2::new(100.0, 200.0), "a table alone changes nothing");
|
||||
bind(&mut d, binding(BoundProperty::X, "x", 11));
|
||||
assert_eq!(placed(&d, 0).translation(), Vec2::new(0.0, 200.0));
|
||||
assert!((placed(&d, 5).translation().x - 150.0).abs() < 1e-3);
|
||||
assert_eq!(placed(&d, 10).translation(), Vec2::new(300.0, 200.0));
|
||||
assert_eq!(placed(&d, 30).translation().x, 300.0, "held after the span");
|
||||
bind(&mut d, binding(BoundProperty::ScaleY, "s", 11));
|
||||
let m = placed(&d, 10);
|
||||
assert!((m.apply(Vec2::new(10.0, 10.0)) - Vec2::new(310.0, 230.0)).length() < 1e-3, "{m:?}");
|
||||
bind(&mut d, binding(BoundProperty::Rotation, "r", 11));
|
||||
// Turned a quarter clockwise at the end: the symbol's x axis points down the stage.
|
||||
let m = placed(&d, 10);
|
||||
assert!((m.apply(Vec2::new(10.0, 0.0)) - Vec2::new(300.0, 210.0)).length() < 1e-3, "{m:?}");
|
||||
// The document itself is untouched: time is a function.
|
||||
let own = d.timeline(0).layers[0].keyframes[0].elements[0].transform;
|
||||
assert_eq!(own, Affine::translate(100.0, 200.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scale_and_rotation_turn_about_the_transformation_point() {
|
||||
let mut d = doc();
|
||||
add_table(&mut d, DataTable::new(DataId(90), "t", vec![nums("s", &[200.0])], None));
|
||||
let l = Arc::make_mut(&mut d.timeline_mut(0).layers[0]);
|
||||
Arc::make_mut(&mut l.keyframe_mut(0).unwrap().elements[0]).set_pivot(Some(Vec2::new(0.0, 10.0)));
|
||||
bind(&mut d, binding(BoundProperty::ScaleY, "s", 1));
|
||||
let m = placed(&d, 0);
|
||||
// The point (the bar's foot) stays where it was; the top goes up.
|
||||
assert!((m.apply(Vec2::new(0.0, 10.0)) - Vec2::new(100.0, 210.0)).length() < 1e-3, "{m:?}");
|
||||
assert!((m.apply(Vec2::new(0.0, 0.0)) - Vec2::new(100.0, 190.0)).length() < 1e-3, "{m:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alpha_and_the_frame_shown_follow_a_column() {
|
||||
let mut d = doc();
|
||||
add_table(&mut d, DataTable::new(DataId(90), "t", vec![nums("a", &[100.0, 0.0]), nums("level", &[0.0, 1.0, 2.0, 7.0])], None));
|
||||
// (The table has four rows; the alpha column has numbers on the first two.)
|
||||
bind(&mut d, Binding { to: Some(1.0), ..binding(BoundProperty::Alpha, "a", 11) });
|
||||
let alpha = |d: &Document, f| {
|
||||
let dl = evaluate(d, f);
|
||||
dl.effective_alpha(&dl.items[0])
|
||||
};
|
||||
assert!((alpha(&d, 0) - 1.0).abs() < 1e-5);
|
||||
assert!((alpha(&d, 5) - 0.5).abs() < 1e-5);
|
||||
assert!(alpha(&d, 10).abs() < 1e-5);
|
||||
// The frame a graphic shows: the symbol's squares are 10, 20 and 30 wide.
|
||||
bind(&mut d, Binding { interp: Interp::Step, ..binding(BoundProperty::Frame, "level", 4) });
|
||||
let width = |d: &Document, f| evaluate(d, f).items[0].path.bounds().width();
|
||||
assert_eq!(width(&d, 0), 10.0);
|
||||
assert_eq!(width(&d, 1), 20.0);
|
||||
assert_eq!(width(&d, 2), 30.0);
|
||||
assert_eq!(width(&d, 3), 30.0, "a frame past the symbol's end shows its last");
|
||||
// A looping instance is held on the frame the column picks.
|
||||
let l = Arc::make_mut(&mut d.timeline_mut(0).layers[0]);
|
||||
if let ElementKind::Symbol { loop_mode, .. } = &mut Arc::make_mut(&mut l.keyframe_mut(0).unwrap().elements[0]).kind {
|
||||
*loop_mode = LoopMode::Loop;
|
||||
}
|
||||
assert_eq!(width(&d, 1), 20.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_binding_follows_its_instance_through_a_tween() {
|
||||
let mut d = doc();
|
||||
let l = Arc::make_mut(&mut d.timeline_mut(0).layers[0]);
|
||||
let mut k0 = Keyframe::new(0, 10);
|
||||
k0.elements.push(Arc::new(instance(50, SymbolId(40), 0.0, 0.0)));
|
||||
k0.tween = Some(Tween::default());
|
||||
let mut k1 = Keyframe::new(10, 1);
|
||||
k1.elements.push(Arc::new(instance(50, SymbolId(40), 100.0, 50.0)));
|
||||
l.keyframes = vec![Arc::new(k0), Arc::new(k1)];
|
||||
add_table(&mut d, DataTable::new(DataId(90), "t", vec![nums("y", &[500.0, 600.0])], None));
|
||||
bind(&mut d, binding(BoundProperty::Y, "y", 11));
|
||||
// x still tweens; y is the column's.
|
||||
let p = placed(&d, 5).translation();
|
||||
assert!((p - Vec2::new(50.0, 550.0)).length() < 1e-3, "{p:?}");
|
||||
assert_eq!(placed(&d, 10).translation(), Vec2::new(100.0, 600.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_binding_with_nothing_to_read_leaves_the_instance_as_placed() {
|
||||
let mut d = doc();
|
||||
let at = Vec2::new(100.0, 200.0);
|
||||
bind(&mut d, binding(BoundProperty::X, "x", 10));
|
||||
assert_eq!(placed(&d, 3).translation(), at, "no such table");
|
||||
add_table(&mut d, DataTable::new(DataId(90), "t", vec![col("gaps", &[None, None]), nums("y", &[7.0])], None));
|
||||
assert_eq!(placed(&d, 3).translation(), at, "no such column");
|
||||
bind(&mut d, binding(BoundProperty::X, "gaps", 10));
|
||||
assert_eq!(placed(&d, 3).translation(), at, "a column of gaps");
|
||||
// Another property with a value still applies.
|
||||
bind(&mut d, binding(BoundProperty::Y, "y", 10));
|
||||
assert_eq!(placed(&d, 3).translation(), Vec2::new(100.0, 7.0));
|
||||
// A shape is never bound, whatever the bindings say.
|
||||
let mut b = binding(BoundProperty::X, "y", 10);
|
||||
b.element = ElementId(42);
|
||||
bind(&mut d, b);
|
||||
assert_eq!(evaluate(&d, 0).items[0].path.bounds().width(), 10.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_bindings_and_values_stay_finite() {
|
||||
let mut d = doc();
|
||||
add_table(&mut d, DataTable::new(DataId(90), "t", vec![nums("v", &[1e300, -1e300, 1e-300])], None));
|
||||
for p in BoundProperty::ALL {
|
||||
bind(&mut d, Binding { scale: 1e9, offset: -1e9, start: u32::MAX, frames: 0, from: Some(f64::NAN), to: Some(f64::INFINITY), ..binding(p, "v", 3) });
|
||||
}
|
||||
assert!(d.data.bindings.iter().all(|b| b.frames >= 1 && b.start <= MAX_SPAN && b.from.is_none() && b.to.is_none()));
|
||||
for f in [0, 1, 2, 50, u32::MAX] {
|
||||
let dl = evaluate(&d, f.min(39));
|
||||
assert!(dl.items.iter().all(|i| i.transform.is_finite()), "frame {f}");
|
||||
for b in &d.data.bindings {
|
||||
assert!(b.value_at(&d.data, f).is_none_or(f32::is_finite));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bindings_stay_sorted_and_one_per_property() {
|
||||
let mut set = DataSet::default();
|
||||
for (el, p) in [(9, BoundProperty::Y), (3, BoundProperty::Alpha), (9, BoundProperty::X), (3, BoundProperty::X), (9, BoundProperty::Y)] {
|
||||
let mut b = binding(p, "v", 2);
|
||||
b.element = ElementId(el);
|
||||
assert!(set.bind(b));
|
||||
}
|
||||
let order: Vec<(u64, BoundProperty)> = set.bindings.iter().map(|b| (b.element.0, b.property)).collect();
|
||||
assert_eq!(order, [(3, BoundProperty::X), (3, BoundProperty::Alpha), (9, BoundProperty::X), (9, BoundProperty::Y)]);
|
||||
assert_eq!(set.bindings_of(ElementId(9)).len(), 2);
|
||||
assert_eq!(set.bindings_of(ElementId(4)).len(), 0);
|
||||
assert_eq!(set.unbind(ElementId(9), Some(BoundProperty::X)), 1);
|
||||
assert_eq!(set.unbind(ElementId(3), None), 2);
|
||||
assert_eq!(set.bindings.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_round_trips_through_the_file_and_older_files_open() {
|
||||
let mut d = doc();
|
||||
add_table(&mut d, DataTable::new(DataId(90), "pollen", vec![nums("age", &[1.0, 2.0]), col("pinus", &[Some(0.5), None])], Some("age".into())));
|
||||
bind(&mut d, Binding { interp: Interp::Step, scale: 2.0, offset: 3.0, from: Some(2.0), ..binding(BoundProperty::ScaleY, "pinus", 24) });
|
||||
let json = serde_json::to_string(&d).unwrap();
|
||||
let mut back: Document = serde_json::from_str(&json).unwrap();
|
||||
back.sanitize();
|
||||
assert_eq!(back.data, d.data);
|
||||
assert_eq!(back, d);
|
||||
// A document without data writes no `data` field, and one without the field opens.
|
||||
let plain = serde_json::to_value(doc()).unwrap();
|
||||
assert!(plain.get("data").is_none());
|
||||
let old: Document = serde_json::from_value(plain).unwrap();
|
||||
assert!(old.data.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loading_repairs_hostile_data() {
|
||||
let mut d = doc();
|
||||
let folder = FolderId(77);
|
||||
let mut bad = DataTable { id: DataId(90), name: " a/b ".into(), columns: vec![col("x", &[Some(f64::NAN)]), col("x", &[Some(1.0), Some(2.0)])], key: Some("zz".into()), source: "C:\\secret\\data.csv".into(), folder: Some(folder) };
|
||||
bad.columns[0].values[0] = Some(f64::INFINITY);
|
||||
let twin = DataTable { id: DataId(90), ..bad.clone() };
|
||||
let same_name = DataTable { id: DataId(91), name: "T".into(), columns: Vec::new(), key: None, source: String::new(), folder: None };
|
||||
let same_name_2 = DataTable { id: DataId(92), name: "t".into(), ..same_name.clone() };
|
||||
let data = Arc::make_mut(&mut d.data);
|
||||
data.tables = vec![Arc::new(bad), Arc::new(twin), Arc::new(same_name), Arc::new(same_name_2)];
|
||||
// Unsorted, repeated, and one for an instance that is nowhere.
|
||||
data.bindings = vec![binding(BoundProperty::Y, "x", 0), binding(BoundProperty::X, "x", 5), binding(BoundProperty::Y, "x", 9), Binding { element: ElementId(9_999), ..binding(BoundProperty::X, "x", 5) }];
|
||||
d.next_id = 1;
|
||||
d.sanitize();
|
||||
let names: Vec<&str> = d.data.tables.iter().map(|t| t.name.as_str()).collect();
|
||||
assert_eq!(names, ["Table 1", "T", "t 2"]);
|
||||
let t = &d.data.tables[0];
|
||||
assert_eq!((t.folder, t.key.as_deref(), t.source.as_str()), (None, None, "data.csv"));
|
||||
assert_eq!(t.columns.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["x", "x 2"]);
|
||||
assert_eq!(t.columns[0].values, [None, None]);
|
||||
assert_eq!(d.data.bindings.iter().map(|b| (b.element.0, b.property, b.frames)).collect::<Vec<_>>(), [(50, BoundProperty::X, 5), (50, BoundProperty::Y, 1)]);
|
||||
assert!(d.next_id > 92, "table ids count towards the id counter");
|
||||
// Sound data is left alone (the same allocation).
|
||||
let before = d.data.clone();
|
||||
d.sanitize();
|
||||
assert!(Arc::ptr_eq(&before, &d.data));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_table_is_a_library_item() {
|
||||
use crate::library::{LibraryEntry, LibraryItem};
|
||||
let mut d = doc();
|
||||
add_table(&mut d, DataTable::new(DataId(90), "pollen", vec![nums("v", &[1.0])], None));
|
||||
let item = LibraryItem::Data(DataId(90));
|
||||
assert!(d.library_items().any(|i| i == item));
|
||||
assert_eq!(d.item_name(item), Some("pollen"));
|
||||
assert_eq!(d.unused_items(), vec![item], "a table nothing reads is unused");
|
||||
bind(&mut d, binding(BoundProperty::X, "v", 1));
|
||||
assert_eq!(d.library_uses().get(&item), Some(&1));
|
||||
assert!(d.unused_items().is_empty());
|
||||
let f = d.ensure_folder_path("Data").unwrap();
|
||||
d.place_entry(LibraryEntry::Item(item), Some(f));
|
||||
assert_eq!(d.parent_of(LibraryEntry::Item(item)), Some(f));
|
||||
assert_eq!(d.entry_path(LibraryEntry::Item(item)), "Data/pollen");
|
||||
assert!(d.library_children(Some(f)).contains(&LibraryEntry::Item(item)));
|
||||
assert!(d.library_tree.placed.is_empty(), "a table's folder is kept on the table");
|
||||
assert!(d.name_taken(Some(f), "POLLEN", None));
|
||||
}
|
||||
@@ -756,6 +756,8 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut
|
||||
});
|
||||
}
|
||||
let Some((kf_start, elements)) = shown else { continue };
|
||||
// Data bindings (ADR 0118): a table's column in place of a bound instance's property.
|
||||
let elements = doc.bound_elements(elements, frame);
|
||||
let lc = LayerCtx { layer, frame, kf_start, clip, masks, guide, outline: layer_outline, xf: layer_xf };
|
||||
// A layer below full opacity (its own, or a folder's it is in; ADR 0111) fades as one:
|
||||
// its artwork composites in a group, and the group blends at the layer's opacity, so
|
||||
|
||||
+15
-3
@@ -17,6 +17,7 @@ pub mod warp;
|
||||
mod bitmap;
|
||||
mod color_effect;
|
||||
pub mod camera;
|
||||
pub mod data;
|
||||
mod filter;
|
||||
mod easing;
|
||||
mod eval;
|
||||
@@ -48,6 +49,7 @@ pub use sound::{EnvelopePoint, FrameSound, Sound, SoundEffect, SoundFormat, Soun
|
||||
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, DepthKey};
|
||||
pub use data::{Binding, BoundProperty, DataColumn, DataId, DataSet, DataTable, Interp};
|
||||
pub use swatch::{MAX_SWATCHES, Swatch, SwatchPaint};
|
||||
pub use parenting::{MAX_RIG_DEPTH, RigError};
|
||||
pub use aids::{Aids, GUIDE_REACH, Grid, Guide, GuideAxis, MAX_GUIDES};
|
||||
@@ -1948,6 +1950,9 @@ pub struct Document {
|
||||
/// Eases the artist saved by name (ADR 0081), offered with the presets.
|
||||
#[serde(default, skip_serializing_if = "eases_is_empty")]
|
||||
pub eases: Arc<Vec<SavedEase>>,
|
||||
/// Data tables and what they drive (ADR 0118). Left out of a file that has none.
|
||||
#[serde(default, skip_serializing_if = "data_is_empty")]
|
||||
pub data: Arc<DataSet>,
|
||||
/// Next free id for layers, elements and symbols.
|
||||
pub next_id: u64,
|
||||
}
|
||||
@@ -1987,6 +1992,8 @@ struct DocumentFile {
|
||||
aids: Arc<Aids>,
|
||||
#[serde(default)]
|
||||
eases: Arc<Vec<SavedEase>>,
|
||||
#[serde(default)]
|
||||
data: Arc<DataSet>,
|
||||
#[serde(default = "first_id")]
|
||||
next_id: u64,
|
||||
}
|
||||
@@ -1997,7 +2004,7 @@ impl From<DocumentFile> for Document {
|
||||
if let Some(tl) = f.timeline {
|
||||
scenes.insert(0, Arc::new(Scene { name: "Scene 1".into(), timeline: tl, guides: Vec::new() }));
|
||||
}
|
||||
Document { stage: f.stage, scenes, library: f.library, bitmaps: f.bitmaps, sounds: f.sounds, library_tree: f.library_tree, document_class: f.document_class, publish: f.publish, aids: f.aids, swatches: f.swatches, eases: f.eases, next_id: f.next_id }
|
||||
Document { stage: f.stage, scenes, library: f.library, bitmaps: f.bitmaps, sounds: f.sounds, library_tree: f.library_tree, document_class: f.document_class, publish: f.publish, aids: f.aids, swatches: f.swatches, eases: f.eases, data: f.data, next_id: f.next_id }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2009,6 +2016,10 @@ fn library_tree_is_empty(t: &Arc<LibraryTree>) -> bool {
|
||||
t.is_empty()
|
||||
}
|
||||
|
||||
fn data_is_empty(d: &Arc<DataSet>) -> bool {
|
||||
d.is_empty()
|
||||
}
|
||||
|
||||
fn eases_is_empty(e: &Arc<Vec<SavedEase>>) -> bool {
|
||||
e.is_empty()
|
||||
}
|
||||
@@ -2026,13 +2037,13 @@ static NO_TIMELINE: Timeline = Timeline { layers: Vec::new() };
|
||||
|
||||
impl PartialEq for Document {
|
||||
fn eq(&self, o: &Document) -> bool {
|
||||
self.stage == o.stage && self.next_id == o.next_id && self.document_class == o.document_class && arcs_eq(&self.scenes, &o.scenes) && arcs_eq(&self.library, &o.library) && arcs_eq(&self.bitmaps, &o.bitmaps) && arcs_eq(&self.sounds, &o.sounds) && arc_eq(&self.library_tree, &o.library_tree) && arc_eq(&self.publish, &o.publish) && arc_eq(&self.aids, &o.aids) && arc_eq(&self.swatches, &o.swatches) && arc_eq(&self.eases, &o.eases)
|
||||
self.stage == o.stage && self.next_id == o.next_id && self.document_class == o.document_class && arcs_eq(&self.scenes, &o.scenes) && arcs_eq(&self.library, &o.library) && arcs_eq(&self.bitmaps, &o.bitmaps) && arcs_eq(&self.sounds, &o.sounds) && arc_eq(&self.library_tree, &o.library_tree) && arc_eq(&self.publish, &o.publish) && arc_eq(&self.aids, &o.aids) && arc_eq(&self.swatches, &o.swatches) && arc_eq(&self.eases, &o.eases) && arc_eq(&self.data, &o.data)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Document {
|
||||
fn default() -> Self {
|
||||
let mut d = Document { stage: Stage::default(), scenes: vec![Arc::new(Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Arc::default(), document_class: String::new(), publish: Arc::default(), aids: Arc::default(), swatches: default_swatches(), eases: Arc::default(), next_id: 1 };
|
||||
let mut d = Document { stage: Stage::default(), scenes: vec![Arc::new(Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Arc::default(), document_class: String::new(), publish: Arc::default(), aids: Arc::default(), swatches: default_swatches(), eases: Arc::default(), data: Arc::default(), next_id: 1 };
|
||||
let id = LayerId(d.alloc_id());
|
||||
d.timeline_mut(0).layers.push(Arc::new(Layer::new(id, "Layer 1")));
|
||||
d
|
||||
@@ -2218,6 +2229,7 @@ impl Document {
|
||||
max_id = max_id.max(s.id.0);
|
||||
}
|
||||
self.sanitize_library_tree(&mut max_id);
|
||||
self.sanitize_data(&mut max_id);
|
||||
self.next_id = self.next_id.max(max_id.saturating_add(1));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
//! or renaming a folder touches one small table, never a symbol's timeline, and documents from
|
||||
//! before folders open with every item at the top level.
|
||||
|
||||
use crate::{BitmapId, Document, ElementId, ElementKind, LayerId, Paint, SoundId, Symbol, SymbolId, Timeline};
|
||||
use crate::{BitmapId, DataId, Document, ElementId, ElementKind, LayerId, Paint, SoundId, Symbol, SymbolId, Timeline};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
@@ -14,13 +14,14 @@ use std::sync::Arc;
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub struct FolderId(pub u64);
|
||||
|
||||
/// A symbol, bitmap or sound in the Library.
|
||||
/// A symbol, bitmap, sound or data table (ADR 0118) in the Library.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum LibraryItem {
|
||||
Symbol(SymbolId),
|
||||
Bitmap(BitmapId),
|
||||
Sound(SoundId),
|
||||
Data(DataId),
|
||||
}
|
||||
|
||||
impl LibraryItem {
|
||||
@@ -30,6 +31,7 @@ impl LibraryItem {
|
||||
LibraryItem::Symbol(i) => i.0,
|
||||
LibraryItem::Bitmap(i) => i.0,
|
||||
LibraryItem::Sound(i) => i.0,
|
||||
LibraryItem::Data(i) => i.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -139,13 +141,23 @@ pub fn clean_name(name: &str) -> Result<String, NameError> {
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// Every item in the Library: symbols, then bitmaps, then sounds.
|
||||
/// Every item in the Library: symbols, then bitmaps, then sounds, then data tables.
|
||||
pub fn library_items(&self) -> impl Iterator<Item = LibraryItem> + '_ {
|
||||
self.library
|
||||
.iter()
|
||||
.map(|s| LibraryItem::Symbol(s.id))
|
||||
.chain(self.bitmaps.iter().map(|b| LibraryItem::Bitmap(b.id)))
|
||||
.chain(self.sounds.iter().map(|s| LibraryItem::Sound(s.id)))
|
||||
.chain(self.data.tables.iter().map(|t| LibraryItem::Data(t.id)))
|
||||
}
|
||||
|
||||
/// The folder `item` is in (`None`: the top level). A data table keeps its own (ADR 0118);
|
||||
/// the others are in the tree's placements.
|
||||
pub fn item_folder(&self, item: LibraryItem) -> Option<FolderId> {
|
||||
match item {
|
||||
LibraryItem::Data(id) => self.data.table(id).and_then(|t| t.folder),
|
||||
other => self.library_tree.placed.get(&other).copied(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn has_item(&self, item: LibraryItem) -> bool {
|
||||
@@ -157,6 +169,7 @@ impl Document {
|
||||
LibraryItem::Symbol(id) => self.symbol(id).map(|s| s.name.as_str()),
|
||||
LibraryItem::Bitmap(id) => self.bitmap(id).map(|b| b.name.as_str()),
|
||||
LibraryItem::Sound(id) => self.sound(id).map(|s| s.name.as_str()),
|
||||
LibraryItem::Data(id) => self.data.table(id).map(|t| t.name.as_str()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,7 +194,7 @@ impl Document {
|
||||
/// The folder `e` is in (`None`: the top level).
|
||||
pub fn parent_of(&self, e: LibraryEntry) -> Option<FolderId> {
|
||||
match e {
|
||||
LibraryEntry::Item(i) => self.library_tree.placed.get(&i).copied(),
|
||||
LibraryEntry::Item(i) => self.item_folder(i),
|
||||
LibraryEntry::Folder(f) => self.folder(f).and_then(|f| f.parent),
|
||||
}
|
||||
}
|
||||
@@ -217,7 +230,7 @@ impl Document {
|
||||
/// The folders and items directly in `parent` (`None`: the top level), folders first.
|
||||
pub fn library_children(&self, parent: Option<FolderId>) -> Vec<LibraryEntry> {
|
||||
let folders = self.library_tree.folders.iter().filter(|f| f.parent == parent).map(|f| LibraryEntry::Folder(f.id));
|
||||
let items = self.library_items().filter(|i| self.library_tree.placed.get(i).copied() == parent).map(LibraryEntry::Item);
|
||||
let items = self.library_items().filter(|i| self.item_folder(*i) == parent).map(LibraryEntry::Item);
|
||||
folders.chain(items).collect()
|
||||
}
|
||||
|
||||
@@ -226,7 +239,7 @@ impl Document {
|
||||
let inside: Vec<FolderId> = self.library_tree.folders.iter().filter(|f| f.id != id && self.folder_within(f.id, id)).map(|f| f.id).collect();
|
||||
let mut all = inside.clone();
|
||||
all.push(id);
|
||||
let items = self.library_items().filter(|i| self.library_tree.placed.get(i).is_some_and(|f| all.contains(f)));
|
||||
let items = self.library_items().filter(|i| self.item_folder(*i).is_some_and(|f| all.contains(&f)));
|
||||
inside.into_iter().map(LibraryEntry::Folder).chain(items.map(LibraryEntry::Item)).collect()
|
||||
}
|
||||
|
||||
@@ -275,6 +288,12 @@ impl Document {
|
||||
|
||||
/// Moves `e` into folder `to` (`None`: the top level). No checks: see `library.move`.
|
||||
pub fn place_entry(&mut self, e: LibraryEntry, to: Option<FolderId>) {
|
||||
if let LibraryEntry::Item(LibraryItem::Data(id)) = e {
|
||||
if let Some(t) = Arc::make_mut(&mut self.data).tables.iter_mut().find(|t| t.id == id) {
|
||||
Arc::make_mut(t).folder = to;
|
||||
}
|
||||
return;
|
||||
}
|
||||
let tree = Arc::make_mut(&mut self.library_tree);
|
||||
match e {
|
||||
LibraryEntry::Item(i) => match to {
|
||||
@@ -327,6 +346,10 @@ impl Document {
|
||||
for tl in self.scenes.iter().map(|s| &s.timeline).chain(self.library.iter().map(|s| &s.timeline)) {
|
||||
visit_refs(tl, |item| *uses.entry(item).or_default() += 1);
|
||||
}
|
||||
// A data table is used once by each binding that reads it (ADR 0118).
|
||||
for b in &self.data.bindings {
|
||||
*uses.entry(LibraryItem::Data(b.table)).or_default() += 1;
|
||||
}
|
||||
uses
|
||||
}
|
||||
|
||||
@@ -355,6 +378,10 @@ impl Document {
|
||||
visit_refs(&sym.timeline, |item| reach(item, &mut reached, &mut stack));
|
||||
}
|
||||
}
|
||||
// A data table is reached by a binding that reads it (whatever instance it drives).
|
||||
for b in &self.data.bindings {
|
||||
reached.insert(LibraryItem::Data(b.table));
|
||||
}
|
||||
self.library_items().filter(|i| !reached.contains(i)).collect()
|
||||
}
|
||||
|
||||
@@ -407,7 +434,7 @@ impl Document {
|
||||
t.folders.len() <= MAX_FOLDERS
|
||||
&& t.folders.iter().all(|f| ids.insert(f.id) && clean_name(&f.name).as_deref() == Ok(f.name.as_str()) && f.parent.is_none_or(|p| p != f.id && d.folder(p).is_some()))
|
||||
&& t.folders.iter().all(|f| d.folder_chain(f.id).first().is_some_and(|top| d.folder(*top).is_some_and(|x| x.parent.is_none())))
|
||||
&& t.placed.iter().all(|(i, f)| d.has_item(*i) && d.folder(*f).is_some())
|
||||
&& t.placed.iter().all(|(i, f)| !matches!(i, LibraryItem::Data(_)) && d.has_item(*i) && d.folder(*f).is_some())
|
||||
};
|
||||
for f in &self.library_tree.folders {
|
||||
*max_id = (*max_id).max(f.id.0);
|
||||
@@ -448,7 +475,7 @@ impl Document {
|
||||
}
|
||||
}
|
||||
let items: HashSet<LibraryItem> = self.library_items().collect();
|
||||
tree.placed.retain(|i, f| items.contains(i) && ids.contains(f));
|
||||
tree.placed.retain(|i, f| !matches!(i, LibraryItem::Data(_)) && items.contains(i) && ids.contains(f));
|
||||
self.library_tree = Arc::new(tree);
|
||||
}
|
||||
}
|
||||
|
||||
+17
-10
@@ -374,6 +374,22 @@ impl Props {
|
||||
}
|
||||
}
|
||||
|
||||
/// The transform `props` give `base` (whose own values are `base_props`). With a
|
||||
/// transformation point (ADR 0111) the position values carry the point, and the object turns,
|
||||
/// scales and skews about it. What a motion tween's curves and a data binding (ADR 0118) place
|
||||
/// their object by.
|
||||
pub(crate) fn placed(base: &Element, base_props: &Props, props: &Props) -> Affine {
|
||||
let mut m = props.transform();
|
||||
if let Some(p) = base.pivot() {
|
||||
let (d0, d1) = (base_props.transform().translation(), m.translation());
|
||||
let at = base.transform.apply(p) + (d1 - d0);
|
||||
let about = Affine { m: [m.m[0], m.m[1], m.m[2], m.m[3], 0.0, 0.0] };
|
||||
let o = about.apply(p);
|
||||
m = Affine::translate(at.x - o.x, at.y - o.y).mul(&about);
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// The object's own value of `p`: its transform's and colour effect's, or a filter's number
|
||||
/// (`None` when it has no filter there with that number, ADR 0092).
|
||||
pub fn own_value(el: &Element, p: Property) -> Option<f32> {
|
||||
@@ -1285,16 +1301,7 @@ impl MotionTween {
|
||||
}
|
||||
}
|
||||
if on_path.is_some() || self.tracks.iter().any(|t| t.property.is_transform()) {
|
||||
let mut m = props.transform();
|
||||
// With a transformation point (ADR 0111) the position tracks carry the point, and
|
||||
// the target turns, scales and skews about it.
|
||||
if let Some(p) = base.pivot() {
|
||||
let (d0, d1) = (base_props.transform().translation(), m.translation());
|
||||
let at = base.transform.apply(p) + (d1 - d0);
|
||||
let about = Affine { m: [m.m[0], m.m[1], m.m[2], m.m[3], 0.0, 0.0] };
|
||||
let o = about.apply(p);
|
||||
m = Affine::translate(at.x - o.x, at.y - o.y).mul(&about);
|
||||
}
|
||||
let m = placed(base, &base_props, &props);
|
||||
if m.is_finite() {
|
||||
el.transform = m;
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ fn key(start: u32, duration: u32, elements: Vec<Arc<Element>>, tween: Option<Eas
|
||||
|
||||
/// Builds the demo document: a bouncing ball, a spinning star, a pulsing sun over hills.
|
||||
pub fn demo() -> Document {
|
||||
let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), aids: Default::default(), swatches: Arc::new(crate::swatch::default_set()), eases: Default::default(), next_id: 1 };
|
||||
let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), aids: Default::default(), swatches: Arc::new(crate::swatch::default_set()), eases: Default::default(), data: Default::default(), next_id: 1 };
|
||||
let (w, h) = (1280.0, 720.0);
|
||||
|
||||
// --- library -------------------------------------------------------------------------
|
||||
@@ -174,7 +174,7 @@ pub fn arm() -> Document {
|
||||
|
||||
/// An empty document with the demo's defaults.
|
||||
fn demo_base() -> Document {
|
||||
Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), aids: Default::default(), swatches: Arc::new(crate::swatch::default_set()), eases: Default::default(), next_id: 1 }
|
||||
Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), aids: Default::default(), swatches: Arc::new(crate::swatch::default_set()), eases: Default::default(), data: Default::default(), next_id: 1 }
|
||||
}
|
||||
|
||||
/// A small interactive movie (ADR 0024): a menu that stops on its first frame with a Play
|
||||
@@ -182,7 +182,7 @@ fn demo_base() -> Document {
|
||||
/// whose last frame traces a line and goes back to the menu.
|
||||
pub fn interactive() -> Document {
|
||||
use crate::actions::{Action, ButtonEvent, EventHandler, FrameRef, FrameScript, Target};
|
||||
let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::hex(0x1d2333) }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), aids: Default::default(), swatches: Arc::new(crate::swatch::default_set()), eases: Default::default(), next_id: 1 };
|
||||
let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::hex(0x1d2333) }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), aids: Default::default(), swatches: Arc::new(crate::swatch::default_set()), eases: Default::default(), data: Default::default(), next_id: 1 };
|
||||
const LEN: u32 = 36;
|
||||
let solid = |c: u32| Paint::Solid(Rgba::hex(c));
|
||||
|
||||
@@ -246,7 +246,7 @@ pub fn interactive() -> Document {
|
||||
/// `shapes` shapes each, keyed every 12 frames over `frames` frames with classic tweens.
|
||||
/// Every element keeps one `Arc<Path>` across its keyframes, as a real tweened shape does.
|
||||
pub fn stress(layers: u32, shapes: u32, frames: u32) -> Document {
|
||||
let mut d = Document { stage: Stage { width: 1920, height: 1080, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), aids: Default::default(), swatches: Arc::new(crate::swatch::default_set()), eases: Default::default(), next_id: 1 };
|
||||
let mut d = Document { stage: Stage { width: 1920, height: 1080, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), aids: Default::default(), swatches: Arc::new(crate::swatch::default_set()), eases: Default::default(), data: Default::default(), next_id: 1 };
|
||||
let (layers, shapes, frames) = (layers.clamp(1, 1000), shapes.clamp(1, 100_000), frames.clamp(1, 10_000));
|
||||
let mut seed = 0x2545_f491_u32;
|
||||
let mut rnd = move || {
|
||||
|
||||
@@ -26,6 +26,8 @@ craft-image-codecs.workspace = true
|
||||
craft-apng-container.workspace = true
|
||||
craft-webp.workspace = true
|
||||
regex.workspace = true
|
||||
# CSV and TSV data tables (ADR 0118).
|
||||
craft-csv.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
# Packs the XFL corpus into .fla archives in tests (ADR 0054; already in the tree through xfl).
|
||||
|
||||
@@ -0,0 +1,547 @@
|
||||
//! Data tables that drive animation (ADR 0118): the `data.*` commands.
|
||||
//!
|
||||
//! * Tables: `data.import_table` reads a CSV, TSV or JSON file ([`crate::data_import`]),
|
||||
//! `data.set_table` takes the values inline (scripts, MCP, plug-ins); importing or setting a
|
||||
//! table that is already there replaces its values and keeps its id, so every binding stays.
|
||||
//! `data.list` and `data.get` read them; `data.set_cell` and `data.set_key` edit one.
|
||||
//! * Bindings: `data.bind` lets a column drive a property of a symbol instance over a span of
|
||||
//! frames, `data.unbind` takes that away, `data.bindings` lists them with the values at the
|
||||
//! playhead, and `data.bake` writes what the bindings show as plain keyframes.
|
||||
//!
|
||||
//! The model, the sampling and what a binding does to its instance are `anicraft_doc::data`
|
||||
//! (pure, applied inside `evaluate`); this module checks params and edits the document.
|
||||
|
||||
use crate::data_import::{self, Format, Parsed};
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Session};
|
||||
use anicraft_doc::data::{MAX_BINDINGS, MAX_SPAN, MAX_TABLES, MAX_VALUE, with_values};
|
||||
use anicraft_doc::motion::MAX_KEYS;
|
||||
use anicraft_doc::{Binding, BoundProperty, DataId, DataTable, Document, Element, ElementId, ElementKind, Interp, LayerId, LayerKind, LibraryItem, LoopMode, SymbolId, SymbolKind, Timeline};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Most rows `data.get` returns at once.
|
||||
pub const MAX_GET_ROWS: usize = 10_000;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, params, mutates, run| CommandSpec { id, label, menu, shortcut: None, params, mutates, run };
|
||||
vec![
|
||||
c(
|
||||
"data.import_table",
|
||||
"Import Data Table…",
|
||||
"File/Import",
|
||||
"{path (.csv, .tsv or .json, up to 32 MB: the first record names the columns; cells that aren't numbers become gaps, and a column with no number is left out), name? (default the file's name), table? (id or name of a table to replace: its bindings stay), key? (the column rows are looked up by, e.g. an age or a time; default by row number, or the replaced table's key), format?: auto|csv|tsv|json} → {table, name, rows, columns, key, skipped, gaps, truncated, replaced, bindings, missing (columns bindings read that are gone)}",
|
||||
true,
|
||||
import_table as crate::RunFn,
|
||||
),
|
||||
c(
|
||||
"data.set_table",
|
||||
"Set Data Table",
|
||||
"",
|
||||
"{name, columns: [{name, values: [number | null, ..]}, ..] (in this order) | {name: [..], ..} (sorted by name) | [names] with rows: [[..], ..], key?, table? (id or name of the table to replace; default the table called `name`)} the table's values inline (null is a gap); replacing a table keeps its bindings → as data.import_table",
|
||||
true,
|
||||
set_table,
|
||||
),
|
||||
c("data.list", "Data Tables", "", "{} → {tables: [{table, name, rows, columns: [names], key, source, folder, bindings}], bindings (how many in the document)}", false, list),
|
||||
c("data.get", "Data Table Values", "", "{table (id or name), from? (first row, 0-based), count? (rows, at most 10,000)} → {table, name, key, rows, from, columns: [{name, values: [number | null, ..]}]}", false, get),
|
||||
c("data.set_cell", "Set Data Cell", "", "{table (id or name), column, row (0-based), value (number, or null for a gap)}: every binding that reads the cell shows the new value", true, set_cell),
|
||||
c("data.set_key", "Set Key Column", "", "{table (id or name), key (a column's name, or null: rows are looked up by row number)}: a table with a key keeps its rows in the key's ascending order", true, set_key),
|
||||
c("data.remove", "Delete Data Table", "", "{table (id or name)} deletes the table and the bindings that read it (undoable) → {deleted, uses}", true, remove),
|
||||
c(
|
||||
"data.bind",
|
||||
"Bind to Data…",
|
||||
"Modify/Data",
|
||||
"{property: x|y|scale_x|scale_y|rotation|alpha|frame (x, y pixels; scales and alpha percent; rotation degrees; frame: the 0-based frame of its symbol a graphic instance shows), table (id or name), column, element? (a symbol instance's id; default the selected one), start? (the span's first frame, 0-based; default the first frame the instance is on), frames? (the span's length; default one frame per row, or with a key column the frames the instance is on), from?, to? (the keys the first and last frame show; default the table's first and last; to before from plays it backwards), interpolation?: linear|step, scale?, offset? (value = column × scale + offset)} one binding per property of an instance; before the span it shows the first frame's value, after it the last's → {element, property, table, column, start, frames, value}",
|
||||
true,
|
||||
bind,
|
||||
),
|
||||
c("data.unbind", "Remove Data Bindings", "Modify/Data", "{element? (default every selected instance), property? (default all of them)} → {removed}", true, unbind),
|
||||
c("data.bindings", "Data Bindings", "", "{element? (default every binding in the document)} → {bindings: [{element, property, table, table_name, column, start, frames, from, to, interpolation, scale, offset, live (the table and column exist), value (at the playhead, or null)}]}", false, bindings),
|
||||
c(
|
||||
"data.bake",
|
||||
"Bake Data to Keyframes",
|
||||
"Modify/Data",
|
||||
"{element? (default every selected instance with bindings), property? (default all of them)} writes what the bindings show as keyframes on the instance's layer (one where the value changes; one per frame inside a classic tween) and removes the bindings: every frame looks as it did → {keys, elements, removed}",
|
||||
true,
|
||||
bake,
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
fn state(msg: impl Into<String>) -> EngineError {
|
||||
EngineError::State(msg.into())
|
||||
}
|
||||
|
||||
fn param(msg: impl Into<String>) -> EngineError {
|
||||
EngineError::Param(msg.into())
|
||||
}
|
||||
|
||||
fn short(s: &str) -> String {
|
||||
s.chars().take(60).collect()
|
||||
}
|
||||
|
||||
/// The table param `key` names: an id, or a name (without case).
|
||||
fn table_param(s: &Session, p: &Value, key: &str) -> Result<Option<DataId>> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::String(name)) => s.doc.data_table_named(name).map(|t| Some(t.id)).ok_or_else(|| state(format!("no data table named '{}' (data.list shows them)", short(name)))),
|
||||
Some(v) => {
|
||||
let id = v.as_u64().map(DataId).ok_or_else(|| param(format!("param '{key}' must be a data table's id or name")))?;
|
||||
s.doc.data_table(id).map(|t| Some(t.id)).ok_or_else(|| state(format!("no data table with id {}", id.0)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn table_req(s: &Session, p: &Value) -> Result<DataId> {
|
||||
table_param(s, p, "table")?.ok_or_else(|| param("param 'table' is required (a data table's id or name)"))
|
||||
}
|
||||
|
||||
fn table_mut(s: &mut Session, id: DataId) -> Result<&mut DataTable> {
|
||||
Arc::make_mut(&mut s.doc.data).tables.iter_mut().find(|t| t.id == id).map(Arc::make_mut).ok_or_else(|| state("the data table went away"))
|
||||
}
|
||||
|
||||
fn table_json(d: &Document, t: &DataTable) -> Value {
|
||||
json!({
|
||||
"table": t.id.0,
|
||||
"name": t.name,
|
||||
"rows": t.rows(),
|
||||
"columns": t.columns.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(),
|
||||
"key": t.key,
|
||||
"source": t.source,
|
||||
"folder": t.folder.map(|f| f.0),
|
||||
"bindings": d.data.uses(t.id),
|
||||
})
|
||||
}
|
||||
|
||||
/// A name no other table has (commands name tables by name) and nothing else at the Library's
|
||||
/// top level has.
|
||||
fn fresh_name(d: &Document, wanted: &str) -> String {
|
||||
let base = d.unique_name(None, if wanted.trim().is_empty() { "Table" } else { wanted });
|
||||
if d.data_table_named(&base).is_none() {
|
||||
return base;
|
||||
}
|
||||
(2..=MAX_TABLES + 2).map(|n| format!("{base} {n}")).find(|c| d.data_table_named(c).is_none() && !d.name_taken(None, c, None)).unwrap_or(base)
|
||||
}
|
||||
|
||||
/// The key a store sets: `None` keeps what the table has, `Some(None)` clears it.
|
||||
type KeyParam = Option<Option<String>>;
|
||||
|
||||
fn key_param(p: &Value) -> Result<KeyParam> {
|
||||
match p.get("key") {
|
||||
None => Ok(None),
|
||||
Some(Value::Null) => Ok(Some(None)),
|
||||
Some(Value::String(k)) => Ok(Some(Some(k.clone()))),
|
||||
Some(_) => Err(param("param 'key' must be a column's name, or null")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Puts `parsed` in the document: over table `target` (or the one called `name`), keeping its
|
||||
/// id, name, folder and bindings; else as a new table.
|
||||
fn store(s: &mut Session, name: Option<&str>, target: Option<DataId>, parsed: Parsed, key: KeyParam, source: &str) -> Result<Value> {
|
||||
let Parsed { columns, skipped, gaps, truncated } = parsed;
|
||||
if let Some(Some(k)) = &key
|
||||
&& !columns.iter().any(|c| c.name.to_lowercase() == k.trim().to_lowercase())
|
||||
{
|
||||
let have: Vec<&str> = columns.iter().map(|c| c.name.as_str()).take(20).collect();
|
||||
return Err(param(format!("the table has no column '{}' to be its key (it has: {})", short(k), have.join(", "))));
|
||||
}
|
||||
let target = target.or_else(|| name.and_then(|n| s.doc.data_table_named(n)).map(|t| t.id));
|
||||
let (id, replaced) = match target {
|
||||
Some(id) => {
|
||||
let t = table_mut(s, id)?;
|
||||
t.columns = columns;
|
||||
match key {
|
||||
Some(k) => t.key = k.map(|k| k.trim().to_string()),
|
||||
// The key it had, while the column is still there.
|
||||
None => t.key = t.key.take().filter(|k| t.columns.iter().any(|c| c.name.to_lowercase() == k.to_lowercase())),
|
||||
}
|
||||
if !source.is_empty() {
|
||||
t.source = source.to_string();
|
||||
}
|
||||
t.normalize();
|
||||
(id, true)
|
||||
}
|
||||
None => {
|
||||
if s.doc.data.tables.len() >= MAX_TABLES {
|
||||
return Err(state(format!("a document keeps at most {MAX_TABLES} data tables; delete one first")));
|
||||
}
|
||||
let name = match name {
|
||||
Some(n) => {
|
||||
let n = anicraft_doc::library::clean_name(n).map_err(|e| param(e.to_string()))?;
|
||||
if s.doc.name_taken(None, &n, None) { fresh_name(&s.doc, &n) } else { n }
|
||||
}
|
||||
None => fresh_name(&s.doc, "Table"),
|
||||
};
|
||||
let id = DataId(s.doc.alloc_id());
|
||||
let mut t = DataTable::new(id, name, columns, key.flatten().map(|k| k.trim().to_string()));
|
||||
t.source = source.to_string();
|
||||
t.normalize();
|
||||
Arc::make_mut(&mut s.doc.data).tables.push(Arc::new(t));
|
||||
(id, false)
|
||||
}
|
||||
};
|
||||
let d = &s.doc;
|
||||
let t = d.data_table(id).ok_or_else(|| state("the data table went away"))?;
|
||||
// Columns that bindings read and the table no longer has: those bindings rest until it does.
|
||||
let mut missing: Vec<&str> = d.data.bindings.iter().filter(|b| b.table == id && t.column_index(&b.column).is_none()).map(|b| b.column.as_str()).collect();
|
||||
missing.sort_unstable();
|
||||
missing.dedup();
|
||||
let mut out = table_json(d, t);
|
||||
out["skipped"] = json!(skipped);
|
||||
out["gaps"] = json!(gaps);
|
||||
out["truncated"] = json!(truncated);
|
||||
out["replaced"] = json!(replaced);
|
||||
out["missing"] = json!(missing);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn import_table(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = PathBuf::from(str_req(p, "path")?);
|
||||
let format = match opt_str(p, "format")? {
|
||||
None => None,
|
||||
Some(f) => Format::from_key(f).ok_or_else(|| param(format!("unknown format '{}' (auto, csv, tsv or json)", short(f))))?,
|
||||
};
|
||||
let target = table_param(s, p, "table")?;
|
||||
let key = key_param(p)?;
|
||||
if crate::vfs::len(&path)? > data_import::MAX_FILE_BYTES {
|
||||
return Err(param(format!("{} is larger than {} MB, the most a data table is read from", path.display(), data_import::MAX_FILE_BYTES >> 20)));
|
||||
}
|
||||
let file: String = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let parsed = data_import::parse(&crate::vfs::read(&path)?, &file, format).map_err(|e| param(format!("{}: {e}", path.display())))?;
|
||||
let stem: String = path.file_stem().map_or_else(String::new, |n| n.to_string_lossy().replace('/', "-").chars().take(128).collect());
|
||||
let name = match opt_str(p, "name")? {
|
||||
Some(n) => Some(n.to_string()),
|
||||
None if target.is_some() => None,
|
||||
None => Some(if stem.trim().is_empty() { "Table".to_string() } else { stem }),
|
||||
};
|
||||
store(s, name.as_deref(), target, parsed, key, &file)
|
||||
}
|
||||
|
||||
/// The inline values of `data.set_table` as JSON text one of [`data_import::parse_json`]'s
|
||||
/// shapes reads.
|
||||
fn inline_json(p: &Value) -> Result<String> {
|
||||
let cols = p.get("columns").filter(|v| !v.is_null()).ok_or_else(|| param("param 'columns' is required: {name: [numbers], ..}, [{name, values}, ..], or [names] with 'rows'"))?;
|
||||
let v = match (cols, p.get("rows").filter(|v| !v.is_null())) {
|
||||
(Value::Array(_), Some(rows @ Value::Array(_))) => json!({"columns": cols, "rows": rows}),
|
||||
(_, Some(_)) => return Err(param("with 'rows' (a list of rows), 'columns' is the list of column names")),
|
||||
(Value::Object(_), None) => cols.clone(),
|
||||
(Value::Array(list), None) => {
|
||||
// Written by hand: the columns keep the order they were given in (an object's
|
||||
// members reach a command sorted by name).
|
||||
let mut parts = Vec::with_capacity(list.len());
|
||||
for (i, c) in list.iter().enumerate() {
|
||||
let name = c.get("name").and_then(Value::as_str).map_or_else(|| format!("Column {}", i + 1), str::to_string);
|
||||
let values = c.get("values").filter(|v| v.is_array()).ok_or_else(|| param("each of 'columns' is {name, values: [numbers]}"))?;
|
||||
parts.push(format!("{}: {values}", Value::String(name)));
|
||||
}
|
||||
return Ok(format!("{{{}}}", parts.join(", ")));
|
||||
}
|
||||
_ => return Err(param("param 'columns' must be {name: [numbers], ..}, [{name, values}, ..], or [names] with 'rows'")),
|
||||
};
|
||||
serde_json::to_string(&v).map_err(|e| param(e.to_string()))
|
||||
}
|
||||
|
||||
fn set_table(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let target = table_param(s, p, "table")?;
|
||||
let name = opt_str(p, "name")?;
|
||||
if target.is_none() && name.is_none() {
|
||||
return Err(param("param 'name' is required (the table's name), or 'table' to replace one"));
|
||||
}
|
||||
let key = key_param(p)?;
|
||||
let parsed = data_import::parse_json(&inline_json(p)?).map_err(param)?;
|
||||
store(s, name, target, parsed, key, "")
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let d = &s.doc;
|
||||
let tables: Vec<Value> = d.data.tables.iter().map(|t| table_json(d, t)).collect();
|
||||
Ok(json!({"tables": tables, "bindings": d.data.bindings.len()}))
|
||||
}
|
||||
|
||||
fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = table_req(s, p)?;
|
||||
let t = s.doc.data_table(id).ok_or_else(|| state("the data table went away"))?;
|
||||
let rows = t.rows();
|
||||
let from = (opt_u64(p, "from")?.unwrap_or(0) as usize).min(rows);
|
||||
let count = opt_u64(p, "count")?.map_or(MAX_GET_ROWS, |n| n as usize).min(MAX_GET_ROWS).min(rows - from);
|
||||
let columns: Vec<Value> = t.columns.iter().map(|c| json!({"name": c.name, "values": c.values.iter().skip(from).take(count).collect::<Vec<_>>()})).collect();
|
||||
Ok(json!({"table": t.id.0, "name": t.name, "key": t.key, "rows": rows, "from": from, "count": count, "columns": columns}))
|
||||
}
|
||||
|
||||
fn set_cell(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = table_req(s, p)?;
|
||||
let column = str_req(p, "column")?.to_string();
|
||||
let row = opt_u64(p, "row")?.ok_or_else(|| param("param 'row' is required (0-based)"))? as usize;
|
||||
let value = match p.get("value") {
|
||||
None => return Err(param("param 'value' is required (a number, or null for a gap)")),
|
||||
Some(Value::Null) => None,
|
||||
Some(v) => Some(v.as_f64().filter(|f| f.is_finite()).ok_or_else(|| param("param 'value' must be a finite number, or null for a gap"))?),
|
||||
};
|
||||
let t = table_mut(s, id)?;
|
||||
let rows = t.rows();
|
||||
let ci = t.column_index(&column).ok_or_else(|| param(format!("the table has no column '{}'", short(&column))))?;
|
||||
let slot = t.columns.get_mut(ci).and_then(|c| c.values.get_mut(row)).ok_or_else(|| param(format!("the table has {rows} rows (0 to {})", rows.saturating_sub(1))))?;
|
||||
*slot = value;
|
||||
// A changed key may move the row.
|
||||
t.normalize();
|
||||
Ok(json!({"table": id.0, "column": column, "row": row, "value": value}))
|
||||
}
|
||||
|
||||
fn set_key(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = table_req(s, p)?;
|
||||
let key = key_param(p)?.ok_or_else(|| param("param 'key' is required (a column's name, or null)"))?;
|
||||
let t = table_mut(s, id)?;
|
||||
t.key = match key {
|
||||
None => None,
|
||||
Some(k) => Some(t.column(&k).map(|c| c.name.clone()).ok_or_else(|| param(format!("the table has no column '{}'", short(&k))))?),
|
||||
};
|
||||
t.normalize();
|
||||
Ok(json!({"table": id.0, "key": t.key}))
|
||||
}
|
||||
|
||||
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = table_req(s, p)?;
|
||||
Ok(crate::cmds_library::remove(s, &[LibraryItem::Data(id)], &[]))
|
||||
}
|
||||
|
||||
/// Where an instance is: its layer, the first frame it is on and how many frames from there to
|
||||
/// the end of the last keyframe that holds it.
|
||||
struct Found {
|
||||
layer: LayerId,
|
||||
first: u32,
|
||||
life: u32,
|
||||
el: Arc<Element>,
|
||||
/// On the timeline being edited (else on another scene's, or inside a symbol).
|
||||
here: bool,
|
||||
}
|
||||
|
||||
fn find_in(tl: &Timeline, id: ElementId) -> Option<Found> {
|
||||
for l in &tl.layers {
|
||||
let mut found: Option<Found> = None;
|
||||
for k in &l.keyframes {
|
||||
let Some(e) = k.elements.iter().find(|e| e.id == id) else { continue };
|
||||
match &mut found {
|
||||
Some(f) => f.life = k.end().saturating_sub(f.first),
|
||||
None => found = Some(Found { layer: l.id, first: k.start, life: k.duration.max(1), el: e.clone(), here: false }),
|
||||
}
|
||||
}
|
||||
if found.is_some() {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn find(s: &Session, id: ElementId) -> Option<Found> {
|
||||
if let Some(f) = find_in(s.timeline(), id) {
|
||||
return Some(Found { here: true, ..f });
|
||||
}
|
||||
s.doc.scenes.iter().map(|x| &x.timeline).chain(s.doc.library.iter().map(|x| &x.timeline)).find_map(|tl| find_in(tl, id))
|
||||
}
|
||||
|
||||
/// The instances a command works on: `element`, else the selected ones.
|
||||
fn targets(s: &Session, p: &Value) -> Result<Vec<ElementId>> {
|
||||
if let Some(id) = opt_u64(p, "element")? {
|
||||
return Ok(vec![ElementId(id)]);
|
||||
}
|
||||
let sel: Vec<ElementId> = s.selection.ids().collect();
|
||||
if sel.is_empty() {
|
||||
return Err(state("nothing is selected: select an instance, or pass 'element'"));
|
||||
}
|
||||
Ok(sel)
|
||||
}
|
||||
|
||||
fn property_param(p: &Value) -> Result<Option<BoundProperty>> {
|
||||
match opt_str(p, "property")? {
|
||||
None => Ok(None),
|
||||
Some(k) => BoundProperty::from_key(k).map(Some).ok_or_else(|| param(format!("unknown property '{}' ({})", short(k), BoundProperty::ALL.map(BoundProperty::key).join(", ")))),
|
||||
}
|
||||
}
|
||||
|
||||
fn opt_f64(p: &Value, key: &str) -> Result<Option<f64>> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v.as_f64().filter(|f| f.is_finite() && f.abs() <= MAX_VALUE).map(Some).ok_or_else(|| param(format!("param '{key}' must be a finite number within ±1,000,000,000"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn binding_json(d: &Document, b: &Binding, frame: u32) -> Value {
|
||||
let table = d.data_table(b.table);
|
||||
json!({
|
||||
"element": b.element.0,
|
||||
"property": b.property.key(),
|
||||
"table": b.table.0,
|
||||
"table_name": table.map(|t| t.name.as_str()),
|
||||
"column": b.column,
|
||||
"start": b.start,
|
||||
"frames": b.frames,
|
||||
"from": b.from,
|
||||
"to": b.to,
|
||||
"interpolation": b.interp.key(),
|
||||
"scale": b.scale,
|
||||
"offset": b.offset,
|
||||
"live": table.is_some_and(|t| t.column_index(&b.column).is_some()),
|
||||
"value": b.value_at(&d.data, frame),
|
||||
})
|
||||
}
|
||||
|
||||
fn bind(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let property = property_param(p)?.ok_or_else(|| param(format!("param 'property' is required ({})", BoundProperty::ALL.map(BoundProperty::key).join(", "))))?;
|
||||
let table = table_req(s, p)?;
|
||||
let column = str_req(p, "column")?;
|
||||
let ids = targets(s, p)?;
|
||||
let [id] = ids.as_slice() else { return Err(state("a binding drives one instance: select one, or pass 'element'")) };
|
||||
let found = find(s, *id).ok_or_else(|| state(format!("no object with id {} in the document", id.0)))?;
|
||||
let ElementKind::Symbol { symbol, .. } = &found.el.kind else {
|
||||
return Err(state("data drives symbol instances: convert the artwork with Modify › Convert to Symbol first"));
|
||||
};
|
||||
if property == BoundProperty::Frame && s.doc.symbol(*symbol).is_none_or(|x| x.kind != SymbolKind::Graphic) {
|
||||
return Err(state("only a graphic symbol's instance shows a frame picked by data (a movie clip plays on its own): change the symbol's type to Graphic"));
|
||||
}
|
||||
let t = s.doc.data_table(table).ok_or_else(|| state("the data table went away"))?;
|
||||
let ci = t.column_index(column).ok_or_else(|| {
|
||||
let have: Vec<&str> = t.columns.iter().map(|c| c.name.as_str()).take(20).collect();
|
||||
param(format!("table '{}' has no column '{}' (it has: {})", t.name, short(column), have.join(", ")))
|
||||
})?;
|
||||
let column = t.columns.get(ci).map(|c| c.name.clone()).unwrap_or_default();
|
||||
let start = opt_u32(p, "start")?.unwrap_or(found.first);
|
||||
let frames = match opt_u32(p, "frames")? {
|
||||
Some(n) => n,
|
||||
// One frame per row; with a key, the record over the frames the instance is on.
|
||||
None if t.key.is_some() => found.life,
|
||||
None => t.rows() as u32,
|
||||
};
|
||||
if start > MAX_SPAN || !(1..=MAX_SPAN).contains(&frames.max(1)) {
|
||||
return Err(param(format!("'start' is at most {MAX_SPAN} and 'frames' between 1 and {MAX_SPAN}")));
|
||||
}
|
||||
let interp = match opt_str(p, "interpolation")? {
|
||||
None => Interp::Linear,
|
||||
Some(k) => Interp::from_key(k).ok_or_else(|| param(format!("unknown interpolation '{}' (linear or step)", short(k))))?,
|
||||
};
|
||||
let b = Binding { element: *id, property, table, column, start, frames: frames.max(1), from: opt_f64(p, "from")?, to: opt_f64(p, "to")?, interp, scale: opt_f64(p, "scale")?.unwrap_or(1.0), offset: opt_f64(p, "offset")?.unwrap_or(0.0) };
|
||||
if !Arc::make_mut(&mut s.doc.data).bind(b.clone()) {
|
||||
return Err(state(format!("a document keeps at most {MAX_BINDINGS} data bindings")));
|
||||
}
|
||||
Ok(binding_json(&s.doc, &b, s.frame))
|
||||
}
|
||||
|
||||
fn unbind(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let property = property_param(p)?;
|
||||
let ids = targets(s, p)?;
|
||||
if !ids.iter().any(|id| s.doc.data.bindings_of(*id).iter().any(|b| property.is_none_or(|q| q == b.property))) {
|
||||
return Err(state("no data binding to remove there"));
|
||||
}
|
||||
let data = Arc::make_mut(&mut s.doc.data);
|
||||
let removed: usize = ids.iter().map(|id| data.unbind(*id, property)).sum();
|
||||
Ok(json!({"removed": removed}))
|
||||
}
|
||||
|
||||
fn bindings(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let d = &s.doc;
|
||||
let list: Vec<Value> = match opt_u64(p, "element")? {
|
||||
Some(id) => d.data.bindings_of(ElementId(id)).iter().map(|b| binding_json(d, b, s.frame)).collect(),
|
||||
None => d.data.bindings.iter().map(|b| binding_json(d, b, s.frame)).collect(),
|
||||
};
|
||||
Ok(json!({"bindings": list}))
|
||||
}
|
||||
|
||||
/// Bakes instance `id`'s bindings (of `property`, or all) into keyframes on its layer. How many
|
||||
/// keyframes were made.
|
||||
fn bake_one(s: &mut Session, id: ElementId, property: Option<BoundProperty>) -> Result<usize> {
|
||||
let found = find(s, id).ok_or_else(|| state(format!("no object with id {} in the document", id.0)))?;
|
||||
if !found.here {
|
||||
return Err(state("the instance is on another timeline: open the scene or symbol it is in, then bake"));
|
||||
}
|
||||
let bound: Vec<Binding> = s.doc.data.bindings_of(id).iter().filter(|b| property.is_none_or(|q| q == b.property)).cloned().collect();
|
||||
let data = s.doc.data.clone();
|
||||
let values_at = |f: u32| -> Vec<(BoundProperty, f32)> { bound.iter().filter_map(|b| b.value_at(&data, f).map(|v| (b.property, v))).collect() };
|
||||
let tl = s.timeline();
|
||||
let layer = tl.layer(found.layer).ok_or_else(|| state("the layer went away"))?;
|
||||
if layer.kind == LayerKind::Armature {
|
||||
return Err(state(format!("'{}' is an armature layer: its poses place its objects, so data can't be baked there", layer.name)));
|
||||
}
|
||||
if layer.locked || tl.locked_by_folder(layer.id) {
|
||||
return Err(state(format!("layer '{}' is locked", layer.name)));
|
||||
}
|
||||
// The frames that get a keyframe.
|
||||
let mut cuts: Vec<u32> = Vec::new();
|
||||
for (i, k) in layer.keyframes.iter().enumerate() {
|
||||
if !k.elements.iter().any(|e| e.id == id) {
|
||||
continue;
|
||||
}
|
||||
if k.motion.is_some() {
|
||||
return Err(state(format!("layer '{}' has a motion tween on frame {}: keyframes would cut it up. Remove the motion tween first (Insert › Remove Tween)", layer.name, k.start + 1)));
|
||||
}
|
||||
let tweened = k.tween.is_some() && layer.keyframes.get(i + 1).is_some_and(|n| n.start == k.end());
|
||||
let mut prev = values_at(k.start);
|
||||
for f in k.start.saturating_add(1)..k.end() {
|
||||
let v = values_at(f);
|
||||
if tweened || v != prev {
|
||||
cuts.push(f);
|
||||
if cuts.len() > MAX_KEYS {
|
||||
return Err(state(format!("that is more than {MAX_KEYS} keyframes at once: shorten the binding's span, or use step interpolation")));
|
||||
}
|
||||
}
|
||||
prev = v;
|
||||
}
|
||||
}
|
||||
// A graphic instance cut onto a new keyframe carries on from the frame it was showing.
|
||||
let lengths: HashMap<SymbolId, u32> = s.doc.library.iter().filter(|x| x.kind == SymbolKind::Graphic).map(|x| (x.id, x.timeline.frame_count())).collect();
|
||||
let (first, end) = (found.first, found.first.saturating_add(found.life));
|
||||
let layer = s.layer_mut(Some(found.layer))?;
|
||||
for &f in &cuts {
|
||||
// (The keyframe it is cut from: an earlier cut may have made it.)
|
||||
let from = layer.keyframe_at(f).map_or(f, |k| k.start);
|
||||
crate::cmds_timeline::insert_keyframe_at(layer, f, true)?;
|
||||
let Some(k) = layer.keyframe_starting_at(f).and_then(|i| layer.keyframe_mut(i)) else { continue };
|
||||
for e in &mut k.elements {
|
||||
let ElementKind::Symbol { symbol, loop_mode, first_frame, .. } = &e.kind else { continue };
|
||||
let Some(&len) = lengths.get(symbol) else { continue };
|
||||
let shown = loop_mode.local_frame(f - from, *first_frame, len);
|
||||
if *loop_mode != LoopMode::SingleFrame
|
||||
&& shown != *first_frame
|
||||
&& let ElementKind::Symbol { first_frame, .. } = &mut Arc::make_mut(e).kind
|
||||
{
|
||||
*first_frame = shown;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Every keyframe that holds the instance gets it as the bindings show it there.
|
||||
let at = layer.keyframes.partition_point(|k| k.start < first);
|
||||
let count = layer.keyframes.iter().skip(at).take_while(|k| k.start < end).count();
|
||||
for i in at..at + count {
|
||||
let Some(k) = layer.keyframe_mut(i) else { continue };
|
||||
let vals = values_at(k.start);
|
||||
if vals.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Some(slot) = k.elements.iter_mut().find(|e| e.id == id) {
|
||||
let next = with_values(slot, &vals);
|
||||
if next != **slot {
|
||||
*slot = Arc::new(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(cuts.len())
|
||||
}
|
||||
|
||||
fn bake(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let property = property_param(p)?;
|
||||
let ids: Vec<ElementId> = targets(s, p)?.into_iter().filter(|id| s.doc.data.bindings_of(*id).iter().any(|b| property.is_none_or(|q| q == b.property))).collect();
|
||||
if ids.is_empty() {
|
||||
return Err(state("no data binding to bake there"));
|
||||
}
|
||||
let mut keys = 0;
|
||||
for id in &ids {
|
||||
keys += bake_one(s, *id, property)?;
|
||||
}
|
||||
let data = Arc::make_mut(&mut s.doc.data);
|
||||
let removed: usize = ids.iter().map(|id| data.unbind(*id, property)).sum();
|
||||
Ok(json!({"keys": keys, "elements": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "removed": removed}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "data_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1160,10 +1160,12 @@ pub(crate) fn place(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
LibraryItem::Symbol(id) => format!("no symbol with id {}", id.0),
|
||||
LibraryItem::Bitmap(id) => format!("no bitmap with id {}", id.0),
|
||||
LibraryItem::Sound(id) => format!("no sound with id {} in the library", id.0),
|
||||
LibraryItem::Data(id) => format!("no data table with id {}", id.0),
|
||||
}));
|
||||
}
|
||||
match i {
|
||||
LibraryItem::Symbol(id) if crate::editing::would_nest(s, id) => return Err(EngineError::State("a symbol can't be placed inside itself".into())),
|
||||
LibraryItem::Data(_) => return Err(EngineError::State("a data table isn't artwork, so it can't be placed: bind one of its columns to an instance (Modify › Data › Bind to Data, or data.bind)".into())),
|
||||
LibraryItem::Sound(id) => {
|
||||
if sound.is_some_and(|x| x != id) {
|
||||
return Err(EngineError::State("a keyframe holds one sound; place sounds one at a time, on different keyframes or layers".into()));
|
||||
@@ -1183,7 +1185,7 @@ pub(crate) fn place(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
match i {
|
||||
LibraryItem::Symbol(id) => placed.push(place_symbol(s, id, x, y)?),
|
||||
LibraryItem::Bitmap(id) => placed.push(place_bitmap(s, id, x, y)?),
|
||||
LibraryItem::Sound(_) => {}
|
||||
LibraryItem::Sound(_) | LibraryItem::Data(_) => {}
|
||||
}
|
||||
}
|
||||
let mut out = json!({"element": placed.first().map(|e| e.0), "elements": placed.iter().map(|e| e.0).collect::<Vec<_>>()});
|
||||
|
||||
@@ -33,16 +33,17 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
/// Most entries one command takes.
|
||||
const MAX_ENTRIES: usize = 100_000;
|
||||
|
||||
/// The entry a JSON object names: `{"symbol": id}`, `{"bitmap": id}`, `{"sound": id}` or
|
||||
/// `{"folder": id}`.
|
||||
/// The entry a JSON object names: `{"symbol": id}`, `{"bitmap": id}`, `{"sound": id}`,
|
||||
/// `{"data": id}` (a data table, ADR 0118) or `{"folder": id}`.
|
||||
pub(crate) fn entry_of(v: &Value) -> Result<LibraryEntry> {
|
||||
let id = |k: &str| v.get(k).and_then(Value::as_u64);
|
||||
match (id("symbol"), id("bitmap"), id("sound"), id("folder")) {
|
||||
(Some(i), None, None, None) => Ok(LibraryEntry::Item(LibraryItem::Symbol(SymbolId(i)))),
|
||||
(None, Some(i), None, None) => Ok(LibraryEntry::Item(LibraryItem::Bitmap(BitmapId(i)))),
|
||||
(None, None, Some(i), None) => Ok(LibraryEntry::Item(LibraryItem::Sound(SoundId(i)))),
|
||||
(None, None, None, Some(i)) => Ok(LibraryEntry::Folder(FolderId(i))),
|
||||
_ => Err(EngineError::Param("name one Library entry: {\"symbol\" | \"bitmap\" | \"sound\" | \"folder\": id}".into())),
|
||||
match (id("symbol"), id("bitmap"), id("sound"), id("data"), id("folder")) {
|
||||
(Some(i), None, None, None, None) => Ok(LibraryEntry::Item(LibraryItem::Symbol(SymbolId(i)))),
|
||||
(None, Some(i), None, None, None) => Ok(LibraryEntry::Item(LibraryItem::Bitmap(BitmapId(i)))),
|
||||
(None, None, Some(i), None, None) => Ok(LibraryEntry::Item(LibraryItem::Sound(SoundId(i)))),
|
||||
(None, None, None, Some(i), None) => Ok(LibraryEntry::Item(LibraryItem::Data(anicraft_doc::DataId(i)))),
|
||||
(None, None, None, None, Some(i)) => Ok(LibraryEntry::Folder(FolderId(i))),
|
||||
_ => Err(EngineError::Param("name one Library entry: {\"symbol\" | \"bitmap\" | \"sound\" | \"data\" | \"folder\": id}".into())),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,6 +53,7 @@ pub fn entry_json(e: LibraryEntry) -> Value {
|
||||
LibraryEntry::Item(LibraryItem::Symbol(i)) => json!({"symbol": i.0}),
|
||||
LibraryEntry::Item(LibraryItem::Bitmap(i)) => json!({"bitmap": i.0}),
|
||||
LibraryEntry::Item(LibraryItem::Sound(i)) => json!({"sound": i.0}),
|
||||
LibraryEntry::Item(LibraryItem::Data(i)) => json!({"data": i.0}),
|
||||
LibraryEntry::Folder(f) => json!({"folder": f.0}),
|
||||
}
|
||||
}
|
||||
@@ -81,6 +83,7 @@ fn describe(e: LibraryEntry) -> String {
|
||||
LibraryEntry::Item(LibraryItem::Symbol(i)) => format!("symbol {}", i.0),
|
||||
LibraryEntry::Item(LibraryItem::Bitmap(i)) => format!("bitmap {}", i.0),
|
||||
LibraryEntry::Item(LibraryItem::Sound(i)) => format!("sound {}", i.0),
|
||||
LibraryEntry::Item(LibraryItem::Data(i)) => format!("data table {}", i.0),
|
||||
LibraryEntry::Folder(f) => format!("folder {}", f.0),
|
||||
}
|
||||
}
|
||||
@@ -158,6 +161,13 @@ fn items(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
v["seconds"] = json!(x.seconds());
|
||||
}
|
||||
}
|
||||
LibraryItem::Data(id) => {
|
||||
if let Some(t) = d.data_table(id) {
|
||||
v["kind"] = json!("data");
|
||||
v["rows"] = json!(t.rows());
|
||||
v["columns"] = json!(t.columns.len());
|
||||
}
|
||||
}
|
||||
}
|
||||
v
|
||||
})
|
||||
@@ -205,6 +215,16 @@ pub(crate) fn rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Arc::make_mut(x).name = name.clone();
|
||||
}
|
||||
}
|
||||
LibraryEntry::Item(LibraryItem::Data(id)) => {
|
||||
// Commands name a table by its name, so no two tables share one, whatever folder
|
||||
// they are in (ADR 0118).
|
||||
if d.data.tables.iter().any(|t| t.id != id && t.name.to_lowercase() == name.to_lowercase()) {
|
||||
return Err(EngineError::Param(format!("another data table is already named “{name}”")));
|
||||
}
|
||||
if let Some(x) = Arc::make_mut(&mut d.data).tables.iter_mut().find(|x| x.id == id) {
|
||||
Arc::make_mut(x).name = name.clone();
|
||||
}
|
||||
}
|
||||
LibraryEntry::Folder(id) => {
|
||||
if let Some(f) = Arc::make_mut(&mut d.library_tree).folders.iter_mut().find(|f| f.id == id) {
|
||||
f.name = name.clone();
|
||||
@@ -319,7 +339,7 @@ fn strip_in(tl: &mut Timeline, gone: &HashSet<LibraryItem>, depth: usize) -> usi
|
||||
}
|
||||
|
||||
/// Deletes `items` and `folders` from the Library and every use of the items from the movie.
|
||||
fn remove(s: &mut Session, items: &[LibraryItem], folders: &[FolderId]) -> Value {
|
||||
pub(crate) fn remove(s: &mut Session, items: &[LibraryItem], folders: &[FolderId]) -> Value {
|
||||
let gone: HashSet<LibraryItem> = items.iter().copied().collect();
|
||||
let mut uses = 0;
|
||||
if !gone.is_empty() {
|
||||
@@ -331,6 +351,14 @@ fn remove(s: &mut Session, items: &[LibraryItem], folders: &[FolderId]) -> Value
|
||||
s.doc.library.retain(|x| !gone.contains(&LibraryItem::Symbol(x.id)));
|
||||
s.doc.bitmaps.retain(|x| !gone.contains(&LibraryItem::Bitmap(x.id)));
|
||||
s.doc.sounds.retain(|x| !gone.contains(&LibraryItem::Sound(x.id)));
|
||||
// A data table goes with the bindings that read it (ADR 0118): each counts as a use.
|
||||
if s.doc.data.tables.iter().any(|t| gone.contains(&LibraryItem::Data(t.id))) {
|
||||
let data = Arc::make_mut(&mut s.doc.data);
|
||||
data.tables.retain(|t| !gone.contains(&LibraryItem::Data(t.id)));
|
||||
let before = data.bindings.len();
|
||||
data.bindings.retain(|b| !gone.contains(&LibraryItem::Data(b.table)));
|
||||
uses += before - data.bindings.len();
|
||||
}
|
||||
for sym in &mut s.doc.library {
|
||||
if strip_needed(&sym.timeline, &gone) {
|
||||
uses += strip(&mut Arc::make_mut(sym).timeline, &gone);
|
||||
@@ -348,6 +376,14 @@ fn remove(s: &mut Session, items: &[LibraryItem], folders: &[FolderId]) -> Value
|
||||
let t = Arc::make_mut(&mut s.doc.library_tree);
|
||||
t.placed.retain(|i, f| !gone.contains(i) && !dead.contains(f));
|
||||
t.folders.retain(|f| !dead.contains(&f.id));
|
||||
// (A data table keeps its own folder; one left in a deleted folder goes to the top.)
|
||||
if s.doc.data.tables.iter().any(|x| x.folder.is_some_and(|f| dead.contains(&f))) {
|
||||
for x in &mut Arc::make_mut(&mut s.doc.data).tables {
|
||||
if x.folder.is_some_and(|f| dead.contains(&f)) {
|
||||
Arc::make_mut(x).folder = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
// A folder whose parent went (it was named on its own) goes to the top level.
|
||||
let ids: HashSet<FolderId> = t.folders.iter().map(|f| f.id).collect();
|
||||
for f in &mut t.folders {
|
||||
|
||||
@@ -57,6 +57,9 @@ pub fn plugin_may_call(id: &str) -> std::result::Result<(), &'static str> {
|
||||
// The document's swatches are document data; swatch files are files.
|
||||
"swatch" if matches!(id, "swatch.import" | "swatch.export") => Err("plug-ins can't read or write swatch files"),
|
||||
"swatch" => Ok(()),
|
||||
// Data tables and bindings are the document's (ADR 0118); a table file is a file.
|
||||
"data" if id == "data.import_table" => Err("plug-ins can't read files: pass the values to data.set_table"),
|
||||
"data" => Ok(()),
|
||||
"plugin" => Err("plug-ins can't install, run or remove plug-ins"),
|
||||
// Saved commands are files in your preferences (ADR 0097), and running one from a
|
||||
// plug-in would let the two call each other.
|
||||
|
||||
@@ -0,0 +1,590 @@
|
||||
//! Reading a data table (ADR 0118) from CSV, TSV or JSON text.
|
||||
//!
|
||||
//! Delimited text goes through `craft-csv` (craft-libs): encoding and delimiter detection and a
|
||||
//! bounded record parser; what a field means is decided here. JSON is read by a small serde
|
||||
//! visitor that keeps numbers only and stops storing at the table's limits, so a hostile file
|
||||
//! costs no more memory than the largest table. Nothing here touches a document or a file.
|
||||
//!
|
||||
//! * The first record names the columns, unless every field of it is a number (then the
|
||||
//! columns are `Column 1`, `Column 2`, …).
|
||||
//! * A cell that isn't a finite number is a gap. A column with no number at all (sample ids,
|
||||
//! notes) is left out and reported.
|
||||
//! * JSON may be an array of records (`[{"age": 1, "pinus": 3}, …]`), an array of rows
|
||||
//! (`[["age", "pinus"], [1, 3], …]`), an object of columns (`{"age": [1, …], "pinus": [3, …]}`)
|
||||
//! or `{"columns": [names], "rows": [[…], …]}`; a plain array of numbers is one column.
|
||||
|
||||
use anicraft_doc::DataColumn;
|
||||
use anicraft_doc::data::{MAX_CELLS, MAX_COLUMNS, MAX_COLUMN_NAME, MAX_ROWS, clean_column_name};
|
||||
use serde::de::{DeserializeSeed, Deserializer, IgnoredAny, MapAccess, SeqAccess, Visitor};
|
||||
use std::cell::Cell;
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
|
||||
/// Largest file `data.import_table` reads.
|
||||
pub const MAX_FILE_BYTES: u64 = 32 << 20;
|
||||
|
||||
/// How a table file is written.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Format {
|
||||
/// Comma, semicolon or tab separated: the delimiter is detected.
|
||||
Delimited,
|
||||
Tsv,
|
||||
Json,
|
||||
}
|
||||
|
||||
impl Format {
|
||||
pub fn from_key(s: &str) -> Option<Option<Format>> {
|
||||
match s.trim().to_ascii_lowercase().as_str() {
|
||||
"auto" | "" => Some(None),
|
||||
"csv" => Some(Some(Format::Delimited)),
|
||||
"tsv" | "tab" => Some(Some(Format::Tsv)),
|
||||
"json" => Some(Some(Format::Json)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The format of a file named `name` holding `text`: by its extension, else by how the text
|
||||
/// starts.
|
||||
pub fn detect(name: &str, text: &str) -> Format {
|
||||
let ext = name.rsplit('.').next().unwrap_or("").to_ascii_lowercase();
|
||||
match ext.as_str() {
|
||||
"json" => Format::Json,
|
||||
"tsv" | "tab" => Format::Tsv,
|
||||
"csv" => Format::Delimited,
|
||||
_ if text.trim_start().starts_with(['{', '[']) => Format::Json,
|
||||
_ => Format::Delimited,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a file held.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Parsed {
|
||||
/// The columns with numbers, each as long as the table has rows.
|
||||
pub columns: Vec<DataColumn>,
|
||||
/// Columns left out because they held no number.
|
||||
pub skipped: Vec<String>,
|
||||
/// Cells of the kept columns with no number.
|
||||
pub gaps: usize,
|
||||
/// The file held more rows, columns or cells than a table keeps.
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
impl Parsed {
|
||||
pub fn rows(&self) -> usize {
|
||||
self.columns.first().map_or(0, |c| c.values.len())
|
||||
}
|
||||
}
|
||||
|
||||
/// A number as tables write it: plain or scientific, with an optional sign and percent sign;
|
||||
/// with `decimal_comma` (semicolon or tab separated files) a single comma is the decimal mark.
|
||||
/// `None` for anything else, and for infinities and NaN.
|
||||
pub fn parse_number(s: &str, decimal_comma: bool) -> Option<f64> {
|
||||
let s = s.trim().trim_end_matches('%').trim_end();
|
||||
if s.is_empty() || s.len() > 64 || !s.bytes().any(|b| b.is_ascii_digit()) || s.bytes().any(|b| b.is_ascii_alphabetic() && !matches!(b, b'e' | b'E')) {
|
||||
return None;
|
||||
}
|
||||
let v = if decimal_comma && s.bytes().filter(|b| *b == b',').count() == 1 && !s.contains('.') { s.replace(',', ".").parse::<f64>() } else { s.parse::<f64>() };
|
||||
v.ok().filter(|v| v.is_finite())
|
||||
}
|
||||
|
||||
/// A table being read: columns grow together, a row at a time.
|
||||
#[derive(Default)]
|
||||
struct Builder {
|
||||
names: Vec<String>,
|
||||
cols: Vec<Vec<Option<f64>>>,
|
||||
/// Each column by its name without case.
|
||||
by_name: HashMap<String, usize>,
|
||||
rows: usize,
|
||||
truncated: bool,
|
||||
}
|
||||
|
||||
impl Builder {
|
||||
/// The column called `name` (made when new, padded to the rows so far). `None` past the
|
||||
/// column limit.
|
||||
fn column(&mut self, name: &str) -> Option<usize> {
|
||||
let key = clean_column_name(name).to_lowercase();
|
||||
if let Some(&i) = self.by_name.get(&key) {
|
||||
return Some(i);
|
||||
}
|
||||
self.add(name)
|
||||
}
|
||||
|
||||
fn add(&mut self, name: &str) -> Option<usize> {
|
||||
if self.cols.len() >= MAX_COLUMNS {
|
||||
self.truncated = true;
|
||||
return None;
|
||||
}
|
||||
let i = self.cols.len();
|
||||
let clean = clean_column_name(name);
|
||||
let clean = if clean.is_empty() { format!("Column {}", i + 1) } else { clean };
|
||||
self.by_name.entry(clean.to_lowercase()).or_insert(i);
|
||||
self.names.push(clean);
|
||||
self.cols.push(vec![None; self.rows]);
|
||||
Some(i)
|
||||
}
|
||||
|
||||
/// Column `i` by position (made as `Column n` when the header was shorter).
|
||||
fn nth(&mut self, i: usize) -> Option<usize> {
|
||||
while self.cols.len() <= i {
|
||||
self.add("")?;
|
||||
}
|
||||
Some(i)
|
||||
}
|
||||
|
||||
/// Whether another row fits.
|
||||
fn room(&mut self) -> bool {
|
||||
let ok = self.rows < MAX_ROWS && (self.rows + 1).saturating_mul(self.cols.len().max(1)) <= MAX_CELLS;
|
||||
if !ok {
|
||||
self.truncated = true;
|
||||
}
|
||||
ok
|
||||
}
|
||||
|
||||
/// Ends the row: every column gets a cell (a gap where the row had none).
|
||||
fn end_row(&mut self) {
|
||||
self.rows += 1;
|
||||
for c in &mut self.cols {
|
||||
c.resize(self.rows, None);
|
||||
}
|
||||
}
|
||||
|
||||
fn set(&mut self, col: usize, v: Option<f64>) {
|
||||
if let Some(c) = self.cols.get_mut(col) {
|
||||
c.resize(self.rows + 1, None);
|
||||
if let Some(slot) = c.get_mut(self.rows) {
|
||||
*slot = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(mut self) -> Result<Parsed, String> {
|
||||
for c in &mut self.cols {
|
||||
c.resize(self.rows, None);
|
||||
}
|
||||
let mut columns = Vec::new();
|
||||
let mut skipped = Vec::new();
|
||||
for (name, values) in self.names.into_iter().zip(self.cols) {
|
||||
if values.iter().any(Option::is_some) { columns.push(DataColumn { name, values }) } else { skipped.push(name) }
|
||||
}
|
||||
if columns.is_empty() {
|
||||
return Err(if skipped.is_empty() { "the file has no rows of numbers".to_string() } else { "the file has no numbers: a data table keeps numeric columns (cells that aren't numbers become gaps)".to_string() });
|
||||
}
|
||||
skipped.truncate(MAX_COLUMNS);
|
||||
let gaps = columns.iter().map(|c| c.values.iter().filter(|v| v.is_none()).count()).sum();
|
||||
Ok(Parsed { columns, skipped, gaps, truncated: self.truncated })
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a table from the bytes of a file called `name` (for its extension), as `format` or as
|
||||
/// detected.
|
||||
pub fn parse(bytes: &[u8], name: &str, format: Option<Format>) -> Result<Parsed, String> {
|
||||
if bytes.len() as u64 > MAX_FILE_BYTES {
|
||||
return Err(format!("the file is larger than {} MB, the most a data table is read from", MAX_FILE_BYTES >> 20));
|
||||
}
|
||||
let text = craft_csv::decode_text(bytes);
|
||||
match format.unwrap_or_else(|| Format::detect(name, &text)) {
|
||||
Format::Json => parse_json(&text),
|
||||
Format::Tsv => parse_delimited(&text, Some('\t')),
|
||||
Format::Delimited => parse_delimited(&text, None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads delimited text; `delimiter` `None` detects comma, semicolon or tab.
|
||||
pub fn parse_delimited(text: &str, delimiter: Option<char>) -> Result<Parsed, String> {
|
||||
let delim = delimiter.unwrap_or_else(|| char::from(craft_csv::sniff_delimiter(text, '"')));
|
||||
let decimal_comma = delim != ',';
|
||||
let mut b = Builder::default();
|
||||
let mut first = true;
|
||||
craft_csv::parse_records(text, delim, '"', MAX_COLUMNS + 1, |record| {
|
||||
// A blank line is no row.
|
||||
if record.iter().all(|f| f.trim().is_empty()) {
|
||||
return true;
|
||||
}
|
||||
if record.len() > MAX_COLUMNS {
|
||||
b.truncated = true;
|
||||
}
|
||||
if first {
|
||||
first = false;
|
||||
let header = record.iter().any(|f| !f.trim().is_empty() && parse_number(f, decimal_comma).is_none());
|
||||
if header {
|
||||
for f in record.iter().take(MAX_COLUMNS) {
|
||||
// (A repeated name still gets its own column: `add`, not `column`.)
|
||||
b.add(f);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if !b.room() {
|
||||
return false;
|
||||
}
|
||||
for (i, f) in record.iter().take(MAX_COLUMNS).enumerate() {
|
||||
if let Some(c) = b.nth(i) {
|
||||
b.set(c, parse_number(f, decimal_comma));
|
||||
}
|
||||
}
|
||||
b.end_row();
|
||||
true
|
||||
});
|
||||
b.finish()
|
||||
}
|
||||
|
||||
// ----- JSON -------------------------------------------------------------------------------------
|
||||
|
||||
/// How many cells may still be stored, and whether any were dropped.
|
||||
struct Limits {
|
||||
cells: Cell<usize>,
|
||||
truncated: Cell<bool>,
|
||||
}
|
||||
|
||||
impl Limits {
|
||||
fn take(&self) -> bool {
|
||||
match self.cells.get() {
|
||||
0 => {
|
||||
self.truncated.set(true);
|
||||
false
|
||||
}
|
||||
n => {
|
||||
self.cells.set(n - 1);
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum JCell {
|
||||
Num(f64),
|
||||
/// Text that isn't a number (its first characters: a column name, or a gap).
|
||||
Text(String),
|
||||
Gap,
|
||||
}
|
||||
|
||||
impl JCell {
|
||||
fn number(&self) -> Option<f64> {
|
||||
match self {
|
||||
JCell::Num(v) => Some(*v),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum JItem {
|
||||
Cell(JCell),
|
||||
Row(Vec<JCell>),
|
||||
Record(Vec<(String, JCell)>),
|
||||
}
|
||||
|
||||
fn text_cell(s: &str) -> JCell {
|
||||
match parse_number(s, false) {
|
||||
Some(v) => JCell::Num(v),
|
||||
None => JCell::Text(s.chars().take(MAX_COLUMN_NAME * 2).collect()),
|
||||
}
|
||||
}
|
||||
|
||||
fn num_cell(v: f64) -> JCell {
|
||||
if v.is_finite() { JCell::Num(v) } else { JCell::Gap }
|
||||
}
|
||||
|
||||
/// One scalar; an array or object where a cell belongs is read past and is a gap.
|
||||
struct CellSeed;
|
||||
|
||||
impl<'de> DeserializeSeed<'de> for CellSeed {
|
||||
type Value = JCell;
|
||||
fn deserialize<D: Deserializer<'de>>(self, d: D) -> Result<JCell, D::Error> {
|
||||
d.deserialize_any(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Visitor<'de> for CellSeed {
|
||||
type Value = JCell;
|
||||
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("a number")
|
||||
}
|
||||
fn visit_f64<E>(self, v: f64) -> Result<JCell, E> {
|
||||
Ok(num_cell(v))
|
||||
}
|
||||
fn visit_i64<E>(self, v: i64) -> Result<JCell, E> {
|
||||
Ok(num_cell(v as f64))
|
||||
}
|
||||
fn visit_u64<E>(self, v: u64) -> Result<JCell, E> {
|
||||
Ok(num_cell(v as f64))
|
||||
}
|
||||
fn visit_str<E>(self, v: &str) -> Result<JCell, E> {
|
||||
Ok(text_cell(v))
|
||||
}
|
||||
fn visit_bool<E>(self, _: bool) -> Result<JCell, E> {
|
||||
Ok(JCell::Gap)
|
||||
}
|
||||
fn visit_unit<E>(self) -> Result<JCell, E> {
|
||||
Ok(JCell::Gap)
|
||||
}
|
||||
fn visit_seq<A: SeqAccess<'de>>(self, mut a: A) -> Result<JCell, A::Error> {
|
||||
while a.next_element::<IgnoredAny>()?.is_some() {}
|
||||
Ok(JCell::Gap)
|
||||
}
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut a: A) -> Result<JCell, A::Error> {
|
||||
while a.next_entry::<IgnoredAny, IgnoredAny>()?.is_some() {}
|
||||
Ok(JCell::Gap)
|
||||
}
|
||||
}
|
||||
|
||||
/// A row: a scalar, an array of scalars or an object of them.
|
||||
struct ItemSeed<'a>(&'a Limits);
|
||||
|
||||
impl<'de> DeserializeSeed<'de> for ItemSeed<'_> {
|
||||
type Value = JItem;
|
||||
fn deserialize<D: Deserializer<'de>>(self, d: D) -> Result<JItem, D::Error> {
|
||||
d.deserialize_any(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Visitor<'de> for ItemSeed<'_> {
|
||||
type Value = JItem;
|
||||
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("a row of numbers")
|
||||
}
|
||||
fn visit_f64<E>(self, v: f64) -> Result<JItem, E> {
|
||||
Ok(JItem::Cell(num_cell(v)))
|
||||
}
|
||||
fn visit_i64<E>(self, v: i64) -> Result<JItem, E> {
|
||||
Ok(JItem::Cell(num_cell(v as f64)))
|
||||
}
|
||||
fn visit_u64<E>(self, v: u64) -> Result<JItem, E> {
|
||||
Ok(JItem::Cell(num_cell(v as f64)))
|
||||
}
|
||||
fn visit_str<E>(self, v: &str) -> Result<JItem, E> {
|
||||
Ok(JItem::Cell(text_cell(v)))
|
||||
}
|
||||
fn visit_bool<E>(self, _: bool) -> Result<JItem, E> {
|
||||
Ok(JItem::Cell(JCell::Gap))
|
||||
}
|
||||
fn visit_unit<E>(self) -> Result<JItem, E> {
|
||||
Ok(JItem::Cell(JCell::Gap))
|
||||
}
|
||||
fn visit_seq<A: SeqAccess<'de>>(self, mut a: A) -> Result<JItem, A::Error> {
|
||||
let mut row = Vec::new();
|
||||
while let Some(c) = a.next_element_seed(CellSeed)? {
|
||||
if row.len() < MAX_COLUMNS && self.0.take() {
|
||||
row.push(c);
|
||||
} else {
|
||||
self.0.truncated.set(true);
|
||||
}
|
||||
}
|
||||
Ok(JItem::Row(row))
|
||||
}
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut a: A) -> Result<JItem, A::Error> {
|
||||
let mut rec = Vec::new();
|
||||
while let Some(k) = a.next_key::<String>()? {
|
||||
let c = a.next_value_seed(CellSeed)?;
|
||||
if rec.len() < MAX_COLUMNS && self.0.take() {
|
||||
rec.push((k, c));
|
||||
} else {
|
||||
self.0.truncated.set(true);
|
||||
}
|
||||
}
|
||||
Ok(JItem::Record(rec))
|
||||
}
|
||||
}
|
||||
|
||||
/// An array of rows (anything else is read past and is empty).
|
||||
struct ItemsSeed<'a>(&'a Limits);
|
||||
|
||||
impl<'de> DeserializeSeed<'de> for ItemsSeed<'_> {
|
||||
type Value = Vec<JItem>;
|
||||
fn deserialize<D: Deserializer<'de>>(self, d: D) -> Result<Vec<JItem>, D::Error> {
|
||||
d.deserialize_any(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Visitor<'de> for ItemsSeed<'_> {
|
||||
type Value = Vec<JItem>;
|
||||
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("an array")
|
||||
}
|
||||
fn visit_f64<E>(self, _: f64) -> Result<Vec<JItem>, E> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
fn visit_i64<E>(self, _: i64) -> Result<Vec<JItem>, E> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
fn visit_u64<E>(self, _: u64) -> Result<Vec<JItem>, E> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
fn visit_str<E>(self, _: &str) -> Result<Vec<JItem>, E> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
fn visit_bool<E>(self, _: bool) -> Result<Vec<JItem>, E> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
fn visit_unit<E>(self) -> Result<Vec<JItem>, E> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut a: A) -> Result<Vec<JItem>, A::Error> {
|
||||
while a.next_entry::<IgnoredAny, IgnoredAny>()?.is_some() {}
|
||||
Ok(Vec::new())
|
||||
}
|
||||
fn visit_seq<A: SeqAccess<'de>>(self, mut a: A) -> Result<Vec<JItem>, A::Error> {
|
||||
let mut out = Vec::new();
|
||||
while let Some(item) = a.next_element_seed(ItemSeed(self.0))? {
|
||||
// One more than the rows a table keeps: the first may name the columns.
|
||||
let fits = out.len() <= MAX_ROWS && (!matches!(item, JItem::Cell(_)) || self.0.take());
|
||||
if fits {
|
||||
out.push(item);
|
||||
} else {
|
||||
self.0.truncated.set(true);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
enum Top {
|
||||
Rows(Vec<JItem>),
|
||||
Object(Vec<(String, Vec<JItem>)>),
|
||||
}
|
||||
|
||||
struct TopSeed<'a>(&'a Limits);
|
||||
|
||||
impl<'de> DeserializeSeed<'de> for TopSeed<'_> {
|
||||
type Value = Top;
|
||||
fn deserialize<D: Deserializer<'de>>(self, d: D) -> Result<Top, D::Error> {
|
||||
d.deserialize_any(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Visitor<'de> for TopSeed<'_> {
|
||||
type Value = Top;
|
||||
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("an array of rows or an object of columns")
|
||||
}
|
||||
fn visit_seq<A: SeqAccess<'de>>(self, a: A) -> Result<Top, A::Error> {
|
||||
ItemsSeed(self.0).visit_seq(a).map(Top::Rows)
|
||||
}
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut a: A) -> Result<Top, A::Error> {
|
||||
let mut out = Vec::new();
|
||||
while let Some(k) = a.next_key::<String>()? {
|
||||
let v = a.next_value_seed(ItemsSeed(self.0))?;
|
||||
if out.len() < MAX_COLUMNS + 2 {
|
||||
out.push((k, v));
|
||||
} else {
|
||||
self.0.truncated.set(true);
|
||||
}
|
||||
}
|
||||
Ok(Top::Object(out))
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds `items` as rows: arrays by position (the first naming the columns when it is all
|
||||
/// text, or `names` when given), objects by name.
|
||||
fn rows_into(b: &mut Builder, items: Vec<JItem>, names: Option<Vec<String>>) {
|
||||
let mut first = names.is_none();
|
||||
if let Some(names) = names {
|
||||
for n in names.iter().take(MAX_COLUMNS) {
|
||||
b.add(n);
|
||||
}
|
||||
}
|
||||
for item in items {
|
||||
let was_first = std::mem::replace(&mut first, false);
|
||||
match item {
|
||||
JItem::Row(row) => {
|
||||
if was_first && !row.is_empty() && row.iter().all(|c| matches!(c, JCell::Text(_))) {
|
||||
for c in &row {
|
||||
if let JCell::Text(t) = c {
|
||||
b.add(t);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if !b.room() {
|
||||
return;
|
||||
}
|
||||
for (i, c) in row.iter().enumerate() {
|
||||
if let Some(col) = b.nth(i) {
|
||||
b.set(col, c.number());
|
||||
}
|
||||
}
|
||||
b.end_row();
|
||||
}
|
||||
JItem::Record(rec) => {
|
||||
if !b.room() {
|
||||
return;
|
||||
}
|
||||
for (k, c) in &rec {
|
||||
if let Some(col) = b.column(k) {
|
||||
b.set(col, c.number());
|
||||
}
|
||||
}
|
||||
b.end_row();
|
||||
}
|
||||
// A scalar among rows: a row of one cell.
|
||||
JItem::Cell(c) => {
|
||||
if !b.room() {
|
||||
return;
|
||||
}
|
||||
if let Some(col) = b.nth(0) {
|
||||
b.set(col, c.number());
|
||||
}
|
||||
b.end_row();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a table from JSON text (see the module's notes for the shapes).
|
||||
pub fn parse_json(text: &str) -> Result<Parsed, String> {
|
||||
let limits = Limits { cells: Cell::new(MAX_CELLS + MAX_COLUMNS), truncated: Cell::new(false) };
|
||||
let mut de = serde_json::Deserializer::from_str(text);
|
||||
let top = TopSeed(&limits).deserialize(&mut de).map_err(|e| format!("not a JSON table ({e}): a data table is an array of rows or records, or an object of columns"))?;
|
||||
de.end().map_err(|e| format!("not a JSON table ({e})"))?;
|
||||
let mut b = Builder { truncated: limits.truncated.get(), ..Builder::default() };
|
||||
match top {
|
||||
Top::Rows(items) => {
|
||||
if !items.is_empty() && items.iter().all(|i| matches!(i, JItem::Cell(_))) {
|
||||
b.add("value");
|
||||
}
|
||||
rows_into(&mut b, items, None);
|
||||
}
|
||||
Top::Object(mut entries) => {
|
||||
let is_rows = |items: &[JItem]| items.iter().any(|i| !matches!(i, JItem::Cell(_)));
|
||||
if let Some(at) = entries.iter().position(|(k, v)| k == "rows" && is_rows(v)) {
|
||||
let names = entries.iter().find(|(k, _)| k == "columns").map(|(_, v)| {
|
||||
v.iter()
|
||||
.map(|i| match i {
|
||||
JItem::Cell(JCell::Text(t)) => t.clone(),
|
||||
JItem::Cell(JCell::Num(n)) => n.to_string(),
|
||||
_ => String::new(),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
});
|
||||
let rows = entries.get_mut(at).map(|e| std::mem::take(&mut e.1)).unwrap_or_default();
|
||||
rows_into(&mut b, rows, names.filter(|n| !n.is_empty()));
|
||||
} else {
|
||||
// Columns: the table is as long as the longest.
|
||||
let rows = entries.iter().map(|(_, v)| v.len()).max().unwrap_or(0).min(MAX_ROWS);
|
||||
for (name, items) in &entries {
|
||||
if is_rows(items) {
|
||||
continue;
|
||||
}
|
||||
let Some(col) = b.add(name) else { break };
|
||||
if let Some(c) = b.cols.get_mut(col) {
|
||||
*c = items.iter().take(rows).map(|i| if let JItem::Cell(c) = i { c.number() } else { None }).collect();
|
||||
}
|
||||
}
|
||||
let cols = b.cols.len().max(1);
|
||||
let keep = rows.min(MAX_CELLS / cols);
|
||||
b.truncated |= keep < entries.iter().map(|(_, v)| v.len()).max().unwrap_or(0);
|
||||
b.rows = keep;
|
||||
for c in &mut b.cols {
|
||||
c.resize(keep, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
b.finish()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "data_import_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,173 @@
|
||||
use super::*;
|
||||
use anicraft_doc::data::{MAX_CELLS, MAX_COLUMNS, MAX_ROWS};
|
||||
|
||||
fn names(p: &Parsed) -> Vec<&str> {
|
||||
p.columns.iter().map(|c| c.name.as_str()).collect()
|
||||
}
|
||||
|
||||
fn col<'a>(p: &'a Parsed, name: &str) -> &'a [Option<f64>] {
|
||||
&p.columns.iter().find(|c| c.name == name).unwrap_or_else(|| panic!("no column {name}: {:?}", names(p))).values
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_are_read_plainly() {
|
||||
for (s, v) in [("1", 1.0), (" -2.5 ", -2.5), ("+3", 3.0), (".5", 0.5), ("1e3", 1000.0), ("2.5E-1", 0.25), ("45%", 45.0), ("12 %", 12.0)] {
|
||||
assert_eq!(parse_number(s, false), Some(v), "{s:?}");
|
||||
}
|
||||
for s in ["", " ", "abc", "nan", "NaN", "inf", "-Infinity", "1e999", "1,5", "1 2", "0x10", "--1", "e", "%", "١٢"] {
|
||||
assert_eq!(parse_number(s, false), None, "{s:?}");
|
||||
}
|
||||
// A decimal comma, where the comma can't be the delimiter.
|
||||
assert_eq!(parse_number("1,5", true), Some(1.5));
|
||||
assert_eq!(parse_number("1.234,5", true), None);
|
||||
assert_eq!(parse_number("1,2,3", true), None);
|
||||
assert_eq!(parse_number(&"9".repeat(100), false), None, "an endless digit string is not a number");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_with_a_header_gaps_and_a_text_column() {
|
||||
let p = parse(b"sample,depth,pinus,note\r\nA1,0.5,12,first\r\nA2,1.5,,\r\nA3,2.5,n/a,third\r\n", "core.csv", None).unwrap();
|
||||
assert_eq!(names(&p), ["depth", "pinus"]);
|
||||
assert_eq!(p.skipped, ["sample", "note"], "columns with no number are left out and reported");
|
||||
assert_eq!(col(&p, "depth"), [Some(0.5), Some(1.5), Some(2.5)]);
|
||||
assert_eq!(col(&p, "pinus"), [Some(12.0), None, None], "an empty cell and text are gaps");
|
||||
assert_eq!((p.rows(), p.gaps, p.truncated), (3, 2, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_edge_cases() {
|
||||
// Quoted fields, a quoted delimiter and line break, a byte order mark, blank lines, no
|
||||
// newline at the end.
|
||||
let p = parse("\u{feff}\"a, b\",\"c\nd\"\n\n\"1\",\"2\"\n \n3,4".as_bytes(), "x.csv", None).unwrap();
|
||||
assert_eq!(names(&p), ["a, b", "cd"], "a line break in a name is dropped");
|
||||
assert_eq!(p.columns[0].values, [Some(1.0), Some(3.0)]);
|
||||
assert_eq!(p.columns[1].values, [Some(2.0), Some(4.0)]);
|
||||
// No header: every field of the first record is a number.
|
||||
let p = parse(b"1,2\n3,4\n", "x.csv", None).unwrap();
|
||||
assert_eq!(names(&p), ["Column 1", "Column 2"]);
|
||||
assert_eq!(p.rows(), 2);
|
||||
// Ragged rows: short ones are padded with gaps, long ones grow the table.
|
||||
let p = parse(b"a,b\n1\n2,3,4\n", "x.csv", None).unwrap();
|
||||
assert_eq!(names(&p), ["a", "b", "Column 3"]);
|
||||
assert_eq!(col(&p, "b"), [None, Some(3.0)]);
|
||||
assert_eq!(col(&p, "Column 3"), [None, Some(4.0)]);
|
||||
// Repeated and empty names each keep their own column (the table makes them unique).
|
||||
let p = parse(b"v,v,\n1,2,3\n", "x.csv", None).unwrap();
|
||||
assert_eq!(p.columns.len(), 3);
|
||||
// A semicolon file with decimal commas; a tab file by its extension.
|
||||
let p = parse(b"age;value\n1,5;2,25\n", "x.csv", None).unwrap();
|
||||
assert_eq!(col(&p, "age"), [Some(1.5)]);
|
||||
assert_eq!(col(&p, "value"), [Some(2.25)]);
|
||||
let p = parse(b"age\tvalue\n1\t2\n", "x.tsv", None).unwrap();
|
||||
assert_eq!(col(&p, "value"), [Some(2.0)]);
|
||||
let p = parse(b"a b\tc,d\n1\t2\n", "x.txt", Some(Format::Tsv)).unwrap();
|
||||
assert_eq!(names(&p), ["a b", "c,d"]);
|
||||
// Windows-1252 text in a header still reads.
|
||||
let p = parse(b"temp\xe9rature\n3\n", "x.csv", None).unwrap();
|
||||
assert_eq!(names(&p), ["temp\u{e9}rature"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_without_numbers_are_refused() {
|
||||
for bytes in [&b""[..], b"\n\n\n", b"a,b\n", b"a,b\nx,y\n", b"\x00\x01\x02\xff\xfe", b"[]", b"{}", b"{\"a\": []}", b"[[\"a\", \"b\"]]"] {
|
||||
assert!(parse(bytes, "x.csv", None).is_err(), "{bytes:?}");
|
||||
}
|
||||
for bytes in [&b"{"[..], b"[1, 2", b"nope", b"3", b"\"text\"", b"[1] trailing"] {
|
||||
assert!(parse(bytes, "x.json", None).is_err(), "{bytes:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_in_every_shape() {
|
||||
// Records.
|
||||
let p = parse(br#"[{"age": 1, "pinus": 10, "id": "a"}, {"age": 2, "pinus": null}, {"pinus": "30", "age": 3, "extra": 7}]"#, "x.json", None).unwrap();
|
||||
assert_eq!(names(&p), ["age", "pinus", "extra"]);
|
||||
assert_eq!(col(&p, "pinus"), [Some(10.0), None, Some(30.0)], "a numeric string is a number");
|
||||
assert_eq!(col(&p, "extra"), [None, None, Some(7.0)]);
|
||||
assert_eq!(p.skipped, ["id"]);
|
||||
// Rows with a header row; nested values are gaps.
|
||||
let p = parse(br#"[["age", "v"], [1, 2], [3, [4]], [5, {"x": 1}], [6]]"#, "x.json", None).unwrap();
|
||||
assert_eq!(names(&p), ["age", "v"]);
|
||||
assert_eq!(col(&p, "v"), [Some(2.0), None, None, None]);
|
||||
// Rows without a header.
|
||||
let p = parse(b"[[1, 2], [3, 4]]", "x.json", None).unwrap();
|
||||
assert_eq!(names(&p), ["Column 1", "Column 2"]);
|
||||
// Columns, of different lengths.
|
||||
let p = parse(br#"{"age": [1, 2, 3], "v": [10, true], "label": ["a", "b"], "meta": {"x": 1}, "n": 4}"#, "x.json", None).unwrap();
|
||||
assert_eq!(names(&p), ["age", "v"]);
|
||||
assert_eq!(col(&p, "v"), [Some(10.0), None, None]);
|
||||
// Names and rows.
|
||||
let p = parse(br#"{"rows": [[1, 2], [3, 4]], "columns": ["a", "b"]}"#, "x.json", None).unwrap();
|
||||
assert_eq!(names(&p), ["a", "b"]);
|
||||
assert_eq!(col(&p, "b"), [Some(2.0), Some(4.0)]);
|
||||
// A plain list of numbers is one column.
|
||||
let p = parse(b"[3, 1, null, 2]", "x.json", None).unwrap();
|
||||
assert_eq!(names(&p), ["value"]);
|
||||
assert_eq!(col(&p, "value"), [Some(3.0), Some(1.0), None, Some(2.0)]);
|
||||
// Detected by its first character when the extension says nothing.
|
||||
assert_eq!(parse(b" [[1, 2]]", "data.txt", None).unwrap().rows(), 1);
|
||||
// A number too large for a table is refused by the reader, and never an infinity.
|
||||
assert!(parse(b"[1e400, 1, -1e400]", "x.json", None).is_err());
|
||||
let p = parse(b"[\"1e400\", 1, 1e308]", "x.json", None).unwrap();
|
||||
assert_eq!(col(&p, "value"), [None, Some(1.0), Some(1e308)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_tables_are_cut_to_the_limits() {
|
||||
// More rows than a table keeps.
|
||||
let mut csv = String::from("v\n");
|
||||
for i in 0..MAX_ROWS + 50 {
|
||||
csv.push_str(&format!("{i}\n"));
|
||||
}
|
||||
let p = parse(csv.as_bytes(), "x.csv", None).unwrap();
|
||||
assert_eq!((p.rows(), p.truncated), (MAX_ROWS, true));
|
||||
// More columns.
|
||||
let wide = format!("{}\n", (0..MAX_COLUMNS + 40).map(|i| i.to_string()).collect::<Vec<_>>().join(","));
|
||||
let p = parse(wide.repeat(3).as_bytes(), "x.csv", None).unwrap();
|
||||
assert_eq!((p.columns.len(), p.truncated), (MAX_COLUMNS, true));
|
||||
// More cells: 200 columns keep MAX_CELLS / 200 rows.
|
||||
let row = format!("{}\n", vec!["1"; 200].join(","));
|
||||
let p = parse(row.repeat(MAX_CELLS / 200 + 10).as_bytes(), "x.csv", None).unwrap();
|
||||
assert_eq!((p.rows(), p.truncated), (MAX_CELLS / 200, true));
|
||||
// The same through JSON: rows, a wide row, and columns.
|
||||
let json = format!("[{}]", vec!["[1,2]"; MAX_ROWS + 10].join(","));
|
||||
let p = parse(json.as_bytes(), "x.json", None).unwrap();
|
||||
assert_eq!((p.rows(), p.truncated), (MAX_ROWS, true));
|
||||
let json = format!("[[{}]]", vec!["1"; MAX_COLUMNS * 3].join(","));
|
||||
let p = parse(json.as_bytes(), "x.json", None).unwrap();
|
||||
assert_eq!((p.columns.len(), p.truncated), (MAX_COLUMNS, true));
|
||||
let json = format!("{{{}}}", (0..40).map(|i| format!("\"c{i}\": [{}]", vec!["1"; 60_000].join(","))).collect::<Vec<_>>().join(","));
|
||||
let p = parse(json.as_bytes(), "x.json", None).unwrap();
|
||||
assert!(p.truncated && p.rows() * p.columns.len() <= MAX_CELLS, "{} x {}", p.rows(), p.columns.len());
|
||||
// Deep nesting is refused by the reader, not the stack.
|
||||
let deep = format!("{}1{}", "[".repeat(100_000), "]".repeat(100_000));
|
||||
assert!(parse(deep.as_bytes(), "x.json", None).is_err());
|
||||
// An endless quoted field, a row of delimiters, and control characters are just text.
|
||||
assert!(parse(format!("a\n\"{}", "x".repeat(200_000)).as_bytes(), "x.csv", None).is_err());
|
||||
assert!(parse(",".repeat(500_000).as_bytes(), "x.csv", None).is_err());
|
||||
let p = parse(b"a\x00\x07b,c\n1,2\n", "x.csv", None).unwrap();
|
||||
assert_eq!(p.columns.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_reader_never_panics_on_junk() {
|
||||
// A small deterministic fuzz over bytes that look like tables.
|
||||
let alphabet: &[u8] = b"0123456789.,;\t\n\r\"-+eE%[]{}: anx\\\xff\x00";
|
||||
let mut seed = 0x2545_f491_4f6c_dd1du64;
|
||||
let mut next = move || {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
seed
|
||||
};
|
||||
for round in 0..3_000 {
|
||||
let len = (next() % 200) as usize;
|
||||
let bytes: Vec<u8> = (0..len).map(|_| alphabet[(next() % alphabet.len() as u64) as usize]).collect();
|
||||
for name in ["x.csv", "x.tsv", "x.json", "x"] {
|
||||
if let Ok(p) = parse(&bytes, name, None) {
|
||||
let rows = p.rows();
|
||||
assert!(!p.columns.is_empty() && p.columns.iter().all(|c| c.values.len() == rows && c.values.iter().all(|v| v.is_none_or(f64::is_finite))), "round {round} {name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
//! Data tables and bindings end to end (ADR 0118): import and re-import, inline tables, binding,
|
||||
//! what `evaluate` shows, baking to keyframes, the Library, undo, the file and plug-ins.
|
||||
|
||||
use crate::{Session, format};
|
||||
use anicraft_doc::{BoundProperty, DataId, Document, ElementId, ElementKind, LibraryItem, LoopMode, evaluate};
|
||||
use anicraft_geom::Affine;
|
||||
use serde_json::{Value, json};
|
||||
use std::path::Path;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
match s.execute(id, &p) {
|
||||
Ok(v) => v,
|
||||
Err(e) => panic!("{id} {p}: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn fails(s: &mut Session, id: &str, p: Value) -> String {
|
||||
match s.execute(id, &p) {
|
||||
Ok(v) => panic!("{id} {p} should fail, gave {v}"),
|
||||
Err(e) => e.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `f` on a thread of its own with the in-memory file store.
|
||||
fn in_memory(f: impl FnOnce() + Send + 'static) {
|
||||
std::thread::spawn(move || {
|
||||
crate::vfs::use_memory();
|
||||
f();
|
||||
})
|
||||
.join()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// A document whose first layer runs 40 frames and holds one instance (selected) of a graphic
|
||||
/// symbol: a 20 × 100 bar. The instance's id.
|
||||
fn bar_doc() -> (Session, u64) {
|
||||
let mut s = Session::new(Document::default());
|
||||
run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 20, "h": 100, "fill": "#3366cc", "object": true}));
|
||||
run(&mut s, "modify.convert_to_symbol", json!({"name": "Bar", "kind": "graphic"}));
|
||||
run(&mut s, "timeline.insert_frame", json!({"frame": 39}));
|
||||
let id = s.selection.ids().next().expect("the instance is selected").0;
|
||||
(s, id)
|
||||
}
|
||||
|
||||
fn table(s: &mut Session, name: &str, columns: Value) -> u64 {
|
||||
run(s, "data.set_table", json!({"name": name, "columns": columns}))["table"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
/// What every frame of the movie shows: each item's transform and opacity.
|
||||
fn movie(s: &Session) -> Vec<Vec<(Affine, f32, f32)>> {
|
||||
(0..s.doc.frame_count())
|
||||
.map(|f| {
|
||||
let dl = evaluate(&s.doc, f);
|
||||
dl.items.iter().map(|i| (i.transform, dl.effective_alpha(i), i.path.bounds().width())).collect()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn same_movie(a: &[Vec<(Affine, f32, f32)>], b: &[Vec<(Affine, f32, f32)>]) {
|
||||
assert_eq!(a.len(), b.len());
|
||||
for (f, (x, y)) in a.iter().zip(b).enumerate() {
|
||||
assert_eq!(x.len(), y.len(), "frame {f}");
|
||||
for ((ma, aa, wa), (mb, ab, wb)) in x.iter().zip(y) {
|
||||
assert!(ma.m.iter().zip(mb.m).all(|(p, q)| (p - q).abs() < 1e-3), "frame {f}: {ma:?} vs {mb:?}");
|
||||
assert!((aa - ab).abs() < 1e-4 && wa == wb, "frame {f}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_reads_files_and_importing_again_keeps_bindings() {
|
||||
in_memory(|| {
|
||||
let (mut s, el) = bar_doc();
|
||||
crate::vfs::put(Path::new("dir/core.csv"), b"sample,age,pinus,betula\nA,100,10,1\nB,300,30,3\nC,200,20,2\n".to_vec()).unwrap();
|
||||
let v = run(&mut s, "data.import_table", json!({"path": "dir/core.csv", "key": "age"}));
|
||||
assert_eq!((v["name"].as_str(), v["rows"].as_u64(), v["key"].as_str(), v["replaced"].as_bool()), (Some("core"), Some(3), Some("age"), Some(false)));
|
||||
assert_eq!(v["columns"], json!(["age", "pinus", "betula"]));
|
||||
assert_eq!(v["skipped"], json!(["sample"]));
|
||||
assert_eq!(v["source"], "core.csv", "the file's name, never its folder");
|
||||
let id = v["table"].as_u64().unwrap();
|
||||
// Keyed: the rows are in the key's order.
|
||||
let got = run(&mut s, "data.get", json!({"table": "CORE"}));
|
||||
assert_eq!(got["columns"][0]["values"], json!([100.0, 200.0, 300.0]));
|
||||
assert_eq!(got["columns"][1]["values"], json!([10.0, 20.0, 30.0]));
|
||||
run(&mut s, "data.bind", json!({"property": "scale_y", "table": "core", "column": "pinus"}));
|
||||
run(&mut s, "data.bind", json!({"property": "x", "table": id, "column": "betula"}));
|
||||
// Again, revised: the same table (by its name), its bindings and its key stay.
|
||||
crate::vfs::put(Path::new("dir/core.csv"), b"age,pinus\n100,50\n200,60\n".to_vec()).unwrap();
|
||||
let v = run(&mut s, "data.import_table", json!({"path": "dir/core.csv"}));
|
||||
assert_eq!((v["table"].as_u64(), v["replaced"].as_bool(), v["bindings"].as_u64(), v["key"].as_str()), (Some(id), Some(true), Some(2), Some("age")));
|
||||
assert_eq!(v["missing"], json!(["betula"]), "a binding whose column went rests");
|
||||
let b = run(&mut s, "data.bindings", json!({"element": el}));
|
||||
assert_eq!(b["bindings"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(b["bindings"][0]["live"], false);
|
||||
assert_eq!((b["bindings"][1]["live"].as_bool(), b["bindings"][1]["value"].as_f64()), (Some(true), Some(50.0)));
|
||||
// Under another name, or into a table named by id.
|
||||
let other = run(&mut s, "data.import_table", json!({"path": "dir/core.csv", "name": "Second"}));
|
||||
assert_ne!(other["table"].as_u64(), Some(id));
|
||||
crate::vfs::put(Path::new("new.json"), br#"[{"age": 1, "pinus": 2}]"#.to_vec()).unwrap();
|
||||
let v = run(&mut s, "data.import_table", json!({"path": "new.json", "table": id}));
|
||||
assert_eq!((v["table"].as_u64(), v["name"].as_str(), v["rows"].as_u64(), v["source"].as_str()), (Some(id), Some("core"), Some(1), Some("new.json")));
|
||||
// Refused: no file, no numbers, a key that isn't there, a format that isn't one.
|
||||
assert!(fails(&mut s, "data.import_table", json!({"path": "missing.csv"})).contains("I/O"));
|
||||
crate::vfs::put(Path::new("text.csv"), b"a,b\nx,y\n".to_vec()).unwrap();
|
||||
assert!(fails(&mut s, "data.import_table", json!({"path": "text.csv"})).contains("no numbers"));
|
||||
assert!(fails(&mut s, "data.import_table", json!({"path": "dir/core.csv", "name": "Third", "key": "depth"})).contains("no column 'depth'"));
|
||||
assert!(fails(&mut s, "data.import_table", json!({"path": "dir/core.csv", "format": "xlsx"})).contains("unknown format"));
|
||||
assert_eq!(s.doc.data.tables.len(), 2, "a refused import leaves nothing behind");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_tables_in_every_shape() {
|
||||
let mut s = Session::new(Document::default());
|
||||
let a = table(&mut s, "A", json!({"x": [1, 2, null], "y": [4, 5, 6]}));
|
||||
let got = run(&mut s, "data.get", json!({"table": a}));
|
||||
assert_eq!(got["columns"], json!([{"name": "x", "values": [1.0, 2.0, null]}, {"name": "y", "values": [4.0, 5.0, 6.0]}]));
|
||||
let b = table(&mut s, "B", json!([{"name": "v", "values": [1, 2]}]));
|
||||
assert_eq!(run(&mut s, "data.get", json!({"table": b, "from": 1}))["columns"][0]["values"], json!([2.0]));
|
||||
let c = run(&mut s, "data.set_table", json!({"name": "C", "columns": ["t", "v"], "rows": [[0, 1], [10, 2]], "key": "t"}));
|
||||
assert_eq!((c["rows"].as_u64(), c["key"].as_str()), (Some(2), Some("t")));
|
||||
// Setting a table that is there replaces it.
|
||||
let again = run(&mut s, "data.set_table", json!({"name": "a", "columns": {"x": [9]}}));
|
||||
assert_eq!((again["table"].as_u64(), again["replaced"].as_bool(), again["rows"].as_u64()), (Some(a), Some(true), Some(1)));
|
||||
let l = run(&mut s, "data.list", json!({}));
|
||||
assert_eq!(l["tables"].as_array().unwrap().iter().map(|t| t["name"].as_str().unwrap()).collect::<Vec<_>>(), ["A", "B", "C"]);
|
||||
// One cell, and the key.
|
||||
run(&mut s, "data.set_cell", json!({"table": "C", "column": "t", "row": 0, "value": 20}));
|
||||
assert_eq!(run(&mut s, "data.get", json!({"table": "C"}))["columns"][1]["values"], json!([2.0, 1.0]), "a changed key moves its row");
|
||||
run(&mut s, "data.set_cell", json!({"table": "C", "column": "v", "row": 1, "value": null}));
|
||||
run(&mut s, "data.set_key", json!({"table": "C", "key": null}));
|
||||
assert_eq!(run(&mut s, "data.list", json!({}))["tables"][2]["key"], Value::Null);
|
||||
for (p, why) in [
|
||||
(json!({"columns": {"x": [1]}}), "'name' is required"),
|
||||
(json!({"name": "D"}), "'columns' is required"),
|
||||
(json!({"name": "D", "columns": 5}), "'columns' must be"),
|
||||
(json!({"name": "D", "columns": {"x": ["a"]}}), "no numbers"),
|
||||
(json!({"name": "D", "columns": {"x": [1]}, "rows": [[1]]}), "column names"),
|
||||
(json!({"name": "a/b", "columns": {"x": [1]}}), "/"),
|
||||
(json!({"name": "D", "columns": {"x": [1]}, "key": "y"}), "no column 'y'"),
|
||||
(json!({"table": 999, "columns": {"x": [1]}}), "no data table with id"),
|
||||
] {
|
||||
let e = fails(&mut s, "data.set_table", p.clone());
|
||||
assert!(e.contains(why), "{p}: {e}");
|
||||
}
|
||||
assert!(fails(&mut s, "data.set_cell", json!({"table": "C", "column": "v", "row": 9, "value": 1})).contains("2 rows"));
|
||||
assert!(fails(&mut s, "data.set_cell", json!({"table": "C", "column": "v", "row": 0, "value": "x"})).contains("finite number"));
|
||||
assert!(fails(&mut s, "data.get", json!({"table": "nope"})).contains("no data table named"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_binding_drives_the_instance_and_follows_the_table() {
|
||||
let (mut s, el) = bar_doc();
|
||||
let t = table(&mut s, "pollen", json!({"pinus": [100, 200, 50], "x": [0, 10, 20]}));
|
||||
let own = evaluate(&s.doc, 0).items[0].transform;
|
||||
let v = run(&mut s, "data.bind", json!({"property": "scale_y", "table": "pollen", "column": "PINUS"}));
|
||||
assert_eq!((v["start"].as_u64(), v["frames"].as_u64(), v["column"].as_str(), v["value"].as_f64()), (Some(0), Some(3), Some("pinus"), Some(100.0)), "one frame per row, from the instance's first frame");
|
||||
let sy = |s: &Session, f| evaluate(&s.doc, f).items[0].transform.m[3];
|
||||
assert!((sy(&s, 0) - 1.0).abs() < 1e-5 && (sy(&s, 1) - 2.0).abs() < 1e-5 && (sy(&s, 2) - 0.5).abs() < 1e-5);
|
||||
assert!((sy(&s, 30) - 0.5).abs() < 1e-5, "held after the span");
|
||||
// Editing one number changes the frame; nothing else is touched.
|
||||
run(&mut s, "data.set_cell", json!({"table": t, "column": "pinus", "row": 1, "value": 400}));
|
||||
assert!((sy(&s, 1) - 4.0).abs() < 1e-5);
|
||||
// A span of its own, with scale and offset; rebinding a property replaces its binding.
|
||||
run(&mut s, "data.bind", json!({"property": "scale_y", "table": t, "column": "pinus", "element": el, "start": 10, "frames": 21, "scale": 0.5, "offset": 100, "interpolation": "step"}));
|
||||
assert_eq!(s.doc.data.bindings.len(), 1);
|
||||
assert!((sy(&s, 0) - 1.5).abs() < 1e-5 && (sy(&s, 19) - 1.5).abs() < 1e-5 && (sy(&s, 20) - 3.0).abs() < 1e-5 && (sy(&s, 30) - 1.25).abs() < 1e-5);
|
||||
// Unbind: as placed again. Undo brings the binding back.
|
||||
run(&mut s, "data.unbind", json!({}));
|
||||
assert_eq!(evaluate(&s.doc, 20).items[0].transform, own);
|
||||
s.undo().unwrap();
|
||||
assert!((sy(&s, 20) - 3.0).abs() < 1e-5);
|
||||
// What is refused.
|
||||
for (p, why) in [
|
||||
(json!({"table": t, "column": "pinus"}), "'property' is required"),
|
||||
(json!({"property": "skew", "table": t, "column": "pinus"}), "unknown property"),
|
||||
(json!({"property": "x", "column": "pinus"}), "'table' is required"),
|
||||
(json!({"property": "x", "table": t, "column": "quercus"}), "it has: pinus, x"),
|
||||
(json!({"property": "x", "table": t, "column": "x", "element": 999_999}), "no object with id"),
|
||||
(json!({"property": "x", "table": t, "column": "x", "frames": 1_000_000}), "between 1 and"),
|
||||
(json!({"property": "x", "table": t, "column": "x", "scale": 1e300}), "finite number"),
|
||||
(json!({"property": "x", "table": t, "column": "x", "interpolation": "cubic"}), "unknown interpolation"),
|
||||
] {
|
||||
let e = fails(&mut s, "data.bind", p.clone());
|
||||
assert!(e.contains(why), "{p}: {e}");
|
||||
}
|
||||
// Only symbol instances; only a graphic shows a frame picked by data.
|
||||
run(&mut s, "draw.rect", json!({"x": 300, "y": 100, "w": 20, "h": 20, "object": true}));
|
||||
assert!(fails(&mut s, "data.bind", json!({"property": "x", "table": t, "column": "x"})).contains("symbol instances"));
|
||||
run(&mut s, "modify.convert_to_symbol", json!({"name": "Clip", "kind": "movie_clip"}));
|
||||
assert!(fails(&mut s, "data.bind", json!({"property": "frame", "table": t, "column": "x"})).contains("graphic"));
|
||||
run(&mut s, "data.bind", json!({"property": "alpha", "table": t, "column": "x"}));
|
||||
s.selection = Default::default();
|
||||
assert!(fails(&mut s, "data.unbind", json!({})).contains("nothing is selected"));
|
||||
assert!(fails(&mut s, "data.unbind", json!({"element": el, "property": "rotation"})).contains("no data binding"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_keyed_table_maps_onto_the_frames_the_instance_is_on() {
|
||||
let (mut s, _) = bar_doc();
|
||||
table(&mut s, "ages", json!({"age": [0, 1000, 4000], "v": [100, 200, 500]}));
|
||||
run(&mut s, "data.set_key", json!({"table": "ages", "key": "age"}));
|
||||
let v = run(&mut s, "data.bind", json!({"property": "scale_x", "table": "ages", "column": "v"}));
|
||||
assert_eq!((v["start"].as_u64(), v["frames"].as_u64()), (Some(0), Some(40)));
|
||||
let sx = |s: &Session, f| evaluate(&s.doc, f).items[0].transform.m[0];
|
||||
assert!((sx(&s, 0) - 1.0).abs() < 1e-5 && (sx(&s, 39) - 5.0).abs() < 1e-5);
|
||||
// Backwards, old to young.
|
||||
run(&mut s, "data.bind", json!({"property": "scale_x", "table": "ages", "column": "v", "from": 4000, "to": 0}));
|
||||
assert!((sx(&s, 0) - 5.0).abs() < 1e-5 && (sx(&s, 39) - 1.0).abs() < 1e-5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bake_writes_keyframes_and_every_frame_looks_as_it_did() {
|
||||
// Step data on a static span: a keyframe where the value changes.
|
||||
let (mut s, el) = bar_doc();
|
||||
table(&mut s, "d", json!({"v": [100, 100, 250, 250, 250, 40], "a": [100, 80, 60, 40, 20, 0]}));
|
||||
run(&mut s, "data.bind", json!({"property": "scale_y", "table": "d", "column": "v", "interpolation": "step"}));
|
||||
let live = movie(&s);
|
||||
let v = run(&mut s, "data.bake", json!({}));
|
||||
assert_eq!((v["keys"].as_u64(), v["removed"].as_u64()), (Some(2), Some(1)));
|
||||
assert!(s.doc.data.bindings.is_empty());
|
||||
assert_eq!(s.timeline().layers[0].keyframes.iter().map(|k| k.start).collect::<Vec<_>>(), [0, 2, 5]);
|
||||
same_movie(&live, &movie(&s));
|
||||
// One undo step brings the binding (and the single keyframe) back.
|
||||
s.undo().unwrap();
|
||||
assert_eq!((s.doc.data.bindings.len(), s.timeline().layers[0].keyframes.len()), (1, 1));
|
||||
|
||||
// Linear data over more frames than rows, two properties: a keyframe a frame while it moves.
|
||||
run(&mut s, "data.bind", json!({"property": "scale_y", "table": "d", "column": "v", "frames": 21}));
|
||||
run(&mut s, "data.bind", json!({"property": "alpha", "table": "d", "column": "a", "start": 5, "frames": 11}));
|
||||
let live = movie(&s);
|
||||
// Only one of them: the other stays live.
|
||||
let v = run(&mut s, "data.bake", json!({"property": "alpha"}));
|
||||
assert_eq!((v["keys"].as_u64(), v["removed"].as_u64()), (Some(10), Some(1)));
|
||||
assert_eq!(s.doc.data.bindings.iter().map(|b| b.property).collect::<Vec<_>>(), [BoundProperty::ScaleY]);
|
||||
same_movie(&live, &movie(&s));
|
||||
run(&mut s, "data.bake", json!({"element": el}));
|
||||
same_movie(&live, &movie(&s));
|
||||
assert!(fails(&mut s, "data.bake", json!({"element": el})).contains("no data binding"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bake_inside_a_classic_tween_and_with_a_looping_graphic() {
|
||||
let (mut s, el) = bar_doc();
|
||||
// The instance tweens across the stage over frames 0..20 and holds to 39.
|
||||
run(&mut s, "timeline.insert_keyframe", json!({"frame": 20}));
|
||||
run(&mut s, "timeline.goto", json!({"frame": 20}));
|
||||
s.select_only([ElementId(el)]);
|
||||
run(&mut s, "element.set_transform", json!({"x": 400, "y": 300}));
|
||||
run(&mut s, "timeline.create_tween", json!({"frame": 0}));
|
||||
table(&mut s, "d", json!({"v": [100, 300, 50, 200]}));
|
||||
run(&mut s, "data.bind", json!({"property": "scale_y", "table": "d", "column": "v", "element": el, "start": 4, "frames": 30}));
|
||||
let live = movie(&s);
|
||||
assert!((live[10][0].0.m[4] - live[0][0].0.m[4]).abs() > 50.0, "the tween still moves it");
|
||||
run(&mut s, "data.bake", json!({"element": el}));
|
||||
same_movie(&live, &movie(&s));
|
||||
|
||||
// A looping graphic of three frames (20, 60 and 90 wide): after the bake cuts its span,
|
||||
// each new keyframe carries on from the frame it was showing.
|
||||
let (mut s, el) = bar_doc();
|
||||
let sym = s.doc.library[0].id.0;
|
||||
run(&mut s, "symbol.edit", json!({"symbol": sym}));
|
||||
for f in 1..3u32 {
|
||||
run(&mut s, "timeline.insert_blank_keyframe", json!({"frame": f}));
|
||||
run(&mut s, "timeline.goto", json!({"frame": f}));
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 30 * (f + 1), "h": 10, "object": true}));
|
||||
}
|
||||
run(&mut s, "symbol.exit", json!({}));
|
||||
assert!(matches!(&s.timeline().layers[0].keyframes[0].elements[0].kind, ElementKind::Symbol { loop_mode: LoopMode::Loop, .. }));
|
||||
table(&mut s, "d", json!({"x": [0, 0, 0, 0, 50, 50, 50, 90]}));
|
||||
run(&mut s, "data.bind", json!({"property": "x", "table": "d", "column": "x", "element": el, "interpolation": "step"}));
|
||||
let live = movie(&s);
|
||||
let widths: Vec<f32> = live.iter().take(6).map(|f| f[0].2).collect();
|
||||
assert_ne!(widths[0], widths[1], "the graphic loops: {widths:?}");
|
||||
assert_eq!(run(&mut s, "data.bake", json!({"element": el}))["keys"], 2);
|
||||
same_movie(&live, &movie(&s));
|
||||
|
||||
// The frame a graphic shows, picked by a column and baked.
|
||||
let (mut s2, el2) = (s, el);
|
||||
s2.undo().unwrap();
|
||||
run(&mut s2, "data.unbind", json!({"element": el2}));
|
||||
table(&mut s2, "f", json!({"level": [2, 0, 1, 1]}));
|
||||
run(&mut s2, "data.bind", json!({"property": "frame", "table": "f", "column": "level", "element": el2, "interpolation": "step"}));
|
||||
let live = movie(&s2);
|
||||
assert_eq!(live.iter().take(5).map(|f| f[0].2).collect::<Vec<_>>(), [90.0, 20.0, 60.0, 60.0, 60.0]);
|
||||
run(&mut s2, "data.bake", json!({"element": el2}));
|
||||
same_movie(&live, &movie(&s2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bake_refuses_what_it_would_break() {
|
||||
let (mut s, el) = bar_doc();
|
||||
table(&mut s, "d", json!({"v": [100, 300]}));
|
||||
run(&mut s, "data.bind", json!({"property": "scale_y", "table": "d", "column": "v", "frames": 20}));
|
||||
let layer = s.layer.0;
|
||||
run(&mut s, "layer.toggle_lock", json!({"layer": layer, "on": true}));
|
||||
assert!(fails(&mut s, "data.bake", json!({"element": el})).contains("locked"));
|
||||
run(&mut s, "layer.toggle_lock", json!({"layer": layer, "on": false}));
|
||||
run(&mut s, "timeline.create_motion_tween", json!({"frame": 0}));
|
||||
let before = s.doc.clone();
|
||||
assert!(fails(&mut s, "data.bake", json!({"element": el})).contains("motion tween"));
|
||||
assert_eq!(s.doc, before, "a refused bake changes nothing");
|
||||
// A binding inside a symbol bakes once that symbol is open.
|
||||
let (mut s, el) = bar_doc();
|
||||
table(&mut s, "d", json!({"v": [100, 300]}));
|
||||
run(&mut s, "data.bind", json!({"property": "scale_y", "table": "d", "column": "v", "frames": 20}));
|
||||
s.select_only([ElementId(el)]);
|
||||
run(&mut s, "modify.convert_to_symbol", json!({"name": "Outer", "kind": "graphic"}));
|
||||
assert!(fails(&mut s, "data.bake", json!({"element": el})).contains("another timeline"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tables_are_library_items() {
|
||||
let (mut s, _) = bar_doc();
|
||||
let t = table(&mut s, "pollen", json!({"v": [1, 2]}));
|
||||
run(&mut s, "data.bind", json!({"property": "x", "table": t, "column": "v"}));
|
||||
let items = run(&mut s, "library.items", json!({}));
|
||||
let row = items["items"].as_array().unwrap().iter().find(|i| i["data"] == t).expect("the table is listed").clone();
|
||||
assert_eq!((row["kind"].as_str(), row["rows"].as_u64(), row["columns"].as_u64(), row["uses"].as_u64(), row["unused"].as_bool()), (Some("data"), Some(2), Some(1), Some(1), Some(false)));
|
||||
// Rename (bindings follow: they name the table by id), move into a folder, refuse a clash.
|
||||
run(&mut s, "library.rename", json!({"data": t, "name": "Pollen 2026"}));
|
||||
let f = run(&mut s, "library.new_folder", json!({"name": "Data"}))["folder"].as_u64().unwrap();
|
||||
run(&mut s, "library.move", json!({"items": [{"data": t}], "to": f}));
|
||||
assert_eq!(s.doc.entry_path(anicraft_doc::LibraryEntry::Item(LibraryItem::Data(DataId(t)))), "Data/Pollen 2026");
|
||||
table(&mut s, "other", json!({"v": [1]}));
|
||||
assert!(fails(&mut s, "library.rename", json!({"data": t, "name": "OTHER"})).contains("already named"));
|
||||
assert_eq!(run(&mut s, "data.bindings", json!({}))["bindings"][0]["table_name"], "Pollen 2026");
|
||||
// A table can't be placed on the stage.
|
||||
assert!(fails(&mut s, "library.place", json!({"data": t})).contains("isn't artwork") || fails(&mut s, "library.place", json!({"items": [{"data": t}]})).contains("isn't artwork"));
|
||||
// Deleting the folder's table takes its bindings with it; undo brings both back.
|
||||
let v = run(&mut s, "library.delete", json!({"items": [{"folder": f}], "confirm": true}));
|
||||
assert_eq!((v["deleted"].as_u64(), v["uses"].as_u64()), (Some(1), Some(1)));
|
||||
assert!(s.doc.data.bindings.is_empty() && s.doc.data.tables.len() == 1);
|
||||
s.undo().unwrap();
|
||||
assert_eq!((s.doc.data.bindings.len(), s.doc.data.tables.len()), (1, 2));
|
||||
assert_eq!(run(&mut s, "data.remove", json!({"table": "Pollen 2026"}))["uses"], 1);
|
||||
// Unused tables go with Delete Unused Items.
|
||||
assert_eq!(run(&mut s, "library.unused", json!({}))["items"], json!([{"data": s.doc.data.tables[0].id.0}]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_is_saved_and_older_files_stay_the_same() {
|
||||
let (mut s, _) = bar_doc();
|
||||
let plain = format::to_json(&s.doc).unwrap();
|
||||
assert!(!plain.contains("\"data\""), "a document without data writes no data field");
|
||||
table(&mut s, "pollen", json!({"age": [3, 1, 2], "v": [1.5, null, -2e-3]}));
|
||||
run(&mut s, "data.set_key", json!({"table": "pollen", "key": "age"}));
|
||||
run(&mut s, "data.bind", json!({"property": "rotation", "table": "pollen", "column": "v", "scale": 2, "interpolation": "step"}));
|
||||
let text = format::to_json(&s.doc).unwrap();
|
||||
assert_eq!(format::version_for(&s.doc), format::BASE_VERSION, "data needs no newer file version");
|
||||
let back = format::from_json(&text).unwrap();
|
||||
assert_eq!(back, s.doc);
|
||||
assert_eq!(movie(&Session::new(back)), movie(&s));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plug_ins_may_use_tables_but_not_read_files() {
|
||||
use crate::cmds_plugin::plugin_may_call;
|
||||
for id in ["data.set_table", "data.list", "data.get", "data.set_cell", "data.set_key", "data.remove", "data.bind", "data.unbind", "data.bindings", "data.bake"] {
|
||||
assert!(crate::find_command(id).is_some(), "{id}");
|
||||
assert!(plugin_may_call(id).is_ok(), "{id}");
|
||||
}
|
||||
assert!(plugin_may_call("data.import_table").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_params_never_panic() {
|
||||
let (mut s, el) = bar_doc();
|
||||
table(&mut s, "d", json!({"v": [1, 2, 3]}));
|
||||
let junk = [
|
||||
Value::Null,
|
||||
json!([]),
|
||||
json!({"table": -1, "column": 7, "property": 3, "element": "x"}),
|
||||
json!({"table": "d", "column": "v", "property": "x", "element": el, "start": u64::MAX, "frames": 0, "from": 1e308, "to": -1e308, "scale": f64::MAX}),
|
||||
json!({"table": "d", "column": "v", "property": "frame", "element": el, "frames": 100_000, "from": -1e9, "to": 1e9, "scale": 1e9, "offset": -1e9}),
|
||||
json!({"table": "d", "column": "v", "row": u64::MAX, "value": 1e308, "key": 5, "from": u64::MAX, "count": u64::MAX}),
|
||||
json!({"name": "x".repeat(10_000), "columns": {"": [1e308, -1e308, null, "x", [1], {"a": 1}]}, "key": ""}),
|
||||
json!({"name": "n", "columns": (0..600).map(|i| json!({"name": format!("c{i}"), "values": [i]})).collect::<Vec<_>>()}),
|
||||
json!({"name": "n", "columns": ["a"], "rows": (0..2_000).map(|i| json!([i, i, i])).collect::<Vec<_>>()}),
|
||||
json!({"path": "", "format": "json", "table": "d"}),
|
||||
json!({"path": "\u{0}/../..", "name": "/", "key": null}),
|
||||
];
|
||||
for c in crate::commands().into_iter().filter(|c| c.id.starts_with("data.")) {
|
||||
for p in &junk {
|
||||
let _ = s.execute(c.id, p);
|
||||
for f in [0, 1, 39] {
|
||||
assert!(evaluate(&s.doc, f).items.iter().all(|i| i.transform.is_finite()), "{} {p}", c.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The numbers in ADR 0118 (`cargo test -p anicraft-engine data_timings -- --ignored --nocapture`).
|
||||
#[test]
|
||||
#[ignore = "prints timings; not a check"]
|
||||
fn data_timings() {
|
||||
use std::time::Instant;
|
||||
// Import: 100 000 rows of 10 columns.
|
||||
let mut csv = String::from("age,a,b,c,d,e,f,g,h,i\n");
|
||||
for r in 0..100_000 {
|
||||
csv.push_str(&format!("{r},{}.5,{},{},{},{},{},{},{},{}\n", r % 97, r % 13, r * 3, r % 7, r % 11, r % 5, r % 3, r % 2, r % 17));
|
||||
}
|
||||
let t = Instant::now();
|
||||
let p = crate::data_import::parse(csv.as_bytes(), "big.csv", None).unwrap();
|
||||
println!("import: {} rows x {} columns from {:.1} MB of CSV in {:.1} ms", p.rows(), p.columns.len(), csv.len() as f64 / 1e6, t.elapsed().as_secs_f64() * 1e3);
|
||||
// Evaluate: 200 instances, each bound to a 1 000-row keyed table.
|
||||
let (mut s, first) = bar_doc();
|
||||
let sym = s.doc.library[0].id.0;
|
||||
let mut bars = vec![first];
|
||||
for i in 1..200 {
|
||||
bars.push(run(&mut s, "library.place", json!({"symbol": sym, "x": 10 + i * 4, "y": 200}))["element"].as_u64().unwrap());
|
||||
}
|
||||
let frames = s.doc.frame_count();
|
||||
let time = |s: &Session| {
|
||||
let t = Instant::now();
|
||||
for round in 0..5 {
|
||||
for f in 0..frames {
|
||||
std::hint::black_box(evaluate(&s.doc, (f + round) % frames));
|
||||
}
|
||||
}
|
||||
t.elapsed().as_secs_f64() * 1e6 / f64::from(frames * 5)
|
||||
};
|
||||
let plain = time(&s);
|
||||
let age: Vec<u32> = (0..1_000).collect();
|
||||
let v: Vec<f64> = (0..1_000).map(|i| 50.0 + f64::from(i % 100)).collect();
|
||||
run(&mut s, "data.set_table", json!({"name": "t", "columns": [{"name": "age", "values": age}, {"name": "v", "values": v}], "key": "age"}));
|
||||
for el in &bars {
|
||||
run(&mut s, "data.bind", json!({"element": el, "property": "scale_y", "table": "t", "column": "v"}));
|
||||
}
|
||||
println!("evaluate, 200 instances: {plain:.0} us a frame unbound, {:.0} us with 200 bindings on a 1 000-row keyed table", time(&s));
|
||||
let t = Instant::now();
|
||||
s.select_only(bars.iter().map(|b| ElementId(*b)));
|
||||
let v = run(&mut s, "data.bake", json!({}));
|
||||
println!("bake: {} keyframes for 200 instances in {:.1} ms", v["keys"], t.elapsed().as_secs_f64() * 1e3);
|
||||
}
|
||||
@@ -342,6 +342,6 @@ pub fn unique_bytes(old: &Document, new: &Document) -> usize {
|
||||
|
||||
/// Estimated total bytes of a document (as if nothing were shared). Used for reporting.
|
||||
pub fn document_bytes(doc: &Document) -> usize {
|
||||
let empty = Document { stage: doc.stage, scenes: Vec::new(), library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), aids: doc.aids.clone(), swatches: doc.swatches.clone(), eases: doc.eases.clone(), next_id: doc.next_id };
|
||||
let empty = Document { stage: doc.stage, scenes: Vec::new(), library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), aids: doc.aids.clone(), swatches: doc.swatches.clone(), eases: doc.eases.clone(), data: Default::default(), next_id: doc.next_id };
|
||||
unique_bytes(doc, &empty)
|
||||
}
|
||||
@@ -48,6 +48,8 @@ pub mod cmds_plugin;
|
||||
mod cmds_scene;
|
||||
pub mod cmds_sound;
|
||||
pub mod cmds_audio_keys;
|
||||
pub mod cmds_data;
|
||||
pub mod data_import;
|
||||
pub mod cmds_text;
|
||||
mod cmds_timeline;
|
||||
mod cmds_view;
|
||||
@@ -189,6 +191,7 @@ pub fn commands() -> Vec<CommandSpec> {
|
||||
v.extend(cmds_erase::specs());
|
||||
v.extend(cmds_paint::specs());
|
||||
v.extend(cmds_swatch::specs());
|
||||
v.extend(cmds_data::specs());
|
||||
v.extend(cmds_text::specs());
|
||||
v.extend(cmds_width::specs());
|
||||
v.extend(cmds_stroke::specs());
|
||||
|
||||
@@ -189,6 +189,8 @@ fn every_command_namespace_has_a_plugin_policy() {
|
||||
"filter" => assert_eq!(verdict.is_ok(), matches!(c.id, "filter.move" | "filter.enable" | "filter.remove" | "filter.preset_list" | "filter.preset_apply"), "{}", c.id),
|
||||
// Swatches (ADR 0078): document data yes, swatch files no.
|
||||
"swatch" => assert_eq!(verdict.is_ok(), !matches!(c.id, "swatch.import" | "swatch.export"), "{}", c.id),
|
||||
// Data tables (ADR 0118): the document's tables and bindings yes, reading a file no.
|
||||
"data" => assert_eq!(verdict.is_ok(), c.id != "data.import_table", "{}", c.id),
|
||||
// Rulers, grid and guides (ADR 0076): a scene's guides yes, how you see and snap no.
|
||||
// A reference video (ADR 0116) is a file read by a program AniCraft starts.
|
||||
"layer" if c.id == "layer.set_video" => assert!(verdict.is_err(), "{} must be refused", c.id),
|
||||
|
||||
@@ -88,6 +88,8 @@ pub(crate) fn carry(s: &Session, roots: &[Element], sounds: impl IntoIterator<It
|
||||
}
|
||||
LibraryItem::Bitmap(id) => out.bitmaps.extend(s.doc.bitmaps.iter().find(|b| b.id == id).cloned()),
|
||||
LibraryItem::Sound(id) => out.sounds.extend(s.doc.sounds.iter().find(|x| x.id == id).cloned()),
|
||||
// Artwork never refers to a data table (bindings do, and they aren't copied).
|
||||
LibraryItem::Data(_) => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
|
||||
@@ -53,6 +53,7 @@ pub const PAGES: &[Page] = &[
|
||||
page!("text.md"),
|
||||
page!("images-and-sound.md"),
|
||||
page!("interactivity.md"),
|
||||
page!("data-driven-animation.md"),
|
||||
page!("exporting-and-publish.md"),
|
||||
page!("opening-animate-files.md"),
|
||||
page!("preferences-shortcuts-accessibility.md"),
|
||||
@@ -79,6 +80,8 @@ pub const IMAGES: &[(&str, &[u8])] = &[
|
||||
image!("images/preferences.png"),
|
||||
image!("images/audio-to-keyframes.png"),
|
||||
image!("images/lip-sync.png"),
|
||||
image!("images/data-chart.png"),
|
||||
image!("images/data-table.png"),
|
||||
];
|
||||
|
||||
const STYLE: &str = include_str!("style.css");
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
# ADR 0118: Data tables that drive animation
|
||||
|
||||
* Status: accepted (2026-11-18)
|
||||
* Relates to: ADR 0001 (the persistent document), ADR 0016 (motion tweens), ADR 0050 (the
|
||||
Library), ADR 0111 (the transformation point), ADR 0114 (audio to keyframes), ADR 0017
|
||||
(plug-ins), ADR 0004 (destructive actions), issues #416, #417, #418 (split from #414),
|
||||
roadmap M6
|
||||
|
||||
## Context
|
||||
|
||||
Three requests from one user, a scientist animating a lake-sediment record: keep the numbers
|
||||
behind an animation in the document (#416), let a column of them drive an instance's position,
|
||||
scale, rotation or alpha over a span of frames (#417), and let a column pick the frame a graphic
|
||||
symbol shows (#418). Today a script can turn numbers into keyframes, but then the document holds
|
||||
only the keyframes, and every revision of the data means writing them again.
|
||||
|
||||
Animate has nothing like this; After Effects has data-driven animation through expressions.
|
||||
AniCraft has no expression language and should not grow one for this: a chart, a caption
|
||||
counter or a record played over time needs "this number, at this frame, is that property", and
|
||||
nothing more.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **The document keeps tables and bindings, apart from the timelines**
|
||||
(`Document::data`, `anicraft_doc::data`). A **table** has an id, a Library name, named columns
|
||||
of `f64` cells where a cell may be a gap, and an optional **key column**. A **binding** names
|
||||
a symbol instance by element id, one property, a table by id, a column by name, a span of
|
||||
frames, the keys the span runs between, an interpolation, and a scale and offset. The field
|
||||
is left out of files with no data, so those files are byte for byte what they were, and
|
||||
`FORMAT_VERSION` does not change: an older build opens a file with data and ignores it (and
|
||||
drops it if it saves, as with every optional field before this one).
|
||||
|
||||
Bindings are kept in the document, keyed by element id, not on the element. An instance is
|
||||
copied onto every keyframe of its layer, and a binding on the element would have to be kept
|
||||
the same on all of them; keyed by id, one binding follows the instance through keyframes and
|
||||
tweens and touches neither. It also keeps `Element` as it is for the hundred places that
|
||||
build one. The cost: a copy, paste or duplicate makes a new id and so does not carry the
|
||||
bindings (not yet, below), and bindings of an instance that was deleted stay until the file
|
||||
is next opened (undo brings the instance back with them).
|
||||
|
||||
2. **A row per frame, or a row per keyed time.** Without a key column, rows are looked up by row
|
||||
number, and a binding of as many frames as the table has rows shows exactly one row per
|
||||
frame (the arithmetic multiplies before it divides, so frame *n* is row *n* to the bit; a
|
||||
test walks 997 rows). With a key column (an age, a depth, a time) rows are looked up by its
|
||||
value, and a table with a key keeps its rows in the key's ascending order, rows without a key
|
||||
last, so a lookup is a binary search. Playing a record from old to young is a binding whose
|
||||
last key is before its first, not a second ordering of the table.
|
||||
|
||||
3. **Reading a column.** Between the nearest rows with a number on either side: straight across
|
||||
(**Linear**) or held from the earlier row (**Step**, which gives regime holds with no new
|
||||
ease). Gaps are skipped, so a patchy column still draws. Before the first number and after
|
||||
the last, theirs. A column with no number, a missing column or a missing table gives no
|
||||
value, and the instance stays as it is placed: a binding never hides or breaks its instance.
|
||||
|
||||
4. **A binding replaces the property's value; it does not add to it.** Value = column × scale +
|
||||
offset, in the property's own units (pixels, percent, degrees), within the range a motion
|
||||
tween's curve may take. X and Y are the registration point; scale and rotation turn about
|
||||
the instance's transformation point when it has one (ADR 0111), which is how a bar grows
|
||||
from its foot. The code that places the instance is the motion tween's
|
||||
(`motion::placed`), so a bound instance and a tweened one agree. Alpha keeps the rest of the
|
||||
colour effect. The other properties still tween: a bound Y on an instance whose X is tweened
|
||||
moves along both.
|
||||
|
||||
**Before the span the instance shows the span's first frame, after it the last.** A chart
|
||||
whose data ends should hold its last value, not snap back to where the bar was drawn. The
|
||||
span exists to map frames onto keys, not to switch the binding on and off.
|
||||
|
||||
5. **The frame a graphic shows** (#418) is one more bound property, `frame`: the value, rounded,
|
||||
is the 0-based frame of the symbol (as `first_frame` is in every command), and the instance is
|
||||
shown as Single Frame whatever its looping says, since a frame picked by data and a loop
|
||||
offset can't both be meant. Only a graphic symbol's instance takes it (a movie clip plays on
|
||||
its own).
|
||||
|
||||
6. **Only symbol instances are bound**, as only they tween. A shape's own space is the stage's,
|
||||
so scaling one about its origin would throw it across the stage; Convert to Symbol is one
|
||||
key away and gives the artist a registration point to scale about.
|
||||
|
||||
7. **Applied inside `evaluate`, purely.** `eval_timeline` hands each layer's elements, after
|
||||
tweens, motion paths and poses, to `Document::bound_elements`, which swaps in the bound
|
||||
properties for that timeline's frame. A document with no bindings pays one emptiness check
|
||||
per layer; one with bindings pays a binary search per element (bindings are kept sorted by
|
||||
element and property). Scrubbing, the stage, the oracle, the GPU stage, Test Movie and every
|
||||
export that draws through `evaluate` (PNG, sequences, GIF, APNG, WebP, video, sprite sheets,
|
||||
SVG frames, the HTML canvas page's baked frames) therefore agree, with nothing to keep in
|
||||
step. Bindings apply on whatever timeline holds the instance, a symbol's own included.
|
||||
|
||||
Editing tools read the authored element (`Session::elements_on`), so dragging a bound
|
||||
instance moves what is under the binding; the selection box follows what is drawn, since it
|
||||
comes from the display list. Properties shows the authored values and, in the Data section,
|
||||
what each binding gives at the playhead.
|
||||
|
||||
8. **Bake to Keyframes** (`data.bake`) writes what the bindings show as plain keyframes and
|
||||
removes them, for people who want keys, and for exports that write keys from the document's
|
||||
structure (Lottie). It inserts a keyframe where the bound value changes on a held span, one
|
||||
per frame inside a classic tween (the tween is kept on both sides of each cut), and sets the
|
||||
instance on every keyframe that holds it. A looping graphic cut onto a new keyframe carries
|
||||
on from the frame it was showing. Tests compare every frame of the movie before and after.
|
||||
It refuses armature layers (poses place their objects), locked layers and motion tween spans
|
||||
(keyframes would cut the tween up; its curves are the right target, later), and changes
|
||||
nothing when it refuses.
|
||||
|
||||
9. **Tables are Library items** (`LibraryItem::Data`): listed, renamed, moved into folders,
|
||||
counted (a use per binding), found by Select Unused Items and deleted like the others;
|
||||
deleting a table deletes the bindings that read it (undoable, and counted in the
|
||||
confirmation as uses). Two differences. Table names are unique among tables whatever folder
|
||||
they are in, because commands name a table by name. And a table keeps its own folder
|
||||
(`DataTable::folder`), not an entry in the Library tree's placements: an older build reads
|
||||
those placements strictly, and one it doesn't know would make the whole file unreadable.
|
||||
|
||||
10. **Import** (`data.import_table`, File › Import › Import Data Table…) reads CSV, TSV or JSON,
|
||||
up to 32 MB. Delimited text goes through **craft-csv** (craft-libs: encoding and delimiter
|
||||
detection and a bounded record parser), as the shared-libraries rule asks; what a field
|
||||
means is ours. The first record names the columns unless all of it is numbers; a cell that
|
||||
isn't a finite number is a gap; a column with no number at all is left out and named in the
|
||||
report; a single decimal comma is read in semicolon and tab files. JSON may be an array of
|
||||
records, an array of rows, an object of columns, or `{columns, rows}`; a small serde visitor
|
||||
keeps numbers only and stops storing at the limits, so a hostile file costs no more memory
|
||||
than the largest table. `data.set_table` takes the same values inline for scripts, MCP and
|
||||
plug-ins.
|
||||
|
||||
**Importing over a table keeps its id**, so every binding stays (bindings name columns by
|
||||
name, so reordered columns are fine). A binding whose column is gone rests, and the report
|
||||
names it. The table remembers the file's name only, never its folder, so a shared document
|
||||
doesn't carry someone's paths.
|
||||
|
||||
11. **Limits.** 256 tables; 256 columns, 100 000 rows and 1 000 000 cells a table; 64-character
|
||||
column names; 10 000 bindings; spans of at most 100 000 frames; scale, offset and keys
|
||||
within ±1e9. Opening a file repairs data and never refuses the file for it: tables with
|
||||
repeated ids are dropped, names made usable and unique, short columns padded, non-finite
|
||||
cells turned into gaps, keyed rows sorted, bindings sorted and made one per property, and
|
||||
bindings of instances that are nowhere dropped.
|
||||
|
||||
12. **Commands, in a new `data` namespace**: `data.import_table`, `data.set_table`,
|
||||
`data.list`, `data.get`, `data.set_cell`, `data.set_key`, `data.remove`, `data.bind`,
|
||||
`data.unbind`, `data.bindings`, `data.bake`. All work headless, over the CLI and MCP.
|
||||
**Plug-ins** may call all of them but `data.import_table`, which reads a file (as
|
||||
`swatch.import` is refused); they pass values to `data.set_table`.
|
||||
|
||||
13. **In the shell.** A table shows in the Library with a preview of its first rows, its key
|
||||
column and Import Again; a double-click opens the **table viewer**, a window that draws
|
||||
only the cells in view. A symbol instance's Properties get a **Data** section: Bind to Data
|
||||
adds a binding, whose table, column, frames, keys, scale, offset and interpolation are
|
||||
edited in place and show on the stage as they change, with no dialog; Bake to Keyframes
|
||||
sits beside it. Modify › Data has Bind to Data, Remove Data Bindings and Bake Data to
|
||||
Keyframes.
|
||||
|
||||
## Measured
|
||||
|
||||
Test profile, Windows 10 (`cargo test -p anicraft-engine data_timings -- --ignored --nocapture`):
|
||||
|
||||
* Import: 100 000 rows of 10 columns from 3.2 MB of CSV in 63 ms.
|
||||
* `evaluate` of a frame with 200 instances: 15 µs unbound, 82 µs with each bound to a column of a
|
||||
1 000-row keyed table (about 0.33 µs a binding: a binary search and a decompose and compose).
|
||||
The unbound figure includes the new step: one emptiness check per layer.
|
||||
* Bake of those 200 instances over 40 frames: 39 keyframes in 4.9 ms.
|
||||
|
||||
## Not yet
|
||||
|
||||
* Bindings that follow copy, paste, Duplicate and Duplicate Symbol.
|
||||
* Baking inside a motion tween (as its property curves), and a warning from Lottie export when
|
||||
a document has live bindings (it writes keys from the document's structure; bake first).
|
||||
* Editing cells in the viewer (`data.set_cell` does it headless), adding and renaming columns,
|
||||
text columns that drive captions.
|
||||
* Binding other properties (skew, tint, filter values), shapes, text and group members.
|
||||
* Expressions between columns, and audio amplitude written into a table (#332's other half).
|
||||
* XFL has no counterpart; nothing is imported or exported there.
|
||||
|
||||
## Consequences
|
||||
|
||||
A revision of the data is one Import Again. The numbers travel with the document. `evaluate`
|
||||
gains one more pure step, and the file format one more optional field. The Library has a fourth
|
||||
kind of item, so every `match` on `LibraryItem` now says what a table means there.
|
||||
@@ -0,0 +1,142 @@
|
||||
# Data-driven animation
|
||||
|
||||
Numbers can animate for you. Keep a table of them in your document, let a column drive a
|
||||
property of an instance, and the animation follows the data: a bar chart that grows month by
|
||||
month, a marker that moves with a measured level, an outline that changes with a record. When
|
||||
the numbers are revised, import the file again and every frame follows, with no keyframes to
|
||||
redo.
|
||||
|
||||

|
||||
|
||||
## Importing a table
|
||||
|
||||
**File › Import › Import Data Table…** reads a table of numbers into the Library from:
|
||||
|
||||
* **CSV** or **TSV** text (comma, semicolon or tab separated), as spreadsheets export it. The
|
||||
first line names the columns. In semicolon and tab files a decimal comma is read (`3,5`).
|
||||
* **JSON**: a list of records (`[{"age": 100, "pinus": 12}, …]`), a list of rows with the names
|
||||
first (`[["age", "pinus"], [100, 12], …]`), or columns by name (`{"age": [100, …], "pinus":
|
||||
[12, …]}`).
|
||||
|
||||
A table keeps numbers. A cell that isn't a number (an empty cell, `n/a`) becomes a **gap**, and
|
||||
a column with no numbers at all, such as sample names, is left out; the status bar tells you
|
||||
which. A table holds up to 100,000 rows, 256 columns and a million cells, and a file up to
|
||||
32 MB is read.
|
||||
|
||||
The table appears in the **Library** with a small grid icon, like a symbol or a sound. The
|
||||
Library shows its first rows; **View Table** (or a double-click) opens every row and column.
|
||||
|
||||

|
||||
|
||||
### A row per frame, or a row per time
|
||||
|
||||
How rows are looked up is the table's **Key**:
|
||||
|
||||
* **Row number** (the default): rows are counted from the top. Bind a column over as many
|
||||
frames as the table has rows and each frame shows one row.
|
||||
* **A column**, such as an age, a depth or a time in seconds: rows are looked up by that
|
||||
column's value, and the table sorts itself by it. Choose this when your rows aren't evenly
|
||||
spaced.
|
||||
|
||||
Set it in the Library, under the table's preview, or in the viewer.
|
||||
|
||||
### When the data changes
|
||||
|
||||
Select the table and choose **Import Again…**, then pick the file (the same one, revised, or
|
||||
another). The table's values are replaced and everything bound to it follows at once. Bindings
|
||||
find their columns by name, so the columns may come in another order. If a column a binding
|
||||
reads is gone, that binding rests (its instance stays as you placed it) and the status bar names
|
||||
the column.
|
||||
|
||||
## Binding a column to an instance
|
||||
|
||||
Data drives **symbol instances**. To bind one:
|
||||
|
||||
1. Select the instance on the stage (convert artwork with **Modify › Convert to Symbol** first).
|
||||
2. Choose **Modify › Data › Bind to Data…**, or **Bind to Data** in the **Data** section of
|
||||
Properties, and pick the property there.
|
||||
3. In Properties, under **Data**, choose the **Table** and the **Column**.
|
||||
|
||||
The stage shows the result as you change it. You can bind each of these once per instance:
|
||||
|
||||
| Property | The column's number is |
|
||||
|---|---|
|
||||
| **X**, **Y** | the position in pixels |
|
||||
| **Scale X**, **Scale Y** | the size in percent (100 is the size you drew) |
|
||||
| **Rotation** | degrees, clockwise |
|
||||
| **Alpha** | opacity in percent |
|
||||
| **Frame shown** | which frame of a graphic symbol shows, counted from 0 |
|
||||
|
||||
Under each binding:
|
||||
|
||||
* **Frames**: the first frame of the span the table plays over, and how many frames it lasts.
|
||||
Before the span the instance shows the first frame's value and after it the last's, so a
|
||||
chart holds its last value when the data ends.
|
||||
* **Rows** (or **Keys**, for a table with a key column): what the first and the last frame of
|
||||
the span show. They start as the whole table; **All** goes back to that. Set the second
|
||||
before the first to play the table backwards, for ages that run from old to young.
|
||||
* **Value**: the column's number **×** a scale **+** an offset. Use them to turn your units into
|
||||
pixels or percent: a rainfall of 0 to 300 mm with × 0.5 is a bar 0 to 150 % tall.
|
||||
* **Between**: **Linear** moves straight from one row's value to the next; **Step** holds each
|
||||
row's value until the next row.
|
||||
|
||||
The number beside the binding's name is what it gives at the playhead. A binding replaces the
|
||||
property; the rest still animates as usual, so an instance whose X is tweened and whose Y is
|
||||
bound moves along both.
|
||||
|
||||
> **A bar that grows from its foot.** Scale and rotation turn about the instance's
|
||||
> transformation point. With the Free Transform tool, drag the small circle to the bar's foot
|
||||
> (or set **Pivot** in Properties), and a bound **Scale Y** grows the bar upwards.
|
||||
|
||||
### A shape that changes with the data
|
||||
|
||||
Draw the states in a **graphic** symbol, one per frame, or a shape tween from one outline to
|
||||
another. Bind the instance's **Frame shown** to a column: the data picks which frame of the
|
||||
symbol shows. 0 is the symbol's first frame; use **Value** to turn your numbers into frames. With
|
||||
**Step** the outline holds through each regime; with **Linear** it changes smoothly.
|
||||
|
||||
## Baking to keyframes
|
||||
|
||||
**Bake to Keyframes** (in the Data section, or **Modify › Data › Bake Data to Keyframes**)
|
||||
writes what the bindings show as ordinary keyframes and removes the bindings. Every frame looks
|
||||
as it did. Bake when you want to adjust keys by hand, or before **Lottie** export, which writes
|
||||
keys rather than pictures. The other exports (PNG, GIF, video, HTML canvas, sprite sheets) show
|
||||
bindings as they are.
|
||||
|
||||
Baking can't cut a motion tween (remove the tween first) or work on an armature layer or a
|
||||
locked layer; it tells you, and changes nothing.
|
||||
|
||||
**Modify › Data › Remove Data Bindings** takes the bindings off the selected instances without
|
||||
writing keys: each property is the instance's own again.
|
||||
|
||||
## Managing tables
|
||||
|
||||
A table is a Library item: rename it, put it in a folder, or delete it there. Deleting a table
|
||||
also removes the bindings that read it; **Edit › Undo** brings both back. The **Uses** column
|
||||
counts the bindings that read each table, and **Select Unused Items** finds tables nothing
|
||||
reads.
|
||||
|
||||
The numbers are saved inside your `.anicraft` file, so the document carries its data with it.
|
||||
The table remembers the name of the file it came from, never its folder.
|
||||
|
||||
## From scripts and AI assistants
|
||||
|
||||
Every step is a command, so a pipeline can build a chart without the window (see
|
||||
[Working headless](working-headless.md)): `data.import_table` or `data.set_table` for the
|
||||
numbers, `data.bind` for each instance, `data.bake` for plain keys, and `data.list`, `data.get`
|
||||
and `data.bindings` to read them back. The [command reference](reference/commands.md) lists
|
||||
their parameters. Plug-ins can use all of them except reading a file.
|
||||
|
||||
## Not yet
|
||||
|
||||
* Copying, pasting or duplicating a bound instance doesn't copy its bindings.
|
||||
* Cells can't be edited in the viewer yet (`data.set_cell` changes one from a script).
|
||||
* Only symbol instances are bound, and only the properties above; captions driven by text
|
||||
columns are planned.
|
||||
* Baking inside a motion tween.
|
||||
|
||||
## Next steps
|
||||
|
||||
* [Tweens](tweens.md): animate the properties data doesn't drive.
|
||||
* [Symbols and the Library](symbols-and-library.md): graphic symbols and the transformation point.
|
||||
* [Exporting and Publish](exporting-and-publish.md): share the result.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 82 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 108 KiB |
+10
-9
@@ -24,24 +24,25 @@ the panels, tools and shortcuts you know to AniCraft's, and lists what works dif
|
||||
8. [Text](text.md): static, dynamic and input text.
|
||||
9. [Images and sound](images-and-sound.md): bitmaps, SVG files and sound on the timeline.
|
||||
10. [Interactivity](interactivity.md): actions, buttons, frame scripts and Test Movie.
|
||||
11. [Data-driven animation](data-driven-animation.md): tables of numbers that drive charts, markers and shapes.
|
||||
|
||||
## Sharing your work
|
||||
|
||||
11. [Exporting and Publish](exporting-and-publish.md): pictures, GIFs, animated PNG and WebP, video, HTML and Publish Settings.
|
||||
12. [Opening Animate files](opening-animate-files.md): what comes across from `.fla` and XFL, and what AniCraft tells you about the rest.
|
||||
12. [Exporting and Publish](exporting-and-publish.md): pictures, GIFs, animated PNG and WebP, video, HTML and Publish Settings.
|
||||
13. [Opening Animate files](opening-animate-files.md): what comes across from `.fla` and XFL, and what AniCraft tells you about the rest.
|
||||
|
||||
## Making AniCraft yours
|
||||
|
||||
13. [Preferences, shortcuts, accessibility and languages](preferences-shortcuts-accessibility.md).
|
||||
14. [Plug-ins](plugins.md): add commands safely.
|
||||
15. [Saved commands](saved-commands.md): keep steps from the History panel and run them again on any selection.
|
||||
16. [Working headless](working-headless.md): the command line and AI assistants, for pipelines.
|
||||
14. [Preferences, shortcuts, accessibility and languages](preferences-shortcuts-accessibility.md).
|
||||
15. [Plug-ins](plugins.md): add commands safely.
|
||||
16. [Saved commands](saved-commands.md): keep steps from the History panel and run them again on any selection.
|
||||
17. [Working headless](working-headless.md): the command line and AI assistants, for pipelines.
|
||||
|
||||
## Help
|
||||
|
||||
17. [Using this guide](using-this-guide.md): searching it, and help for whatever you are working on (**F1**).
|
||||
18. [Troubleshooting and FAQ](troubleshooting-and-faq.md).
|
||||
19. [Coming from Animate](coming-from-animate.md).
|
||||
18. [Using this guide](using-this-guide.md): searching it, and help for whatever you are working on (**F1**).
|
||||
19. [Troubleshooting and FAQ](troubleshooting-and-faq.md).
|
||||
20. [Coming from Animate](coming-from-animate.md).
|
||||
|
||||
## Reference
|
||||
|
||||
|
||||
@@ -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 384 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 (**Help › Keyboard Shortcuts**) 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 395 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 (**Help › Keyboard Shortcuts**) 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.
|
||||
|
||||
@@ -48,6 +48,8 @@ This page is generated from the command registry, so it always matches the versi
|
||||
Parameters: `{formats? ([format, …]: only these; default: the ones Publish Settings has on), confirm? (to replace files already there)}`
|
||||
- **Recover Autosaved Documents…** `file.recovery_list`
|
||||
Parameters: `{dir (the recovery folder)}`
|
||||
- **Import Data Table…** `data.import_table` · File › Import · changes the document
|
||||
Parameters: `{path (.csv, .tsv or .json, up to 32 MB: the first record names the columns; cells that aren't numbers become gaps, and a column with no number is left out), name? (default the file's name), table? (id or name of a table to replace: its bindings stay), key? (the column rows are looked up by, e.g. an age or a time; default by row number, or the replaced table's key), format?: auto|csv|tsv|json} → {table, name, rows, columns, key, skipped, gaps, truncated, replaced, bindings, missing (columns bindings read that are gone)}`
|
||||
- **Import to Library…** `file.import_to_library` · File › Import · changes the document
|
||||
Parameters: `{path (.wav, .ogg or .mp3 sound; .png or .jpg image; .svg drawing: a graphic symbol named after the file holding its shapes), name?}`
|
||||
- **Export Audio…** `file.export_audio` · File › Export
|
||||
@@ -244,6 +246,12 @@ This page is generated from the command registry, so it always matches the versi
|
||||
Parameters: `{}`
|
||||
- **Distribute Vertical Centers** `align.distribute_v` · Modify › Align · changes the document
|
||||
Parameters: `{}`
|
||||
- **Bind to Data…** `data.bind` · Modify › Data · changes the document
|
||||
Parameters: `{property: x|y|scale_x|scale_y|rotation|alpha|frame (x, y pixels; scales and alpha percent; rotation degrees; frame: the 0-based frame of its symbol a graphic instance shows), table (id or name), column, element? (a symbol instance's id; default the selected one), start? (the span's first frame, 0-based; default the first frame the instance is on), frames? (the span's length; default one frame per row, or with a key column the frames the instance is on), from?, to? (the keys the first and last frame show; default the table's first and last; to before from plays it backwards), interpolation?: linear|step, scale?, offset? (value = column × scale + offset)} one binding per property of an instance; before the span it shows the first frame's value, after it the last's → {element, property, table, column, start, frames, value}`
|
||||
- **Remove Data Bindings** `data.unbind` · Modify › Data · changes the document
|
||||
Parameters: `{element? (default every selected instance), property? (default all of them)} → {removed}`
|
||||
- **Bake Data to Keyframes** `data.bake` · Modify › Data · changes the document
|
||||
Parameters: `{element? (default every selected instance with bindings), property? (default all of them)} writes what the bindings show as keyframes on the instance's layer (one where the value changes; one per frame inside a classic tween) and removes the bindings: every frame looks as it did → {keys, elements, removed}`
|
||||
- **Attach Text to Path** `text.attach_path` · Modify › Text · changes the document
|
||||
Parameters: `{path?: element id of a shape (default: the other selected element, a shape), x?, y? (pick the shape at this stage point instead), offset? (px along the path; default by the text's alignment: its start, middle or end), flip?: bool} sets the selected static text along a copy of the shape's outline (its first contour); the shape stays as it is (ADR 0070)`
|
||||
- **Release Text from Path** `text.release_path` · Modify › Text · changes the document
|
||||
@@ -715,6 +723,20 @@ These commands have no menu item: the panels, the stage and the timeline use the
|
||||
Parameters: `{path: a swatch file (.json, from swatch.export) or a GIMP palette (.gpl), replace?: bool (default false: added at the end)} → {imported, count}`
|
||||
- **Export Swatches** `swatch.export`
|
||||
Parameters: `{path} writes the document's swatches to a swatch file (JSON) → {written, swatches}`
|
||||
- **Set Data Table** `data.set_table` · changes the document
|
||||
Parameters: ``{name, columns: [{name, values: [number | null, ..]}, ..] (in this order) | {name: [..], ..} (sorted by name) | [names] with rows: [[..], ..], key?, table? (id or name of the table to replace; default the table called `name`)} the table's values inline (null is a gap); replacing a table keeps its bindings → as data.import_table``
|
||||
- **Data Tables** `data.list`
|
||||
Parameters: `{} → {tables: [{table, name, rows, columns: [names], key, source, folder, bindings}], bindings (how many in the document)}`
|
||||
- **Data Table Values** `data.get`
|
||||
Parameters: `{table (id or name), from? (first row, 0-based), count? (rows, at most 10,000)} → {table, name, key, rows, from, columns: [{name, values: [number | null, ..]}]}`
|
||||
- **Set Data Cell** `data.set_cell` · changes the document
|
||||
Parameters: `{table (id or name), column, row (0-based), value (number, or null for a gap)}: every binding that reads the cell shows the new value`
|
||||
- **Set Key Column** `data.set_key` · changes the document
|
||||
Parameters: `{table (id or name), key (a column's name, or null: rows are looked up by row number)}: a table with a key keeps its rows in the key's ascending order`
|
||||
- **Delete Data Table** `data.remove` · changes the document
|
||||
Parameters: `{table (id or name)} deletes the table and the bindings that read it (undoable) → {deleted, uses}`
|
||||
- **Data Bindings** `data.bindings`
|
||||
Parameters: `{element? (default every binding in the document)} → {bindings: [{element, property, table, table_name, column, start, frames, from, to, interpolation, scale, offset, live (the table and column exist), value (at the playhead, or null)}]}`
|
||||
- **New Text** `text.create` · changes the document
|
||||
Parameters: `{text (may be empty for an input field), type?: static|dynamic|input, x?, y? (top-left; default: centred), width?, font?, size? (px), bold?, italic?, color?, letter_spacing?, shift?: normal|superscript|subscript, underline?, url? ("": none), align?: left|center|right, indent? (px, first line), left_margin?, right_margin? (px), line_spacing? (px), runs?: [{chars, …character keys}] (styles of the text's characters in order; unset keys take the style above), paragraphs?: [{…paragraph keys}] (one per line of the text)} (ADR 0085)`
|
||||
- **Edit Text** `text.edit` · changes the document
|
||||
|
||||
@@ -260,6 +260,12 @@ shrink together in proportion. If you turn the guides off, AniCraft remembers wh
|
||||
The HTML canvas export doesn't do 9-slice scaling yet. It scales such instances as a whole,
|
||||
and its report says so.
|
||||
|
||||
## Data tables
|
||||
|
||||
The Library also keeps **data tables**: numbers imported from a CSV, TSV or JSON file that can
|
||||
drive an instance's position, size, rotation, opacity or the frame it shows. See
|
||||
[Data-driven animation](data-driven-animation.md).
|
||||
|
||||
## Not there yet
|
||||
|
||||
* Shared libraries, and dragging items out of another open document's Library (copy and paste
|
||||
|
||||
@@ -121,6 +121,22 @@ anicraft-cli run shot010.anicraft title.json --save shot010_titled.anicraft
|
||||
Steps run in order. The first one that fails stops the run, and the error names the step. The
|
||||
results of all the steps print as a JSON array.
|
||||
|
||||
### A chart from numbers
|
||||
|
||||
Tables of numbers can drive instances (see [Data-driven animation](data-driven-animation.md)).
|
||||
This script gives a document a table and lets one of its columns set the height of the selected
|
||||
bar, frame by frame:
|
||||
|
||||
```json
|
||||
[
|
||||
{"cmd": "data.set_table", "params": {"name": "Rainfall", "columns": [{"name": "Jan", "values": [40, 85, 120, 96]}]}},
|
||||
{"cmd": "data.bind", "params": {"property": "scale_y", "table": "Rainfall", "column": "Jan", "frames": 24}}
|
||||
]
|
||||
```
|
||||
|
||||
`data.import_table` reads the numbers from a CSV, TSV or JSON file instead, and importing a
|
||||
table that is already there replaces its values and keeps what is bound to it.
|
||||
|
||||
### Publishing a document
|
||||
|
||||
If a document has **File › Publish Settings** set up, one command writes every format it has
|
||||
|
||||
@@ -29,6 +29,10 @@ accepts `webpki-root-certs` 1.0.12 under CDLA-Permissive-2.0 for Mozilla certifi
|
||||
in by the HTTPS verifier. It applies only to that data crate and version; the code licence
|
||||
allowlist is unchanged.
|
||||
|
||||
Data tables (ADR 0118) read CSV and TSV through `craft-csv` (MIT OR Apache-2.0; its only
|
||||
dependency is `thiserror`), pinned to the same reviewed commit of `storytold/craft-libs` as
|
||||
`craft-mime` and `craft-gif`. No new licence.
|
||||
|
||||
**Shared-library exceptions (approved by the project lead, 2026-11-17).** The move to the shared
|
||||
Craft crates brought two licences the allowlist doesn't name. Both are accepted as crate-scoped
|
||||
exceptions in `deny.toml`, and the allowlist itself is unchanged:
|
||||
|
||||
+3
-2
@@ -23,6 +23,7 @@ This integration depends on craft-libs #1962 and still requires hosted parity va
|
||||
| Documents | **Several open at once** (ADR 0112): tabs above the edit bar, the shown document in `App`, the others parked whole (session, view, autosave) and exchanged in O(1) (0.2 µs median); the engine and the CLI/MCP stay one document per session. Cross-document paste remaps Library ids (`engine::transfer`). Not yet: a tab in its own window, another document's Library in the panel, session restore, a shared undo budget. |
|
||||
| Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **animated PNG and animated WebP export** (WebP container writing delegates to shared `craft-webp`; APNG framing remains app-local; ADR 0063: full colour and real alpha, transparent or on the stage colour; every frame exactly the renderer's; repeated frames merged into longer delays; later frames only the rectangle that changed (APNG blends opaque changes over, WebP replaces); APNG delays exact fractions of the frame rate, WebP milliseconds that never drift; loop forever, once or N times; File › Export, Publish Settings, the web build's downloads, `anicraft-cli apng`/`webp`; not yet: lossy WebP (no permissive pure-Rust VP8 encoder exists), dispose-to-background frames, palette or RGB APNG for smaller files), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. One damaged bitmap, sound or library symbol is left out and reported rather than refusing the whole file (#226), and a document without a stage colour gets Animate's default white (#163). Archives whose end record overstates the directory's size, as Flash CS5 to Animate write most `.fla` files, open (#356; until the shared reader does it, storytold/craft-libs#1986). Binary `.fla` (Flash CS4 and earlier) is not read and says so (#163, #289: a stretch goal in `requirements.md`, no clean-room reader yet). Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Colour effects in every style (Brightness, Tint, Advanced, Alpha; ADR 0056), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). Shared `craft-xfl` readers now parse filters, shape hints, tween easing, and frame-sound envelopes; AniCraft retains document-model mapping and validation. The XFL schema audit remains in progress, including per-character styles and motion-tween records; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, styleLine truncated
|
||||
| Library | **Library management, first slice** (ADR 0050): nested **folders** (New Folder, rename, drag items and folders in and out, Move to; deleting a folder that holds items asks), **inline rename** (F2 or double-click the name; names unique per folder, case aside), **Duplicate Symbol** (fresh ids, same folder, “Ball copy”), **Swap Symbol** in Properties (keeps transform, colour effect, filters, looping and name), a **use count** column, **Select Unused Items** and **Delete Unused Items** (unused = not reachable from any scene; linkage classes count as used; asks first), deleting used items asks and removes their instances, fills and keyframe sounds, **sort** by name, type, use count or date added, **search** (opens the folders that lead to a match), multiple selection, a **preview** (a symbol's first frame from the oracle, a bitmap as smoothed or not, a sound's waveform with play) and **item properties** (symbol type and linkage class, bitmap **Allow Smoothing**, which the oracle, the GPU stage, SVG and HTML honour). Folders are a side table in the document (older files open flat); XFL import keeps folders and Allow Smoothing. Headless: `library.items/new_folder/rename/move/duplicate/delete/unused/delete_unused/set_smoothing`, `element.swap_symbol`. **Second slice** (ADR 0053): **drag items onto the stage** (symbols and bitmaps land at the pointer on the active layer at the playhead, sounds go onto its keyframe; several at once; one undo step; inside a symbol open for editing too), **Place on Stage** (button, right-click, or Enter) at the centre of the view, **Swap Bitmap** in Properties (a placed bitmap keeps its corner and takes the new size; a bitmap fill keeps its shape), a **Convert to Symbol** dialog with name, type and **folder** that offers the last folder and type again, and **"mixed" on every Properties row** for several elements (Scale, Rotation, Alpha, Symbol, Type, Filters, Blending, Looping, First frame, Fill, Bitmap, Stroke, Width, Style; each row compares only the elements it edits; editing a mixed row sets all, and Type sets every selected instance's symbol). Headless: `library.place {items, x, y}` (and `sound`), `element.swap_bitmap`, `kind` and `folder` on `modify.convert_to_symbol`. **9-slice scaling** (ADR 0055): Enable guides for 9-slice scaling on a symbol (Library or Properties). Scaled instances keep their corners, stretch their edges one way and the centre both ways, and strokes keep their width. Rotation and skew apply after; nested symbols, text and bitmaps scale normally. Guides are dragged as dashed lines while editing the symbol in place, or typed in Properties. The CPU, GPU, SVG and Lottie output all show it, and XFL `scaleGrid*` attributes are imported; guides switched off are kept and come back when switched on (ADR 0057). Not yet: 9-slice in HTML canvas export (scaled as a whole and reported), guides in Library previews, snapping guides. Not yet: shared libraries and importing items from another document, linkage on bitmaps and sounds, bitmap compression, dropping files from the desktop, a picture of the item while dragging, Swap Bitmap on a Library item (every use), mixed text style rows, a Colour Effect row with tint. |
|
||||
| Data-driven animation | **Data tables that drive animation, first slice** (ADR 0118, #416, #417, #418): numeric **tables kept in the document** as Library items, imported from **CSV, TSV or JSON** (File › Import › Import Data Table; through craft-csv; named columns, gaps, text-only columns left out and reported, a row per frame or a **key column** for a row per keyed time; 256 tables, 100 000 rows, 1 000 000 cells, files up to 32 MB; hostile input refused or cut to the limits), a **table viewer**, **Import Again** that keeps every binding; **bindings** that let a column drive a symbol instance's **X, Y, Scale X, Scale Y, Rotation, Alpha** or **the frame a graphic shows** over a span of frames, with scale, offset, linear or step interpolation and reversed key ranges, edited live in Properties › Data and evaluated purely in `evaluate` (stage, oracle, GPU stage, Test Movie and every export that draws frames agree); **Bake to Keyframes** (every frame looks as it did); `data.*` commands headless, over the CLI and MCP, and for plug-ins (all but reading a file). Not yet: bindings that follow copy, paste and duplicate; baking inside a motion tween and a Lottie export warning for live bindings; editing cells in the viewer, adding and renaming columns; text columns for captions; binding skew, tint, filter values, shapes, text and group members; expressions; audio amplitude into a table. |
|
||||
| Find & navigation | **Find and Replace, and the Movie Explorer, first slice** (ADR 0058): Edit › Find and Replace (Ctrl+F) finds text (text fields, frame labels, layer and instance names, frame scripts; match case, whole word, regular expressions on a linear-time engine), fonts, colours, symbols, sounds and bitmaps, in this scene with its symbols or the whole document; results as you type; F3 / Shift+F3 go there, opening symbols in place; Replace, and Replace All as one undo step that asks above 100 places. Window › Movie Explorer (Alt+F3), beside the Library: scenes › layers › keyframes › instances (into their symbols), text, sounds, bitmaps and scripts, symbol definitions, Show filters and search, double-click to go there. Headless `find.search`, `find.replace`, `find.goto`, `explorer.tree`. Not yet: action parameters, ActionScript strings apart from code, font size and style, colour tolerance, renaming in the explorer. |
|
||||
| Tests | 133 tests (adds point editing, closed-path anchors, curve fitting, pen/pencil/subselection commands, the Pen's path data, frame ranges, keyframe moves, range confirmations, frame selection and the frame clipboard): unit, analytic render, band/determinism, robustness fuzz over all commands, round trip (v1 and v2 files), structural sharing and history budget, render-service equivalence, confirmations, clipboard, transforms and align, GIF decode and timing, free-transform maths, UI-guideline enforcement, CLI. |
|
||||
| Ease of use & safety | **Visual language** (ADR 0008, revised): graphite palette, corners by role (square structure, softened controls, rounder menus and dialogs with soft depth), borders only between layout regions, flat buttons with a visible focus ring, vibrant timeline blocks (mint artwork, violet tweens), sentence-case headings, **collapsible sections with rules** (Preferences, Properties, dock, shortcut sheet), **Lucide icons** stroked as vectors via a new full SVG path reader; click targets ≥ 28 px (tools 40, rows 28, toggles 24); palette contrast, target sizes and "no raw colours or radii" are enforced by tests. Product principles written (`docs/product-principles.md`). Tiered destructive-action confirmations, enforced in the engine (ADR 0004). Unsaved-changes guard on close/new/open. **Crash-recovery autosave** (ADR 0015): unsaved work is copied in the background (every minute or 25 changes by default; Preferences › Files › Autosave, with an off switch) to `Recovery` in the settings folder, atomically and never over the user's file; an OS file lock per running window tells crashed sessions from open ones; the next start offers what was left behind in a non-blocking window (Restore as unsaved work with its original path, Discard with a second click, Later; File › Recover Autosaved Documents… brings it back); saves and clean exits remove the copy; headless `file.recovery_list/recover/discard_recovery/autosave`. Not yet: several open documents, older copies, the undo history. Overwrite checks for saves and exports. "Ctrl+Z to undo" hints. Command palette (Ctrl+K). Shortcut sheet (F1). Right-click menus on stage, frames and layers. Save As (Ctrl+Shift+S). **Shortcut editor** (F1): every menu command, tool and view key can be rebound, given extra keys or unbound; recording asks before taking a key from another action, reserved keys (palette, editor, Preferences, quit, play, Esc, Space, Tab) stay fixed, per-action and global reset; only the changes are saved in preferences, so untouched actions follow new defaults; menus, tooltips and the palette show the keys in effect. |
|
||||
@@ -44,7 +45,7 @@ This integration depends on craft-libs #1962 and still requires hosted parity va
|
||||
| **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); ~~stroke coverage as one union, no double-darkening~~ ✅ (ADR 0110: one outline per stroke from the oracle, so both renderers follow; 2,000 outlined shapes at 1080p 9.3 → 9.0 ms, self-crossing scribbles +4 to 8 %; not yet: stroke and converted fill from the same curves, an outline cache); ~~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); ~~surviving GPU failures mid-session~~ ✅ (ADR 0092: the stage drops to the CPU at once and retries the GPU after 3, 15, 60 and 300 s or on a resize; the window's device gets an error handler and a loss callback instead of wgpu's panic, a failing surface is reconfigured then recreated, and a lost window device autosaves, reopens the window a safer way and makes the next 3 starts try it late; not yet: recreating the window's device in place, which eframe doesn't offer); 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); ~~sound and video items, self-extracting and top-folder `.fla` archives~~ ✅ (ADR 0086: sound effects and custom envelopes, every sound and video that doesn't come across named with its format, Screen Video stills, zipped XFL folders and self-extracting stubs; not yet: sound in/out points, AIFF and compressed WAV, video playback); ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (~~easing curves instead of per-frame keys~~ ✅, ADR 0089: keyframes with Bézier eases, moving artwork under group transforms, playback parity at every frame; not yet: motion along curved guides as spatial tangents, orient to path, nested tweens as nested transforms); ~~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 and paragraph styles~~ ✅ first slice (ADR 0085: styled runs (font, size, bold, italic, colour, letter spacing, superscript/subscript by the font's OS/2 metrics, underline, link) set on the selected characters while typing, mixed values in Properties, paragraph alignment, indent, margins and line spacing, runs shaped one by one and wrapped across, one fill per colour in every export, SVG links, XFL `DOMTextRun`s kept in one block, `text.style`/`text.paragraph`/`text.styles`; not yet: justified text, runs on a path's underlines, `htmlText` in fields, links that click in Test Movie and the HTML page, SVG `<text>`/`<tspan>` output, the editor showing the real faces and alignment); ~~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); ~~audio output polish (latency-aware clock, event tails, monitor volume and mute, scrubbing preference, device recovery, Web Audio)~~ ✅ (ADR 0095); ~~Convert Audio to Keyframes and auto lip-sync~~ ✅ first slice (ADR 0114, #332: loudness per frame onto scale, alpha, position, rotation or a graphic's first frame, as keyframes or a motion tween curve, with threshold, smoothing and a live preview; five mouth shapes from band energies keyed onto a mouth symbol's frames; not yet: more mouth shapes, the camera, armatures and filters as targets, classic tweens between keys); ~~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~~ ✅ (ADR 0091: drag or Alt+arrows to reorder, an eye per filter that keeps its settings, Copy/Paste Filters, presets in your preferences with a JSON file to move them; classic tweens pair lists with switched-off filters), ~~motion-tween tracks per filter property in the Motion Editor~~ ✅ (ADR 0092: blur, strength, angle, distance and Adjust Color's four, by filter slot, with curves, eases and retiming, auto-keyed from Properties › Filters, following reorders and removals), ~~filter colours, quality and switches as tracks, built-in presets and filters on text~~ ✅ (ADR 0099: a filter's colours and ramp stops channel by channel in the tint's units, with a swatch row in the Motion Editor; quality, Inner, Knockout and Hide Object as stepped tracks; classic tweens of lists that differ pair what matches and fade the rest; eight built-in presets that can be hidden, not deleted; filters on static, dynamic and input text, in every export and from XFL; not yet: the Type and on/off as tracks, ramp stop positions as tracks, Animate's filter tracks from XFL motion tweens, typed text of an input field filtered in the HTML page) and ~~blend modes~~ ✅ on Movie Clips; ~~importing video for reference and rotoscoping~~ ✅ first slice (#369, ADR 0116: frames in the document or a reference layer, through the user's ffmpeg; not yet: sound with a reference layer, transforming the reference on the stage, alpha). |
|
||||
| **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 plug-ins~~ ✅ (ADR 0088); ~~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~~ ✅ first slice (ADR 0097: every undo step records its commands; History › Save As Command with steps rewritten to act on the selection or refused with the step named; saved commands at the end of the Commands menu with shortcuts; Manage Saved Commands; Run Command…; one transactional undo step; small JSON files in the settings folder; `macro.*` headless, CLI and MCP; macros call only what plug-ins may. Not yet: Replay Steps without saving, editing a macro's steps, macros that ask for values, the browser build and the command palette). **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. |
|
||||
| **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 plug-ins~~ ✅ (ADR 0088); ~~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~~ ✅ first slice (ADR 0097: every undo step records its commands; History › Save As Command with steps rewritten to act on the selection or refused with the step named; saved commands at the end of the Commands menu with shortcuts; Manage Saved Commands; Run Command…; one transactional undo step; small JSON files in the settings folder; `macro.*` headless, CLI and MCP; macros call only what plug-ins may. Not yet: Replay Steps without saving, editing a macro's steps, macros that ask for values, the browser build and the command palette); ~~data tables that drive animation~~ ✅ first slice (ADR 0118: tables in the Library from CSV, TSV or JSON, bindings of a column to an instance's position, scale, rotation, alpha or the frame a graphic shows, evaluated in `evaluate`, Bake to Keyframes, `data.*` headless. Not yet: bindings through copy and paste, baking in motion tweens, cell editing, text columns). **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: outline-following ARAP meshes, symbols, pins bound to bones, a GPU textured path, bent bitmaps in HTML/Lottie); ~~springs, joint translation, editing members in place~~ ✅ second slice (ADR 0084); not yet: runtime armatures, XFL armature import); ~~shape armatures~~ ✅ first slice (ADR 0071: bones inside one shape, automatic binding, linear blend skinning, Bind tool); ~~painted weights and reshaping a bound shape~~ ✅ second slice (ADR 0090; not yet: reshaping at a posed frame); ~~mixed armatures: symbol instances and shapes in one armature~~ ✅ (ADR 0098: bones inside a shape and bones that move instances or whole shapes in one armature, several skinned shapes, chains across the kinds with the Bone tool, one pose for IK, tweens, springs and translation, file format version 4 only for documents that use it; not yet: joining two armatures, joining a whole shape from a shape's bone by dragging, XFL import of armatures); ~~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); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles) and brush library; ~~tilt, textured brushes, erasing inside symbols, gradients and width profiles in the merge~~ ✅ second slice (ADR 0093: tilt turns and widens the tip per sample, paper-grain texture and scatter as vector paint, Charcoal and Spatter, the Eraser's hint for symbols and objects, width profiles carried into each merged piece; not yet: reading tilt on desktop systems (winit 0.30 reports it only on iOS), bitmap, art and pattern brushes, eraser pressure and presets, the live preview through texture and tilt); ~~graph-based easing presets library~~ ✅ first slice (ADR 0081: presets, custom multi-segment eases, saved eases, per-group classic eases, Motion Editor properties, XFL import; not yet: updating every tween that uses a saved ease, a user ease library shared between documents, Lottie-native eases instead of baked frames, motion-tween eases from XFL); ~~layer parenting~~ ✅ first slice (ADR 0113, #388: a layer follows the first object on its parent layer through position, rotation, scale and skew, chains, the timeline's parenting view with draggable dots and a parent menu, parenting keeps the stage position in one undo step, followers edited in stage space, every export; not yet: a parent that changes over time, Edit Multiple Frames and motion path editing in stage space on a follower, armature layers as followers, XFL import (no public format description)). |
|
||||
| **M8** | Release quality | ~~**Several documents open at once**~~ ✅ first slice (ADR 0112, #420: a tab per open document above the edit bar, with a dot for unsaved changes and a close button; click, middle-click, drag to reorder, right-click Close / Close Others / Close All / show the file; Ctrl+Tab, Ctrl+PageDown, Ctrl+W, Ctrl+Alt+W; each tab its own session, undo history, selection, playhead, view and Motion Editor state; New, Open, recent files, drops and restored copies open a tab, a file already open is shown; closing a tab with unsaved changes asks, quitting asks once for all; one recovery copy per open document; paste across documents brings symbols, bitmaps and sounds, renamed on a clash; a document not shown keeps no render caches; next: tearing a tab off into its own window, another document's Library in the Library panel, reopening last session's documents, a shared undo budget); ~~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); ~~AppImage desktop integration, portable mode, store readiness checks~~ ✅ (ADR 0094); next: 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), ~~user themes from a folder~~ ✅ first slice (ADR 0117, #340: a theme is a small JSON file of colours for the palette's roles in the settings folder's `themes`; Preferences › Theme lists them with Open Themes Folder, Reload and Export Current Theme; a theme whose text, icons or focus ring fall below WCAG AA, or that names an unknown role, is refused whole with the pair and the numbers; `icon_accent` gives two-tone icons and `accent_end` a gradient on the accent bars; `--check-theme`, `--theme <file>`; not yet: icon packs and multi-colour icon artwork, separate pressed and focus looks, bevel or gradient surfaces, metrics, drop to install, a file watcher, themes in the browser), 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), ~~search and context help~~ Line truncated
|
||||
|
||||
@@ -65,7 +66,7 @@ titled with its milestone.
|
||||
| M3 | GPU stage: GPU binning inside masks and groups, filtered layers shared across a frame's tiles, more than 16 images per tile (first slice ✅ ADR 0019, no readback and masks/groups ✅ ADR 0029, bitmaps, filters and the default ✅ ADR 0032, GPU binning and hairlines ✅ ADR 0048) | CPU oracle, tiled stage, GPU stage slices 1–4 |
|
||||
| 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); ~~exporter and easing plug-ins~~ ✅ (ADR 0088); ~~command macros~~ ✅ first slice (ADR 0097); next: growing the ActionScript subset (`switch`, arrays, event bubbling) | command registry, plug-in host, action IR and player |
|
||||
| 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); ~~exporter and easing plug-ins~~ ✅ (ADR 0088); ~~command macros~~ ✅ first slice (ADR 0097); ~~data tables that drive animation~~ ✅ first slice (ADR 0118); next: 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), ~~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), ~~painted weights and reshaping~~ ✅ (ADR 0090), ~~mixed armatures (instances and shapes together)~~ ✅ (ADR 0098), ~~bone springs and joint translation~~ ✅ (ADR 0084), ~~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), ~~tilt, texture, profiles in the merge~~ ✅ (ADR 0093), ~~layer parenting~~ ✅ first slice (ADR 0113); next: reading pen tilt from the toolkit, art brushes | strokes, Pen and Pencil, width profiles, timeline evaluation |
|
||||
| M8 | ~~Several documents open at once~~ ✅ first slice (ADR 0112, #420), ~~Crash-recovery autosave~~ ✅, ~~accessibility first pass~~ ✅ (ADR 0022), ~~installers and signing~~ ✅ first slice (ADR 0026), ~~portable mode and AppImage desktop integration~~ ✅ (ADR 0094), ~~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); ~~user themes from a folder~~ ✅ first slice (ADR 0117, #340); ~~CI on macOS and Windows~~ ✅ (ADR 0067); ~~guide search and context help~~ ✅ (ADR 0096); ~~dockable panels and workspaces~~ ✅ first and second slices (ADR 0075, ADR 0087); next: live screen-reader passes | `.anicraft` format, session, AccessKit in eframe |
|
||||
|
||||
|
||||
@@ -30,7 +30,9 @@ $Shots = @(
|
||||
@("publish-settings", "publish"),
|
||||
@("preferences", "prefs"),
|
||||
@("audio-to-keyframes", "audiokeys"),
|
||||
@("lip-sync", "lipsynced")
|
||||
@("lip-sync", "lipsynced"),
|
||||
@("data-chart", "datachart"),
|
||||
@("data-table", "datatable")
|
||||
)
|
||||
New-Item -ItemType Directory -Force $Out | Out-Null
|
||||
foreach ($s in $Shots) {
|
||||
|
||||
@@ -31,6 +31,8 @@ SHOTS=(
|
||||
"preferences prefs"
|
||||
"audio-to-keyframes audiokeys"
|
||||
"lip-sync lipsynced"
|
||||
"data-chart datachart"
|
||||
"data-table datatable"
|
||||
)
|
||||
mkdir -p "$OUT"
|
||||
for row in "${SHOTS[@]}"; do
|
||||
|
||||
+1
-1
@@ -443,7 +443,7 @@ mod tests {
|
||||
for tool in [Tool::Bone, Tool::Bind, Tool::Warp, Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::PaintBrush, Tool::Eraser, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Pen] {
|
||||
found.extend(check(&format!("{tool:?} tool"), |a, _| a.tool = tool));
|
||||
}
|
||||
for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "springbones", "shapebones", "shapeweights", "mixedbones", "warp", "sound", "envelope", "audiokeys", "audiokeysevent", "lipsync", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "layerprops", "layeropacity", "pivot", "frameview", "layercolour", "timelinepolish", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer", "publish", "publishreport", "publishanim", "start", "drop", "droplibrary", "testmovie", "testmovieinside", "templates", "savetemplate", "droptimeline", "textfields", "testtext", "richtext", "softmask", "pathtext", "gradient", "gradientbucket", "swatches", "swatchpanel", "brushlibrary", "brushcurve", "paintbrush", "videoimport"] {
|
||||
for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "springbones", "shapebones", "shapeweights", "mixedbones", "warp", "sound", "envelope", "audiokeys", "audiokeysevent", "lipsync", "datachart", "datatable", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "layerprops", "layeropacity", "pivot", "frameview", "layercolour", "timelinepolish", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer", "publish", "publishreport", "publishanim", "start", "drop", "droplibrary", "testmovie", "testmovieinside", "templates", "savetemplate", "droptimeline", "textfields", "testtext", "richtext", "softmask", "pathtext", "gradient", "gradientbucket", "swatches", "swatchpanel", "brushlibrary", "brushcurve", "paintbrush", "videoimport"] {
|
||||
found.extend(check(panel, |a, _| a.open_panel(Some(panel))));
|
||||
}
|
||||
// Every panel in front where it docks, and floating (ADR 0075); the other workspaces.
|
||||
|
||||
+44
-1
@@ -397,6 +397,10 @@ pub struct App {
|
||||
/// (its preview is a gesture it keeps open until OK or Cancel), and what it was last given.
|
||||
pub audio_keys: Option<crate::audio_keys::Dialog>,
|
||||
pub audio_keys_last: crate::audio_keys::Settings,
|
||||
/// The data table the table viewer shows, while it is open (ADR 0118).
|
||||
pub data_view: Option<anicraft_engine::doc::DataId>,
|
||||
/// Import Again: the table the next Import Data Table replaces.
|
||||
pub data_reimport: Option<anicraft_engine::doc::DataId>,
|
||||
pub show_about: bool,
|
||||
pub show_files: bool,
|
||||
pub show_licenses: bool,
|
||||
@@ -782,6 +786,8 @@ impl App {
|
||||
convert_last: Default::default(),
|
||||
shape_dialog: None,
|
||||
audio_keys: None,
|
||||
data_view: None,
|
||||
data_reimport: None,
|
||||
audio_keys_last: crate::audio_keys::Settings::default(),
|
||||
shape_last: Default::default(),
|
||||
show_about: false,
|
||||
@@ -2651,6 +2657,12 @@ impl App {
|
||||
self.brush_samples = (0..=30).map(|i| (anicraft_engine::geom::Vec2::new(720.0 + i as f32 * 12.0, 310.0), None)).collect();
|
||||
crate::erasertool::commit(self, crate::pathtools::Xf { origin: egui::Pos2::ZERO, zoom: 1.0 });
|
||||
}
|
||||
Some(which @ ("datachart" | "datatable")) => {
|
||||
// Data tables that drive animation (ADR 0118): a bar chart whose bars follow a
|
||||
// table's columns, one selected with its bindings in Properties; `datatable`
|
||||
// also has the table viewer open.
|
||||
crate::data_ui::sample_chart(self, which == "datatable");
|
||||
}
|
||||
Some("eyedropper") => {
|
||||
// The sample's sky gradient picked with the Eyedropper: the fill swatch holds it.
|
||||
self.run("paint.pick", json!({"x": 640, "y": 40}));
|
||||
@@ -3328,6 +3340,14 @@ impl App {
|
||||
{
|
||||
o.insert("folder".into(), json!(f.display().to_string()));
|
||||
}
|
||||
// Import Again (ADR 0118): the file picked replaces the table it was asked for.
|
||||
if id == "data.import_table"
|
||||
&& let Some(t) = self.data_reimport.take()
|
||||
&& params.get("table").is_none()
|
||||
&& let Some(o) = params.as_object_mut()
|
||||
{
|
||||
o.insert("table".into(), json!(t.0));
|
||||
}
|
||||
// New and Open bring their document in a tab of its own (ADR 0112): the one being
|
||||
// edited stays open, so there is nothing to ask about.
|
||||
if crate::tabs::opens_document(id) {
|
||||
@@ -3436,6 +3456,15 @@ impl App {
|
||||
let path = v["saved"].as_str().unwrap_or("");
|
||||
self.status_ok(if platform::WEB { tr!("Saved {path} to your downloads", path = path) } else { tr!("Saved {path}", path = path) });
|
||||
}
|
||||
"data.import_table" => crate::data_ui::imported(self, v),
|
||||
"data.unbind" => {
|
||||
let n = v["removed"].as_u64().unwrap_or(0);
|
||||
self.status_ok(trn!("Removed {n} data binding. {undo} to undo.", "Removed {n} data bindings. {undo} to undo.", n, undo = self.undo_key()));
|
||||
}
|
||||
"data.bake" => {
|
||||
let n = v["keys"].as_u64().unwrap_or(0);
|
||||
self.status_ok(trn!("Baked the data into {n} new keyframe. {undo} to undo.", "Baked the data into {n} new keyframes. {undo} to undo.", n, undo = self.undo_key()));
|
||||
}
|
||||
"file.import" | "file.import_to_library" if v.get("sound").is_some() => {
|
||||
let id = anicraft_engine::doc::SoundId(v["sound"].as_u64().unwrap_or(0));
|
||||
self.library_sel = Some(LibraryItem::Sound(id));
|
||||
@@ -3738,6 +3767,17 @@ impl App {
|
||||
crate::audio_keys::open(self, crate::audio_keys::Kind::Lips);
|
||||
return;
|
||||
}
|
||||
// Modify › Data › Bind to Data binds the selected instance's next property to a table's
|
||||
// column, to be changed in Properties (ADR 0118; headless, the command takes them).
|
||||
if id == "data.bind" {
|
||||
crate::data_ui::bind_from_menu(self);
|
||||
return;
|
||||
}
|
||||
// A plain Import Data Table makes a new table (Import Again names the one to replace
|
||||
// after asking for the file).
|
||||
if id == "data.import_table" {
|
||||
self.data_reimport = None;
|
||||
}
|
||||
if id == "modify.transform_origin" {
|
||||
// The key or the menu moves to the next mode, and says which it is.
|
||||
if let Some(v) = self.run(id, json!({})) {
|
||||
@@ -3792,10 +3832,12 @@ impl App {
|
||||
// The document's swatches (ADR 0078): a swatch file, or a GIMP palette to import.
|
||||
"swatch.export" => Some((tr_noop!("Export swatches (a swatch file)"), "path", "swatches.json".to_string())),
|
||||
"swatch.import" => Some((tr_noop!("Import swatches (a swatch file or a GIMP palette)"), "path", "swatches.json".to_string())),
|
||||
// A table of numbers for the Library (ADR 0118).
|
||||
"data.import_table" => Some((tr_noop!("Import a data table (CSV, TSV or JSON)"), "path", "data.csv".to_string())),
|
||||
_ => None,
|
||||
};
|
||||
if let Some((title, key, text)) = prompt {
|
||||
let is_file = matches!(key, "path" | "dir") && (id.starts_with("file.") || matches!(id, "layer.set_video" | "plugin.install" | "macro.run" | "macro.import" | "brush.preset_export" | "brush.preset_import" | "filter.preset_export" | "filter.preset_import" | "swatch.export" | "swatch.import"));
|
||||
let is_file = matches!(key, "path" | "dir") && (id.starts_with("file.") || matches!(id, "layer.set_video" | "plugin.install" | "macro.run" | "macro.import" | "brush.preset_export" | "brush.preset_import" | "filter.preset_export" | "filter.preset_import" | "swatch.export" | "swatch.import" | "data.import_table"));
|
||||
if is_file && platform::WEB && platform::reads_file(id) {
|
||||
// The browser's file picker (ADR 0036). The file arrives on a later frame
|
||||
// (`open_picked`); a save or export asks for the download's name below.
|
||||
@@ -4698,6 +4740,7 @@ impl App {
|
||||
crate::desktop_ui::offer(self, &ctx);
|
||||
crate::plugins_ui::show(self, &ctx);
|
||||
crate::audio_keys::show(self, &ctx);
|
||||
crate::data_ui::show(self, &ctx);
|
||||
crate::plugin_export_ui::show(self, &ctx);
|
||||
crate::dock_float::floating(self, &ctx);
|
||||
crate::workspaces_window::show(self, &ctx);
|
||||
|
||||
@@ -201,6 +201,10 @@ pub const COMMAND_TOPICS: &[(&str, &str)] = &[
|
||||
("control.", "interactivity.md#test-movie"),
|
||||
("desktop.", "getting-started.md#running-the-appimage"),
|
||||
("doc.", "workspace.md#properties"),
|
||||
("data.", "data-driven-animation.md#binding-a-column-to-an-instance"),
|
||||
("data.bake", "data-driven-animation.md#baking-to-keyframes"),
|
||||
("data.import_table", "data-driven-animation.md#importing-a-table"),
|
||||
("data.set_key", "data-driven-animation.md#a-row-per-frame-or-a-row-per-time"),
|
||||
("draw.", "drawing.md#drawing-shapes-and-lines"),
|
||||
("ease.", "tweens.md#easing"),
|
||||
("edit.", "drawing.md#clipboard-and-duplicates"),
|
||||
|
||||
+553
@@ -0,0 +1,553 @@
|
||||
//! Data tables that drive animation (ADR 0118), in the shell.
|
||||
//!
|
||||
//! * In the Library a table is an item like the others: its row, a preview of its first rows,
|
||||
//! its key column and Import Again; a double-click opens the **table viewer**, a window with
|
||||
//! every row and column (only the cells in view are drawn).
|
||||
//! * A symbol instance's Properties get a **Data** section: Bind to Data adds a binding of a
|
||||
//! property to a column; its table, column, span of frames, keys, scale, offset and
|
||||
//! interpolation are edited in place, live on the stage; Bake to Keyframes writes what the
|
||||
//! bindings show as plain keyframes.
|
||||
//!
|
||||
//! Everything here runs `data.*` commands; the only state is which table the viewer shows.
|
||||
|
||||
use crate::a11y::{self, Named};
|
||||
use crate::app::App;
|
||||
use crate::theme::{self, FORM_LABEL_DOCK, Section, T, Type, color, font, form_row, text, with_type};
|
||||
use anicraft_engine::doc::data::{MAX_SPAN, MAX_VALUE};
|
||||
use anicraft_engine::doc::{Binding, BoundProperty, DataId, DataTable, ElementId, ElementKind, Interp, LibraryItem, SymbolKind};
|
||||
use egui::{Align2, Rect, Sense, Stroke, StrokeKind, WidgetType, pos2, vec2};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The engine's English for what the section lists, for the catalogs: translated where drawn.
|
||||
#[cfg_attr(not(test), allow(dead_code))]
|
||||
pub const TEXTS: [&str; 9] = [tr_noop!("X"), tr_noop!("Y"), tr_noop!("Scale X"), tr_noop!("Scale Y"), tr_noop!("Rotation"), tr_noop!("Alpha"), tr_noop!("Frame shown"), tr_noop!("Linear"), tr_noop!("Step")];
|
||||
|
||||
/// Width of a column of the grid, of its row numbers, and the height of a row.
|
||||
const CELL_W: f32 = 92.0;
|
||||
const NUMBER_W: f32 = 52.0;
|
||||
const ROW_H: f32 = 22.0;
|
||||
|
||||
/// What a table is, for its tooltip and screen readers (“Data table · 200 rows × 5 columns”).
|
||||
pub fn table_detail(t: &DataTable) -> String {
|
||||
let rows = trn!("{n} row", "{n} rows", t.rows());
|
||||
let columns = trn!("{n} column", "{n} columns", t.columns.len());
|
||||
tr!("Data table · {rows} × {columns}", rows = rows, columns = columns)
|
||||
}
|
||||
|
||||
/// A table's Library icon: a small grid.
|
||||
pub fn paint_table_icon(p: &egui::Painter, r: Rect, c: egui::Color32) {
|
||||
p.rect_stroke(r, 2.0, Stroke::new(1.5, c), StrokeKind::Inside);
|
||||
let y = r.top() + r.height() * 0.38;
|
||||
p.line_segment([pos2(r.left(), y), pos2(r.right(), y)], Stroke::new(1.0, c));
|
||||
p.line_segment([pos2(r.center().x, r.top()), pos2(r.center().x, r.bottom())], Stroke::new(1.0, c));
|
||||
}
|
||||
|
||||
/// A number as the grid shows it: plain, to four decimals, or scientific when very large or
|
||||
/// small.
|
||||
pub fn fmt_num(v: f64) -> String {
|
||||
let a = v.abs();
|
||||
if a != 0.0 && !(1e-4..1e9).contains(&a) {
|
||||
return format!("{v:.3e}");
|
||||
}
|
||||
let s = format!("{v:.4}");
|
||||
let s = s.trim_end_matches('0').trim_end_matches('.');
|
||||
if s == "-0" { "0".to_string() } else { s.to_string() }
|
||||
}
|
||||
|
||||
fn cell_text(v: Option<f64>) -> String {
|
||||
v.map_or_else(|| "–".to_string(), fmt_num)
|
||||
}
|
||||
|
||||
/// The Library's preview of a table: its first rows.
|
||||
pub fn preview(app: &App, ui: &egui::Ui, r: Rect, id: DataId) {
|
||||
let Some(t) = app.s.doc.data_table(id) else { return };
|
||||
let p = ui.painter().with_clip_rect(r);
|
||||
let cols = ((r.width() / 64.0).floor() as usize).clamp(1, t.columns.len().max(1));
|
||||
let w = r.width() / cols as f32;
|
||||
let rows = ((r.height() / 15.0).floor() as usize).saturating_sub(1);
|
||||
for (i, c) in t.columns.iter().take(cols).enumerate() {
|
||||
let x = r.left() + (i + 1) as f32 * w - 4.0;
|
||||
let is_key = t.key.as_deref() == Some(c.name.as_str());
|
||||
let name: String = c.name.chars().take(10).collect();
|
||||
p.text(pos2(x, r.top()), Align2::RIGHT_TOP, name, font(Type::Caption), if is_key { T.accent } else { color(Type::Label) });
|
||||
for (j, v) in c.values.iter().take(rows).enumerate() {
|
||||
p.text(pos2(x, r.top() + (j + 1) as f32 * 15.0), Align2::RIGHT_TOP, cell_text(*v), font(Type::DataSmall), color(Type::Data));
|
||||
}
|
||||
}
|
||||
p.line_segment([pos2(r.left(), r.top() + 14.0), pos2(r.right(), r.top() + 14.0)], Stroke::new(1.0, T.separator));
|
||||
}
|
||||
|
||||
/// The key column's chooser: Row number, or one of the columns.
|
||||
fn key_combo(app: &mut App, ui: &mut egui::Ui, id: DataId, place: &str) {
|
||||
let Some((key, names)) = app.s.doc.data_table(id).map(|t| (t.key.clone(), t.columns.iter().map(|c| c.name.clone()).collect::<Vec<_>>())) else { return };
|
||||
let shown = key.clone().unwrap_or_else(|| tr!("Row number").to_string());
|
||||
let mut pick: Option<Option<String>> = None;
|
||||
egui::ComboBox::from_id_salt(egui::Id::new("data_key").with(place))
|
||||
.width(theme::fit(ui, 150.0))
|
||||
.selected_text(text(Type::Body, shown))
|
||||
.show_ui(ui, |ui| {
|
||||
if ui.selectable_label(key.is_none(), tr!("Row number")).clicked() && key.is_some() {
|
||||
pick = Some(None);
|
||||
}
|
||||
for n in &names {
|
||||
if ui.selectable_label(key.as_deref() == Some(n.as_str()), n.as_str()).clicked() && key.as_deref() != Some(n.as_str()) {
|
||||
pick = Some(Some(n.clone()));
|
||||
}
|
||||
}
|
||||
})
|
||||
.response
|
||||
.on_hover_text(tr!("How rows are looked up: by row number (a row per frame), or by a column such as an age, a depth or a time"))
|
||||
.set_name(tr!("Key column"));
|
||||
if let Some(k) = pick {
|
||||
app.run("data.set_key", json!({"table": id.0, "key": k}));
|
||||
}
|
||||
}
|
||||
|
||||
/// Asks for a file and imports it over table `id` (its bindings stay).
|
||||
fn import_again(app: &mut App, id: DataId) {
|
||||
// (A plain import clears the table to replace, so it is named after asking.)
|
||||
app.invoke("data.import_table");
|
||||
app.data_reimport = Some(id);
|
||||
}
|
||||
|
||||
/// The Library's settings of a table: where it came from, its key column, the viewer and
|
||||
/// Import Again.
|
||||
pub fn library_properties(app: &mut App, ui: &mut egui::Ui, id: DataId) {
|
||||
let Some((detail, source, uses)) = app.s.doc.data_table(id).map(|t| (table_detail(t), t.source.clone(), app.s.doc.data.uses(id))) else { return };
|
||||
ui.label(text(Type::Caption, detail));
|
||||
if !source.is_empty() {
|
||||
ui.label(text(Type::Caption, tr!("From {file}", file = source)));
|
||||
}
|
||||
if uses > 0 {
|
||||
ui.label(text(Type::Caption, trn!("Drives {n} property", "Drives {n} properties", uses)));
|
||||
}
|
||||
form_row(ui, FORM_LABEL_DOCK, tr!("Key"), |ui| key_combo(app, ui, id, "library"));
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if ui.button(tr!("View Table")).on_hover_text(tr!("Shows every row and column (or double-click the table in the list)")).clicked() {
|
||||
app.data_view = Some(id);
|
||||
}
|
||||
if ui.button(tr!("Import Again…")).on_hover_text(tr!("Reads the file again, or a revised one: the table's values change and everything bound to it follows")).clicked() {
|
||||
import_again(app, id);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Every row and column of `t`, scrolling both ways with the column names and row numbers in
|
||||
/// place; only the cells in view are drawn.
|
||||
fn grid(ui: &mut egui::Ui, t: &DataTable) {
|
||||
let (rows, cols) = (t.rows(), t.columns.len());
|
||||
let size = vec2(NUMBER_W + cols as f32 * CELL_W, (rows + 1) as f32 * ROW_H);
|
||||
egui::ScrollArea::both().id_salt("data_grid").auto_shrink([false, false]).show_viewport(ui, |ui, view| {
|
||||
let (rect, resp) = ui.allocate_exact_size(size, Sense::hover());
|
||||
a11y::control(ui, &resp, WidgetType::Label, &tr!("{name}: {detail}", name = t.name, detail = table_detail(t)), None);
|
||||
let p = ui.painter_at(ui.clip_rect());
|
||||
let o = rect.min;
|
||||
let (top, left) = (o.y + view.min.y, o.x + view.min.x);
|
||||
let r0 = ((view.min.y / ROW_H).floor().max(0.0) as usize).min(rows);
|
||||
let r1 = ((view.max.y / ROW_H).ceil().max(0.0) as usize).min(rows);
|
||||
let c0 = (((view.min.x - NUMBER_W) / CELL_W).floor().max(0.0) as usize).min(cols);
|
||||
let c1 = ((view.max.x / CELL_W).ceil().max(0.0) as usize).min(cols);
|
||||
for r in r0..r1 {
|
||||
let y = o.y + (r + 1) as f32 * ROW_H;
|
||||
if r % 2 == 1 {
|
||||
p.rect_filled(Rect::from_min_size(pos2(left, y), vec2(view.width(), ROW_H)), 0.0, T.cell_tint);
|
||||
}
|
||||
for (c, column) in t.columns.iter().enumerate().take(c1).skip(c0) {
|
||||
let v = column.values.get(r).copied().flatten();
|
||||
let x = o.x + NUMBER_W + (c + 1) as f32 * CELL_W - 8.0;
|
||||
p.text(pos2(x, y + ROW_H / 2.0), Align2::RIGHT_CENTER, cell_text(v), font(Type::Data), if v.is_some() { color(Type::Data) } else { T.text_faint });
|
||||
}
|
||||
}
|
||||
// The column names stay at the top, the row numbers at the left.
|
||||
p.rect_filled(Rect::from_min_size(pos2(left, top), vec2(view.width(), ROW_H)), 0.0, T.header);
|
||||
for (c, column) in t.columns.iter().enumerate().take(c1).skip(c0) {
|
||||
let x = o.x + NUMBER_W + (c + 1) as f32 * CELL_W - 8.0;
|
||||
let is_key = t.key.as_deref() == Some(column.name.as_str());
|
||||
let name: String = if column.name.chars().count() > 13 { format!("{}…", column.name.chars().take(12).collect::<String>()) } else { column.name.clone() };
|
||||
p.text(pos2(x, top + ROW_H / 2.0), Align2::RIGHT_CENTER, name, font(Type::Label), if is_key { T.accent } else { color(Type::Body) });
|
||||
}
|
||||
p.rect_filled(Rect::from_min_size(pos2(left, top + ROW_H), vec2(NUMBER_W, view.height() - ROW_H)), 0.0, T.header);
|
||||
for r in r0..r1 {
|
||||
let y = o.y + (r + 1) as f32 * ROW_H;
|
||||
if y + ROW_H > top + ROW_H {
|
||||
p.text(pos2(left + NUMBER_W - 8.0, y + ROW_H / 2.0), Align2::RIGHT_CENTER, (r + 1).to_string(), font(Type::DataSmall), T.text_dim);
|
||||
}
|
||||
}
|
||||
p.rect_filled(Rect::from_min_size(pos2(left, top), vec2(NUMBER_W, ROW_H)), 0.0, T.header);
|
||||
p.line_segment([pos2(left, top + ROW_H), pos2(left + view.width(), top + ROW_H)], Stroke::new(1.0, T.separator));
|
||||
p.line_segment([pos2(left + NUMBER_W, top), pos2(left + NUMBER_W, top + view.height())], Stroke::new(1.0, T.separator));
|
||||
});
|
||||
}
|
||||
|
||||
/// The table viewer window, while a table is open in it.
|
||||
pub fn show(app: &mut App, ctx: &egui::Context) {
|
||||
let Some(id) = app.data_view else { return };
|
||||
let Some(t) = app.s.doc.data.tables.iter().find(|t| t.id == id).cloned() else {
|
||||
app.data_view = None;
|
||||
return;
|
||||
};
|
||||
let mut open = true;
|
||||
let at = crate::windows::work_area(ctx).center() - vec2(280.0, 220.0);
|
||||
let shown = crate::windows::new(ctx, tr!("Data Table")).id(egui::Id::new("data_table_view")).open(&mut open).default_pos(at).default_size([560.0, 400.0]).min_width(320.0).resizable(true).collapsible(false).show(ctx, |ui| {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(text(Type::Heading, t.name.as_str()));
|
||||
ui.label(text(Type::Caption, table_detail(&t)));
|
||||
});
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(text(Type::Label, tr!("Key")));
|
||||
key_combo(app, ui, id, "viewer");
|
||||
if ui.button(tr!("Import Again…")).on_hover_text(tr!("Reads the file again, or a revised one: the table's values change and everything bound to it follows")).clicked() {
|
||||
import_again(app, id);
|
||||
}
|
||||
let uses = app.s.doc.data.uses(id);
|
||||
if uses > 0 {
|
||||
ui.label(text(Type::Caption, trn!("Drives {n} property", "Drives {n} properties", uses)));
|
||||
}
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
if t.rows() == 0 {
|
||||
ui.label(text(Type::Caption, tr!("This table has no rows.")));
|
||||
} else {
|
||||
grid(ui, &t);
|
||||
}
|
||||
});
|
||||
a11y::name_title_bar(&shown, tr!("Data Table"));
|
||||
if !open {
|
||||
app.data_view = None;
|
||||
}
|
||||
}
|
||||
|
||||
// ----- bindings ---------------------------------------------------------------------------------
|
||||
|
||||
/// The selected symbol instance, when exactly one is selected: its id and whether its symbol is
|
||||
/// a graphic.
|
||||
fn bindable(app: &App) -> Option<(ElementId, bool)> {
|
||||
let sel = app.s.selected_elements();
|
||||
let [(_, e)] = sel.as_slice() else { return None };
|
||||
match &e.kind {
|
||||
ElementKind::Symbol { symbol, .. } => Some((e.id, app.s.doc.symbol(*symbol).is_some_and(|s| s.kind == SymbolKind::Graphic))),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether Modify › Data › Bind to Data has something to bind: one instance and a table.
|
||||
pub fn can_bind(app: &App) -> bool {
|
||||
bindable(app).is_some() && !app.s.doc.data.tables.is_empty()
|
||||
}
|
||||
|
||||
/// Whether the selection has data bindings (to remove or bake).
|
||||
pub fn has_bindings(app: &App) -> bool {
|
||||
app.s.selection.ids().any(|id| !app.s.doc.data.bindings_of(id).is_empty())
|
||||
}
|
||||
|
||||
fn binding_params(b: &Binding) -> Value {
|
||||
json!({"element": b.element.0, "property": b.property.key(), "table": b.table.0, "column": b.column, "start": b.start, "frames": b.frames, "from": b.from, "to": b.to, "interpolation": b.interp.key(), "scale": b.scale, "offset": b.offset})
|
||||
}
|
||||
|
||||
/// The first column of `t` that isn't its key.
|
||||
fn first_column(t: &DataTable) -> Option<&str> {
|
||||
t.columns.iter().find(|c| t.key.as_deref() != Some(c.name.as_str())).or(t.columns.first()).map(|c| c.name.as_str())
|
||||
}
|
||||
|
||||
/// Binds `property` of the selected instance to the first table's first column (the span and
|
||||
/// keys as `data.bind` chooses them), to be changed in Properties.
|
||||
pub fn add_binding(app: &mut App, property: BoundProperty) {
|
||||
let Some((el, _)) = bindable(app) else {
|
||||
app.status_err(tr!("Select one symbol instance to bind to data."));
|
||||
return;
|
||||
};
|
||||
// The table the instance's other bindings read, else the first.
|
||||
let table = app.s.doc.data.bindings_of(el).first().map(|b| b.table).or_else(|| app.s.doc.data.tables.first().map(|t| t.id));
|
||||
let Some((table, column, name)) = table.and_then(|id| app.s.doc.data_table(id)).and_then(|t| first_column(t).map(|c| (t.id, c.to_string(), t.name.clone()))) else {
|
||||
app.status_err(tr!("There is no data table yet: import one with File › Import › Import Data Table."));
|
||||
return;
|
||||
};
|
||||
if app.run("data.bind", json!({"element": el.0, "property": property.key(), "table": table.0, "column": column})).is_some() {
|
||||
app.show_panel(crate::dock::Panel::Properties);
|
||||
app.status_ok(tr!("{property} follows {table} · {column}. Change it under Data in Properties. {undo} to undo.", property = crate::i18n::t(property.label()), table = name, column = column, undo = app.undo_key()));
|
||||
}
|
||||
}
|
||||
|
||||
/// Modify › Data › Bind to Data: the first property the instance hasn't bound yet (Scale Y
|
||||
/// first, a chart's bar).
|
||||
pub fn bind_from_menu(app: &mut App) {
|
||||
let Some((el, graphic)) = bindable(app) else {
|
||||
app.status_err(tr!("Select one symbol instance to bind to data."));
|
||||
return;
|
||||
};
|
||||
let bound: Vec<BoundProperty> = app.s.doc.data.bindings_of(el).iter().map(|b| b.property).collect();
|
||||
let order = [BoundProperty::ScaleY, BoundProperty::ScaleX, BoundProperty::X, BoundProperty::Y, BoundProperty::Rotation, BoundProperty::Alpha, BoundProperty::Frame];
|
||||
match order.into_iter().find(|p| !bound.contains(p) && (graphic || *p != BoundProperty::Frame)) {
|
||||
Some(p) => add_binding(app, p),
|
||||
None => app.status_ok(tr!("Every property of this instance is bound already: change them under Data in Properties.")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The Data section of a symbol instance's Properties: its bindings, each edited in place.
|
||||
pub fn instance_section(app: &mut App, ui: &mut egui::Ui, el: ElementId) {
|
||||
let Some((id, graphic)) = bindable(app).filter(|(id, _)| *id == el) else { return };
|
||||
let bindings: Vec<Binding> = app.s.doc.data.bindings_of(id).to_vec();
|
||||
let has_tables = !app.s.doc.data.tables.is_empty();
|
||||
if bindings.is_empty() && !has_tables {
|
||||
return;
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
let count = bindings.len().to_string();
|
||||
theme::section(ui, "prop_data", Section::Rule, tr!("Data"), (!bindings.is_empty()).then_some(count.as_str()), |ui| {
|
||||
for b in &bindings {
|
||||
ui.push_id(("data_binding", b.property.key()), |ui| binding_rows(app, ui, b));
|
||||
ui.add_space(4.0);
|
||||
}
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let free: Vec<BoundProperty> = BoundProperty::ALL.into_iter().filter(|p| !bindings.iter().any(|b| b.property == *p) && (graphic || *p != BoundProperty::Frame)).collect();
|
||||
ui.add_enabled_ui(has_tables && !free.is_empty(), |ui| {
|
||||
ui.menu_button(tr!("Bind to Data"), |ui| {
|
||||
for p in &free {
|
||||
if ui.button(crate::i18n::t(p.label())).clicked() {
|
||||
ui.close();
|
||||
add_binding(app, *p);
|
||||
}
|
||||
}
|
||||
})
|
||||
.response
|
||||
.on_hover_text(tr!("A column of a data table drives one of this instance's properties, frame by frame"));
|
||||
});
|
||||
if !bindings.is_empty() && ui.button(tr!("Bake to Keyframes")).on_hover_text(tr!("Writes what the bindings show as plain keyframes and removes the bindings: every frame looks as it did")).clicked() {
|
||||
bake(app, id);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// Bake Data to Keyframes for instance `el` (or the selection), with a status line.
|
||||
pub fn bake(app: &mut App, el: ElementId) {
|
||||
if let Some(v) = app.run("data.bake", json!({"element": el.0})) {
|
||||
let n = v["keys"].as_u64().unwrap_or(0);
|
||||
app.status_ok(trn!("Baked the data into {n} new keyframe. {undo} to undo.", "Baked the data into {n} new keyframes. {undo} to undo.", n, undo = app.undo_key()));
|
||||
}
|
||||
}
|
||||
|
||||
/// One binding: its name with Remove, then what it reads and how.
|
||||
fn binding_rows(app: &mut App, ui: &mut egui::Ui, b: &Binding) {
|
||||
let label = crate::i18n::t(b.property.label());
|
||||
let table = app.s.doc.data_table(b.table).cloned();
|
||||
let value = b.value_at(&app.s.doc.data, app.s.frame);
|
||||
let mut next = b.clone();
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(text(Type::Body, label).strong());
|
||||
let shown = match value {
|
||||
Some(v) => format!("{}{}", fmt_num(f64::from(v)), b.property.unit()),
|
||||
None => tr!("no value").to_string(),
|
||||
};
|
||||
with_type(ui, Type::Data, |ui| ui.label(text(Type::Data, shown)).on_hover_text(tr!("What the binding gives at the playhead (the instance stays as placed when the table or column is missing or has no number)")));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if crate::timeline::icon_button(ui, &tr!("Remove the {property} binding", property = label), None, crate::icons::Icon::Trash).on_hover_text(tr!("Removes this binding: the property is the instance's own again")).clicked() {
|
||||
app.run("data.unbind", json!({"element": b.element.0, "property": b.property.key()}));
|
||||
}
|
||||
});
|
||||
});
|
||||
let tables: Vec<(DataId, String)> = app.s.doc.data.tables.iter().map(|t| (t.id, t.name.clone())).collect();
|
||||
form_row(ui, FORM_LABEL_DOCK, tr!("Table"), |ui| {
|
||||
let shown = table.as_ref().map_or_else(|| tr!("(missing)").to_string(), |t| t.name.clone());
|
||||
egui::ComboBox::from_id_salt("data_bind_table")
|
||||
.width(theme::fit(ui, 150.0))
|
||||
.selected_text(text(Type::Body, shown))
|
||||
.show_ui(ui, |ui| {
|
||||
for (tid, name) in &tables {
|
||||
if ui.selectable_label(*tid == b.table, name.as_str()).clicked() && *tid != b.table {
|
||||
next.table = *tid;
|
||||
// A column of the same name if the new table has one, else its first.
|
||||
if let Some(t) = app.s.doc.data_table(*tid)
|
||||
&& t.column_index(&b.column).is_none()
|
||||
{
|
||||
next.column = first_column(t).unwrap_or("").to_string();
|
||||
}
|
||||
(next.from, next.to) = (None, None);
|
||||
}
|
||||
}
|
||||
})
|
||||
.response
|
||||
.set_name(tr!("Data table"));
|
||||
});
|
||||
form_row(ui, FORM_LABEL_DOCK, tr!("Column"), |ui| {
|
||||
let live = table.as_ref().is_some_and(|t| t.column_index(&b.column).is_some());
|
||||
let shown = if live { b.column.clone() } else { tr!("{column} (missing)", column = b.column).to_string() };
|
||||
egui::ComboBox::from_id_salt("data_bind_column")
|
||||
.width(theme::fit(ui, 150.0))
|
||||
.selected_text(text(Type::Body, shown))
|
||||
.show_ui(ui, |ui| {
|
||||
for c in table.iter().flat_map(|t| &t.columns) {
|
||||
if ui.selectable_label(c.name == b.column, c.name.as_str()).clicked() {
|
||||
next.column = c.name.clone();
|
||||
}
|
||||
}
|
||||
})
|
||||
.response
|
||||
.set_name(tr!("Column"));
|
||||
});
|
||||
form_row(ui, FORM_LABEL_DOCK, tr!("Frames"), |ui| {
|
||||
with_type(ui, Type::Data, |ui| {
|
||||
let mut first = next.start + 1;
|
||||
if ui.add(egui::DragValue::new(&mut first).range(1..=MAX_SPAN + 1).speed(0.2)).on_hover_text(tr!("The first frame of the span the table is played over")).named(tr!("First frame of the span")).changed() {
|
||||
next.start = first.saturating_sub(1);
|
||||
}
|
||||
ui.label(text(Type::Caption, tr!("for")));
|
||||
ui.add(egui::DragValue::new(&mut next.frames).range(1..=MAX_SPAN).speed(0.2).suffix(" f")).on_hover_text(tr!("How many frames the span has. Before it the instance shows the first frame's value, after it the last's")).named(tr!("Frames in the span"));
|
||||
});
|
||||
});
|
||||
// The keys the span runs between: the table's first and last unless set.
|
||||
let range = table.as_ref().and_then(|t| t.key_range());
|
||||
let keyed = table.as_ref().is_some_and(|t| t.key.is_some());
|
||||
form_row(ui, FORM_LABEL_DOCK, if keyed { tr!("Keys") } else { tr!("Rows") }, |ui| {
|
||||
with_type(ui, Type::Data, |ui| {
|
||||
let (lo, hi) = range.unwrap_or((0.0, 0.0));
|
||||
// Row numbers show from 1, as the viewer numbers them.
|
||||
let shift = if keyed { 0.0 } else { 1.0 };
|
||||
let (mut from, mut to) = (next.from.unwrap_or(lo) + shift, next.to.unwrap_or(hi) + shift);
|
||||
let speed = if keyed { ((hi - lo).abs() / 200.0).max(0.01) } else { 0.1 };
|
||||
if ui.add(egui::DragValue::new(&mut from).range(-MAX_VALUE..=MAX_VALUE).speed(speed).max_decimals(3)).on_hover_text(tr!("What the span's first frame shows")).named(tr!("First key of the span")).changed() {
|
||||
next.from = Some(from - shift);
|
||||
}
|
||||
ui.label(text(Type::Caption, tr!("to")));
|
||||
if ui.add(egui::DragValue::new(&mut to).range(-MAX_VALUE..=MAX_VALUE).speed(speed).max_decimals(3)).on_hover_text(tr!("What the span's last frame shows. Before the first plays the table backwards")).named(tr!("Last key of the span")).changed() {
|
||||
next.to = Some(to - shift);
|
||||
}
|
||||
if (next.from.is_some() || next.to.is_some()) && ui.small_button(tr!("All")).on_hover_text(tr!("The whole table, however long it gets")).clicked() {
|
||||
(next.from, next.to) = (None, None);
|
||||
}
|
||||
});
|
||||
});
|
||||
form_row(ui, FORM_LABEL_DOCK, tr!("Value"), |ui| {
|
||||
with_type(ui, Type::Data, |ui| {
|
||||
ui.add(egui::DragValue::new(&mut next.scale).range(-MAX_VALUE..=MAX_VALUE).speed(0.01).max_decimals(4).prefix("× ")).on_hover_text(tr!("The column's number times this")).named(tr!("Scale of the value"));
|
||||
ui.add(egui::DragValue::new(&mut next.offset).range(-MAX_VALUE..=MAX_VALUE).speed(0.5).max_decimals(3).prefix("+ ")).on_hover_text(tr!("Added after scaling. The result is the property: pixels, percent, degrees or a frame counted from 0")).named(tr!("Offset of the value"));
|
||||
});
|
||||
});
|
||||
form_row(ui, FORM_LABEL_DOCK, tr!("Between"), |ui| {
|
||||
egui::ComboBox::from_id_salt("data_bind_interp")
|
||||
.width(theme::fit(ui, 150.0))
|
||||
.selected_text(text(Type::Body, crate::i18n::t(b.interp.label())))
|
||||
.show_ui(ui, |ui| {
|
||||
for i in Interp::ALL {
|
||||
if ui.selectable_label(i == b.interp, crate::i18n::t(i.label())).clicked() {
|
||||
next.interp = i;
|
||||
}
|
||||
}
|
||||
})
|
||||
.response
|
||||
.on_hover_text(tr!("Between two rows: Linear goes straight from one value to the next; Step holds each row's value until the next row"))
|
||||
.set_name(tr!("Between rows"));
|
||||
});
|
||||
if next != *b {
|
||||
crate::panels::live(app, tr_noop!("Data Binding"), "data.bind", binding_params(&next));
|
||||
}
|
||||
}
|
||||
|
||||
/// What a finished `data.import_table` did, for the status bar; the table becomes the
|
||||
/// Library's current item.
|
||||
pub fn imported(app: &mut App, v: &Value) {
|
||||
let Some(id) = v["table"].as_u64().map(DataId) else { return };
|
||||
app.library_sel = Some(LibraryItem::Data(id));
|
||||
let name = v["name"].as_str().unwrap_or("");
|
||||
let (rows, cols) = (v["rows"].as_u64().unwrap_or(0), v["columns"].as_array().map_or(0, Vec::len));
|
||||
let rows = trn!("{n} row", "{n} rows", rows);
|
||||
let cols = trn!("{n} column", "{n} columns", cols);
|
||||
let mut msg = if v["replaced"].as_bool() == Some(true) {
|
||||
tr!("{name} now has {rows} × {columns}; what is bound to it follows.", name = name, rows = rows, columns = cols)
|
||||
} else {
|
||||
tr!("{name} is in the Library: {rows} × {columns}. Select an instance and choose Modify › Data › Bind to Data.", name = name, rows = rows, columns = cols)
|
||||
};
|
||||
let skipped: Vec<&str> = v["skipped"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default();
|
||||
if !skipped.is_empty() {
|
||||
let shown = skipped.iter().take(4).copied().collect::<Vec<_>>().join(", ");
|
||||
msg = format!("{msg} {}", trn!("Left out {n} column with no numbers ({names}).", "Left out {n} columns with no numbers ({names}).", skipped.len(), names = shown));
|
||||
}
|
||||
let missing: Vec<&str> = v["missing"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default();
|
||||
if !missing.is_empty() {
|
||||
msg = format!("{msg} {}", tr!("Bindings still read columns that are gone: {names}.", names = missing.join(", ")));
|
||||
}
|
||||
if v["truncated"].as_bool() == Some(true) {
|
||||
msg = format!("{msg} {}", tr!("The file held more than a table keeps; the rest was left out."));
|
||||
}
|
||||
app.status_ok(msg);
|
||||
}
|
||||
|
||||
/// A sample for screenshots: six bars on a baseline, each a graphic instance whose height
|
||||
/// follows a column of a table of twenty-four rows (a row a frame), one bar selected with its
|
||||
/// binding in Properties; with `viewer`, the table viewer open on the table.
|
||||
pub fn sample_chart(app: &mut App, viewer: bool) {
|
||||
app.perform("file.new", json!({"width": 960, "height": 540, "fps": 24}));
|
||||
// i18n-exempt: layer, symbol, table and column names are document data (a screenshot sample)
|
||||
let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"];
|
||||
let columns: Vec<Value> = months
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, m)| {
|
||||
let values: Vec<f64> = (0..24).map(|f| (120.0 + 90.0 * ((f as f64) * 0.26 + i as f64 * 1.1).sin() + 12.0 * i as f64).round()).collect();
|
||||
json!({"name": m, "values": values})
|
||||
})
|
||||
.collect();
|
||||
let Some(table) = app.run("data.set_table", json!({"name": "Rainfall", "columns": columns})).and_then(|v| v["table"].as_u64()) else { return };
|
||||
app.run("draw.line", json!({"x0": 120, "y0": 440, "x1": 840, "y1": 440, "stroke": "#1b2a4a", "stroke_width": 3}));
|
||||
app.run("timeline.insert_frame", json!({"frame": 23}));
|
||||
app.run("layer.new", json!({"name": "Bars"}));
|
||||
app.run("draw.rect", json!({"x": 150, "y": 340, "w": 80, "h": 100, "fill": "#3d8bfd", "stroke": null, "object": true}));
|
||||
let symbol = app.run("modify.convert_to_symbol", json!({"name": "Bar", "kind": "graphic"})).and_then(|v| v["symbol"].as_u64());
|
||||
let mut bars: Vec<u64> = app.s.selection.ids().map(|e| e.0).collect();
|
||||
for i in 1..months.len() {
|
||||
if let Some(el) = app.run("library.place", json!({"symbol": symbol, "x": 190 + 110 * i, "y": 390})).and_then(|v| v["element"].as_u64()) {
|
||||
bars.push(el);
|
||||
}
|
||||
}
|
||||
app.run("timeline.insert_frame", json!({"frame": 23}));
|
||||
for (i, (el, month)) in bars.iter().zip(months).enumerate() {
|
||||
// Each bar grows from its foot on the baseline.
|
||||
app.run("element.select", json!({"ids": [el]}));
|
||||
app.run("modify.transformation_point", json!({"x": 190 + 110 * i, "y": 440}));
|
||||
app.run("data.bind", json!({"element": el, "property": "scale_y", "table": table, "column": month}));
|
||||
}
|
||||
if let Some(el) = bars.get(2) {
|
||||
app.run("data.bind", json!({"element": el, "property": "alpha", "table": table, "column": "Mar", "scale": 0.3, "offset": 40}));
|
||||
app.run("element.select", json!({"ids": [el]}));
|
||||
}
|
||||
app.run("timeline.goto", json!({"frame": 9}));
|
||||
app.library_sel = Some(LibraryItem::Data(DataId(table)));
|
||||
// Room for the Data section under the instance's own properties.
|
||||
for p in [crate::dock::Panel::Align, crate::dock::Panel::History] {
|
||||
app.dock.close(p);
|
||||
}
|
||||
if viewer {
|
||||
app.show_panel(crate::dock::Panel::Library);
|
||||
app.data_view = Some(DataId(table));
|
||||
} else {
|
||||
// The whole of the instance's properties, the Data section last.
|
||||
for p in [crate::dock::Panel::Library, crate::dock::Panel::MovieExplorer] {
|
||||
app.dock.close(p);
|
||||
}
|
||||
}
|
||||
app.show_panel(crate::dock::Panel::Properties);
|
||||
app.s.mark_saved();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn numbers_are_shown_plainly() {
|
||||
for (v, s) in [(0.0, "0"), (1.0, "1"), (-2.5, "-2.5"), (0.123456, "0.1235"), (1234.5, "1234.5"), (1e12, "1.000e12"), (0.00001, "1.000e-5"), (-0.00001, "-1.000e-5"), (-0.00000001 * 1e3, "-1.000e-5")] {
|
||||
assert_eq!(fmt_num(v), s, "{v}");
|
||||
}
|
||||
assert_eq!(cell_text(None), "–");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_engine_label_is_listed_for_the_catalogs() {
|
||||
for p in BoundProperty::ALL {
|
||||
assert!(TEXTS.contains(&p.label()), "{}", p.label());
|
||||
}
|
||||
for i in Interp::ALL {
|
||||
assert!(TEXTS.contains(&i.label()), "{}", i.label());
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -211,7 +211,7 @@ impl Entry {
|
||||
|
||||
/// Commands the palette can run without extra input (everything optional, or prompted).
|
||||
fn runnable(c: &CommandSpec) -> bool {
|
||||
if matches!(c.id, "file.open" | "file.recovery_list" | "file.save_as" | "file.import" | "file.import_video" | "file.export_png" | "file.export_gif" | "file.export_apng" | "file.export_webp" | "file.export_svg" | "file.export_sprite_sheet" | "file.export_video" | "file.export_lottie" | "file.export_html" | "file.export_png_sequence" | "modify.convert_to_symbol" | "layer.rename" | "scene.rename" | "plugin.install") {
|
||||
if matches!(c.id, "file.open" | "file.recovery_list" | "file.save_as" | "file.import" | "file.import_video" | "file.export_png" | "file.export_gif" | "file.export_apng" | "file.export_webp" | "file.export_svg" | "file.export_sprite_sheet" | "file.export_video" | "file.export_lottie" | "file.export_html" | "file.export_png_sequence" | "modify.convert_to_symbol" | "layer.rename" | "scene.rename" | "plugin.install" | "data.import_table" | "data.bind") {
|
||||
return true;
|
||||
}
|
||||
let inner = c.params.trim().trim_start_matches('{').trim_end_matches('}');
|
||||
|
||||
+26
-2
@@ -139,6 +139,7 @@ fn kind_rank(doc: &Document, e: LibraryEntry) -> u8 {
|
||||
},
|
||||
LibraryEntry::Item(LibraryItem::Bitmap(_)) => 4,
|
||||
LibraryEntry::Item(LibraryItem::Sound(_)) => 5,
|
||||
LibraryEntry::Item(LibraryItem::Data(_)) => 6,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,6 +163,7 @@ fn detail(doc: &Document, e: LibraryEntry) -> String {
|
||||
}),
|
||||
LibraryEntry::Item(LibraryItem::Bitmap(id)) => doc.bitmap(id).map_or_else(String::new, |b| tr!("Bitmap · {width}×{height}", width = b.width, height = b.height)),
|
||||
LibraryEntry::Item(LibraryItem::Sound(id)) => doc.sound(id).map_or_else(String::new, |x| tr!("Sound · {seconds} s", seconds = format!("{:.1}", x.seconds()))),
|
||||
LibraryEntry::Item(LibraryItem::Data(id)) => doc.data_table(id).map_or_else(String::new, crate::data_ui::table_detail),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -531,6 +533,7 @@ fn list_ui(app: &mut App, ui: &mut egui::Ui, list: &[Row], unused: &HashSet<Libr
|
||||
}
|
||||
LibraryEntry::Item(LibraryItem::Sound(_)) => icons::paint(p, icon.expand(1.0), Icon::Sound, color(Type::Body)),
|
||||
LibraryEntry::Item(LibraryItem::Bitmap(_)) => icons::paint(p, icon.expand(1.0), Icon::Image, color(Type::Body)),
|
||||
LibraryEntry::Item(LibraryItem::Data(_)) => crate::data_ui::paint_table_icon(p, icon, color(Type::Body)),
|
||||
}
|
||||
let name_rect = Rect::from_min_max(pos2(icon.right() + 8.0, r.top()), pos2(r.right() - 40.0, r.bottom()));
|
||||
let uses_text = row.uses.map(|n| n.to_string()).unwrap_or_default();
|
||||
@@ -674,6 +677,8 @@ fn list_ui(app: &mut App, ui: &mut egui::Ui, list: &[Row], unused: &HashSet<Libr
|
||||
LibraryEntry::Item(LibraryItem::Symbol(id)) => {
|
||||
app.run("symbol.edit", json!({"symbol": id.0}));
|
||||
}
|
||||
// A data table opens in the table viewer (ADR 0118).
|
||||
LibraryEntry::Item(LibraryItem::Data(id)) => app.data_view = Some(id),
|
||||
LibraryEntry::Item(i) => place(app, i),
|
||||
LibraryEntry::Folder(f) => {
|
||||
if !app.library.expanded.remove(&f) {
|
||||
@@ -714,7 +719,15 @@ fn row_menu(app: &mut App, ui: &mut egui::Ui, e: LibraryEntry) {
|
||||
}
|
||||
}
|
||||
}
|
||||
let items = selected_items(app);
|
||||
if let LibraryEntry::Item(LibraryItem::Data(id)) = e
|
||||
&& !many
|
||||
&& ui.button(tr!("View Table")).clicked()
|
||||
{
|
||||
ui.close();
|
||||
app.data_view = Some(id);
|
||||
}
|
||||
// (A data table isn't artwork: it is bound, not placed.)
|
||||
let items: Vec<LibraryItem> = selected_items(app).into_iter().filter(|i| !matches!(i, LibraryItem::Data(_))).collect();
|
||||
if !items.is_empty() {
|
||||
let label = if items.iter().all(|i| matches!(i, LibraryItem::Sound(_))) { tr!("Place on Timeline") } else { tr!("Place on Stage") };
|
||||
if ui.button(label).on_hover_text(tr!("At the centre of the view, on the active layer (Enter; or drag onto the stage)")).clicked() {
|
||||
@@ -772,6 +785,14 @@ fn actions_row(app: &mut App, ui: &mut egui::Ui) {
|
||||
{
|
||||
items.push(i);
|
||||
}
|
||||
// A data table isn't artwork: it is viewed and bound, not placed (ADR 0118).
|
||||
if let [LibraryItem::Data(id)] = items.as_slice() {
|
||||
if ui.button(tr!("View Table")).on_hover_text(tr!("Shows every row and column (or double-click the table in the list)")).clicked() {
|
||||
app.data_view = Some(*id);
|
||||
}
|
||||
return;
|
||||
}
|
||||
items.retain(|i| !matches!(i, LibraryItem::Data(_)));
|
||||
if !items.is_empty() && items.iter().all(|i| matches!(i, LibraryItem::Sound(_))) {
|
||||
if ui.button(tr!("Place on timeline")).on_hover_text(tr!("Puts it on the active layer's keyframe at the playhead (Enter, or drag it onto the stage)")).clicked() {
|
||||
place_items(app, &items, None);
|
||||
@@ -826,6 +847,7 @@ fn properties(app: &mut App, ui: &mut egui::Ui) {
|
||||
with_type(ui, Type::Data, |ui| ui.label(text(Type::Caption, info)));
|
||||
}
|
||||
}
|
||||
LibraryItem::Data(id) => crate::data_ui::library_properties(app, ui, id),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -844,6 +866,8 @@ fn preview(app: &mut App, ui: &mut egui::Ui) {
|
||||
};
|
||||
let inner = r.shrink(6.0);
|
||||
match item {
|
||||
// A data table (ADR 0118): its first rows.
|
||||
LibraryItem::Data(id) => crate::data_ui::preview(app, ui, inner, id),
|
||||
LibraryItem::Sound(id) => {
|
||||
waveform(app, ui, inner, id);
|
||||
let play = Rect::from_min_size(pos2(r.right() - TARGET - 4.0, r.top() + 4.0), vec2(TARGET, TARGET));
|
||||
@@ -915,7 +939,7 @@ fn picture(ctx: &egui::Context, doc: &Document, item: LibraryItem, area: Rect) -
|
||||
let options = if b.smoothing { egui::TextureOptions::LINEAR } else { egui::TextureOptions::NEAREST };
|
||||
Some(ctx.load_texture("library-preview", image, options))
|
||||
}
|
||||
LibraryItem::Sound(_) => None,
|
||||
LibraryItem::Sound(_) | LibraryItem::Data(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -41,6 +41,7 @@ mod bone_tool;
|
||||
mod camera_tool;
|
||||
mod context_help;
|
||||
mod convert_symbol;
|
||||
mod data_ui;
|
||||
mod layer_depth;
|
||||
mod layer_props;
|
||||
mod desktop_ui;
|
||||
@@ -300,7 +301,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 dark|light|high-contrast|<file>.json] [--check-theme <file>.json] [--scale <percent>] [--lang <code>|auto|pseudo] [--control <port>] [--open palette|shortcuts|helpbone|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|shapecommands|expandfill|softenfill|origins|pivot|layeropacity|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|erasemerge|tiltbrush|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|bones|springbones|shapebones|shapeweights|mixedbones|layerdepth|layerdepthview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|richtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|ease|easepreset|plugineases|pluginexport|pluginexportwindow|library|librarymenu|libraryfolders|colour|layerprops|frameview|layercolour|timelinepolish|dock|dockicons|floattabs|docknarrow|workspaces|animator|designer|gradient|gradientbucket|swatches|swatchpanel|video|videoimport]\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 dark|light|high-contrast|<file>.json] [--check-theme <file>.json] [--scale <percent>] [--lang <code>|auto|pseudo] [--control <port>] [--open palette|shortcuts|helpbone|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|shapecommands|expandfill|softenfill|origins|pivot|layeropacity|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|erasemerge|tiltbrush|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|bones|springbones|shapebones|shapeweights|mixedbones|layerdepth|layerdepthview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|richtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|ease|easepreset|plugineases|pluginexport|pluginexportwindow|library|librarymenu|libraryfolders|colour|layerprops|frameview|layercolour|timelinepolish|dock|dockicons|floattabs|docknarrow|workspaces|animator|designer|gradient|gradientbucket|swatches|swatchpanel|video|videoimport|datachart|datatable]\n\
|
||||
--renderer the window's graphics (also ANICRAFT_RENDERER); default automatic, falling back to OpenGL\n\
|
||||
--theme a built-in look, or a theme file of your own, for this run only\n\
|
||||
--check-theme says whether a theme file would be used (exit 0) or why it is refused (exit 1)\n\
|
||||
|
||||
@@ -429,6 +429,9 @@ fn enabled(app: &App, id: &str) -> bool {
|
||||
"modify.soften_fill_edges" => selected_shape(app, |sh| sh.fill.as_ref().is_some_and(|f| !matches!(f, anicraft_engine::doc::Paint::Bitmap { .. }))),
|
||||
// Convert Audio to Keyframes and Auto Lip-Sync read a sound on this timeline (ADR 0114).
|
||||
"sound.to_keyframes" | "sound.lip_sync" => app.s.timeline().layers.iter().any(|l| l.has_sounds()),
|
||||
// Data bindings (ADR 0118): one instance and a table to bind; bindings to remove or bake.
|
||||
"data.bind" => crate::data_ui::can_bind(app),
|
||||
"data.unbind" | "data.bake" => crate::data_ui::has_bindings(app),
|
||||
"layer.delete" => app.s.timeline().layers.len() > 1,
|
||||
"scene.delete" => app.s.doc.scenes.len() > 1,
|
||||
// Ctrl+E opens the selected instance, or goes back to the document (ADR 0045).
|
||||
|
||||
@@ -1318,6 +1318,8 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E
|
||||
} else if kind == SymbolKind::MovieClip {
|
||||
ui.label(text(Type::Caption, trn!("Plays its {n}-frame timeline on a loop from when it appears.", "Plays its {n}-frame timeline on a loop from when it appears.", frames)));
|
||||
}
|
||||
// What a data table drives of this instance (ADR 0118).
|
||||
crate::data_ui::instance_section(app, ui, e.id);
|
||||
}
|
||||
if let ElementKind::Text(t) = &e.kind {
|
||||
ui.add_space(4.0);
|
||||
|
||||
+2
-1
@@ -993,13 +993,14 @@ pub fn filters(cmd: &str) -> (&'static str, &'static [&'static str]) {
|
||||
"filter.preset_export" | "filter.preset_import" => (tr_noop!("Filter preset file"), &["json"]),
|
||||
"swatch.export" => (tr_noop!("Swatch file"), &["json"]),
|
||||
"swatch.import" => (tr_noop!("Swatch file or GIMP palette"), &["json", "gpl"]),
|
||||
"data.import_table" => (tr_noop!("Data table (CSV, TSV or JSON)"), &["csv", "tsv", "tab", "txt", "json"]),
|
||||
_ => (tr_noop!("AniCraft document"), &["anicraft"]),
|
||||
}
|
||||
}
|
||||
|
||||
/// Commands that read a file the user picks (the others write one, or a folder of them).
|
||||
pub fn reads_file(cmd: &str) -> bool {
|
||||
matches!(cmd, "file.open" | "plugin.install" | "file.import" | "file.import_video" | "layer.set_video" | "file.import_to_library" | "brush.preset_import" | "filter.preset_import" | "swatch.import" | "macro.run" | "macro.import")
|
||||
matches!(cmd, "file.open" | "plugin.install" | "file.import" | "file.import_video" | "layer.set_video" | "file.import_to_library" | "brush.preset_import" | "filter.preset_import" | "swatch.import" | "data.import_table" | "macro.run" | "macro.import")
|
||||
}
|
||||
|
||||
/// Shows the platform's own dialog (Windows common dialog, macOS panel, Linux XDG portal), with
|
||||
|
||||
Reference in new issue
Block a user