diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index f4766b84..b626aaf2 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -162,10 +162,7 @@ pub fn open_bytes_linked(session: &mut Session, bytes: &[u8], name: Option Result { let bytes = write_package_at(s, &path)?; s.path = Some(path.clone()); - s.refresh_links(); + s.refresh_saved_links(&path); s.modified = false; s.log(format!("Saved {path}")); Ok(json!({"path": path, "bytes": bytes})) diff --git a/crates/engine/src/linked_files.rs b/crates/engine/src/linked_files.rs index 63b54036..e379e79b 100644 --- a/crates/engine/src/linked_files.rs +++ b/crates/engine/src/linked_files.rs @@ -1,5 +1,6 @@ use crate::document_path; use materialcraft_core::Package; +use std::{collections::BTreeSet, sync::Arc}; pub(crate) fn normalize_references(package: &mut Package, path: &str) { for resource in &mut package.resources { @@ -16,6 +17,60 @@ pub(crate) fn normalize_references(package: &mut Package, path: &str) { } impl crate::Session { + pub(crate) fn load_file_links(&mut self, package: &mut Package) -> Vec { + for (path, source) in &self.pkg.dependencies { + package.dependencies.entry(path.clone()).or_insert_with(|| source.clone()); + } + let pending = references(package); + self.load_sources(package, pending) + } + + fn load_sources(&mut self, package: &mut Package, pending: Vec) -> Vec { + read_references(package, pending, |uri, source| { + // Only aliases actually read from the catalog are owned by it. A caller can supply its own snapshot. + self.library_sources.insert(uri.to_owned(), Arc::clone(source)); + }) + } + + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn refresh_saved_links(&mut self, path: &str) { + use materialcraft_formats::sbs::library; + use std::path::Path; + + let file = Path::new(path); + let mut changed = BTreeSet::new(); + if let Ok(root) = library::root().canonicalize() + && file.starts_with(&root) + { + // The saved path is canonical. The same file may also be reached through a library symlink. + let aliases: Vec<_> = self + .library_sources + .iter() + .filter_map(|(uri, owned)| { + let relative = library::relative_path(uri).ok()?; + (self.linked_sources.get(uri).is_some_and(|source| Arc::ptr_eq(source, owned)) + && root.join(relative).canonicalize().ok()?.as_path() == file) + .then(|| uri.clone()) + }) + .collect(); + if !aliases.is_empty() { + let mut registry = Package { dependencies: self.linked_sources.clone(), ..Default::default() }; + for uri in &aliases { + registry.dependencies.remove(uri); + } + // Read the saved bytes in each alias's own directory so nested links and resources keep their base. + for warning in self.load_sources(&mut registry, aliases.clone()) { + self.warn(warning); + } + changed.extend( + aliases.into_iter().filter(|uri| registry.dependencies.get(uri).is_some_and(|source| self.linked_sources.get(uri) != Some(source))), + ); + self.linked_sources.extend(registry.dependencies); + } + } + self.refresh_links_from(changed); + } + pub(crate) fn discard_source_changes(&mut self, path: &str) { self.linked_sources.remove(path); self.pkg.dependencies.remove(path); @@ -30,29 +85,29 @@ impl crate::Session { // Include inactive dependents so closing a source also refreshes their references package.graphs.extend(self.documents.values().flat_map(|document| document.pkg.graphs.iter().cloned())); package.dependencies = self.linked_sources.clone(); - for warning in load(&mut package) { + let pending = references(&package); + for warning in self.load_sources(&mut package, pending) { self.warn(warning); } self.linked_sources.extend(package.dependencies); } - self.refresh_links_from(std::collections::BTreeSet::from([path.to_string()])); + self.refresh_links_from(BTreeSet::from([path.to_string()])); } } -pub(crate) fn load(package: &mut Package) -> Vec { - load_references(package, references(package)) -} - fn references(package: &Package) -> Vec { package.graphs.iter().flat_map(|graph| graph.instances()).filter(|instance| !instance.package.is_empty()).map(|instance| instance.package.clone()).collect() } /// Seed the registry with already parsed library packages before traversing dependencies. The /// registry stays flat so shared dependencies are parsed once and cannot form Arc ownership cycles. -pub(crate) fn load_references(package: &mut Package, mut pending: Vec) -> Vec { - use std::{collections::BTreeSet, sync::Arc}; +pub(crate) fn load_references(package: &mut Package, pending: Vec) -> Vec { + read_references(package, pending, |_, _| {}) +} + +fn read_references(package: &mut Package, mut pending: Vec, mut catalog_read: impl FnMut(&str, &Arc)) -> Vec { let mut visited = BTreeSet::new(); let mut warnings = Vec::new(); while let Some(path) = pending.pop() { @@ -87,7 +142,11 @@ pub(crate) fn load_references(package: &mut Package, mut pending: Vec) - Ok(mut source) => { normalize_references(&mut source, &path); pending.extend(references(&source)); - package.dependencies.insert(path, Arc::new(source)); + let source = Arc::new(source); + if path.starts_with("sbs://") { + catalog_read(&path, &source); + } + package.dependencies.insert(path, source); } Err(error) => warnings.push(format!("Could not resolve {path}: {error}")), } diff --git a/crates/engine/src/package_file_commands.rs b/crates/engine/src/package_file_commands.rs index 39e92dd3..e7323288 100644 --- a/crates/engine/src/package_file_commands.rs +++ b/crates/engine/src/package_file_commands.rs @@ -36,11 +36,8 @@ fn reload(session: &mut Session, parameters: &Value) -> Result { let bytes = read_package(&path)?; let linked = crate::file_cmds::linked_files(&path); let mut read = crate::file_cmds::read_package_bytes(&bytes, &path, &linked)?; - for (path, source) in &session.pkg.dependencies { - read.pkg.dependencies.entry(path.clone()).or_insert_with(|| source.clone()); - } let safe_path = read.warnings.is_empty().then_some(path.clone()); - read.warnings.extend(crate::linked_files::load(&mut read.pkg)); + read.warnings.extend(session.load_file_links(&mut read.pkg)); crate::file_cmds::replace_package(session, read.pkg, safe_path); session.load_warnings = read.warnings; diff --git a/crates/engine/tests/it/linked_resources.rs b/crates/engine/tests/it/linked_resources.rs index 30f1eb9d..f6a354fa 100644 --- a/crates/engine/tests/it/linked_resources.rs +++ b/crates/engine/tests/it/linked_resources.rs @@ -71,14 +71,18 @@ fn resource_package(source: &str) -> Package { #[test] fn library_resources_resolve_next_to_their_package() { + with_library_files("library_resources_resolve_next_to_their_package", verify_library_resources); +} + +fn with_library_files(test: &str, verify: fn(&std::path::Path)) { const CHILD_ROOT: &str = "MC_LINKED_RESOURCES_TEST_ROOT"; if let Ok(root) = std::env::var(CHILD_ROOT) { - verify_library_resources(std::path::Path::new(&root)); + verify(std::path::Path::new(&root)); return; } // A child process isolates the library root without mutating the test runner's environment - let root = std::env::temp_dir().join(format!("materialcraft-linked-resources-{}", std::process::id())); + let root = std::env::temp_dir().join(format!("materialcraft-linked-resources-{}-{test}", std::process::id())); std::fs::create_dir_all(root.join("assets/sbs/resources")).unwrap(); std::fs::create_dir_all(root.join("assets/sbs/nested/resources")).unwrap(); std::fs::write(root.join("assets/sbs/resources/tile.svg"), TILE).unwrap(); @@ -98,7 +102,7 @@ fn library_resources_resolve_next_to_their_package() { .unwrap(); let status = std::process::Command::new(std::env::current_exe().unwrap()) - .args(["--exact", "linked_resources::library_resources_resolve_next_to_their_package", "--nocapture"]) + .args(["--exact", &format!("linked_resources::{test}"), "--nocapture"]) .env(CHILD_ROOT, &root) .env("MATERIALCRAFT_SBS_DIR", root.join("assets/sbs")) .status() @@ -108,6 +112,38 @@ fn library_resources_resolve_next_to_their_package() { assert!(status.success()); } +#[test] +fn saving_a_catalog_source_updates_open_callers() { + with_library_files("saving_a_catalog_source_updates_open_callers", |root| { + use materialcraft_engine::NodeLibrary; + use std::sync::Arc; + + let alias = "sbs://nested/source.sbs"; + let source = root.join("assets/sbs/nested/source.sbs"); + let caller = root.join("caller.sbs"); + let original = std::fs::read_to_string(root.join("assets/sbs/nested/caller.sbs")).unwrap(); + std::fs::write(&caller, original.replace("source.sbs", alias)).unwrap(); + let check = |project, library, edited, expected| { + let mut session = Session::with_library(project, library); + file_cmds::open_file(&mut session, caller.to_str().unwrap()).unwrap(); + let document = session.document_id; + file_cmds::open_file(&mut session, source.to_str().unwrap()).unwrap(); + let body = FunctionGraph::constant(Value::Float(edited)); + execute(&mut session, "graph.function.set", &json!({"function": body})).unwrap(); + execute(&mut session, "file.save", &json!({})).unwrap(); + session.activate_document(document).unwrap(); + let linked = &session.pkg.dependencies[alias].graphs[0]; + assert_eq!(linked.function.as_ref().unwrap().nodes[0].value, Some(Value::Float(expected))); + assert_eq!(session.graph().unwrap().instances().next().unwrap().package, alias); + }; + check(Package::new("Installed"), NodeLibrary::shared(), 0.375, 0.375); + check(Package::new("Loaded by caller"), Arc::default(), 0.625, 0.625); + let mut project = Package::new("Explicit override"); + project.dependencies.insert(alias.into(), Arc::new(resource_package("resources/tile.svg"))); + check(project, NodeLibrary::shared(), 0.75, 0.5); + }); +} + fn verify_library_resources(root: &std::path::Path) { let library = materialcraft_engine::NodeLibrary::load(&["sbs://nested/caller.sbs".into(), "sbs://nested/source.sbs".into(), "sbs://nested/source.sbs".into()]); diff --git a/docs/parity-fixes.md b/docs/parity-fixes.md index dbc8afaa..81815f61 100644 --- a/docs/parity-fixes.md +++ b/docs/parity-fixes.md @@ -351,6 +351,23 @@ Place four configured callers inside the first of two library directories. Use c Both reference processor counts give the same expected values. The previous writer turned the catalog URI into a relative filename. With the second library selected, it reproduced **0/2,048** edited pixels, maximum error 159 levels. Both dependency trees kept their package hashes through all eight caller saves. As a separate reference check, open the same four file-linked caller bytes beside each independent library, preserving the relative location of the generated image. Fresh reference opens at one and eight processors give **2,048/2,048** for each library, maximum zero. An initial copy supplied the first font under its friendly filename, while the saved package declared a content-addressed filename. This gave 1,992/2,048 in the reference, maximum 135 U8 levels. Providing the same font bytes at the declared path restored the 56 label pixels with the caller and spline package bytes unchanged. The newer writer’s root measurements use compatible linked packages. The older detached-package result remains open. [Reference saves with older links](#ordinary-save-in-the-reference-app-with-the-same-live-dependencies) +### Saving a catalog dependency while its callers stay open + +A caller could keep an old graph or function after another tab saved the physical file selected by its catalog link. The open session refreshed the disk filename and retained an earlier snapshot under the catalog URI. Ordinary Save now refreshes the catalog entries for that file. It reads nested references relative to each catalog entry. An explicit dependency supplied by a project retains its own value. + +Keep one caller open and export its original output. Open the linked package by its physical filename in a second tab. For Points Preview, add a U8 grayscale Uniform at .375 to the linked graph, connect it to the output and save. For Waveform v2, set the linked two-component hash function’s result to .375 and save. Return to the caller tab and export. Undo the connection or function edit, save the dependency a second time and export from the still-open caller. Verify the caller’s file hash through the three exports. Repeat with a relative filename and a catalog URI in each configured caller. [Four Points Preview views and font placement](#points-preview-graph-links-after-switching-the-configured-library) · [Four Waveform sizes, seeds and storage formats](#saving-older-linked-packages-at-their-existing-paths) + +Each cell gives exact pixels against fresh reference buffers for the same saved source state, followed by maximum absolute error. The counts hold separately at one and eight reference processors. Points Preview uses U8. Waveform uses U8, U16, F16 and F32. The previous Waveform differences are all in U16. + +| Caller and link | Original | Saved edit before fix | Saved edit after fix | Undo and save | +|---|---:|---:|---:|---:| +| Points Preview · relative filename | 2,048/2,048 · 0 | 2,048/2,048 · 0 | 2,048/2,048 · 0 | 2,048/2,048 · 0 | +| Points Preview · catalog URI | 2,048/2,048 · 0 | 0/2,048 · 159 | 2,048/2,048 · 0 | 2,048/2,048 · 0 | +| Waveform v2 · relative filename | 8,448/8,448 · 0 | 8,448/8,448 · 0 | 8,448/8,448 · 0 | 8,448/8,448 · 0 | +| Waveform v2 · catalog URI | 8,448/8,448 · 0 | 8,410/8,448 · 65,535 | 8,448/8,448 · 0 | 8,448/8,448 · 0 | + +All 16 caller files kept their original bytes. Fresh reference opens of the relative-file callers against the newly saved graph and function packages also match **10,496/10,496** pixels after the edit and **10,496/10,496** after undo, at each processor count. For this check, keep the caller bytes, the locations of the generated image and font, and the saved dependency bytes fixed. The function regression also checks an installed catalog source, one first loaded by the caller, and a project-supplied override. Saving .375 or .625 refreshes the corresponding file-backed entry. The override stays at .5 after a physical save of .75. The previously measured compiler behavior with older external package headers remains open. [Ordinary saves of callers with older linked files](#ordinary-save-in-the-reference-app-with-the-same-live-dependencies) + ### Editing the linked function with a waveform caller open Use the four configured Waveform v2 files and the relative function package. In a single MaterialCraft session, open a caller and export its Waveform output as raw linear F32. Open `curve_lookup.sbs` in another tab, set the result of `hash21` to a scalar constant .375 and save the linked file. Return to the caller tab and export again. Undo the function edit in its tab, save there, return to the caller and export a third time. Leave the caller open throughout and verify its file hash before and after. [Configured callers and dependency](#saving-older-linked-packages-at-their-existing-paths) diff --git a/docs/sbs-root-nodes.md b/docs/sbs-root-nodes.md index dd463353..1cf58435 100644 --- a/docs/sbs-root-nodes.md +++ b/docs/sbs-root-nodes.md @@ -744,7 +744,7 @@ Creased matches 10,947,840/10,947,840 pixels across 100 distinct settings throug | [spline_tools.sbs/internal_tools/get_spline_point_data](../assets/sbs/spline_tools.sbs) | 1 | Yes | [Parity: 4 cases](parity-fixes.md#verified-cases) | | [spline_tools.sbs/internal_tools/modify_spline_property_sub](../assets/sbs/spline_tools.sbs) | 4 | Yes | [Parity · 28,928 exact pixels in 19 renders](parity-fixes.md#clamped-texture-reads-in-spline-graphs) | | [spline_tools.sbs/internal_tools/normalize_spline_distance](../assets/sbs/spline_tools.sbs) | 1 | Yes | [Parity · 16 cases, 52,480 exact pixels](parity-fixes.md#tile-edge-masks-and-normalized-spline-distances) | -| [spline_tools.sbs/internal_tools/points_preview](../assets/sbs/spline_tools.sbs) | 3 | Yes | [In progress · 26,880/26,880 with two matched fonts, 14,592/14,592 on direct reopen with compatible dependencies, older loose links still fail](parity-fixes.md#overlapping-glyphs-and-points-preview-file-handoff) · [25,088/25,088 empty and point-only pixels](parity-fixes.md#font-line-height-and-coverage-over-a-constant-background) · [Five linked files saved in place, 17,920/17,920 and 2,048/2,048 direct](parity-fixes.md#saving-older-linked-packages-at-their-existing-paths) · [2,048/2,048 on each file and catalog selection](parity-fixes.md#points-preview-graph-links-after-switching-the-configured-library) | +| [spline_tools.sbs/internal_tools/points_preview](../assets/sbs/spline_tools.sbs) | 3 | Yes | [In progress · 26,880/26,880 with two matched fonts, 14,592/14,592 on direct reopen with compatible dependencies, older loose links still fail](parity-fixes.md#overlapping-glyphs-and-points-preview-file-handoff) · [25,088/25,088 empty and point-only pixels](parity-fixes.md#font-line-height-and-coverage-over-a-constant-background) · [Five linked files saved in place, 17,920/17,920 and 2,048/2,048 direct](parity-fixes.md#saving-older-linked-packages-at-their-existing-paths) · [2,048/2,048 on each file and catalog selection](parity-fixes.md#points-preview-graph-links-after-switching-the-configured-library) · [Open file and catalog callers follow saved edits and undo, 2,048/2,048 pixels](parity-fixes.md#saving-a-catalog-dependency-while-its-callers-stay-open) | | [spline_tools.sbs/internal_tools/resample_spline_data](../assets/sbs/spline_tools.sbs) | 3 | Yes | [Parity · 29,952 exact pixels in 19 renders](parity-fixes.md#clamped-texture-reads-in-spline-graphs) | | [spline_tools.sbs/internal_tools/scatter_splines_on_splines_preprocess](../assets/sbs/spline_tools.sbs) | 5 | Yes | [Parity · 622,592/622,592 pixels and 16/16 counts, both full-library saves exact](parity-fixes.md#spline-preprocessing-with-empty-inputs-and-complete-library-saves) · [Four output formats](parity-fixes.md#spline-preprocessing-with-wired-counts) | | [spline_tools.sbs/internal_tools/select_spline_sub](../assets/sbs/spline_tools.sbs) | 3 | Yes | [Parity · 622,592 exact pixels in 19 renders](parity-fixes.md#clamped-texture-reads-in-spline-graphs) | @@ -776,7 +776,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,295/142,592 across 19 established settings, four ordinary saves compared](parity-fixes.md#whole-caustic-scratch-splatter-tile-and-vertical-noise-comparisons) · [Earlier comparison · 142,088/142,592 whole pixels, first differing stages measured](parity-fixes.md#tile-weave-splatter-and-fiber-stage-comparisons) · [Bricks 01 tile and noise stages](parity-fixes.md#tile-luminance-variation-in-bricks-01) | -| [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) · [179,968/179,968 with the updated dependency header](parity-fixes.md#version-of-a-detached-function-package-and-waveform-reopening) · [Unused and invoked file controls](parity-fixes.md#unused-and-unavailable-relative-functions) · [Portable SBS copy with detached functions, 179,968/179,968](parity-fixes.md#reopening-a-portable-copy-with-detached-function-packages) · [Relative function file saved in place, 179,968/179,968 and 8,448/8,448 direct](parity-fixes.md#saving-older-linked-packages-at-their-existing-paths) · [Linked function edit and undo with callers open, 8,448/8,448 per state](parity-fixes.md#editing-the-linked-function-with-a-waveform-caller-open) · [Catalog and relative links saved inside the library, 8,448/8,448 under each library selection](parity-fixes.md#keeping-catalog-links-when-saving-a-caller-inside-its-library) | +| [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) · [179,968/179,968 with the updated dependency header](parity-fixes.md#version-of-a-detached-function-package-and-waveform-reopening) · [Unused and invoked file controls](parity-fixes.md#unused-and-unavailable-relative-functions) · [Portable SBS copy with detached functions, 179,968/179,968](parity-fixes.md#reopening-a-portable-copy-with-detached-function-packages) · [Relative function file saved in place, 179,968/179,968 and 8,448/8,448 direct](parity-fixes.md#saving-older-linked-packages-at-their-existing-paths) · [Linked function edit and undo with callers open, 8,448/8,448 per state](parity-fixes.md#editing-the-linked-function-with-a-waveform-caller-open) · [Catalog and relative links saved inside the library, 8,448/8,448 under each library selection](parity-fixes.md#keeping-catalog-links-when-saving-a-caller-inside-its-library) · [Open file and catalog callers follow saved edits and undo, 8,448/8,448 pixels](parity-fixes.md#saving-a-catalog-dependency-while-its-callers-stay-open) | | [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) |