From dc5b37c68f6a6ce767f2d494761550fe7a7eee12 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Sat, 21 Nov 2026 10:57:43 -0500 Subject: [PATCH] Keep portable links for unchanged library functions on save --- crates/engine/src/file_cmds.rs | 27 ++++++++++++++++++++++- crates/engine/tests/session.rs | 36 +++++++++++++++++++++++++++++++ crates/formats/src/sbs/library.rs | 31 ++++++++++++++++++++++++++ docs/parity-fixes.md | 22 +++++++++++++++++++ docs/sbs-root-nodes.md | 2 +- 5 files changed, 116 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index f559015d..96c86df5 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -214,15 +214,40 @@ fn package_for_save(session: &Session, path: Option<&str>) -> Package { } } + let mut packages = std::collections::BTreeMap::new(); for instance in package.graphs.iter_mut().flat_map(|graph| graph.instances_mut()) { if !instance.package.is_empty() { - instance.package = crate::document_path::relative(path, &instance.package); + let source = std::mem::take(&mut instance.package); + let reference = packages.entry(source).or_insert_with_key(|source| package_reference(&session.pkg, path, source)); + instance.package.clone_from(reference); } } } package } +fn package_reference(_package: &Package, destination: &str, source: &str) -> String { + #[cfg(not(target_arch = "wasm32"))] + { + use materialcraft_formats::sbs::library; + use std::path::Path; + + // A function library with external calls or resources can rely on other local edits. + if Path::new(source).is_absolute() + && let Some(dependency) = _package.dependencies.get(source) + && dependency.resources.is_empty() + && !dependency.graphs.is_empty() + && dependency.graphs.iter().all(|graph| graph.function.is_some() && graph.instances().all(|instance| instance.package.is_empty())) + && !library::contains_file(Path::new(destination)) + && let Ok(root) = library::root().canonicalize() + && let Some(uri) = library::bundled_package_uri(&root, Path::new(source)) + { + return uri; + } + } + crate::document_path::relative(destination, source) +} + pub fn save_files_at(session: &Session, path: &str) -> Result { session.package(session.document_id)?; let archive = is_mcraft(path); diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 5aa7cd8e..5688fa47 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -170,6 +170,42 @@ fn native_sbs_is_the_default_save_format() { assert_eq!(run(&mut session, "file.save", json!({}))["path"], json!(saved)); } +#[test] +fn saving_a_library_graph_opened_from_disk_keeps_its_portable_function_links() { + let directory = TempDir::new("library-function-export"); + let name = "waveform_01_v2.sbs"; + let library = materialcraft_engine::formats::sbs::library::root(); + let mut session = sample_session(); + for (index, source) in [library.join(name).to_str().unwrap().to_string(), format!("sbs://{name}")].into_iter().enumerate() { + run(&mut session, "file.open", json!({ "path": source })); + let saved = directory.file(&format!("caller-{index}.sbs")); + run(&mut session, "file.saveAs", json!({ "path": saved })); + let xml = std::fs::read_to_string(&saved).unwrap(); + for helper in ["functions.sbs", "functions_hash.sbs"] { + assert!(xml.contains(&format!(r#" bool { path.parent().and_then(|parent| parent.canonicalize().ok()).is_some_and(|parent| parent.starts_with(root)) } +/// Return a portable package link for an unchanged bundled file beneath the canonical library root. +#[cfg(not(target_arch = "wasm32"))] +pub fn bundled_package_uri(canonical_root: &std::path::Path, path: &std::path::Path) -> Option { + use std::io::Read; + + if !path.is_absolute() { + return None; + } + let file = path.canonicalize().ok()?; + let relative = file.strip_prefix(canonical_root).ok()?.to_str()?.replace('\\', "/"); + let uri = format!("sbs://{relative}"); + relative_path(&uri).ok()?; + BUNDLED.binary_search(&uri.as_str()).ok()?; + + // A locally edited package at a shipped path must keep pointing to those edits. + let mut file = std::fs::File::open(file).ok()?; + let expected = read_embedded(&relative).ok()?; + if file.metadata().ok()?.len() != expected.len() as u64 { + return None; + } + let mut buffer = [0; 8192]; + for chunk in expected.chunks(buffer.len()) { + let actual = buffer.get_mut(..chunk.len())?; + file.read_exact(actual).ok()?; + if actual != chunk { + return None; + } + } + (file.read(&mut buffer).ok()? == 0).then_some(uri) +} + /// Read a validated library alias from the configured directory or the embedded fallback. pub fn read(uri: &str) -> Result, String> { let relative = relative_path(uri)?; diff --git a/docs/parity-fixes.md b/docs/parity-fixes.md index 46f24d34..0a2ba68b 100644 --- a/docs/parity-fixes.md +++ b/docs/parity-fixes.md @@ -1246,6 +1246,28 @@ The six-setting authored-shape and disc controls from the earlier branch compari Splatter Color and Weave 2 have measured parity across the reported settings. Pattern Weave 2 still differs on 351 whole pixels. Grayscale Splatter differs on the 16 × 64 default fed by the 32 × 16 field at seed 811492. Its input bridge matched all 1,024 U16 words. The following pattern draw differed on all 1,024 words, maximum 9,366. Rebinding the measured bridge levels as a 16 × 64 original-field input gave 1,024/1,024 matching F32 output pixels, maximum zero. +### Portable function links when opening a library graph from disk + +Open the physical `waveform_01_v2.sbs` beneath the configured package library in MaterialCraft. Save to a directory outside that library with `file.saveAs`. Close and reopen the new file directly in both applications. Repeat the [seven-size and fixed-field waveform comparisons](#waveform-v2-with-library-and-file-based-hash-functions). Include a second save and reopen. + +Before the fix, opening the graph through its physical path wrote relative links to the two local function packages. Opening through the library alias preserved both portable links. At the 16² default and the changed 64 × 32 and 128 × 32 F32 controls, the two saved files produced the following results. + +| How MaterialCraft opened the original | Saved F32 pixels exact / compared | Maximum error | +|---|---:|---:| +| Physical path | 4,712/6,400 | 1 | +| Library alias | 6,400/6,400 | 0 | + +When a graph is saved outside the configured library, unchanged, self-contained function packages from that library use portable URIs. The positive control uses the package files bundled with the tested build. The second library contains the earlier general math file from revision `97f2e06` and the unchanged hash file. The earlier math file differs byte-for-byte from the bundled version and keeps its relative link. + +| Source directory used to open the waveform | Saved general math link | Saved hash link | First save, 20 renders | Second save, 10 renders | Fixed-field reopens, 13 renders | +|---|---|---|---:|---:|---:| +| Bundled files | Library URI | Library URI | 109,056/109,056 | 44,288/44,288 | 26,624/26,624 | +| Earlier file for general math | Relative file path | Library URI | 109,056/109,056 | 44,288/44,288 | 26,624/26,624 | + +All **179,968/179,968** pixels on each route matched across applications and repeated the original render in each application. The U8, U16, F16 and F32 maxima were zero. Saving within the same configured library to a child directory wrote relative links resolving to both original functions. A detached older hash file still has the [separate measured handoff difference](#waveform-v2-with-library-and-file-based-hash-functions). Waveform v2 remains in progress for that case. + +The normal open/save/reopen regression failed before the change and passed after it. Separate controls retain file identity for a same-length edit and a byte-identical copy outside the library. The release engine and format suites passed, along with the hostile-command check, formatting, strict workspace Clippy, dependency layering and WebAssembly. + ## 2026-11-20 root comparisons ### Hue, saturation, lightness and Replace Color diff --git a/docs/sbs-root-nodes.md b/docs/sbs-root-nodes.md index 584188ce..2b479bde 100644 --- a/docs/sbs-root-nodes.md +++ b/docs/sbs-root-nodes.md @@ -652,7 +652,7 @@ Creased matches 10,947,840/10,947,840 pixels across 100 distinct settings throug | [vector_morph.sbs/vector_morph](../assets/sbs/vector_morph.sbs) | 2 | No | [Parity · 171,264/171,264 pixels in 18 renders](parity-fixes.md#quad-swirl-trapezoid-and-vector-morph-comparisons) | | [vector_morph.sbs/vector_morph_grayscale](../assets/sbs/vector_morph.sbs) | 2 | No | [Parity · 171,264/171,264 pixels in 18 renders](parity-fixes.md#quad-swirl-trapezoid-and-vector-morph-comparisons) | | [vertical_noise.sbs/vertical_noise](../assets/sbs/vertical_noise.sbs) | 0 | Yes | [In progress · 142,088/142,592 whole pixels, first differing stages measured](parity-fixes.md#tile-weave-splatter-and-fiber-stage-comparisons) | -| [waveform_01_v2.sbs/waveform_01_v2](../assets/sbs/waveform_01_v2.sbs) | 0 | No | [In progress · 313,088/313,088 originals, 179,968/179,968 library reopens](parity-fixes.md#waveform-v2-with-library-and-file-based-hash-functions) · [Older relative hash dependency, 167,194/179,968](parity-fixes.md#reopened-starburst-symmetry-tile-and-waveform-graphs) · [Earlier measurements](parity-fixes.md#plane-light-splatter-symmetry-and-waveform-comparisons) · [Stamp-width recheck](parity-fixes.md#pixel-reciprocals-for-stamp-edge-widths) | +| [waveform_01_v2.sbs/waveform_01_v2](../assets/sbs/waveform_01_v2.sbs) | 0 | No | [In progress · 313,088/313,088 originals, 179,968/179,968 reopens from a library path](parity-fixes.md#portable-function-links-when-opening-a-library-graph-from-disk) · [Function-link controls](parity-fixes.md#waveform-v2-with-library-and-file-based-hash-functions) · [Older relative hash dependency, 167,194/179,968](parity-fixes.md#reopened-starburst-symmetry-tile-and-waveform-graphs) · [Earlier measurements](parity-fixes.md#plane-light-splatter-symmetry-and-waveform-comparisons) · [Stamp-width recheck](parity-fixes.md#pixel-reciprocals-for-stamp-edge-widths) | | [waveform_1.sbs/waveform_1](../assets/sbs/waveform_1.sbs) | 0 | Yes | [Parity · 313,088/313,088 pixels across 54 distinct settings](parity-fixes.md#reopened-starburst-symmetry-tile-and-waveform-graphs) · [Earlier measurements](parity-fixes.md#plane-light-splatter-symmetry-and-waveform-comparisons) · [Stamp-width recheck](parity-fixes.md#pixel-reciprocals-for-stamp-edge-widths) | | [weave_1.sbs/weave_1](../assets/sbs/weave_1.sbs) | 0 | Yes | [Parity · 332,032/332,032 pixels across 39 distinct settings](parity-fixes.md#reopened-perlin-scratches-shape-and-weave-generators) · [Earlier measurements](parity-fixes.md#tile-weave-splatter-and-fiber-stage-comparisons) | | [weave_2.sbs/weave_2](../assets/sbs/weave_2.sbs) | 0 | Yes | [Parity · 3,139,840/3,139,840 pixels across 95 distinct settings](parity-fixes.md#saved-splatter-and-weave-graphs-across-independent-fields) · [Earlier measurements](parity-fixes.md#fixed-and-input-driven-rotation-bounds-for-oblique-stamps) |