mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Open documents through migrations in the CLI and add a regression tool
This commit is contained in:
1 parent
f36ee54ccd
commit
b3ffdffbcb
17 files changed
+804
-159
No files matched your search
Generated
+17
@@ -2159,6 +2159,8 @@ dependencies = [
|
||||
"image",
|
||||
"interpreted-executor",
|
||||
"log",
|
||||
"migration-formats",
|
||||
"migration-nodes",
|
||||
"preprocessor",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
@@ -5101,6 +5103,21 @@ version = "0.8.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "caf4aa5b0f434c91fe5c7f1ecb6a5ece2130b02ad2a590589dda5146df959001"
|
||||
|
||||
[[package]]
|
||||
name = "regression"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"document-format",
|
||||
"fern",
|
||||
"graphene-cli",
|
||||
"image",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "renderdoc-sys"
|
||||
version = "1.1.0"
|
||||
|
||||
@@ -43,6 +43,7 @@ members = [
|
||||
"tools/third-party-licenses",
|
||||
"tools/editor-message-tree",
|
||||
"tools/node-docs",
|
||||
"tools/regression",
|
||||
"tools/web-editor-driver",
|
||||
]
|
||||
default-members = [
|
||||
|
||||
@@ -85,6 +85,8 @@ pub struct Gdd<L: Layout = GddV1Layout> {
|
||||
/// Per-network view settings (node-graph nav + previewing), keyed by stable [`NetworkId`]. Same per-peer
|
||||
/// `session.json` treatment as [`view_settings`](Self::view_settings), but scoped per network.
|
||||
pub(crate) network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, document_graph_storage::Value>>,
|
||||
/// Whether opening ran a format step or node migration, and so rewrote the working copy.
|
||||
pub(crate) migrated: bool,
|
||||
}
|
||||
|
||||
/// Native folder-backed convenience constructors. On wasm the editor builds an OPFS-backed
|
||||
@@ -198,6 +200,7 @@ impl<L: Layout> Gdd<L> {
|
||||
manifest,
|
||||
view_settings: session_state.view_settings,
|
||||
network_view_settings: session_state.network_view_settings,
|
||||
migrated: false,
|
||||
};
|
||||
|
||||
#[cfg(feature = "migrations")]
|
||||
@@ -206,6 +209,7 @@ impl<L: Layout> Gdd<L> {
|
||||
if format_outcome.is_some() || migrated_nodes {
|
||||
gdd.manifest.format_version = gdd.manifest.format_version.max(manifest::SUPPORTED_FORMAT_VERSION);
|
||||
gdd.persist_all()?;
|
||||
gdd.migrated = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -235,6 +239,7 @@ impl<L: Layout> Gdd<L> {
|
||||
manifest,
|
||||
view_settings: std::collections::BTreeMap::new(),
|
||||
network_view_settings: std::collections::BTreeMap::new(),
|
||||
migrated: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -278,6 +283,11 @@ impl<L: Layout> Gdd<L> {
|
||||
&self.manifest
|
||||
}
|
||||
|
||||
/// Whether opening ran a format step or node migration, and so rewrote the working copy.
|
||||
pub fn migrated(&self) -> bool {
|
||||
self.migrated
|
||||
}
|
||||
|
||||
pub fn layout(&self) -> &L {
|
||||
&self.layout
|
||||
}
|
||||
|
||||
@@ -51,12 +51,14 @@ fn opening_migrates_nodes_and_persists_the_result() {
|
||||
assert!(migrated.registry().resources.contains_key(&target.id), "the target declaration is a registered resource");
|
||||
assert_eq!(migrated.declarations(&migrated).await[&target.id], target.proto, "its bytes are stored");
|
||||
assert_eq!(migrated.manifest().format_version, manifest::SUPPORTED_FORMAT_VERSION);
|
||||
assert!(migrated.migrated());
|
||||
|
||||
// The rewritten history persisted, so a reopen has nothing left to migrate
|
||||
let registry = migrated.registry().clone();
|
||||
let (working, layout) = migrated.into_storage();
|
||||
let reopened = GddV1::open_in(working, layout).await.unwrap();
|
||||
assert!(reopened.registry().value_equal(®istry));
|
||||
assert!(!reopened.migrated());
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -25,8 +25,10 @@ graphene-std = { workspace = true }
|
||||
interpreted-executor = { workspace = true }
|
||||
graph-craft = { workspace = true, features = ["loading"] }
|
||||
preprocessor = { workspace = true }
|
||||
document-format = { workspace = true, features = ["zip", "xz"] }
|
||||
document-format = { workspace = true, features = ["zip", "xz", "migrations"] }
|
||||
document-container = { workspace = true, features = ["zip", "xz"] }
|
||||
migration-formats = { workspace = true }
|
||||
migration-nodes = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
log = { workspace = true }
|
||||
|
||||
@@ -61,7 +61,7 @@ pub fn detect_file_type(path: &Path) -> Result<FileType, String> {
|
||||
}
|
||||
|
||||
/// One rendered frame of the document, as SVG text or as 8-bit RGBA pixels with straight alpha.
|
||||
enum RenderedFrame {
|
||||
pub enum RenderedFrame {
|
||||
Svg(String),
|
||||
Raster { data: Vec<u8>, width: u32, height: u32 },
|
||||
}
|
||||
@@ -152,7 +152,7 @@ fn combine_bounds([a_min, a_max]: [DVec2; 2], [b_min, b_max]: [DVec2; 2]) -> [DV
|
||||
}
|
||||
|
||||
/// Renders the document at the given animation time, as SVG text for an SVG export and as pixels for every other file type.
|
||||
async fn render_frame(
|
||||
pub async fn render_frame(
|
||||
executor: &DynamicExecutor,
|
||||
wgpu_executor: &wgpu_executor::WgpuExecutor,
|
||||
settings: ExportSettings,
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
//! Opens, compiles, and renders Graphite documents without the editor. A `.gdd` opens through the format steps and node migrations
|
||||
//! this crate links, so every binary built on it reads documents the way the current build writes them.
|
||||
|
||||
pub mod dump;
|
||||
pub mod export;
|
||||
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
|
||||
use graph_craft::document::{NodeId, NodeNetwork};
|
||||
use graph_craft::graphene_compiler::Compiler;
|
||||
use graph_craft::proto::ProtoNetwork;
|
||||
use graph_craft::util::load_network;
|
||||
use graphene_std::application_io::ApplicationIo;
|
||||
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use std::collections::HashMap;
|
||||
use std::error::Error;
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
// Referenced so the linker keeps their self-registering migrations
|
||||
use migration_formats as _;
|
||||
use migration_nodes as _;
|
||||
|
||||
/// A document as the CLI loads it: the runtime network, plus the `.gdd` it came from, if any.
|
||||
pub struct OpenedDocument {
|
||||
pub gdd: Option<GddV1>,
|
||||
pub network: NodeNetwork,
|
||||
/// What `dump` shows for each node and network, when asked for.
|
||||
pub names: Option<HashMap<Vec<NodeId>, String>>,
|
||||
}
|
||||
|
||||
/// Open a `.gdd` from its archive bytes into memory, running the migrations this crate links.
|
||||
pub async fn open_gdd(archive: &[u8]) -> Result<GddV1, Box<dyn Error>> {
|
||||
let container = AnyContainer::Memory(MemoryBackend::new());
|
||||
let gdd = GddV1::open_from_archive(archive, container, GddV1Layout)
|
||||
.await
|
||||
.map_err(|error| format!("Failed to open document: {error}"))?;
|
||||
Ok(gdd)
|
||||
}
|
||||
|
||||
/// Open `path` by extension: `.gdd` as an archive, anything else as a legacy `.graphite` document. `with_names` also collects its display names.
|
||||
pub async fn open_document(path: &Path, with_names: bool) -> Result<OpenedDocument, Box<dyn Error>> {
|
||||
let is_gdd = path.extension().is_some_and(|extension| extension.eq_ignore_ascii_case("gdd"));
|
||||
|
||||
if !is_gdd {
|
||||
let document_string = std::fs::read_to_string(path).map_err(|error| format!("Failed to read document {}: {error}", path.display()))?;
|
||||
return Ok(OpenedDocument {
|
||||
gdd: None,
|
||||
network: load_network(&document_string),
|
||||
names: with_names.then(|| dump::legacy_names(&document_string)),
|
||||
});
|
||||
}
|
||||
|
||||
let archive = std::fs::read(path).map_err(|error| format!("Failed to read document {}: {error}", path.display()))?;
|
||||
let gdd = open_gdd(&archive).await?;
|
||||
let declarations = gdd.declarations(&gdd).await;
|
||||
let (network, nodes, networks) = gdd.registry().to_runtime_with_full_metadata(&declarations)?;
|
||||
let references = networks.into_iter().filter_map(|network| Some((network.network_path, network.reference?)));
|
||||
let names = nodes.into_iter().filter_map(|node| Some(([node.network_path, vec![node.local_id]].concat(), node.display_name?)));
|
||||
let names = with_names.then(|| references.chain(names).filter(|(_, name)| !name.is_empty()).collect());
|
||||
Ok(OpenedDocument { gdd: Some(gdd), network, names })
|
||||
}
|
||||
|
||||
/// A document compiled against a GPU context, ready to turn into a [`Renderer`].
|
||||
pub struct CompiledDocument {
|
||||
pub proto_network: ProtoNetwork,
|
||||
application_io: Arc<PlatformApplicationIo>,
|
||||
runtime: AsyncRuntime,
|
||||
spawner: Arc<TokioSpawner>,
|
||||
}
|
||||
|
||||
/// Compile `document` against a fresh GPU context, resolving its resources from its `.gdd`.
|
||||
pub async fn compile_document(document: OpenedDocument) -> Result<CompiledDocument, Box<dyn Error>> {
|
||||
log::info!("Creating GPU context");
|
||||
let mut application_io = PlatformApplicationIo::new().await;
|
||||
if let Some(gdd) = &document.gdd {
|
||||
application_io.inject_resource_proxy(Box::new(gdd.resource_proxy()));
|
||||
}
|
||||
let application_io = Arc::new(application_io);
|
||||
if let Some(executor) = application_io.gpu_executor() {
|
||||
let info = executor.context().adapter.get_info();
|
||||
log::info!("Rendering on {} ({:?}, {:?}, driver {})", info.name, info.backend, info.device_type, info.driver);
|
||||
}
|
||||
|
||||
let editor_api = Arc::new(PlatformEditorApi {
|
||||
application_io: Some(application_io.clone()),
|
||||
});
|
||||
let spawner = Arc::new(TokioSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone());
|
||||
|
||||
let mut network = wrap_network_in_scope(document.network, editor_api, runtime.handle());
|
||||
|
||||
// A `.gdd` resolves resource hashes from its registry; a legacy `.graphite` has no resource store
|
||||
let preprocessor = preprocessor::Preprocessor::new();
|
||||
let preprocessed = match &document.gdd {
|
||||
Some(gdd) => preprocessor.preprocess(&mut network, &|resource_id| gdd.registry().resources.get(&resource_id).and_then(|resource| resource.hash)),
|
||||
None => preprocessor.preprocess(&mut network, &|_| None),
|
||||
};
|
||||
preprocessed.map_err(|error| format!("Failed to expand network: {error:?}"))?;
|
||||
|
||||
let compiled_network = Compiler {}.compile_single(network)?;
|
||||
for warning in &compiled_network.warnings {
|
||||
eprintln!("{warning:?}");
|
||||
}
|
||||
|
||||
Ok(CompiledDocument {
|
||||
proto_network: compiled_network.network,
|
||||
application_io,
|
||||
runtime,
|
||||
spawner,
|
||||
})
|
||||
}
|
||||
|
||||
impl CompiledDocument {
|
||||
pub fn into_renderer(self) -> Result<Renderer, Box<dyn Error>> {
|
||||
let executor = DynamicExecutor::new(self.proto_network).map_err(|errors| {
|
||||
let messages: Vec<String> = errors.iter().map(|error| format!("{error:?}")).collect();
|
||||
messages.join("\n")
|
||||
})?;
|
||||
self.runtime.retain_sources(executor.sources());
|
||||
|
||||
let device = self.application_io.gpu_executor().ok_or("No GPU executor is available")?.context().device.clone();
|
||||
let polling = Arc::new(AtomicBool::new(true));
|
||||
let still_polling = polling.clone();
|
||||
std::thread::spawn(move || {
|
||||
while still_polling.load(Ordering::Relaxed) {
|
||||
std::thread::sleep(std::time::Duration::from_nanos(10));
|
||||
if let Err(error) = device.poll(wgpu::PollType::Poll) {
|
||||
log::error!("Polling the GPU device failed: {error}");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(Renderer {
|
||||
executor,
|
||||
application_io: self.application_io,
|
||||
runtime: self.runtime,
|
||||
spawner: self.spawner,
|
||||
polling,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Executes a compiled document, polling its GPU device until dropped.
|
||||
pub struct Renderer {
|
||||
pub executor: DynamicExecutor,
|
||||
pub runtime: AsyncRuntime,
|
||||
pub spawner: Arc<TokioSpawner>,
|
||||
application_io: Arc<PlatformApplicationIo>,
|
||||
polling: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl Renderer {
|
||||
pub fn wgpu_executor(&self) -> &wgpu_executor::WgpuExecutor {
|
||||
self.application_io.gpu_executor().expect("a renderer is only built with a GPU executor")
|
||||
}
|
||||
|
||||
/// Fit `settings` to the artwork, unless they give a size.
|
||||
pub async fn frame(&self, settings: export::ExportSettings) -> Result<export::ExportSettings, Box<dyn Error>> {
|
||||
settings.framed(&self.executor, &self.runtime, &self.spawner).await
|
||||
}
|
||||
|
||||
/// Render one frame at `animation_time`.
|
||||
pub async fn render(&self, settings: export::ExportSettings, animation_time: std::time::Duration) -> Result<export::RenderedFrame, Box<dyn Error>> {
|
||||
export::render_frame(&self.executor, self.wgpu_executor(), settings, animation_time, &self.runtime, &self.spawner).await
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Renderer {
|
||||
fn drop(&mut self) {
|
||||
self.polling.store(false, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the tasks nodes spawn on tokio, so an export can wait for them to settle.
|
||||
#[derive(Default)]
|
||||
pub struct TokioSpawner(Mutex<Vec<tokio::task::JoinHandle<()>>>);
|
||||
|
||||
impl Spawn for TokioSpawner {
|
||||
fn spawn(&self, task: Task) {
|
||||
self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(tokio::spawn(task));
|
||||
}
|
||||
}
|
||||
|
||||
impl TokioSpawner {
|
||||
/// Wait for every spawned task. Returns whether there were any.
|
||||
pub async fn join(&self) -> bool {
|
||||
let tasks = std::mem::take(&mut *self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner));
|
||||
let pending = !tasks.is_empty();
|
||||
for task in tasks {
|
||||
let _ = task.await;
|
||||
}
|
||||
pending
|
||||
}
|
||||
}
|
||||
@@ -1,23 +1,8 @@
|
||||
mod dump;
|
||||
mod export;
|
||||
|
||||
use clap::{Args, Parser, Subcommand};
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
use fern::colors::{Color, ColoredLevelConfig};
|
||||
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
|
||||
use graph_craft::document::*;
|
||||
use graph_craft::graphene_compiler::Compiler;
|
||||
use graph_craft::proto::ProtoNetwork;
|
||||
use graph_craft::util::load_network;
|
||||
use graphene_std::application_io::ApplicationIo;
|
||||
use graphene_std::runtime::{AsyncRuntime, RuntimeHandle, Spawn, Task};
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use graphene_cli::{compile_document, dump, export, open_document};
|
||||
use std::error::Error;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[clap(name = "graphene-cli", version)]
|
||||
@@ -108,14 +93,10 @@ struct GlobalOpts {
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let app = App::parse();
|
||||
|
||||
let log_level = app.global_opts.verbose;
|
||||
init_logging(app.global_opts.verbose);
|
||||
|
||||
init_logging(log_level);
|
||||
|
||||
let document_path = match app.command {
|
||||
Command::Compile { ref document, .. } => document,
|
||||
Command::Export { ref document, .. } => document,
|
||||
Command::ExtractLegacyDoc { ref document } => document,
|
||||
let document_path = match &app.command {
|
||||
Command::Compile { document, .. } | Command::Export { document, .. } | Command::ExtractLegacyDoc { document } => document,
|
||||
Command::ListNodeIdentifiers => {
|
||||
let mut nodes: Vec<_> = graphene_std::registry::NODE_METADATA.lock().unwrap().keys().cloned().collect();
|
||||
nodes.sort_by_key(|x| x.as_str().to_string());
|
||||
@@ -126,79 +107,31 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
||||
}
|
||||
};
|
||||
|
||||
// Load the document by extension: `.gdd` opens the new archive format, anything else is treated as a
|
||||
// legacy `.graphite` document. The legacy path has no `Gdd`, so resources fall back to the default registry.
|
||||
let is_gdd = document_path.extension().is_some_and(|extension| extension.eq_ignore_ascii_case("gdd"));
|
||||
let print = matches!(app.command, Command::Compile { format: Some(_), .. });
|
||||
let mut document = open_document(document_path, print).await?;
|
||||
|
||||
let gdd = if is_gdd {
|
||||
let archive = std::fs::read(document_path).map_err(|error| format!("Failed to read document {}: {error}", document_path.display()))?;
|
||||
let container = AnyContainer::Memory(MemoryBackend::new());
|
||||
let gdd = document_format::Gdd::open_from_archive(archive.as_ref(), container, GddV1Layout)
|
||||
.await
|
||||
.map_err(|error| format!("Failed to open document: {error}"))?;
|
||||
Some(gdd)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if let Command::ExtractLegacyDoc { ref document } = app.command {
|
||||
let Some(gdd) = &gdd else { return Err("ExtractLegacyDoc requires a .gdd document".into()) };
|
||||
if let Command::ExtractLegacyDoc { document: path } = &app.command {
|
||||
let Some(gdd) = &document.gdd else {
|
||||
return Err("ExtractLegacyDoc requires a .gdd document".into());
|
||||
};
|
||||
let Some(legacy_doc) = gdd.read_legacy_document().await else {
|
||||
return Err("gdd file did not contain a legacy .graphite document".into());
|
||||
};
|
||||
let mut new_path = document.clone();
|
||||
new_path.set_extension("graphite");
|
||||
let new_path = path.with_extension("graphite");
|
||||
std::fs::write(&new_path, legacy_doc).map_err(|error| format!("Failed to write .graphite file: {error}"))?;
|
||||
eprintln!("Saved file to {}", new_path.to_string_lossy());
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Build the runtime network: from the `.gdd` registry, or by loading a legacy `.graphite` document.
|
||||
let print = matches!(app.command, Command::Compile { format: Some(_), .. });
|
||||
let (node_network, names) = match &gdd {
|
||||
Some(gdd) => {
|
||||
let declarations = gdd.declarations(gdd).await;
|
||||
let (node_network, nodes, networks) = gdd.registry().to_runtime_with_full_metadata(&declarations)?;
|
||||
let references = networks.into_iter().filter_map(|network| Some((network.network_path, network.reference?)));
|
||||
let names = nodes.into_iter().filter_map(|node| Some(([node.network_path, vec![node.local_id]].concat(), node.display_name?)));
|
||||
(node_network, print.then(|| references.chain(names).filter(|(_, name)| !name.is_empty()).collect()))
|
||||
}
|
||||
None => {
|
||||
let document_string = std::fs::read_to_string(document_path).map_err(|error| format!("Failed to read document {}: {error}", document_path.display()))?;
|
||||
(load_network(&document_string), print.then(|| dump::legacy_names(&document_string)))
|
||||
}
|
||||
};
|
||||
let document = names.map(|names| dump::document(&node_network, names));
|
||||
|
||||
log::info!("Creating GPU context");
|
||||
let mut application_io = PlatformApplicationIo::new().await;
|
||||
if let Some(gdd) = &gdd {
|
||||
application_io.inject_resource_proxy(Box::new(gdd.resource_proxy()));
|
||||
}
|
||||
|
||||
// Convert application_io to Arc first
|
||||
let application_io_arc = Arc::new(application_io);
|
||||
|
||||
// Clone the application_io Arc before borrowing to extract executor
|
||||
let application_io_for_api = application_io_arc.clone();
|
||||
|
||||
// Get reference to wgpu executor and clone device handle
|
||||
let wgpu_executor_ref = application_io_arc.gpu_executor().unwrap();
|
||||
let device = wgpu_executor_ref.context().device.clone();
|
||||
|
||||
let editor_api = Arc::new(PlatformEditorApi {
|
||||
application_io: Some(application_io_for_api),
|
||||
});
|
||||
let spawner = Arc::new(TokioSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone());
|
||||
let proto_graph = compile_graph(node_network, editor_api, gdd.as_ref(), runtime.handle())?;
|
||||
let dump_document = document.names.take().map(|names| dump::document(&document.network, names));
|
||||
let compiled = compile_document(document).await?;
|
||||
|
||||
match app.command {
|
||||
Command::Compile {
|
||||
format, upstream, downstream, depth, ..
|
||||
} => {
|
||||
if let Some((format, document)) = format.zip(document) {
|
||||
dump::print(&proto_graph, &document, format, upstream.as_deref(), downstream.as_deref(), depth)?;
|
||||
if let Some((format, dump_document)) = format.zip(dump_document) {
|
||||
dump::print(&compiled.proto_network, &dump_document, format, upstream.as_deref(), downstream.as_deref(), depth)?;
|
||||
}
|
||||
}
|
||||
Command::Export {
|
||||
@@ -212,48 +145,36 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
||||
duration,
|
||||
..
|
||||
} => {
|
||||
// Spawn thread to poll GPU device
|
||||
std::thread::spawn(move || {
|
||||
loop {
|
||||
std::thread::sleep(std::time::Duration::from_nanos(10));
|
||||
device.poll(wgpu::PollType::Poll).unwrap();
|
||||
}
|
||||
});
|
||||
|
||||
// Detect output file type
|
||||
let file_type = export::detect_file_type(&output)?;
|
||||
|
||||
// Create executor
|
||||
let executor = create_executor(proto_graph)?;
|
||||
runtime.retain_sources(executor.sources());
|
||||
|
||||
if fps <= 0. {
|
||||
return Err("Fps number must be positive".into());
|
||||
}
|
||||
|
||||
// Perform export based on file type, where a multi-frame export to a format besides GIF becomes a numbered image sequence
|
||||
let renderer = compiled.into_renderer()?;
|
||||
let (executor, wgpu_executor, runtime, spawner) = (&renderer.executor, renderer.wgpu_executor(), &renderer.runtime, renderer.spawner.as_ref());
|
||||
|
||||
// A multi-frame export to a format besides GIF becomes a numbered image sequence
|
||||
let settings = export::ExportSettings {
|
||||
file_type,
|
||||
scale,
|
||||
size: (width, height),
|
||||
transparent,
|
||||
framing: None,
|
||||
}
|
||||
.framed(&executor, &runtime, &spawner)
|
||||
.await?;
|
||||
};
|
||||
let settings = renderer.frame(settings).await?;
|
||||
let animation = export::AnimationParams::new(fps, frames, duration);
|
||||
if file_type == export::FileType::Gif {
|
||||
export::export_gif(&executor, wgpu_executor_ref, output, settings, animation, &runtime, &spawner).await?;
|
||||
export::export_gif(executor, wgpu_executor, output, settings, animation, runtime, spawner).await?;
|
||||
} else if animation.frames > 1 {
|
||||
if file_type == export::FileType::Ico {
|
||||
return Err("ICO can't be exported as an image sequence".into());
|
||||
}
|
||||
export::export_image_sequence(&executor, wgpu_executor_ref, output, settings, animation, &runtime, &spawner).await?;
|
||||
export::export_image_sequence(executor, wgpu_executor, output, settings, animation, runtime, spawner).await?;
|
||||
} else {
|
||||
export::export_document(&executor, wgpu_executor_ref, output, settings, &runtime, &spawner).await?;
|
||||
export::export_document(executor, wgpu_executor, output, settings, runtime, spawner).await?;
|
||||
}
|
||||
}
|
||||
_ => unreachable!("All other commands should be handled before this match statement is run"),
|
||||
Command::ListNodeIdentifiers | Command::ExtractLegacyDoc { .. } => unreachable!("Handled before compiling"),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -287,50 +208,3 @@ fn init_logging(log_level: u8) {
|
||||
.apply()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn compile_graph(network: NodeNetwork, editor_api: Arc<PlatformEditorApi>, gdd: Option<&GddV1>, runtime: RuntimeHandle) -> Result<ProtoNetwork, Box<dyn Error>> {
|
||||
let preprocessor = preprocessor::Preprocessor::new();
|
||||
|
||||
let mut network = wrap_network_in_scope(network, editor_api, runtime);
|
||||
|
||||
// A `.gdd` resolves resource hashes from its registry; a legacy `.graphite` has no resource store, so it
|
||||
// preprocesses against an empty registry (matching the pre-`.gdd` CLI behavior).
|
||||
match gdd {
|
||||
Some(gdd) => preprocessor
|
||||
.preprocess(&mut network, &|resource_id| gdd.registry().resources.get(&resource_id).and_then(|r| r.hash))
|
||||
.expect("Failed to expand network"),
|
||||
None => { preprocessor.preprocess(&mut network, &|_| None) }.expect("Failed to expand network"),
|
||||
}
|
||||
|
||||
let compiler = Compiler {};
|
||||
let compiled_network = compiler.compile_single(network)?;
|
||||
for warning in &compiled_network.warnings {
|
||||
eprintln!("{warning:?}");
|
||||
}
|
||||
Ok(compiled_network.network)
|
||||
}
|
||||
|
||||
fn create_executor(proto_network: ProtoNetwork) -> Result<DynamicExecutor, Box<dyn Error>> {
|
||||
let executor = DynamicExecutor::new(proto_network).map_err(|errors| errors.iter().map(|e| format!("{e:?}")).reduce(|acc, e| format!("{acc}\n{e}")).unwrap_or_default())?;
|
||||
Ok(executor)
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct TokioSpawner(Mutex<Vec<tokio::task::JoinHandle<()>>>);
|
||||
|
||||
impl Spawn for TokioSpawner {
|
||||
fn spawn(&self, task: Task) {
|
||||
self.0.lock().unwrap().push(tokio::spawn(task));
|
||||
}
|
||||
}
|
||||
|
||||
impl TokioSpawner {
|
||||
pub(crate) async fn join(&self) -> bool {
|
||||
let tasks = std::mem::take(&mut *self.0.lock().unwrap());
|
||||
let pending = !tasks.is_empty();
|
||||
for task in tasks {
|
||||
let _ = task.await;
|
||||
}
|
||||
pending
|
||||
}
|
||||
}
|
||||
@@ -450,6 +450,8 @@ Every migration ships with:
|
||||
- **Fixtures.** Small source graphs built in the test and assertions on the migrated result.
|
||||
- **The commutation property.** For generated histories `H` over the source declaration, including concurrent branches, `replay(rewrite(H)) == M(replay(H))`. This is the definition of a correct rewrite, so a migration that passes it needs no hand-written history tests. The generator also produces the reachable source states that expose `unrepresentable` failures.
|
||||
|
||||
Whole documents are covered by a regression corpus: a separate git repository of `.gdd` documents with reference renders at chosen animation times, which `cargo run regression check` renders and compares within a per-document tolerance. `add` and `bless` record references, and `upgrade` rewrites documents (by default `demo-artwork/*.gdd`) through the migrations of the current build, so a migration shows up in the corpus as a document change whose renders still match.
|
||||
|
||||
## Crate layout
|
||||
|
||||
```
|
||||
|
||||
@@ -11,6 +11,7 @@ pub enum Action {
|
||||
Explore(Option<String>),
|
||||
Drive,
|
||||
Migration,
|
||||
Regression,
|
||||
}
|
||||
|
||||
pub enum Target {
|
||||
@@ -54,6 +55,16 @@ impl Task {
|
||||
});
|
||||
}
|
||||
|
||||
// Everything after `regression` belongs to the document regression tool
|
||||
if args.first() == Some(&"regression") {
|
||||
return Some(Task {
|
||||
action: Action::Regression,
|
||||
target: Target::Cli,
|
||||
profile: Profile::Default,
|
||||
args: args[1..].iter().map(|s| s.to_string()).collect(),
|
||||
});
|
||||
}
|
||||
|
||||
let split = args.iter().position(|a| *a == "--").unwrap_or(args.len());
|
||||
let passthru_args = args[split..].iter().skip(1).map(|s| s.to_string()).collect();
|
||||
let args = &args[..split];
|
||||
|
||||
@@ -19,6 +19,7 @@ fn usage() {
|
||||
println!(" explore Open an assortment of tools for exploring the codebase");
|
||||
println!(" drive Drive the web editor in an isolated browser (see `cargo run drive help`)");
|
||||
println!(" migration Freeze the stored format or scaffold node migrations (see `cargo run migration help`)");
|
||||
println!(" regression Upgrade documents and check renders of the regression corpus (see `cargo run regression help`)");
|
||||
println!(" help Show this message");
|
||||
println!("<target>:");
|
||||
println!(" [web] Web app (default)");
|
||||
@@ -53,7 +54,10 @@ fn main() -> ExitCode {
|
||||
return drive(&task);
|
||||
}
|
||||
if matches!(task.action, Action::Migration) {
|
||||
return migration(&task);
|
||||
return delegate("migration-snapshot", &task);
|
||||
}
|
||||
if matches!(task.action, Action::Regression) {
|
||||
return delegate("regression", &task);
|
||||
}
|
||||
|
||||
if let Err(e) = run_task(&task) {
|
||||
@@ -106,8 +110,8 @@ fn drive(task: &Task) -> ExitCode {
|
||||
}
|
||||
|
||||
// Exits with the tool's own status, so CI reads a failed check from it
|
||||
fn migration(task: &Task) -> ExitCode {
|
||||
let tool = cmd!("cargo", "run", "--quiet", "--package", "migration-snapshot", "--").args(&task.args).unchecked();
|
||||
fn delegate(package: &str, task: &Task) -> ExitCode {
|
||||
let tool = cmd!("cargo", "run", "--quiet", "--package", package, "--").args(&task.args).unchecked();
|
||||
match Expression::run(&tool) {
|
||||
Ok(output) => ExitCode::from(output.status.code().and_then(|code| u8::try_from(code).ok()).unwrap_or(1)),
|
||||
Err(e) => {
|
||||
@@ -161,7 +165,7 @@ fn run_task(task: &Task) -> Result<(), Error> {
|
||||
profile = match action {
|
||||
Action::Run => &Profile::Debug,
|
||||
Action::Build => &Profile::Release,
|
||||
Action::Explore(_) | Action::Drive | Action::Migration => unreachable!(),
|
||||
Action::Explore(_) | Action::Drive | Action::Migration | Action::Regression => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -188,7 +192,7 @@ fn run_task(task: &Task) -> Result<(), Error> {
|
||||
(Action::Build, Target::Cli, Profile::Debug) => cmd!("cargo", "build", "-p", "graphene-cli").run()?,
|
||||
(Action::Build, Target::Cli, Profile::Release | Profile::Default) => cmd!("cargo", "build", "-r", "-p", "graphene-cli").run()?,
|
||||
|
||||
(Action::Explore(_) | Action::Drive | Action::Migration, _, _) => unreachable!(),
|
||||
(Action::Explore(_) | Action::Drive | Action::Migration | Action::Regression, _, _) => unreachable!(),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
[package]
|
||||
name = "regression"
|
||||
description = "Upgrades Graphite documents through their migrations and checks renders of a document corpus against reference images"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
readme.workspace = true
|
||||
homepage.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
# Local dependencies
|
||||
graphene-cli = { path = "../../node-graph/graphene-cli" }
|
||||
document-format = { workspace = true, features = ["zip", "xz", "migrations"] }
|
||||
|
||||
# Workspace dependencies
|
||||
clap = { workspace = true, features = ["derive"] }
|
||||
fern = { workspace = true }
|
||||
image = { workspace = true }
|
||||
log = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
@@ -0,0 +1,82 @@
|
||||
//! Compares a render to its reference pixel by pixel.
|
||||
|
||||
use crate::corpus::Tolerance;
|
||||
use image::RgbaImage;
|
||||
|
||||
pub enum Comparison {
|
||||
Matches,
|
||||
SizeChanged {
|
||||
reference: (u32, u32),
|
||||
actual: (u32, u32),
|
||||
},
|
||||
/// More pixels than the tolerance allows differ, highlighted in `diff`.
|
||||
Differs {
|
||||
differing: usize,
|
||||
total: usize,
|
||||
diff: RgbaImage,
|
||||
},
|
||||
}
|
||||
|
||||
/// O(pixels).
|
||||
pub fn compare(reference: &RgbaImage, actual: &RgbaImage, tolerance: Tolerance) -> Comparison {
|
||||
if reference.dimensions() != actual.dimensions() {
|
||||
return Comparison::SizeChanged {
|
||||
reference: reference.dimensions(),
|
||||
actual: actual.dimensions(),
|
||||
};
|
||||
}
|
||||
|
||||
// Differing pixels show red over a faded copy of the reference, so they stand out in context
|
||||
let mut diff = RgbaImage::new(actual.width(), actual.height());
|
||||
let mut differing = 0;
|
||||
for ((expected, rendered), marked) in reference.pixels().zip(actual.pixels()).zip(diff.pixels_mut()) {
|
||||
let largest_difference = expected.0.iter().zip(rendered.0).map(|(a, b)| a.abs_diff(b)).max().unwrap_or_default();
|
||||
if largest_difference > tolerance.channel {
|
||||
differing += 1;
|
||||
*marked = image::Rgba([255, 0, 0, 255]);
|
||||
} else {
|
||||
let [red, green, blue, alpha] = expected.0;
|
||||
let luminance = ((red as u32 * 3 + green as u32 * 6 + blue as u32) / 10) as u8;
|
||||
*marked = image::Rgba([luminance, luminance, luminance, alpha / 4]);
|
||||
}
|
||||
}
|
||||
|
||||
let total = (actual.width() * actual.height()) as usize;
|
||||
if differing as f64 > tolerance.pixels * total as f64 {
|
||||
Comparison::Differs { differing, total, diff }
|
||||
} else {
|
||||
Comparison::Matches
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn image_of(pixels: &[[u8; 4]]) -> RgbaImage {
|
||||
RgbaImage::from_raw(pixels.len() as u32, 1, pixels.concat()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_differences_and_few_pixels_are_tolerated() {
|
||||
let reference = image_of(&[[10, 10, 10, 255]; 4]);
|
||||
let close = image_of(&[[12, 9, 10, 255]; 4]);
|
||||
assert!(matches!(compare(&reference, &close, Tolerance::default()), Comparison::Matches));
|
||||
|
||||
let one_off = image_of(&[[10, 10, 10, 255], [10, 10, 10, 255], [10, 10, 10, 255], [200, 10, 10, 255]]);
|
||||
let lenient = Tolerance { channel: 2, pixels: 0.25 };
|
||||
assert!(matches!(compare(&reference, &one_off, lenient), Comparison::Matches));
|
||||
|
||||
let Comparison::Differs { differing, total, diff } = compare(&reference, &one_off, Tolerance::default()) else {
|
||||
panic!("one pixel in four exceeds the default tolerance");
|
||||
};
|
||||
assert_eq!((differing, total), (1, 4));
|
||||
assert_eq!(diff.get_pixel(3, 0).0, [255, 0, 0, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_size_change_never_matches() {
|
||||
let comparison = compare(&image_of(&[[0; 4]; 2]), &image_of(&[[0; 4]; 3]), Tolerance::default());
|
||||
assert!(matches!(comparison, Comparison::SizeChanged { reference: (2, 1), actual: (3, 1) }));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
//! The regression corpus: a directory, usually a git repository of its own, holding `.gdd` documents and the images they must render.
|
||||
//!
|
||||
//! ```text
|
||||
//! corpus.json Which documents to render, how, and how closely they must match
|
||||
//! documents/<name>.gdd
|
||||
//! references/<name>/<time>s.png One reference per animation time
|
||||
//! ```
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub const MANIFEST: &str = "corpus.json";
|
||||
|
||||
#[derive(Debug, Default, Serialize, Deserialize)]
|
||||
pub struct Manifest {
|
||||
pub documents: Vec<Entry>,
|
||||
}
|
||||
|
||||
/// One document and how it renders.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Entry {
|
||||
pub name: String,
|
||||
/// Animation times in seconds, each rendered to its own reference.
|
||||
#[serde(default = "Entry::default_times")]
|
||||
pub times: Vec<f64>,
|
||||
#[serde(default = "Entry::default_scale")]
|
||||
pub scale: f64,
|
||||
/// Output size in pixels, since a render without one is a single pixel.
|
||||
pub size: (u32, u32),
|
||||
#[serde(default)]
|
||||
pub tolerance: Tolerance,
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
pub fn new(name: String, times: Vec<f64>, scale: f64, size: (u32, u32)) -> Self {
|
||||
Self {
|
||||
name,
|
||||
times,
|
||||
scale,
|
||||
size,
|
||||
tolerance: Tolerance::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn default_times() -> Vec<f64> {
|
||||
vec![0.]
|
||||
}
|
||||
|
||||
fn default_scale() -> f64 {
|
||||
1.
|
||||
}
|
||||
}
|
||||
|
||||
/// How far a render may drift from its reference, since GPUs and drivers round differently.
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
|
||||
pub struct Tolerance {
|
||||
/// The largest difference of one channel, out of 255, that still counts as the same pixel.
|
||||
pub channel: u8,
|
||||
/// The share of pixels that may differ by more than `channel`.
|
||||
pub pixels: f64,
|
||||
}
|
||||
|
||||
impl Default for Tolerance {
|
||||
fn default() -> Self {
|
||||
Self { channel: 2, pixels: 0.001 }
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Corpus {
|
||||
pub root: PathBuf,
|
||||
pub manifest: Manifest,
|
||||
}
|
||||
|
||||
impl Corpus {
|
||||
/// Open the corpus at `root`, starting an empty one if it has no manifest yet.
|
||||
pub fn open(root: &Path) -> Result<Self, String> {
|
||||
let manifest_path = root.join(MANIFEST);
|
||||
let manifest = match std::fs::read_to_string(&manifest_path) {
|
||||
Ok(text) => serde_json::from_str(&text).map_err(|error| format!("{}: {error}", manifest_path.display()))?,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Manifest::default(),
|
||||
Err(error) => return Err(format!("{}: {error}", manifest_path.display())),
|
||||
};
|
||||
Ok(Self { root: root.to_path_buf(), manifest })
|
||||
}
|
||||
|
||||
pub fn save(&self) -> Result<(), String> {
|
||||
let manifest_path = self.root.join(MANIFEST);
|
||||
let text = serde_json::to_string_pretty(&self.manifest).map_err(|error| error.to_string())?;
|
||||
std::fs::write(&manifest_path, text + "\n").map_err(|error| format!("{}: {error}", manifest_path.display()))
|
||||
}
|
||||
|
||||
pub fn document(&self, name: &str) -> PathBuf {
|
||||
self.root.join("documents").join(format!("{name}.gdd"))
|
||||
}
|
||||
|
||||
pub fn reference(&self, name: &str, time: f64) -> PathBuf {
|
||||
self.root.join("references").join(name).join(format!("{time:.3}s.png"))
|
||||
}
|
||||
|
||||
/// The entries `names` selects, or every entry when it's empty.
|
||||
pub fn select(&self, names: &[String]) -> Result<Vec<Entry>, String> {
|
||||
if names.is_empty() {
|
||||
return Ok(self.manifest.documents.clone());
|
||||
}
|
||||
|
||||
names
|
||||
.iter()
|
||||
.map(|name| {
|
||||
let entry = self.manifest.documents.iter().find(|entry| &entry.name == name);
|
||||
entry.cloned().ok_or_else(|| format!("the corpus has no document `{name}`"))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Add `entry`, replacing an entry of the same name.
|
||||
pub fn insert(&mut self, entry: Entry) {
|
||||
self.manifest.documents.retain(|existing| existing.name != entry.name);
|
||||
self.manifest.documents.push(entry);
|
||||
self.manifest.documents.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
mod compare;
|
||||
mod corpus;
|
||||
mod render;
|
||||
mod upgrade;
|
||||
|
||||
use clap::{Parser, Subcommand};
|
||||
use compare::Comparison;
|
||||
use corpus::{Corpus, Entry};
|
||||
use std::error::Error;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
|
||||
const CORPUS_VARIABLE: &str = "GRAPHITE_REGRESSION_CORPUS";
|
||||
|
||||
#[derive(Parser)]
|
||||
#[clap(name = "regression", about = "Upgrade Graphite documents and check renders of the regression corpus against its references")]
|
||||
struct App {
|
||||
/// The corpus directory, by default from the GRAPHITE_REGRESSION_CORPUS environment variable
|
||||
#[clap(long, global = true)]
|
||||
corpus: Option<PathBuf>,
|
||||
|
||||
#[clap(subcommand)]
|
||||
command: Command,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Command {
|
||||
/// Rewrite .gdd files through the migrations of this build, as state-only documents
|
||||
Upgrade {
|
||||
/// Documents, or directories whose .gdd files to upgrade
|
||||
#[clap(default_value = "demo-artwork")]
|
||||
paths: Vec<PathBuf>,
|
||||
},
|
||||
/// Copy a document into the corpus and render its references
|
||||
Add {
|
||||
document: PathBuf,
|
||||
/// Name in the corpus, by default the file name
|
||||
#[clap(long)]
|
||||
name: Option<String>,
|
||||
/// Animation times in seconds to render, each to its own reference
|
||||
#[clap(long, value_delimiter = ',', default_value = "0")]
|
||||
times: Vec<f64>,
|
||||
#[clap(long, default_value = "1")]
|
||||
scale: f64,
|
||||
/// Output size in pixels, as WIDTHxHEIGHT
|
||||
#[clap(long, default_value = "1024x1024", value_parser = parse_size)]
|
||||
size: (u32, u32),
|
||||
},
|
||||
/// Render the references again, after an intended change in how documents look
|
||||
Bless {
|
||||
/// Documents to render, by default all of them
|
||||
names: Vec<String>,
|
||||
},
|
||||
/// Render the corpus and compare each image to its reference
|
||||
Check {
|
||||
/// Documents to check, by default all of them
|
||||
names: Vec<String>,
|
||||
/// Where to write the renders and diffs of mismatches
|
||||
#[clap(long, default_value = "target/regression")]
|
||||
output: PathBuf,
|
||||
},
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExitCode {
|
||||
let app = App::parse();
|
||||
init_logging();
|
||||
|
||||
match run(app).await {
|
||||
Ok(true) => ExitCode::SUCCESS,
|
||||
Ok(false) => ExitCode::FAILURE,
|
||||
Err(error) => {
|
||||
eprintln!("Error: {error}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether every document passed.
|
||||
async fn run(app: App) -> Result<bool, Box<dyn Error>> {
|
||||
let corpus_root = || {
|
||||
app.corpus
|
||||
.clone()
|
||||
.or_else(|| std::env::var_os(CORPUS_VARIABLE).map(PathBuf::from))
|
||||
.ok_or(format!("pass --corpus or set {CORPUS_VARIABLE}"))
|
||||
};
|
||||
|
||||
match app.command {
|
||||
Command::Upgrade { paths } => {
|
||||
for path in upgrade::expand(&paths)? {
|
||||
let changed = upgrade::upgrade(&path).await.map_err(|error| format!("{}: {error}", path.display()))?;
|
||||
println!("{} {}", if changed { "Upgraded" } else { "Up to date" }, path.display());
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
Command::Add { document, name, times, scale, size } => {
|
||||
let mut corpus = Corpus::open(&corpus_root()?)?;
|
||||
let name = match name {
|
||||
Some(name) => name,
|
||||
None => document.file_stem().and_then(|stem| stem.to_str()).ok_or("the document has no file name")?.to_string(),
|
||||
};
|
||||
|
||||
let destination = corpus.document(&name);
|
||||
create_parent(&destination)?;
|
||||
std::fs::copy(&document, &destination)?;
|
||||
|
||||
let entry = Entry::new(name, times, scale, size);
|
||||
bless(&corpus, &entry).await?;
|
||||
corpus.insert(entry);
|
||||
corpus.save()?;
|
||||
Ok(true)
|
||||
}
|
||||
Command::Bless { names } => {
|
||||
let corpus = Corpus::open(&corpus_root()?)?;
|
||||
for entry in corpus.select(&names)? {
|
||||
bless(&corpus, &entry).await?;
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
Command::Check { names, output } => {
|
||||
let corpus = Corpus::open(&corpus_root()?)?;
|
||||
let mut passed = true;
|
||||
for entry in corpus.select(&names)? {
|
||||
passed &= check(&corpus, &entry, &output).await;
|
||||
}
|
||||
Ok(passed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn bless(corpus: &Corpus, entry: &Entry) -> Result<(), Box<dyn Error>> {
|
||||
let images = render::render(&corpus.document(&entry.name), entry).await?;
|
||||
for (time, image) in entry.times.iter().zip(images) {
|
||||
let reference = corpus.reference(&entry.name, *time);
|
||||
create_parent(&reference)?;
|
||||
image.save(&reference)?;
|
||||
println!("Rendered {}", reference.display());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether every time of `entry` matches its reference. Mismatches leave their render and diff in `output`.
|
||||
async fn check(corpus: &Corpus, entry: &Entry, output: &Path) -> bool {
|
||||
let images = match render::render(&corpus.document(&entry.name), entry).await {
|
||||
Ok(images) => images,
|
||||
Err(error) => {
|
||||
println!("FAIL {}: rendering failed: {error}", entry.name);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
let mut passed = true;
|
||||
for (time, actual) in entry.times.iter().zip(images) {
|
||||
let label = format!("{} at {time:.3}s", entry.name);
|
||||
let reference = match image::open(corpus.reference(&entry.name, *time)) {
|
||||
Ok(reference) => reference.into_rgba8(),
|
||||
Err(error) => {
|
||||
println!("FAIL {label}: no reference ({error}). Run `bless {}`", entry.name);
|
||||
passed = false;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let (reason, diff) = match compare::compare(&reference, &actual, entry.tolerance) {
|
||||
Comparison::Matches => {
|
||||
println!("ok {label}");
|
||||
continue;
|
||||
}
|
||||
Comparison::SizeChanged { reference, actual } => (format!("the size changed from {reference:?} to {actual:?}"), None),
|
||||
Comparison::Differs { differing, total, diff } => (format!("{differing} of {total} pixels differ"), Some(diff)),
|
||||
};
|
||||
passed = false;
|
||||
|
||||
let written = save_mismatch(output, &entry.name, *time, &actual, diff.as_ref());
|
||||
let location = written.map_or_else(|error| format!("writing the mismatch failed: {error}"), |directory| format!("see {}", directory.display()));
|
||||
println!("FAIL {label}: {reason}, {location}");
|
||||
}
|
||||
passed
|
||||
}
|
||||
|
||||
fn save_mismatch(output: &Path, name: &str, time: f64, actual: &image::RgbaImage, diff: Option<&image::RgbaImage>) -> Result<PathBuf, Box<dyn Error>> {
|
||||
let directory = output.join(name);
|
||||
std::fs::create_dir_all(&directory)?;
|
||||
actual.save(directory.join(format!("{time:.3}s.actual.png")))?;
|
||||
if let Some(diff) = diff {
|
||||
diff.save(directory.join(format!("{time:.3}s.diff.png")))?;
|
||||
}
|
||||
Ok(directory)
|
||||
}
|
||||
|
||||
fn parse_size(size: &str) -> Result<(u32, u32), String> {
|
||||
let (width, height) = size.split_once('x').ok_or("expected WIDTHxHEIGHT")?;
|
||||
let dimension = |text: &str| text.parse::<u32>().map_err(|error| format!("{text}: {error}"));
|
||||
Ok((dimension(width)?, dimension(height)?))
|
||||
}
|
||||
|
||||
fn create_parent(path: &Path) -> Result<(), Box<dyn Error>> {
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Migration progress and errors, without the GPU stack's chatter.
|
||||
fn init_logging() {
|
||||
let result = fern::Dispatch::new()
|
||||
.level(log::LevelFilter::Off)
|
||||
.level_for("document_format", log::LevelFilter::Info)
|
||||
.level_for("graphene_cli", log::LevelFilter::Warn)
|
||||
.format(|out, message, record| out.finish(format_args!("[{}] {message}", record.level())))
|
||||
.chain(std::io::stderr())
|
||||
.apply();
|
||||
if let Err(error) = result {
|
||||
eprintln!("Setting up logging failed: {error}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
//! Renders a corpus document at each of its animation times.
|
||||
|
||||
use crate::corpus::Entry;
|
||||
use graphene_cli::export::{ExportSettings, FileType, RenderedFrame};
|
||||
use graphene_cli::{compile_document, open_document};
|
||||
use image::RgbaImage;
|
||||
use std::error::Error;
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
|
||||
/// One image per time in `entry.times`, with straight alpha so transparency regressions show.
|
||||
pub async fn render(document: &Path, entry: &Entry) -> Result<Vec<RgbaImage>, Box<dyn Error>> {
|
||||
let renderer = compile_document(open_document(document, false).await?).await?.into_renderer()?;
|
||||
let settings = ExportSettings {
|
||||
file_type: FileType::Png,
|
||||
scale: entry.scale,
|
||||
size: (Some(entry.size.0), Some(entry.size.1)),
|
||||
transparent: true,
|
||||
framing: None,
|
||||
};
|
||||
|
||||
let mut images = Vec::with_capacity(entry.times.len());
|
||||
for time in &entry.times {
|
||||
let RenderedFrame::Raster { data, width, height } = renderer.render(settings, Duration::from_secs_f64(*time)).await? else {
|
||||
return Err("a PNG export rendered SVG".into());
|
||||
};
|
||||
images.push(RgbaImage::from_raw(width, height, data).ok_or("the render has fewer pixels than its size")?);
|
||||
}
|
||||
Ok(images)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
//! Rewrites `.gdd` files through the migrations this build links.
|
||||
|
||||
use document_format::{ExportFormat, ExportOptions};
|
||||
use std::error::Error;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// `paths`, with each directory replaced by the `.gdd` files directly in it.
|
||||
pub fn expand(paths: &[PathBuf]) -> Result<Vec<PathBuf>, Box<dyn Error>> {
|
||||
let mut documents = Vec::new();
|
||||
for path in paths {
|
||||
if !path.is_dir() {
|
||||
documents.push(path.clone());
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut found: Vec<PathBuf> = std::fs::read_dir(path)?
|
||||
.filter_map(Result::ok)
|
||||
.map(|entry| entry.path())
|
||||
.filter(|path| path.extension().is_some_and(|extension| extension == "gdd"))
|
||||
.collect();
|
||||
found.sort();
|
||||
documents.extend(found);
|
||||
}
|
||||
Ok(documents)
|
||||
}
|
||||
|
||||
/// Open `path`, which migrates it, and save it back as a state-only xz archive if it needed migrating. Returns whether it did.
|
||||
///
|
||||
/// An archive's bytes aren't stable across a reopen, so the file is only rewritten when it changed. The embedded legacy `.graphite` is dropped, since it doesn't migrate and the editor would open it in place of the migrated state.
|
||||
pub async fn upgrade(path: &Path) -> Result<bool, Box<dyn Error>> {
|
||||
let archive = std::fs::read(path)?;
|
||||
let gdd = graphene_cli::open_gdd(&archive).await?;
|
||||
if !gdd.migrated() {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
let options = ExportOptions {
|
||||
include_history: false,
|
||||
..Default::default()
|
||||
};
|
||||
let upgraded = gdd.export_to_bytes(ExportFormat::Xz, options, &gdd, None).await?;
|
||||
std::fs::write(path, upgraded)?;
|
||||
Ok(true)
|
||||
}
|
||||
Reference in new issue
Block a user