Appearance: read the look chain and replace a look everywhere in one undo step (#6428)
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"en": {
|
||||
"cmd.appearance_chain": "Appearance Chain"
|
||||
},
|
||||
"de": {
|
||||
"cmd.appearance_chain": "Aussehen-Herkunft"
|
||||
},
|
||||
"ja": {
|
||||
"cmd.appearance_chain": "外観の由来"
|
||||
},
|
||||
"zh": {
|
||||
"cmd.appearance_chain": "外观来源"
|
||||
},
|
||||
"ko": {
|
||||
"cmd.appearance_chain": "외관 출처"
|
||||
},
|
||||
"ar": {
|
||||
"cmd.appearance_chain": "سلسلة المظهر"
|
||||
},
|
||||
"he": {
|
||||
"cmd.appearance_chain": "שרשרת מראה"
|
||||
},
|
||||
"vi": {
|
||||
"cmd.appearance_chain": "Chuỗi diện mạo"
|
||||
}
|
||||
}
|
||||
+278
-18
@@ -3,7 +3,7 @@
|
||||
//! a component's over the physical material's look; a body with none of these keeps the colour
|
||||
//! it was imported with.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use solidcraft_geom::Vec3;
|
||||
@@ -129,6 +129,95 @@ impl Appearances {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.bodies.is_empty() && self.faces.is_empty() && self.components.is_empty()
|
||||
}
|
||||
|
||||
/// Bound bulk appearance operations, including designs read from untrusted files.
|
||||
pub fn check_budget(&self) -> crate::Result<()> {
|
||||
if self.bodies.len().saturating_add(self.faces.len()).saturating_add(self.components.len()) > 100_000 {
|
||||
return Err(crate::DocError::Invalid("at most 100000 appearance overrides can be processed".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Build a replacement without changing the source. Equality includes the label and
|
||||
/// every optical value. Physical-material defaults are deliberately outside this scope.
|
||||
/// `None` means no change, allowing callers to preserve history and revision.
|
||||
pub fn replacing(&self, from: &Look, to: &Look, scope: Option<&AppearanceScope>) -> crate::Result<Option<(Self, usize)>> {
|
||||
self.check_budget()?;
|
||||
for look in [from, to] {
|
||||
if !look.opacity.is_finite() || !(0.0..=1.0).contains(&look.opacity) {
|
||||
return Err(crate::DocError::Invalid("opacity must be finite and in 0..1".into()));
|
||||
}
|
||||
look.opaque_surface()?;
|
||||
}
|
||||
if from == to {
|
||||
return Ok(None);
|
||||
}
|
||||
let body_in_scope = |body: &str| scope.is_none_or(|s| s.bodies.contains(body));
|
||||
let component_in_scope = |id: &u64| scope.is_none_or(|s| s.components.contains(id));
|
||||
let count = self.bodies.iter().filter(|(body, look)| body_in_scope(body) && *look == from).count()
|
||||
+ self.faces.iter().filter(|face| body_in_scope(&face.body) && &face.look == from).count()
|
||||
+ self.components.iter().filter(|(id, look)| component_in_scope(id) && *look == from).count();
|
||||
if count == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut replaced = self.clone();
|
||||
for (body, look) in &mut replaced.bodies {
|
||||
if body_in_scope(body) && look == from {
|
||||
*look = to.clone();
|
||||
}
|
||||
}
|
||||
for face in &mut replaced.faces {
|
||||
if body_in_scope(&face.body) && &face.look == from {
|
||||
face.look = to.clone();
|
||||
}
|
||||
}
|
||||
for (id, look) in &mut replaced.components {
|
||||
if component_in_scope(id) && look == from {
|
||||
*look = to.clone();
|
||||
}
|
||||
}
|
||||
Ok(Some((replaced, count)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Exact override containers for replacement. A body includes its face overrides;
|
||||
/// a component selects its own override, independently of the bodies it owns.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct AppearanceScope {
|
||||
pub bodies: BTreeSet<String>,
|
||||
pub components: BTreeSet<u64>,
|
||||
}
|
||||
|
||||
/// A target in an evaluated model. Face indices are those of `model.faces`.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum AppearanceTarget<'a> {
|
||||
Body(&'a str),
|
||||
Face { body: &'a str, face: usize },
|
||||
Component(u64),
|
||||
}
|
||||
|
||||
/// The four override steps, in descending precedence. Imported paint is a display
|
||||
/// fallback, not an override or physical material, and is not a fifth step.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct AppearanceChain {
|
||||
pub face: Option<Look>,
|
||||
pub body: Option<Look>,
|
||||
pub component: Option<Look>,
|
||||
pub material: Option<Look>,
|
||||
}
|
||||
|
||||
impl AppearanceChain {
|
||||
pub fn steps(&self) -> [(&'static str, Option<&Look>); 4] {
|
||||
[("face", self.face.as_ref()), ("body", self.body.as_ref()), ("component", self.component.as_ref()), ("material", self.material.as_ref())]
|
||||
}
|
||||
|
||||
pub fn active(&self) -> Option<&'static str> {
|
||||
self.steps().into_iter().find_map(|(step, look)| look.map(|_| step))
|
||||
}
|
||||
|
||||
pub fn resolved(&self) -> Option<&Look> {
|
||||
self.steps().into_iter().find_map(|(_, look)| look)
|
||||
}
|
||||
}
|
||||
|
||||
/// The built-in appearance library: (name, colour, opacity).
|
||||
@@ -161,6 +250,63 @@ pub fn material_look(material: &str) -> Option<Look> {
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// Read the same precedence used by body and face display resolution. Components
|
||||
/// have no material assignment of their own: the material step is present only
|
||||
/// when their directly owned bodies all have the same material look. Empty or
|
||||
/// mixed components have no material step. Root is not an assignable component.
|
||||
pub fn appearance_chain(&self, state: &crate::ModelState, target: AppearanceTarget<'_>) -> crate::Result<AppearanceChain> {
|
||||
self.appearances.check_budget()?;
|
||||
match target {
|
||||
AppearanceTarget::Body(name) | AppearanceTarget::Face { body: name, .. } => {
|
||||
let body = state.body(name).ok_or_else(|| crate::DocError::Invalid(format!("no body `{name}`")))?;
|
||||
let mut chain = self.body_appearance_chain(body.definition_name(), self.model_body_component(body));
|
||||
if let AppearanceTarget::Face { face, .. } = target {
|
||||
if face >= body.body.face_count() {
|
||||
return Err(crate::DocError::Invalid("unknown face index".into()));
|
||||
}
|
||||
let mut overrides = Vec::new();
|
||||
self.apply_face_overrides(body, &mut overrides);
|
||||
chain.face = overrides.into_iter().find_map(|(index, look)| (index == face).then_some(look));
|
||||
}
|
||||
Ok(chain)
|
||||
}
|
||||
AppearanceTarget::Component(id) => {
|
||||
if id == 0 || !self.components.iter().any(|c| c.id == id) {
|
||||
return Err(crate::DocError::Invalid("unknown or root component".into()));
|
||||
}
|
||||
if state.bodies.len() > 100_000 {
|
||||
return Err(crate::DocError::Invalid("too many bodies to read a component appearance chain".into()));
|
||||
}
|
||||
// Legacy ownership can refer to a feature. Index it once, rather
|
||||
// than scanning the timeline for each body of a large component.
|
||||
let features: BTreeMap<_, _> = self.features.iter().rev().map(|f| (f.id, f.component)).collect();
|
||||
let owner = |b: &&crate::ModelBody| {
|
||||
if b.transferred || b.source_name.is_some() {
|
||||
b.component
|
||||
} else {
|
||||
self.body_components.get(&b.name).copied().or_else(|| features.get(&b.feature).copied()).unwrap_or(0)
|
||||
}
|
||||
};
|
||||
let mut materials = state
|
||||
.bodies
|
||||
.iter()
|
||||
.filter(|b| owner(b) == id)
|
||||
.map(|b| self.materials.get(b.definition_name()).and_then(|m| self.material_look(m)));
|
||||
let material = materials.next().flatten().filter(|first| materials.all(|look| look.as_ref() == Some(first)));
|
||||
Ok(AppearanceChain { face: None, body: None, component: self.appearances.components.get(&id).cloned(), material })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn body_appearance_chain(&self, name: &str, component: u64) -> AppearanceChain {
|
||||
AppearanceChain {
|
||||
face: None,
|
||||
body: self.appearances.bodies.get(name).cloned(),
|
||||
component: (component != 0).then(|| self.appearances.components.get(&component).cloned()).flatten(),
|
||||
material: self.materials.get(name).and_then(|material| self.material_look(material)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve a picked face through the same appearance chain used by the viewport.
|
||||
pub fn model_face_look(&self, body: &crate::ModelBody, face: usize) -> Option<Look> {
|
||||
self.face_colors(body).into_iter().find(|(index, _)| *index == face).map(|(_, look)| look).or_else(|| self.model_display_look(body))
|
||||
@@ -193,13 +339,7 @@ impl Document {
|
||||
|
||||
/// Shared definition appearance for a computed occurrence body.
|
||||
pub fn model_body_look(&self, body: &crate::ModelBody) -> Option<Look> {
|
||||
let name = body.definition_name();
|
||||
self.appearances
|
||||
.bodies
|
||||
.get(name)
|
||||
.cloned()
|
||||
.or_else(|| self.appearances.components.get(&self.model_body_component(body)).cloned())
|
||||
.or_else(|| self.materials.get(name).and_then(|material| self.material_look(material)))
|
||||
self.body_appearance_chain(body.definition_name(), self.model_body_component(body)).resolved().cloned()
|
||||
}
|
||||
/// Effective body opacity, including paint carried from an imported body.
|
||||
pub fn model_body_opacity(&self, body: &crate::ModelBody) -> f64 {
|
||||
@@ -212,15 +352,7 @@ impl Document {
|
||||
/// A body's look (without face appearances): its own, else its component's, else its
|
||||
/// material's.
|
||||
pub fn body_look(&self, name: &str, feature: u64) -> Option<Look> {
|
||||
self.appearances
|
||||
.bodies
|
||||
.get(name)
|
||||
.cloned()
|
||||
.or_else(|| {
|
||||
let c = self.body_component(name, feature);
|
||||
(c != 0).then(|| self.appearances.components.get(&c).cloned()).flatten()
|
||||
})
|
||||
.or_else(|| self.materials.get(name).and_then(|m| self.material_look(m)))
|
||||
self.body_appearance_chain(name, self.body_component(name, feature)).resolved().cloned()
|
||||
}
|
||||
|
||||
/// Face appearances on a body: (point on the face, look).
|
||||
@@ -266,6 +398,11 @@ impl Document {
|
||||
/// these independently so an inherited body look does not hide their face overrides.
|
||||
pub fn authored_face_colors(&self, b: &crate::ModelBody) -> Vec<(usize, Look)> {
|
||||
let mut out = Vec::new();
|
||||
self.apply_face_overrides(b, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
fn apply_face_overrides(&self, b: &crate::ModelBody, out: &mut Vec<(usize, Look)>) {
|
||||
for f in self.appearances.faces.iter().filter(|f| f.body == b.definition_name()) {
|
||||
let (p, look) = (crate::apply_point(&b.source_transform, f.point), f.look.clone());
|
||||
if f.strict_name {
|
||||
@@ -305,7 +442,6 @@ impl Document {
|
||||
out.push((i, look));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
@@ -468,6 +604,130 @@ mod tests {
|
||||
check_imported_appearance_precedence(&body);
|
||||
}
|
||||
|
||||
fn chain_fixture() -> (Document, crate::ModelState) {
|
||||
let mut doc = Document::new("Appearance chain");
|
||||
doc.components.push(crate::Component { id: 1, name: "Part".into(), ..Default::default() });
|
||||
doc.body_components.insert("B".into(), 1);
|
||||
let mut state = crate::ModelState::default();
|
||||
state.bodies.push(crate::ModelBody::new("B".into(), solidcraft_kernel::box_solid(Vec3::ZERO, Vec3::new(10., 10., 10.)).unwrap(), 1));
|
||||
(doc, state)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn appearance_chain_agrees_with_display_and_definition_identity() {
|
||||
let (mut doc, mut state) = chain_fixture();
|
||||
let body_look = library("ABS - Red").unwrap();
|
||||
let face_look = library("Steel - Satin PBR").unwrap();
|
||||
doc.appearances.bodies.insert("B".into(), body_look.clone());
|
||||
doc.appearances.components.insert(1, library("ABS - Blue").unwrap());
|
||||
doc.materials.insert("B".into(), "Brass".into());
|
||||
let body = &state.bodies[0];
|
||||
let spot = crate::naming::face_spots(body)[0].unwrap().point;
|
||||
let face_name = crate::naming::face_names(body)[0].clone();
|
||||
doc.appearances.faces.push(FaceLook {
|
||||
body: "B".into(),
|
||||
point: spot,
|
||||
look: face_look.clone(),
|
||||
name: Some(face_name),
|
||||
strict_name: false,
|
||||
certificate: None,
|
||||
});
|
||||
let chain = doc.appearance_chain(&state, AppearanceTarget::Face { body: "B", face: 0 }).unwrap();
|
||||
assert_eq!(chain.active(), Some("face"));
|
||||
assert_eq!(chain.resolved(), Some(&face_look));
|
||||
assert_eq!(doc.model_face_look(body, 0).as_ref(), chain.resolved());
|
||||
let chain = doc.appearance_chain(&state, AppearanceTarget::Body("B")).unwrap();
|
||||
assert_eq!(chain.active(), Some("body"));
|
||||
assert_eq!(doc.model_body_look(body).as_ref(), chain.resolved());
|
||||
assert_eq!(doc.body_look("B", 1).as_ref(), chain.resolved());
|
||||
assert_eq!(chain.component.as_ref().unwrap().name, "ABS - Blue");
|
||||
assert_eq!(chain.material.as_ref().unwrap().name, "Brass");
|
||||
// A computed placement resolves the definition's assignments, not its label.
|
||||
state.bodies[0].name = "Occurrence/B".into();
|
||||
state.bodies[0].source_name = Some("B".into());
|
||||
state.bodies[0].component = 1;
|
||||
let chain = doc.appearance_chain(&state, AppearanceTarget::Body("Occurrence/B")).unwrap();
|
||||
assert_eq!(chain.body, Some(body_look));
|
||||
assert_eq!(chain.material.as_ref().unwrap().name, "Brass");
|
||||
assert!(doc.appearance_chain(&state, AppearanceTarget::Face { body: "Occurrence/B", face: usize::MAX }).is_err());
|
||||
assert!(doc.appearance_chain(&state, AppearanceTarget::Body("missing")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn appearance_chain_component_material_is_common_or_absent_and_imports_stay_fallbacks() {
|
||||
let (mut doc, mut state) = chain_fixture();
|
||||
state.bodies[0].imported = Some(std::sync::Arc::new(ImportedLook { color: Some([0.2, 0.4, 0.6]), ..Default::default() }));
|
||||
let body = doc.appearance_chain(&state, AppearanceTarget::Body("B")).unwrap();
|
||||
assert_eq!(body.active(), None);
|
||||
assert!(doc.model_display_look(&state.bodies[0]).is_some());
|
||||
doc.materials.insert("B".into(), "Brass".into());
|
||||
assert_eq!(doc.appearance_chain(&state, AppearanceTarget::Component(1)).unwrap().active(), Some("material"));
|
||||
let mut second = state.bodies[0].clone();
|
||||
second.name = "C".into();
|
||||
doc.body_components.insert("C".into(), 1);
|
||||
state.bodies.push(second);
|
||||
assert_eq!(doc.appearance_chain(&state, AppearanceTarget::Component(1)).unwrap().active(), None);
|
||||
doc.materials.insert("C".into(), "Brass".into());
|
||||
assert_eq!(doc.appearance_chain(&state, AppearanceTarget::Component(1)).unwrap().active(), Some("material"));
|
||||
doc.materials.insert("C".into(), "Steel".into());
|
||||
assert_eq!(doc.appearance_chain(&state, AppearanceTarget::Component(1)).unwrap().material, None);
|
||||
doc.appearances.components.insert(1, library("ABS - Blue").unwrap());
|
||||
assert_eq!(doc.appearance_chain(&state, AppearanceTarget::Component(1)).unwrap().active(), Some("component"));
|
||||
state.bodies.clear();
|
||||
assert_eq!(doc.appearance_chain(&state, AppearanceTarget::Component(1)).unwrap().material, None);
|
||||
assert!(doc.appearance_chain(&state, AppearanceTarget::Component(0)).is_err());
|
||||
assert!(doc.appearance_chain(&state, AppearanceTarget::Component(99)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn appearance_replacement_validates_values_and_design_budget_without_mutation() {
|
||||
let from = library("ABS - Red").unwrap();
|
||||
let to = library("ABS - Blue").unwrap();
|
||||
let mut appearances = Appearances::default();
|
||||
appearances.bodies.insert("B".into(), from.clone());
|
||||
for opacity in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1., 2.] {
|
||||
let mut invalid = to.clone();
|
||||
invalid.opacity = opacity;
|
||||
assert!(appearances.replacing(&from, &invalid, None).is_err());
|
||||
assert!(appearances.replacing(&invalid, &to, None).is_err());
|
||||
assert_eq!(appearances.bodies["B"], from);
|
||||
}
|
||||
let mut invalid = library("Steel - Satin PBR").unwrap();
|
||||
invalid.opacity = 0.5;
|
||||
assert!(appearances.replacing(&from, &invalid, None).is_err());
|
||||
let (changed, count) = appearances.replacing(&from, &to, None).unwrap().unwrap();
|
||||
assert_eq!(count, 1);
|
||||
assert_eq!(changed.bodies["B"], to);
|
||||
assert_eq!(appearances.bodies["B"], from);
|
||||
assert!(appearances.replacing(&from, &from, None).unwrap().is_none());
|
||||
for i in 0..100_000 {
|
||||
appearances.components.insert(i, from.clone());
|
||||
}
|
||||
assert!(appearances.replacing(&from, &to, None).is_err());
|
||||
let (mut doc, state) = chain_fixture();
|
||||
doc.appearances = appearances;
|
||||
assert!(doc.appearance_chain(&state, AppearanceTarget::Body("B")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn appearance_chain_of_ten_thousand_body_component_has_four_steps() {
|
||||
let (mut doc, mut state) = chain_fixture();
|
||||
let mut body = state.bodies[0].clone();
|
||||
body.source_name = Some("B".into());
|
||||
body.component = 1;
|
||||
state.bodies = (0..10_000)
|
||||
.map(|i| {
|
||||
let mut b = body.clone();
|
||||
b.name = format!("Placed {i}");
|
||||
b
|
||||
})
|
||||
.collect();
|
||||
doc.materials.insert("B".into(), "Brass".into());
|
||||
let chain = doc.appearance_chain(&state, AppearanceTarget::Component(1)).unwrap();
|
||||
assert_eq!(chain.steps().len(), 4);
|
||||
assert_eq!(chain.active(), Some("material"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn library_and_materials() {
|
||||
assert_eq!(library("abs - red").map(|l| l.color), Some([196, 40, 40]));
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
//! Read the shared document appearance chain and replace exact saved overrides.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use solidcraft_doc::appearance::{AppearanceScope, AppearanceTarget, Look};
|
||||
|
||||
use crate::params::bad;
|
||||
use crate::{Result, Session};
|
||||
|
||||
const MAX_TARGETS: usize = 10_000;
|
||||
|
||||
fn name<'a>(cmd: &str, value: &'a Value) -> Result<&'a str> {
|
||||
value.as_str().filter(|s| !s.is_empty() && s.len() <= 4096).ok_or_else(|| bad(cmd, "target name must have 1..4096 bytes"))
|
||||
}
|
||||
|
||||
fn component(s: &Session, cmd: &str, value: &Value) -> Result<u64> {
|
||||
let key = match value {
|
||||
Value::String(_) => name(cmd, value)?.to_string(),
|
||||
Value::Number(_) => value.as_u64().ok_or_else(|| bad(cmd, "component must be a name or unsigned id"))?.to_string(),
|
||||
_ => return Err(bad(cmd, "component must be a name or unsigned id")),
|
||||
};
|
||||
s.doc.find_component(&key).filter(|id| *id != 0).ok_or_else(|| bad(cmd, "unknown or root component"))
|
||||
}
|
||||
|
||||
pub(super) fn chain(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "appearance.chain";
|
||||
let target = p.get("target").and_then(Value::as_object).ok_or_else(|| bad(cmd, "give one target object"))?;
|
||||
let target = match (target.get("body"), target.get("face"), target.get("component")) {
|
||||
(Some(body), None, None) if target.len() == 1 => AppearanceTarget::Body(name(cmd, body)?),
|
||||
(Some(body), Some(face), None) if target.len() == 2 => AppearanceTarget::Face {
|
||||
body: name(cmd, body)?,
|
||||
face: face.as_u64().and_then(|f| usize::try_from(f).ok()).ok_or_else(|| bad(cmd, "face must be a zero-based unsigned index"))?,
|
||||
},
|
||||
(None, None, Some(id)) if target.len() == 1 => AppearanceTarget::Component(component(s, cmd, id)?),
|
||||
_ => return Err(bad(cmd, "target must be {body}, {body, face}, or {component}")),
|
||||
};
|
||||
let chain = s.doc.appearance_chain(&s.model.state(), target).map_err(|e| bad(cmd, e.to_string()))?;
|
||||
Ok(json!({
|
||||
"steps": chain.steps().into_iter().map(|(step, look)| json!({"step":step,"look":look.map(super::look_json)})).collect::<Vec<_>>(),
|
||||
"active": chain.active(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// A saved in-design look's label is inert; a string explicitly selects a library
|
||||
/// recipe. Reuse assignment's optical parsing rather than a second preset resolver.
|
||||
fn look(cmd: &str, value: &Value) -> Result<Look> {
|
||||
let params = match value {
|
||||
Value::String(_) => Cow::Owned(json!({"appearance":name(cmd, value)?})),
|
||||
Value::Object(_) => Cow::Borrowed(value),
|
||||
_ => return Err(bad(cmd, "from and to must be library names or look objects")),
|
||||
};
|
||||
if let Some(opacity) = params.get("opacity")
|
||||
&& opacity.as_f64().filter(|o| o.is_finite() && (0.0..=1.0).contains(o)).is_none()
|
||||
{
|
||||
return Err(bad(cmd, "opacity must be a finite number in 0..1"));
|
||||
}
|
||||
if let Some(appearance) = params.get("appearance") {
|
||||
name(cmd, appearance)?;
|
||||
}
|
||||
super::appearance_look(cmd, ¶ms)?.ok_or_else(|| bad(cmd, "from and to require a look; use appearance.assign to clear"))
|
||||
}
|
||||
|
||||
fn scope(s: &Session, cmd: &str, value: &Value) -> Result<AppearanceScope> {
|
||||
let object = value
|
||||
.as_object()
|
||||
.filter(|o| !o.is_empty() && o.keys().all(|k| matches!(k.as_str(), "bodies" | "components")))
|
||||
.ok_or_else(|| bad(cmd, "scope must contain bodies and/or components lists"))?;
|
||||
let list =
|
||||
|key: &str| -> Result<&Vec<Value>> { object.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, "scope targets must be lists")) };
|
||||
let mut count = 0usize;
|
||||
for key in object.keys() {
|
||||
count = count.saturating_add(list(key)?.len());
|
||||
if count > MAX_TARGETS {
|
||||
return Err(bad(cmd, "scope has more than 10000 targets"));
|
||||
}
|
||||
}
|
||||
let mut scope = AppearanceScope::default();
|
||||
if object.contains_key("bodies") {
|
||||
let state = s.model.state();
|
||||
let bodies: BTreeSet<_> = state.bodies.iter().map(|b| b.name.as_str()).collect();
|
||||
for body in list("bodies")? {
|
||||
let body = name(cmd, body)?;
|
||||
if !bodies.contains(body) {
|
||||
return Err(bad(cmd, "unknown body in scope"));
|
||||
}
|
||||
scope.bodies.insert(body.into());
|
||||
}
|
||||
}
|
||||
if object.contains_key("components") {
|
||||
// Build indexes once: 10000 repeated component targets must not scan a
|
||||
// 10000-component design once per target.
|
||||
let ids: BTreeSet<_> = s.doc.components.iter().map(|c| c.id).collect();
|
||||
let names: BTreeMap<_, _> = s.doc.components.iter().rev().map(|c| (c.name.as_str(), c.id)).collect();
|
||||
for target in list("components")? {
|
||||
let id = match target {
|
||||
Value::String(_) => {
|
||||
let key = name(cmd, target)?;
|
||||
key.parse::<u64>().ok().filter(|id| ids.contains(id)).or_else(|| names.get(key).copied())
|
||||
}
|
||||
Value::Number(_) => target.as_u64().filter(|id| ids.contains(id)),
|
||||
_ => None,
|
||||
}
|
||||
.filter(|id| *id != 0)
|
||||
.ok_or_else(|| bad(cmd, "unknown component in scope"))?;
|
||||
scope.components.insert(id);
|
||||
}
|
||||
}
|
||||
Ok(scope)
|
||||
}
|
||||
|
||||
pub(super) fn replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "appearance.replace";
|
||||
s.doc.appearances.check_budget().map_err(|e| bad(cmd, e.to_string()))?;
|
||||
let from = look(cmd, p.get("from").ok_or_else(|| bad(cmd, "from is required"))?)?;
|
||||
let to = look(cmd, p.get("to").ok_or_else(|| bad(cmd, "to is required"))?)?;
|
||||
let scope = p.get("scope").map(|v| scope(s, cmd, v)).transpose()?;
|
||||
// Every validation and allocation completes before obtaining a mutable document.
|
||||
let replacement = s.doc.appearances.replacing(&from, &to, scope.as_ref()).map_err(|e| bad(cmd, e.to_string()))?;
|
||||
let count = if let Some((appearances, count)) = replacement {
|
||||
s.doc_mut().appearances = appearances;
|
||||
count
|
||||
} else {
|
||||
0
|
||||
};
|
||||
Ok(json!({"count": count}))
|
||||
}
|
||||
@@ -12,6 +12,9 @@ use super::CommandSpec;
|
||||
use crate::params::{bad, bool_, str_, string_list};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
#[path = "appearance_chain.rs"]
|
||||
mod appearance_chain;
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("inspect.colored_components", "Enable Component Colors", colored_components)
|
||||
.at("SOLID", "INSPECT").icon("colored_components").noundo()
|
||||
@@ -46,6 +49,12 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
appearance?: library name or stable starter.* ID (appearance.library) | color: \"#rrggbb\" or [r, g, b] (0–255), opacity? (0–1, default 1); \
|
||||
name?: inert copied look label (requires color, mutually exclusive with appearance); pbr?: {metallic:0..1, roughness:0.045..1, dielectric_ior:1..3} (requires color/appearance and opacity 1); a starter ID or registered starter name resolves its recipe before color overrides; omitted pbr retains that response and pbr: null explicitly clears it. Unavailable glass recipes refuse through either selector. Other custom labels with an explicit color retain legacy scalar behavior. Neither appearance nor color (or color: null): clear, so the face follows its body, the body its component, the component its material",
|
||||
),
|
||||
CommandSpec::new("appearance.chain", "Appearance Chain", appearance_chain::chain).icon("inspect").noundo().params(
|
||||
"target: {body: name} | {body: name, face: zero-based model.faces index} | {component: name or id}. Returns steps [{step: face|body|component|material, look: {name,color,opacity,pbr?} or null}] in precedence order and active (step or null). Component material is the common default look of its directly owned bodies, null if mixed/empty. Imported paint is a display fallback outside the four steps. Read-only; no dialogs",
|
||||
),
|
||||
CommandSpec::new("appearance.replace", "Replace Appearance", appearance_chain::replace).icon("appearance").params(
|
||||
"from: library name | saved look {name,color,opacity,pbr?} (copy appearance.list in_design); to: library name | assignment look {appearance? | color, name?, opacity?, pbr?} (appearance.assign rules; no clear). Matches the full look including name and PBR. scope?: {bodies?: [names], components?: [names or ids]}, at most 10000 targets; body scope includes face overrides, component scope selects only the component override. Omitted scope means all overrides, including hidden/suppressed ones; physical defaults are unchanged. Duplicate targets count once. Returns count of rewritten overrides; zero adds no history. One undo step, atomic; no dialogs. Designs above 100000 overrides refuse",
|
||||
),
|
||||
CommandSpec::new("appearance.library", "Appearance Library", appearance_library).icon("library")
|
||||
.noundo()
|
||||
.params("→ 20 legacy scalar appearances, six opaque PBR finishes and 40 starter recipes with IDs, categories, provenance, requirements and availability; six starter glass recipes are unavailable"),
|
||||
@@ -474,71 +483,9 @@ pub(super) fn color_param(v: &Value) -> Option<[u8; 3]> {
|
||||
}
|
||||
|
||||
pub(super) fn appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
use solidcraft_doc::appearance::{FaceLook, Look, library};
|
||||
use solidcraft_doc::appearance::FaceLook;
|
||||
let cmd = "appearance.assign";
|
||||
// A saved label is data, not a request to resolve a recipe. Keep the explicit
|
||||
// appearance selector separate so an owned look may have any recipe's ID as its name.
|
||||
let copied_name = match p.get("name") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(name)) if !name.is_empty() && name.chars().count() <= 128 && !name.chars().any(char::is_control) => Some(name),
|
||||
_ => return Err(bad(cmd, "`name` must be a nonempty label of at most 128 characters without controls")),
|
||||
};
|
||||
if copied_name.is_some() && (p.get("color").is_none_or(Value::is_null) || p.get("appearance").is_some_and(|value| !value.is_null())) {
|
||||
return Err(bad(cmd, "`name` requires an explicit color and cannot be combined with `appearance`"));
|
||||
}
|
||||
// Both the stable ID and a registered display name explicitly select a recipe.
|
||||
// Copied labels use `name`, so color overrides cannot bypass unsupported optics.
|
||||
let preset = str_(p, "appearance").and_then(solidcraft_doc::appearance_pack::find);
|
||||
let mut look: Option<Look> = if let Some(preset) = preset {
|
||||
// Refuse unsupported optics before any color/PBR/opacity override.
|
||||
let mut look = preset.opaque_look().map_err(|e| bad(cmd, e.to_string()))?;
|
||||
if let Some(color) = p.get("color").filter(|v| !v.is_null()) {
|
||||
look.color = color_param(color).ok_or_else(|| bad(cmd, "invalid preset color override"))?;
|
||||
}
|
||||
if let Some(opacity) = p.get("opacity").and_then(Value::as_f64).filter(|x| x.is_finite()) {
|
||||
look.opacity = opacity.clamp(0.0, 1.0);
|
||||
}
|
||||
Some(look)
|
||||
} else {
|
||||
match (str_(p, "appearance"), p.get("color")) {
|
||||
// A colour with a name: that colour, called that (a name not in the library is fine).
|
||||
(Some(n), Some(v)) if !v.is_null() => {
|
||||
let c = color_param(v).ok_or_else(|| bad(cmd, "`color` must be \"#rrggbb\" or [r, g, b] with values 0–255"))?;
|
||||
let o = p.get("opacity").and_then(Value::as_f64).filter(|x| x.is_finite()).unwrap_or(1.0);
|
||||
let mut l = Look::custom(c, o);
|
||||
l.name = n.chars().take(128).collect();
|
||||
Some(l)
|
||||
}
|
||||
(Some(n), _) => {
|
||||
let mut l = if let Some(preset) = solidcraft_doc::appearance_pack::find(n) {
|
||||
preset.opaque_look().map_err(|e| bad(cmd, e.to_string()))?
|
||||
} else {
|
||||
library(n).ok_or_else(|| bad(cmd, format!("no appearance `{n}` in the library (appearance.library)")))?
|
||||
};
|
||||
if let Some(o) = p.get("opacity").and_then(Value::as_f64).filter(|x| x.is_finite()) {
|
||||
l.opacity = o.clamp(0.0, 1.0);
|
||||
}
|
||||
Some(l)
|
||||
}
|
||||
(None, None | Some(Value::Null)) => None,
|
||||
(None, Some(v)) => {
|
||||
let c = color_param(v).ok_or_else(|| bad(cmd, "`color` must be \"#rrggbb\" or [r, g, b] with values 0–255"))?;
|
||||
let o = match p.get("opacity") {
|
||||
Some(o) => o.as_f64().filter(|x| x.is_finite() && (0.0..=1.0).contains(x)).ok_or_else(|| bad(cmd, "`opacity` must be 0…1"))?,
|
||||
None => 1.0,
|
||||
};
|
||||
Some(Look::custom(c, o))
|
||||
}
|
||||
}
|
||||
};
|
||||
if let Some(l) = &mut look {
|
||||
if let Some(name) = copied_name {
|
||||
l.name = name.clone();
|
||||
}
|
||||
attach_pbr(cmd, p, l)?;
|
||||
} else if p.get("pbr").is_some_and(|v| !v.is_null()) {
|
||||
return Err(bad(cmd, "`pbr` requires a color or appearance"));
|
||||
}
|
||||
let look = appearance_look(cmd, p)?;
|
||||
let bodies = string_list(p, "bodies");
|
||||
let st = s.model.state();
|
||||
if bodies.iter().any(|b| st.body(b).is_none()) {
|
||||
@@ -642,6 +589,75 @@ pub(super) fn appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}))
|
||||
}
|
||||
|
||||
/// Shared look parser for assignment and atomic replacement.
|
||||
pub(super) fn appearance_look(cmd: &str, p: &Value) -> Result<Option<solidcraft_doc::appearance::Look>> {
|
||||
use solidcraft_doc::appearance::{Look, library};
|
||||
// A saved label is data, not a request to resolve a recipe. Keep the explicit
|
||||
// appearance selector separate so an owned look may have any recipe's ID as its name.
|
||||
let copied_name = match p.get("name") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(name)) if !name.is_empty() && name.chars().count() <= 128 && !name.chars().any(char::is_control) => Some(name),
|
||||
_ => return Err(bad(cmd, "`name` must be a nonempty label of at most 128 characters without controls")),
|
||||
};
|
||||
if copied_name.is_some() && (p.get("color").is_none_or(Value::is_null) || p.get("appearance").is_some_and(|value| !value.is_null())) {
|
||||
return Err(bad(cmd, "`name` requires an explicit color and cannot be combined with `appearance`"));
|
||||
}
|
||||
// Both the stable ID and a registered display name explicitly select a recipe.
|
||||
// Copied labels use `name`, so color overrides cannot bypass unsupported optics.
|
||||
let preset = str_(p, "appearance").and_then(solidcraft_doc::appearance_pack::find);
|
||||
let mut look: Option<Look> = if let Some(preset) = preset {
|
||||
// Refuse unsupported optics before any color/PBR/opacity override.
|
||||
let mut look = preset.opaque_look().map_err(|e| bad(cmd, e.to_string()))?;
|
||||
if let Some(color) = p.get("color").filter(|v| !v.is_null()) {
|
||||
look.color = color_param(color).ok_or_else(|| bad(cmd, "invalid preset color override"))?;
|
||||
}
|
||||
if let Some(opacity) = p.get("opacity").and_then(Value::as_f64).filter(|x| x.is_finite()) {
|
||||
look.opacity = opacity.clamp(0.0, 1.0);
|
||||
}
|
||||
Some(look)
|
||||
} else {
|
||||
match (str_(p, "appearance"), p.get("color")) {
|
||||
// A colour with a name: that colour, called that (a name not in the library is fine).
|
||||
(Some(n), Some(v)) if !v.is_null() => {
|
||||
let c = color_param(v).ok_or_else(|| bad(cmd, "`color` must be \"#rrggbb\" or [r, g, b] with values 0–255"))?;
|
||||
let o = p.get("opacity").and_then(Value::as_f64).filter(|x| x.is_finite()).unwrap_or(1.0);
|
||||
let mut l = Look::custom(c, o);
|
||||
l.name = n.chars().take(128).collect();
|
||||
Some(l)
|
||||
}
|
||||
(Some(n), _) => {
|
||||
let mut l = if let Some(preset) = solidcraft_doc::appearance_pack::find(n) {
|
||||
preset.opaque_look().map_err(|e| bad(cmd, e.to_string()))?
|
||||
} else {
|
||||
library(n).ok_or_else(|| bad(cmd, format!("no appearance `{n}` in the library (appearance.library)")))?
|
||||
};
|
||||
if let Some(o) = p.get("opacity").and_then(Value::as_f64).filter(|x| x.is_finite()) {
|
||||
l.opacity = o.clamp(0.0, 1.0);
|
||||
}
|
||||
Some(l)
|
||||
}
|
||||
(None, None | Some(Value::Null)) => None,
|
||||
(None, Some(v)) => {
|
||||
let c = color_param(v).ok_or_else(|| bad(cmd, "`color` must be \"#rrggbb\" or [r, g, b] with values 0–255"))?;
|
||||
let o = match p.get("opacity") {
|
||||
Some(o) => o.as_f64().filter(|x| x.is_finite() && (0.0..=1.0).contains(x)).ok_or_else(|| bad(cmd, "`opacity` must be 0…1"))?,
|
||||
None => 1.0,
|
||||
};
|
||||
Some(Look::custom(c, o))
|
||||
}
|
||||
}
|
||||
};
|
||||
if let Some(l) = &mut look {
|
||||
if let Some(name) = copied_name {
|
||||
l.name = name.clone();
|
||||
}
|
||||
attach_pbr(cmd, p, l)?;
|
||||
} else if p.get("pbr").is_some_and(|v| !v.is_null()) {
|
||||
return Err(bad(cmd, "`pbr` requires a color or appearance"));
|
||||
}
|
||||
Ok(look)
|
||||
}
|
||||
|
||||
fn dist_to(b: &solidcraft_doc::ModelBody, p: solidcraft_geom::Vec3) -> f64 {
|
||||
let bb = b.mesh().bounds();
|
||||
let c = solidcraft_geom::Vec3::new(p.x.clamp(bb.min.x, bb.max.x), p.y.clamp(bb.min.y, bb.max.y), p.z.clamp(bb.min.z, bb.max.z));
|
||||
|
||||
@@ -637,3 +637,223 @@ fn starter_names_and_ids_share_admission_before_all_overrides() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn chain_read(s: &mut Session, target: serde_json::Value) -> serde_json::Value {
|
||||
s.execute("appearance.chain", &json!({"target":target})).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn appearance_chain_and_from_material_preserve_mass_and_all_four_steps() {
|
||||
let mut s = Session::default();
|
||||
s.execute("component.create", &json!({"name":"Part"})).unwrap();
|
||||
s.execute("solid.box", &json!({"body_name":"Specimen","length":10,"width":20,"height":5})).unwrap();
|
||||
s.execute("material.create", &json!({"name":"Substrate","density_g_cm3":2.3,"appearance":"Steel - Satin PBR"})).unwrap();
|
||||
s.execute("material.assign", &json!({"bodies":["Specimen"],"material":"Substrate"})).unwrap();
|
||||
let mass = s.execute("component.properties", &json!({})).unwrap();
|
||||
let physical = s.doc.user_materials.clone();
|
||||
let face = s.execute("model.faces", &json!({"body":"Specimen"})).unwrap()["faces"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|f| f["point"][2] == 5.0)
|
||||
.unwrap()["index"]
|
||||
.clone();
|
||||
let target = json!({"body":"Specimen","face":face});
|
||||
s.execute("appearance.assign", &json!({"components":["Part"],"appearance":"ABS - Blue"})).unwrap();
|
||||
s.execute("appearance.assign", &json!({"bodies":["Specimen"],"color":"#abcdef","opacity":0.5})).unwrap();
|
||||
s.execute("appearance.assign", &json!({"body":"Specimen","faces":[[5,10,5]],"appearance":"Copper - Clean PBR"})).unwrap();
|
||||
let history = (s.undo.len(), s.redo.len(), s.revision);
|
||||
let doc = s.doc.clone();
|
||||
let chain = chain_read(&mut s, target.clone());
|
||||
assert_eq!(chain["active"], "face");
|
||||
assert_eq!(
|
||||
chain["steps"].as_array().unwrap().iter().map(|s| s["step"].as_str().unwrap()).collect::<Vec<_>>(),
|
||||
["face", "body", "component", "material"]
|
||||
);
|
||||
assert_eq!(chain["steps"][0]["look"]["name"], "Copper - Clean PBR");
|
||||
assert_eq!(chain["steps"][1]["look"]["opacity"], 0.5);
|
||||
assert_eq!(chain["steps"][2]["look"]["name"], "ABS - Blue");
|
||||
assert_eq!(chain["steps"][3]["look"]["pbr"]["metallic"], 1.0);
|
||||
assert!(Arc::ptr_eq(&doc, &s.doc));
|
||||
assert_eq!((s.undo.len(), s.redo.len(), s.revision), history);
|
||||
assert_eq!(chain_read(&mut s, json!({"body":"Specimen"}))["active"], "body");
|
||||
assert_eq!(chain_read(&mut s, json!({"component":"Part"}))["active"], "component");
|
||||
// The existing clear form walks down the same chain, one edit at a time.
|
||||
s.execute("appearance.assign", &json!({"body":"Specimen","faces":[[6,11,5]],"color":null})).unwrap();
|
||||
assert_eq!(chain_read(&mut s, target.clone())["active"], "body");
|
||||
s.execute("appearance.assign", &json!({"bodies":["Specimen"],"color":null})).unwrap();
|
||||
assert_eq!(chain_read(&mut s, target.clone())["active"], "component");
|
||||
s.execute("appearance.assign", &json!({"components":["Part"]})).unwrap();
|
||||
for t in [target.clone(), json!({"body":"Specimen"}), json!({"component":"Part"})] {
|
||||
assert_eq!(chain_read(&mut s, t)["active"], "material");
|
||||
}
|
||||
// Clearing each target independently also restores material when no lower override exists.
|
||||
for assign in [json!({"bodies":["Specimen"]}), json!({"components":["Part"]}), json!({"body":"Specimen","faces":[[5,10,5]]})] {
|
||||
let mut painted = assign.clone();
|
||||
painted["appearance"] = json!("ABS - Red");
|
||||
s.execute("appearance.assign", &painted).unwrap();
|
||||
s.execute("appearance.assign", &assign).unwrap();
|
||||
assert_eq!(chain_read(&mut s, target.clone())["active"], "material");
|
||||
assert_eq!(s.execute("component.properties", &json!({})).unwrap(), mass);
|
||||
}
|
||||
assert_eq!(s.doc.user_materials, physical);
|
||||
let state = s.model.state();
|
||||
let body = state.body("Specimen").unwrap();
|
||||
assert_eq!(s.doc.model_face_look(body, face.as_u64().unwrap() as usize), s.doc.model_display_look(body));
|
||||
let mut reopened = Session::new(crate::doc::Document::from_json(&s.doc.to_json()).unwrap());
|
||||
assert_eq!(chain_read(&mut reopened, target.clone()), chain_read(&mut s, target));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn appearance_replace_is_exact_atomic_one_undo_and_survives_reopen() {
|
||||
let mut s = Session::default();
|
||||
s.execute("component.create", &json!({"name":"Part"})).unwrap();
|
||||
s.execute("solid.box", &json!({"body_name":"Specimen","length":10,"width":20,"height":5})).unwrap();
|
||||
s.execute("material.create", &json!({"name":"Substrate","density_g_cm3":2.3,"appearance":"Steel - Satin PBR"})).unwrap();
|
||||
s.execute("material.assign", &json!({"bodies":["Specimen"],"material":"Substrate"})).unwrap();
|
||||
s.execute(
|
||||
"appearance.assign",
|
||||
&json!({"bodies":["Specimen"],"components":["Part"],"body":"Specimen","faces":[[5,10,5]],"appearance":"Steel - Satin PBR"}),
|
||||
)
|
||||
.unwrap();
|
||||
// Same label and color, different optical values: full equality must distinguish it.
|
||||
let mut scalar = s.doc.appearances.bodies["Specimen"].clone();
|
||||
scalar.pbr = None;
|
||||
s.doc_mut().appearances.bodies.insert("Suppressed fixture".into(), scalar.clone());
|
||||
let mass = s.execute("component.properties", &json!({})).unwrap();
|
||||
let scene = product_scene::extract(&s).unwrap();
|
||||
let before = s.doc.clone();
|
||||
let history = s.undo.len();
|
||||
let listed = s.execute("appearance.list", &json!({})).unwrap();
|
||||
let from = listed["in_design"].as_array().unwrap().iter().find(|l| l.get("pbr").is_some()).unwrap().clone();
|
||||
let params = json!({"from":from,"to":"Copper - Clean PBR"});
|
||||
assert_eq!(s.execute("appearance.replace", ¶ms).unwrap()["count"], 3);
|
||||
assert_eq!(s.undo.len(), history + 1);
|
||||
assert_eq!(s.doc.appearances.bodies["Suppressed fixture"], scalar);
|
||||
assert_eq!(s.doc.user_materials, before.user_materials);
|
||||
assert_eq!(s.doc.materials, before.materials);
|
||||
assert_eq!(s.doc.features, before.features);
|
||||
assert_eq!(s.doc.occurrences, before.occurrences);
|
||||
assert_eq!(s.execute("component.properties", &json!({})).unwrap(), mass);
|
||||
let after_scene = product_scene::extract(&s).unwrap();
|
||||
assert!(Arc::ptr_eq(&scene.meshes[0].mesh, &after_scene.meshes[0].mesh));
|
||||
let after = s.doc.appearances.clone();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.appearances, before.appearances);
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.appearances, after);
|
||||
let reopened = Session::new(crate::doc::Document::from_json(&s.doc.to_json()).unwrap());
|
||||
assert_eq!(reopened.doc.appearances, after);
|
||||
let snapshot = s.doc.clone();
|
||||
let history = (s.undo.len(), s.redo.len(), s.revision);
|
||||
assert_eq!(s.execute("appearance.replace", ¶ms).unwrap()["count"], 0);
|
||||
assert_eq!(s.execute("appearance.replace", &json!({"from":"Copper - Clean PBR","to":"Copper - Clean PBR"})).unwrap()["count"], 0);
|
||||
assert!(Arc::ptr_eq(&snapshot, &s.doc));
|
||||
assert_eq!((s.undo.len(), s.redo.len(), s.revision), history);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn appearance_replace_scope_deduplicates_and_does_not_expand_component_targets() {
|
||||
let mut s = Session::default();
|
||||
s.execute("component.create", &json!({"name":"Part"})).unwrap();
|
||||
s.execute("solid.box", &json!({"body_name":"Specimen","length":10,"width":20,"height":5})).unwrap();
|
||||
let part = s.doc.find_component("Part").unwrap();
|
||||
let assign = json!({"bodies":["Specimen"],"components":["Part"],"body":"Specimen","faces":[[5,10,5]],"appearance":"ABS - Red"});
|
||||
s.execute("appearance.assign", &assign).unwrap();
|
||||
let history = s.undo.len();
|
||||
assert_eq!(
|
||||
s.execute(
|
||||
"appearance.replace",
|
||||
&json!({"from":"ABS - Red","to":{"color":"#123456","opacity":0.4},"scope":{"bodies":["Specimen","Specimen"]}})
|
||||
)
|
||||
.unwrap()["count"],
|
||||
2
|
||||
);
|
||||
assert_eq!(s.undo.len(), history + 1);
|
||||
assert_eq!(s.doc.appearances.components[&part].name, "ABS - Red");
|
||||
assert_eq!(
|
||||
s.execute("appearance.replace", &json!({"from":"ABS - Red","to":"ABS - Blue","scope":{"components":[part,"Part",part.to_string()]}}))
|
||||
.unwrap()["count"],
|
||||
1
|
||||
);
|
||||
assert_eq!(s.doc.appearances.bodies["Specimen"].color, [18, 52, 86]);
|
||||
// Empty scope is an explicit no-op, and a no-op preserves an existing redo entry.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let doc = s.doc.clone();
|
||||
let history = (s.undo.len(), s.redo.len(), s.revision);
|
||||
assert_eq!(s.execute("appearance.replace", &json!({"from":"ABS - Red","to":"ABS - Blue","scope":{"bodies":[]}})).unwrap()["count"], 0);
|
||||
assert!(Arc::ptr_eq(&doc, &s.doc));
|
||||
assert_eq!((s.undo.len(), s.redo.len(), s.revision), history);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn appearance_chain_and_replace_hostile_inputs_refuse_atomically() {
|
||||
let mut s = fixture();
|
||||
s.execute("appearance.assign", &json!({"bodies":["Specimen"],"appearance":"ABS - Red"})).unwrap();
|
||||
let doc = s.doc.clone();
|
||||
let history = (s.undo.len(), s.redo.len(), s.revision);
|
||||
for target in [
|
||||
json!({}),
|
||||
json!({"body":"missing"}),
|
||||
json!({"component":"missing"}),
|
||||
json!({"component":0}),
|
||||
json!({"body":"Specimen","face":u64::MAX}),
|
||||
json!({"body":"Specimen","face":-1}),
|
||||
json!({"body":"Specimen","component":1}),
|
||||
json!({"body":["Specimen"]}),
|
||||
json!({"body":"Specimen","face":null}),
|
||||
] {
|
||||
assert!(s.execute("appearance.chain", &json!({"target":target})).is_err());
|
||||
}
|
||||
for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
|
||||
// JSON has no nonfinite numbers: serde_json encodes these as null.
|
||||
for look in [
|
||||
json!({"color":[value,0,0]}),
|
||||
json!({"color":"#ffffff","opacity":value}),
|
||||
json!({"color":"#ffffff","pbr":{"metallic":value,"roughness":0.3,"dielectric_ior":1.5}}),
|
||||
] {
|
||||
for field in ["from", "to"] {
|
||||
let mut params = json!({"from":"ABS - Red","to":"ABS - Blue"});
|
||||
params[field] = look.clone();
|
||||
assert!(s.execute("appearance.replace", ¶ms).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
for params in [
|
||||
json!({"from":"ABS - Red","to":null}),
|
||||
json!({"from":"unknown","to":"ABS - Blue"}),
|
||||
json!({"from":"ABS - Red","to":{"color":[256,0,0]}}),
|
||||
json!({"from":"ABS - Red","to":{"appearance":"ABS - Blue","opacity":2}}),
|
||||
json!({"from":"ABS - Red","to":{"appearance":"starter.glass.clear-soda-lime","color":"#ffffff","pbr":null}}),
|
||||
json!({"from":"ABS - Red","to":"ABS - Blue","scope":{"bodies":["Specimen","missing"]}}),
|
||||
json!({"from":"ABS - Red","to":"ABS - Blue","scope":{"components":["missing"]}}),
|
||||
json!({"from":"ABS - Red","to":"ABS - Blue","scope":{"bodies":["Specimen"],"components":[false]}}),
|
||||
json!({"from":"ABS - Red","to":"ABS - Blue","scope":{"bodies":vec!["Specimen";10_001]}}),
|
||||
json!({"from":"ABS - Red","to":"ABS - Blue","scope":{"bodies":vec!["Specimen";5001],"components":vec!["missing";5000]}}),
|
||||
json!({"from":"ABS - Red","to":"ABS - Blue","scope":{"bodies":"Specimen"}}),
|
||||
json!({"from":"ABS - Red","to":"ABS - Blue","scope":{"faces":[]}}),
|
||||
] {
|
||||
assert!(s.execute("appearance.replace", ¶ms).is_err(), "{params}");
|
||||
assert!(Arc::ptr_eq(&doc, &s.doc));
|
||||
assert_eq!((s.undo.len(), s.redo.len(), s.revision), history);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn appearance_chain_and_replace_process_ten_thousand_entries_with_bounded_output() {
|
||||
let mut s = fixture();
|
||||
let look = crate::doc::appearance::library("ABS - Red").unwrap();
|
||||
for i in 0..10_000 {
|
||||
// Suppressed definition overrides are still uses and must be replaced.
|
||||
s.doc_mut().appearances.bodies.insert(format!("Dormant {i}"), look.clone());
|
||||
}
|
||||
let chain = chain_read(&mut s, json!({"body":"Specimen"}));
|
||||
assert_eq!(chain["steps"].as_array().unwrap().len(), 4);
|
||||
assert!(chain["active"].is_null());
|
||||
assert_eq!(s.execute("appearance.replace", &json!({"from":"ABS - Red","to":"ABS - Blue"})).unwrap(), json!({"count":10_000}));
|
||||
assert!(s.doc.appearances.bodies.values().all(|l| l.name == "ABS - Blue"));
|
||||
assert_eq!(
|
||||
s.execute("appearance.replace", &json!({"from":"ABS - Blue","to":"ABS - Red","scope":{"bodies":vec!["Specimen";10_000]}})).unwrap()["count"],
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
@@ -17,7 +17,6 @@ macro_rules! waiting {
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
waiting!("appearance.paint", "Paint Appearance", "RENDER APPEARANCE", "APPEARANCE", "appearance", "product picking and appearance painting"),
|
||||
waiting!("appearance.pick_up", "Pick Up Appearance", "RENDER APPEARANCE", "APPEARANCE", "select", "product picking and appearance sampling"),
|
||||
waiting!("appearance.replace", "Replace Appearance", "RENDER APPEARANCE", "APPEARANCE", "appearance", "replacing all uses of an appearance"),
|
||||
waiting!("render.lights.solo", "Solo Light", "RENDER SCENE", "LIGHTS", "render_scene", "light visibility and solo controls"),
|
||||
waiting!("render.compare", "Compare Images", "RENDER", "RESULT", "compare", "retained image comparison"),
|
||||
waiting!("render.batch", "Render All Shots", "RENDER", "BATCH", "render_image", "the saved-shot render queue"),
|
||||
|
||||
@@ -54,6 +54,68 @@ records before writing. V1 imports and v2 looks without PBR explicitly select sc
|
||||
shading and clear a prior PBR response. See [local material libraries](book/src/dev/local-libraries.md).
|
||||
In-design swatches retain and reuse the response.
|
||||
|
||||
## Inspect, replace and inherit a look
|
||||
|
||||
`appearance.chain` is a read-only command. Supply exactly one target: a body,
|
||||
a face index from `model.faces` with its body, or a component name/ID:
|
||||
|
||||
```json
|
||||
{"command":"appearance.chain","params":{"target":{"body":"Specimen","face":0}}}
|
||||
{"command":"appearance.chain","params":{"target":{"component":"Housing"}}}
|
||||
```
|
||||
|
||||
The result contains four `steps`, ordered `face`, `body`, `component`, `material`.
|
||||
Each step contains `step` and `look`: either null or the full saved look
|
||||
(`name`, hex `color`, `opacity`, and optional `pbr`). `active` names the first
|
||||
nonempty step, or is null. Body reads have no face step. Component reads have
|
||||
no face/body steps. Physical materials belong to bodies; a component's material
|
||||
step shows the common material look of its directly owned bodies, or null for
|
||||
mixed/empty components. Root is not an assignable component. Imported paint
|
||||
remains a display fallback outside these four steps, so an all-null chain does
|
||||
not imply a particular viewport color.
|
||||
|
||||
`appearance.replace` rewrites every equal body, face and component override in
|
||||
one undo step. `from` accepts a library name or a complete look copied from
|
||||
`appearance.list`'s `in_design` entries. Equality includes the label, color,
|
||||
opacity and all PBR values, so looks with identical names but different responses
|
||||
remain distinct. `to` accepts a library name or an object with the same look
|
||||
fields as `appearance.assign` (including inert `name` with `color`).
|
||||
|
||||
```json
|
||||
{"command":"appearance.replace","params":{"from":"ABS - Red","to":"Copper - Clean PBR"}}
|
||||
{"command":"appearance.replace","params":{"from":{"name":"Custom","color":"#abcdef","opacity":0.5},"to":{"color":"#123456","opacity":0.4},"scope":{"bodies":["Specimen"]}}}
|
||||
```
|
||||
|
||||
Omit `scope` to replace all stored overrides, including hidden or suppressed
|
||||
ones. Optional `scope.bodies` selects body overrides and face overrides on those
|
||||
bodies; `scope.components` selects only those component overrides. These lists
|
||||
combine as a union. A component scope does not expand to its bodies or descendants.
|
||||
Names and numeric component IDs are accepted; duplicate targets count once.
|
||||
Scope targets must exist in the evaluated model/design. An empty target list
|
||||
selects nothing. At most 10,000 scope entries and 100,000 stored overrides are
|
||||
processed; larger requests/designs refuse. The chain read uses the same override
|
||||
budget and at most 100,000 bodies for a component read.
|
||||
|
||||
The replacement result is `{"count": N}`, counting stored overrides rewritten.
|
||||
Invalid values or targets refuse before mutation. A missing source look, empty
|
||||
scope or identical replacement returns count zero without adding undo history or
|
||||
clearing redo. Geometry, placements, density, mass, physical material defaults
|
||||
and engineering records are unchanged. No command opens a dialog. Existing look
|
||||
records support saving/reopening these edits without a format change.
|
||||
|
||||
**From Material** uses the existing clear form of `appearance.assign`:
|
||||
|
||||
```json
|
||||
{"command":"appearance.assign","params":{"bodies":["Specimen"],"color":null}}
|
||||
{"command":"appearance.assign","params":{"components":["Housing"]}}
|
||||
{"command":"appearance.assign","params":{"body":"Specimen","faces":[[5,10,5]],"color":null}}
|
||||
```
|
||||
|
||||
Clear removes only the selected override. A face then follows its body, a body
|
||||
its component, and finally the physical material's default look. Clear remaining
|
||||
higher-priority overrides when the material should be active. This changes the
|
||||
look without changing density or mass.
|
||||
|
||||
## Original opaque finish presets
|
||||
|
||||
The existing Appearance library includes six additional opaque finishes. Its
|
||||
|
||||
Reference in New Issue
Block a user