Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 20 additions & 4 deletions crates/engine/src/cmd/libraries.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! Scalar local libraries: inspect/export files and copy exact revisions into a design.
//! Local material libraries: inspect/export files and copy exact revisions into a design.
use super::CommandSpec;
use crate::{Result, Session, params::bad};
use serde::Deserialize;
Expand All @@ -7,9 +7,9 @@ use solidcraft_io::catalog::{Catalog, Definition, Provenance};

pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("library.inspect", "Inspect Local Library", inspect).icon("inspect").noundo().doc_only()
.params("path: scalar library JSON; returns validated catalog and exact entry revisions, without changing the design"),
.params("path: v1/v2 library JSON; returns validated catalog and exact entry revisions, without changing the design"),
CommandSpec::new("library.export", "Export Design Library", export).icon("export").noundo().doc_only()
.params("path: .json; id? (default user.local), name?, provenance?, overwrite? false. Copies assigned looks and design-local physical definitions; never changes the design"),
.params("path: .json; id? (default user.local), name?, provenance?, overwrite? false, format? solidcraft-library/2 (default) | solidcraft-library/1 (refuses PBR/cards). Copies assigned looks and design-local physical definitions; never changes the design"),
CommandSpec::new("library.apply", "Apply Local Library Entry", apply).icon("import").enabled(super::not_in_sketch)
.params("path, entry: qualified ID, revision: exact content SHA-256; targets?: {bodies?, faces?: [{body,point}], components?}; name?: physical material name on import. Copies values in one undo step; material conflicts are explicit"),
];
Expand All @@ -31,6 +31,11 @@ struct Export {
provenance: Provenance,
#[serde(default)]
overwrite: bool,
#[serde(default = "default_format")]
format: String,
}
fn default_format() -> String {
solidcraft_io::catalog::FORMAT.into()
}
fn default_id() -> String {
"user.local".into()
Expand Down Expand Up @@ -107,7 +112,9 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
if !request.path.to_ascii_lowercase().ends_with(".json") {
return Err(bad(cmd, "library export path must end in .json"));
}
let catalog = Catalog::from_document(&s.doc, &request.id, &request.name, request.provenance).map_err(|e| bad(cmd, e.to_string()))?;
let catalog = Catalog::from_document(&s.doc, &request.id, &request.name, request.provenance)
.and_then(|catalog| catalog.in_format(&request.format))
.map_err(|e| bad(cmd, e.to_string()))?;
let bytes = catalog.encode().map_err(|e| bad(cmd, e.to_string()))?;
#[cfg(not(target_arch = "wasm32"))]
let result = if request.overwrite {
Expand Down Expand Up @@ -146,6 +153,9 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
target["appearance"] = json!(look.name);
target["color"] = json!(look.color);
target["opacity"] = json!(look.opacity);
if let Some(pbr) = look.pbr {
target["pbr"] = json!(pbr);
}
nested(s, "appearance.assign", &target)?
}
Definition::Material(material) => {
Expand All @@ -172,6 +182,12 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(look) = &material.appearance {
params["color"] = json!(look.color);
params["opacity"] = json!(look.opacity);
if let Some(pbr) = look.pbr {
params["pbr"] = json!(pbr);
}
}
if let Some(card) = &material.physical_card {
params["physical_card"] = json!(card);
}
nested(s, "material.create", &params)?;
// The existing colour API labels a custom look after its material.
Expand Down
119 changes: 114 additions & 5 deletions crates/engine/src/cmd/libraries_tests.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use super::*;
use solidcraft_io::catalog::{Definition, Entry, FORMAT, ScalarLook, ScalarMaterial};
use solidcraft_io::catalog::{Definition, Entry, FORMAT, LibraryLook, LibraryMaterial};
use std::sync::{
Arc,
atomic::{AtomicU64, Ordering},
Expand Down Expand Up @@ -33,16 +33,17 @@ fn catalog() -> Catalog {
entries: vec![
Entry::new(
"user.test",
Definition::Appearance(ScalarLook { name: "Warm oak colour".into(), color: [180, 120, 70], opacity: 0.8 }),
Definition::Appearance(LibraryLook { name: "Warm oak colour".into(), color: [180, 120, 70], opacity: 0.8, pbr: None }),
Provenance::default(),
)
.unwrap(),
Entry::new(
"user.test",
Definition::Material(ScalarMaterial {
Definition::Material(LibraryMaterial {
name: "Timber density".into(),
density_g_cm3: 0.7,
appearance: Some(ScalarLook { name: "Timber tint".into(), color: [180, 120, 70], opacity: 1.0 }),
physical_card: None,
appearance: Some(LibraryLook { name: "Timber tint".into(), color: [180, 120, 70], opacity: 1.0, pbr: None }),
}),
Provenance::default(),
)
Expand All @@ -60,6 +61,113 @@ fn apply_entry(s: &mut Session, file: &File, entry: &Entry, targets: Value) -> R
s.execute("library.apply", &json!({"path":file.0,"entry":entry.id,"revision":entry.revision,"targets":targets}))
}

fn rich_catalog() -> Catalog {
use solidcraft_doc::{pbr_appearance::PbrParameters, physical_material::ValidatedCard};
let mut c = catalog();
if let Definition::Appearance(l) = &mut c.entries[0].definition {
l.opacity = 1.0;
l.pbr = Some(PbrParameters::new(1., 0.25, 1.5).unwrap());
}
if let Definition::Material(m) = &mut c.entries[1].definition {
m.density_g_cm3 = 0.8;
m.appearance.as_mut().unwrap().pbr = Some(PbrParameters::new(0., 0.65, 1.4).unwrap());
m.physical_card = Some(
ValidatedCard::from_value(&json!({"schema_version":1,"designation":"Original synthetic candidate","family":"other",
"sources":[{"id":"fixture","title":"Original invented density","kind":"illustrative"}],
"properties":[{"source_id":"fixture","data":{"kind":"density","kg_m3":700.0}}]}))
.unwrap(),
);
}
for e in &mut c.entries {
*e = Entry::new("user.test", e.definition.clone(), e.provenance.clone()).unwrap();
}
c
}

#[test]
fn rich_appearance_copy_preserves_product_response_and_mass_without_source_file() {
let file = File::new();
let c = rich_catalog();
file.write(&c);
let mut s = session();
let mass = s.execute("component.properties", &json!({})).unwrap();
let scene = crate::product_scene::extract(&s).unwrap();
let undo = s.undo.len();
apply_entry(&mut s, &file, &c.entries[0], json!({"bodies":["Body1"]})).unwrap();
assert_eq!(s.undo.len(), undo + 1);
let after = crate::product_scene::extract(&s).unwrap();
assert!(Arc::ptr_eq(&scene.meshes[0].mesh, &after.meshes[0].mesh));
assert_eq!(after.meshes[0].surface.unwrap().metallic(), 1.0);
assert_eq!(s.execute("component.properties", &json!({})).unwrap(), mass);
let saved = solidcraft_io::write_design(&s.doc);
std::fs::remove_file(&file.0).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc.appearances.bodies.is_empty());
s.execute("edit.redo", &json!({})).unwrap();
let mut reopened = Session::new(solidcraft_io::read_design(&saved).unwrap());
assert_eq!(reopened.doc.appearances, s.doc.appearances);
assert_eq!(reopened.execute("component.properties", &json!({})).unwrap(), mass);
}

#[test]
fn rich_material_copy_retains_engineering_card_label_optics_and_explicit_mass_density() {
let file = File::new();
let c = rich_catalog();
file.write(&c);
let mut s = session();
let undo = s.undo.len();
apply_entry(&mut s, &file, &c.entries[1], json!({"bodies":["Body1"]})).unwrap();
assert_eq!(s.undo.len(), undo + 1);
let material = &s.doc.user_materials[0];
assert_eq!(material.appearance.as_ref().unwrap().name, "Timber tint");
assert_eq!(material.appearance.as_ref().unwrap().pbr.unwrap().roughness(), 0.65);
assert!(material.physical_card.is_some());
assert_eq!(material.density, 0.8);
let mass = s.execute("component.properties", &json!({})).unwrap()["total"]["mass_g"].as_f64().unwrap();
assert!((mass - 0.8).abs() < 1e-8);
let saved = solidcraft_io::write_design(&s.doc);
std::fs::remove_file(&file.0).unwrap();
let reopened = Session::new(solidcraft_io::read_design(&saved).unwrap());
assert_eq!(reopened.doc.user_materials, s.doc.user_materials);
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc.user_materials.is_empty());
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc.user_materials, reopened.doc.user_materials);
}

#[test]
fn explicit_v1_export_refuses_richer_data_before_overwriting_and_scalar_v1_still_works() {
let file = File::new();
let sentinel = b"Existing catalog must survive";
std::fs::write(&file.0, sentinel).unwrap();
let mut s = session();
s.execute(
"appearance.assign",
&json!({"bodies":["Body1"],"color":"#b47846",
"pbr":{"metallic":1,"roughness":0.3,"dielectric_ior":1.5}}),
)
.unwrap();
let before = s.doc.clone();
let history = (s.undo.len(), s.redo.len(), s.revision);
assert!(s.execute("library.export", &json!({"path":file.0,"format":solidcraft_io::catalog::V1_FORMAT,"overwrite":true})).is_err());
assert_eq!(std::fs::read(&file.0).unwrap(), sentinel);
assert!(Arc::ptr_eq(&before, &s.doc));
assert_eq!(history, (s.undo.len(), s.redo.len(), s.revision));
s.execute("library.export", &json!({"path":file.0,"overwrite":true})).unwrap();
assert_eq!(Catalog::read(&file.0).unwrap().format, FORMAT);
s.execute("appearance.assign", &json!({"bodies":["Body1"],"color":"#b47846"})).unwrap();
s.execute("library.export", &json!({"path":file.0,"format":solidcraft_io::catalog::V1_FORMAT,"overwrite":true})).unwrap();
assert_eq!(Catalog::read(&file.0).unwrap().format, solidcraft_io::catalog::V1_FORMAT);
let rich = rich_catalog();
file.write(&rich);
s.execute("material.create", &json!({"name":"Timber density","density_g_cm3":0.8,"color":"#b47846"})).unwrap();
let before = s.doc.clone();
let history = (s.undo.len(), s.redo.len(), s.revision);
assert!(apply_entry(&mut s, &file, &rich.entries[1], json!({"bodies":["Body1"]})).is_err());
assert!(Arc::ptr_eq(&before, &s.doc));
assert_eq!(history, (s.undo.len(), s.redo.len(), s.revision));
}

#[test]
fn catalog_export_obeys_file_scope_in_new_file_and_overwrite_modes() {
let file = File::new();
Expand Down Expand Up @@ -237,7 +345,8 @@ fn lossy_scalar_export_never_creates_or_replaces_a_file_or_changes_history() {
std::fs::write(&file.0, b"preserve existing library").unwrap();
}
for overwrite in [false, true] {
let error = s.execute("library.export", &json!({"path":file.0,"overwrite":overwrite})).unwrap_err();
let error =
s.execute("library.export", &json!({"path":file.0,"overwrite":overwrite,"format":solidcraft_io::catalog::V1_FORMAT})).unwrap_err();
assert!(error.to_string().contains("cannot preserve PBR"));
if existing {
assert_eq!(std::fs::read(&file.0).unwrap(), b"preserve existing library");
Expand Down
14 changes: 11 additions & 3 deletions crates/engine/src/cmd/material_card_persistence_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,11 @@ fn omission_retains_null_clears_and_unrelated_material_edits_retain_cards() {
s.execute("material.edit", &p).unwrap();
assert_eq!(s.doc.user_materials[1].physical_card, original);
}
let error = solidcraft_io::catalog::ScalarMaterial::from_material(&s.doc.user_materials[1]).unwrap_err();
let mut only_card = Document::default();
only_card.user_materials.push(s.doc.user_materials[1].clone());
let error = solidcraft_io::catalog::Catalog::from_document(&only_card, "user.fixture", "Original", Default::default())
.and_then(|c| c.in_format(solidcraft_io::catalog::V1_FORMAT))
.unwrap_err();
assert!(error.to_string().contains("engineering cards"));
s.execute("material.edit", &json!({"material":"Renamed","physical_card":null})).unwrap();
assert!(s.doc.user_materials[1].physical_card.is_none());
Expand Down Expand Up @@ -164,8 +168,12 @@ fn scalar_catalog_refuses_card_export_without_creating_or_replacing_files_or_his
std::fs::write(&file.0, b"keep existing catalog").unwrap();
}
for overwrite in [false, true] {
let error = s.execute("library.export", &json!({"path":file.0,"overwrite":overwrite})).unwrap_err();
assert!(error.to_string().contains("cannot preserve engineering cards"));
// The default writer is rich v2. Request scalar v1 explicitly so this
// regression still exercises refusal rather than a valid lossless copy.
let error =
s.execute("library.export", &json!({"path":file.0,"overwrite":overwrite,"format":solidcraft_io::catalog::V1_FORMAT})).unwrap_err();
let message = error.to_string();
assert!(message.contains("catalog v1") && message.contains("engineering cards"), "{message}");
if existing {
assert_eq!(std::fs::read(&file.0).unwrap(), b"keep existing catalog");
} else {
Expand Down
12 changes: 10 additions & 2 deletions crates/engine/src/cmd/pbr_appearance_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,11 @@ fn invalid_optical_requests_refuse_atomically_and_scalar_export_cannot_lose_them
"pbr":{"metallic":0,"roughness":0.5,"dielectric_ior":1.5}}),
)
.unwrap();
assert!(solidcraft_io::catalog::Catalog::from_document(&s.doc, "user.fixture", "Original", Default::default()).is_err());
assert!(
solidcraft_io::catalog::Catalog::from_document(&s.doc, "user.fixture", "Original", Default::default())
.and_then(|c| c.in_format(solidcraft_io::catalog::V1_FORMAT))
.is_err()
);
let mut invalid: serde_json::Value = serde_json::from_str(&s.doc.to_json()).unwrap();
invalid["appearances"]["bodies"]["Specimen"]["opacity"] = json!(0.5);
assert!(crate::doc::Document::from_json(&invalid.to_string()).is_err());
Expand All @@ -115,7 +119,11 @@ fn physical_default_look_and_face_override_keep_independent_optical_meaning() {
assert!(scene.meshes[0].surface.is_some());
assert!(scene.meshes[0].faces.iter().any(|f| f.color == [0, 128, 160] && f.surface.is_none()));
assert_eq!(s.doc.user_materials[0].density, 0.7);
assert!(solidcraft_io::catalog::Catalog::from_document(&s.doc, "user.fixture", "Original", Default::default()).is_err());
assert!(
solidcraft_io::catalog::Catalog::from_document(&s.doc, "user.fixture", "Original", Default::default())
.and_then(|c| c.in_format(solidcraft_io::catalog::V1_FORMAT))
.is_err()
);
}

#[test]
Expand Down
Loading