SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Agents and scripts: New, Edit, Inspect and Delete Physical Material describe their exact parameters and reply (#11862) (#11865)
austin62jake1fdc56835bbd
diff --git a/crates/engine/src/cmd/materials.rs b/crates/engine/src/cmd/materials.rsindex ebea05d979..2b68a02dc3 100644--- a/crates/engine/src/cmd/materials.rs+++ b/crates/engine/src/cmd/materials.rs@@ -4,27 +4,59 @@//! configuration material cells. The design keeps them, so they are saved and undone like//! features.-use serde_json::{Value, json};+use serde_json::Value;use solidcraft_doc::appearance::{Look, library};use solidcraft_doc::config::Column;use solidcraft_doc::{DEFAULT_MATERIAL, MATERIALS, MAX_USER_MATERIALS, UserMaterial, valid_density};use super::CommandSpec;-use super::inspect::{color_param, look_json};+use super::inspect::color_param;use crate::params::{bad, str_};+use crate::schema::TypedContract;+use crate::schema::appearance::LookReply;+use crate::schema::materials::{+ DensityComparison, MaterialCreateParams, MaterialDeleteParams, MaterialDeleted, MaterialEditParams, MaterialInspectParams, MaterialInspected,+ MaterialReply,+};+use crate::schema::output_schema_for;use crate::{Result, Session};+const CREATE_CONTRACT: TypedContract<MaterialCreateParams> = TypedContract::new();+const EDIT_CONTRACT: TypedContract<MaterialEditParams> = TypedContract::new();+const INSPECT_CONTRACT: TypedContract<MaterialInspectParams> = TypedContract::new();+const DELETE_CONTRACT: TypedContract<MaterialDeleteParams> = TypedContract::new();+pub static COMMANDS: &[CommandSpec] = &[- CommandSpec::new("material.create", "New Physical Material", create).icon("material").params(+ CommandSpec::new("material.create", "New Physical Material", crate::checked!("material.create", create))+ .icon("material")+ .contract(&CREATE_CONTRACT)+ .output(output_schema_for::<MaterialReply>)+ .params("name (not a built-in material's); density_g_cm3: (0, 1000]; appearance?: library name (appearance.library) | color?: \"#rrggbb\" or [r, g, b] (0–255), opacity? (0–1), pbr?: {metallic:0..1, roughness:0.045..1, dielectric_ior:1..3} (opaque only, needs color/appearance): the default look. A named appearance keeps its preset response when pbr is omitted; pbr: null selects scalar shading. Optical edits do not change density. physical_card?: validated SI candidate record (null/omitted means unknown); card density never changes assigned density. Assign it with material.assign",),- CommandSpec::new("material.edit", "Edit Physical Material", edit).icon("material").enabled(has_user_materials).params(+ CommandSpec::new("material.edit", "Edit Physical Material", crate::checked!("material.edit", edit))+ .icon("material")+ .enabled(has_user_materials)+ .contract(&EDIT_CONTRACT)+ .output(output_schema_for::<MaterialReply>)+ .params("material: a material defined in this design; name? (bodies and configuration cells follow); density_g_cm3?; appearance? | color?, opacity?, pbr? (as material.create; color: null clears the look). physical_card?: validated SI candidate record (omitted retains, null clears). Omitted appearance/color retains the entire current look",),- CommandSpec::new("material.inspect", "Inspect Physical Material", inspect).icon("material").noundo().doc_only().params(+ CommandSpec::new("material.inspect", "Inspect Physical Material", crate::checked!("material.inspect", inspect))+ .icon("material")+ .noundo()+ .doc_only()+ .contract(&INSPECT_CONTRACT)+ .output(output_schema_for::<MaterialInspected>)+ .params("material: built-in or design-owned name. Returns assigned density, default appearance, optional physical_card, validation and density comparison. Read-only; missing engineering data remains unknown and card density does not change mass",),- CommandSpec::new("material.delete", "Delete Physical Material", delete).icon("delete").enabled(has_user_materials).params(+ CommandSpec::new("material.delete", "Delete Physical Material", crate::checked!("material.delete", delete))+ .icon("delete")+ .enabled(has_user_materials)+ .contract(&DELETE_CONTRACT)+ .output(output_schema_for::<MaterialDeleted>)+ .params("material: a material defined in this design; replace?: material for the bodies and configuration cells that use it (without it, a material in use is refused)",),];@@ -90,27 +122,52 @@ fn look(cmd: &str, p: &Value, material: &str) -> Result<Option<Option<Look>>> {Ok(Some(Some(l)))}-pub(super) fn material_json(m: &UserMaterial) -> Result<Value> {- let mut out = json!({"name": m.name, "density_g_cm3": m.density, "appearance": m.appearance.as_ref().map(look_json), "user": true});+/// A design material as `material.create` and `material.edit` report it: with its card, the+/// card's check and how the card's measured density compares, when it has a card.+fn material_reply(cmd: &str, m: &UserMaterial) -> Result<MaterialReply> {+ let mut out = MaterialReply {+ name: m.name.clone(),+ density_g_cm3: m.density,+ appearance: m.appearance.as_ref().map(LookReply::from),+ user: true,+ physical_card: None,+ physical_validation: None,+ density_comparison: None,+ bodies: None,+ param_warnings: Vec::new(),+ };if let Some(record) = &m.physical_card {let card = record.card();- out["physical_card"] = json!(record);- out["physical_validation"] = json!(card.validate()?);+ out.physical_card = Some(serde_json::to_value(record).map_err(|e| bad(cmd, e.to_string()))?);+ out.physical_validation = Some(card.validate()?.into());let measured = card.properties.iter().find_map(|p| match p.data {solidcraft_doc::physical_material::PropertyData::Density { kg_m3 } => Some(kg_m3),_ => None,});- if let Some(measured) = measured {+ out.density_comparison = measured.map(|measured| {let assigned = m.density * 1000.0;let relative_difference = (assigned - measured).abs() / assigned.max(measured);- out["density_comparison"] = json!({"assigned_density_kg_m3":assigned,"card_density_kg_m3":measured,- "relative_difference":relative_difference,"matches_within_relative_tolerance":relative_difference <= 1e-9,- "relative_tolerance":1e-9});- }+ DensityComparison {+ assigned_density_kg_m3: assigned,+ card_density_kg_m3: measured,+ relative_difference,+ matches_within_relative_tolerance: relative_difference <= 1e-9,+ relative_tolerance: 1e-9,+ }+ });}Ok(out)}+/// [`material_reply`] as JSON, for `material.list` (`cmd/inspect.rs`), which isn't converted yet.+pub(super) fn material_json(m: &UserMaterial) -> Result<Value> {+ reply("material.list", material_reply("material.list", m)?)+}++fn reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {+ serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))+}+fn physical_card(cmd: &str, p: &Value) -> Result<Option<Option<solidcraft_doc::physical_material::ValidatedCard>>> {match p.get("physical_card") {None => Ok(None),@@ -125,21 +182,38 @@ fn inspect(s: &mut Session, p: &Value) -> Result<Value> {let cmd = "material.inspect";let name = str_(p, "material").ok_or_else(|| bad(cmd, "`material` must be a material name"))?;let canonical = s.doc.material_name(name).ok_or_else(|| bad(cmd, format!("unknown material `{name}` (see material.list)")))?;- let mut out = if let Some(material) = s.doc.user_materials.iter().find(|m| m.name == canonical) {- material_json(material)?+ // The look a material's bodies show: its own, or a built-in material's default.+ let appearance = s.doc.material_look(&canonical).as_ref().map(LookReply::from);+ let out = if let Some(material) = s.doc.user_materials.iter().find(|m| m.name == canonical) {+ let own = material_reply(cmd, material)?;+ MaterialInspected {+ name: own.name,+ density_g_cm3: own.density_g_cm3,+ appearance,+ user: true,+ physical_card: own.physical_card,+ physical_validation: own.physical_validation,+ density_comparison: own.density_comparison,+ param_warnings: Vec::new(),+ }} else {let density = MATERIALS.iter().find(|(n, _)| *n == canonical.as_str()).map(|(_, density)| *density).ok_or_else(|| bad(cmd, "material is unavailable"))?;- json!({"name":canonical,"density_g_cm3":density,"user":false})+ MaterialInspected {+ name: canonical,+ density_g_cm3: density,+ appearance,+ user: false,+ physical_card: None,+ physical_validation: None,+ density_comparison: None,+ param_warnings: Vec::new(),+ }};- out["appearance"] = json!(s.doc.material_look(&canonical).as_ref().map(look_json));- if out.get("physical_card").is_none() {- out["physical_card"] = Value::Null;- }- Ok(out)+ reply(cmd, out)}/// The index of the design material `material` names.@@ -160,7 +234,7 @@ fn create(s: &mut Session, p: &Value) -> Result<Value> {}let material =UserMaterial { density: density(cmd, p)?, appearance: look(cmd, p, &name)?.flatten(), name, physical_card: physical_card(cmd, p)?.flatten() };- let out = material_json(&material)?;+ let out = reply(cmd, material_reply(cmd, &material)?)?;s.doc_mut().user_materials.push(material);Ok(out)}@@ -228,15 +302,15 @@ fn edit(s: &mut Session, p: &Value) -> Result<Value> {};let physical_card = physical_card(cmd, p)?.unwrap_or(old.physical_card);let material = UserMaterial { name: name.clone(), density, appearance, physical_card };- let mut out = material_json(&material)?;+ let mut out = material_reply(cmd, &material)?;if let Some(m) = s.doc_mut().user_materials.get_mut(i) {*m = material;}if name != old.name {move_uses(s, &old.name, &name);}- out["bodies"] = json!(uses(s, &name).0);- Ok(out)+ out.bodies = Some(uses(s, &name).0);+ reply(cmd, out)}fn delete(s: &mut Session, p: &Value) -> Result<Value> {@@ -268,5 +342,5 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> {move_uses(s, &name, r);}s.doc_mut().user_materials.remove(i);- Ok(json!({"deleted": name, "replaced_by": replace, "bodies": bodies}))+ reply(cmd, MaterialDeleted { deleted: name, replaced_by: replace, bodies, param_warnings: Vec::new() })}diff --git a/crates/engine/src/schema/appearance.rs b/crates/engine/src/schema/appearance.rsindex ef18ad14f2..ff697aab3c 100644--- a/crates/engine/src/schema/appearance.rs+++ b/crates/engine/src/schema/appearance.rs@@ -94,6 +94,13 @@ impl JsonSchema for FaceSpots {}}+/// The text form `inspect::color_param` reads: three bytes after any number of `#`, with+/// spaces at either end as Rust's `trim` drops them. A byte is two hex digits, or a `+` and one+/// hex digit, because `u8::from_str_radix` takes a leading `+` (`"+f"` is 15).+fn color_pattern() -> String {+ format!("^[{ws}]*#*(?:[0-9A-Fa-f]{{2}}|\\+[0-9A-Fa-f]){{3}}[{ws}]*$", ws = super::types::whitespace_class())+}+/// A colour, `"#rrggbb"` (the `#` optional) or `[r, g, b]` of numbers 0–255, as/// `inspect::color_param` reads it.#[derive(Clone, Copy, Debug, PartialEq)]@@ -116,7 +123,7 @@ impl JsonSchema for ColorParam {json_schema!({"description": "A colour: \"#rrggbb\" or [r, g, b] with values 0–255.","anyOf": [- {"type": "string", "pattern": "^#?[0-9A-Fa-f]{6}$"},+ {"type": "string", "pattern": color_pattern()},{"type": "array", "items": channel, "minItems": 3, "maxItems": 3}]})diff --git a/crates/engine/src/schema/appearance_tests.rs b/crates/engine/src/schema/appearance_tests.rsindex c25e7aa124..10e7566a97 100644--- a/crates/engine/src/schema/appearance_tests.rs+++ b/crates/engine/src/schema/appearance_tests.rs@@ -80,3 +80,20 @@ fn replies_match_the_output_schema() {assert!(warned["param_warnings"].as_array().is_some_and(|w| !w.is_empty()), "{warned}");matches(output_schema_for::<AppearanceListResult>(), "appearance.list", &warned);}++/// A colour's text pattern allows what `inspect::color_param` reads: spaces at either end, as+/// `trim` drops them, any number of `#` before the three bytes, and a byte written as `+` and+/// one digit, as `from_str_radix` reads it. `conforms` doesn't read patterns, so the pattern's+/// text is pinned here, next to the reader's answers.+#[test]+fn the_colour_pattern_allows_what_the_reader_trims() {+ for text in ["#ff00ff", "ff00ff", " #FF00ff\t", "##ff00ff"] {+ assert_eq!(crate::cmd::inspect::color_param(&json!(text)), Some([255, 0, 255]), "{text}");+ }+ assert_eq!(crate::cmd::inspect::color_param(&json!("# ff00ff")), None, "a space after the `#` isn't trimmed");+ assert_eq!(crate::cmd::inspect::color_param(&json!("+fff00")), Some([15, 255, 0]), "`from_str_radix` takes a leading `+`");+ let schema = schemars::schema_for!(super::ColorParam);+ let ws = crate::schema::types::whitespace_class();+ let pattern = format!("^[{ws}]*#*(?:[0-9A-Fa-f]{{2}}|\\+[0-9A-Fa-f]){{3}}[{ws}]*$");+ assert_eq!(schema.as_value()["anyOf"][0]["pattern"], json!(pattern), "{}", schema.as_value());+}diff --git a/crates/engine/src/schema/material_properties.rs b/crates/engine/src/schema/material_properties.rsindex b04e1e017b..9db21c10e4 100644--- a/crates/engine/src/schema/material_properties.rs+++ b/crates/engine/src/schema/material_properties.rs@@ -33,7 +33,7 @@ pub struct DirectionalModulusParams {}/// The card, checked by the handler (`admit_card`), with its messages.-fn card_schema(_: &mut SchemaGenerator) -> Schema {+pub(super) fn card_schema(_: &mut SchemaGenerator) -> Schema {json_schema!({"description": "A schema_version 1 engineering material card in SI units (see docs/physical-material-cards.md).","type": "object"diff --git a/crates/engine/src/schema/materials.rs b/crates/engine/src/schema/materials.rsnew file mode 100644index 0000000000..9d5f939273--- /dev/null+++ b/crates/engine/src/schema/materials.rs@@ -0,0 +1,313 @@+//! Contracts and result types for the design's own physical materials, in `cmd/materials.rs`+//! (#11862): `material.create`, `material.edit`, `material.inspect` and `material.delete`.+//!+//! The handlers read their parameters from the raw JSON, so each key here reads as its handler+//! reads it and fails with the handler's message. Two things the handlers rely on stay as they+//! are, and the contracts keep them:+//! - `null` means something: `color: null` clears the look, and `physical_card: null` clears+//! the card in an edit. Left out, they keep what the material has.+//! - The look keys are the appearance commands' (`ColorParam`, `PbrParam`), and the card stays+//! the handler's to check (`ValidatedCard::from_value`), with its schema from+//! `schema/material_properties.rs`.++use std::borrow::Cow;++use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};+use serde::de::Error as _;+use serde::{Deserialize, Deserializer, Serialize};+use serde_json::Value;++use super::appearance::{ColorParam, LookReply, PbrParam};+use super::check::whole;+use super::material_properties::CardValidation;++/// `material`: the material the command works on, by name. Anything but text gets the+/// handler's message (`str_` reads text only).+#[derive(Clone, Debug, PartialEq)]+pub struct MaterialRef(pub String);++impl<'de> Deserialize<'de> for MaterialRef {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ match Value::deserialize(d)? {+ Value::String(name) => Ok(MaterialRef(name)),+ _ => Err(D::Error::custom(whole("`material` must be a material name"))),+ }+ }+}++impl JsonSchema for MaterialRef {+ fn schema_name() -> Cow<'static, str> {+ "MaterialRef".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({"description": "A material, by name (letter case doesn't matter).", "type": "string"})+ }+}++/// `density_g_cm3`: a density in g/cm³ above 0 and at most 1000, as `materials::density` reads+/// it, with its message for anything else, `null` included.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Density(pub f64);++impl<'de> Deserialize<'de> for Density {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ Value::deserialize(d)?+ .as_f64()+ .filter(|density| solidcraft_doc::valid_density(*density))+ .map(Density)+ .ok_or_else(|| D::Error::custom(whole("`density_g_cm3` must be a number above 0 and at most 1000")))+ }+}++impl JsonSchema for Density {+ fn schema_name() -> Cow<'static, str> {+ "Density".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "The density in g/cm³: above 0 and at most 1000.",+ "type": "number",+ "exclusiveMinimum": 0,+ "maximum": 1000+ })+ }+}++/// An edit's `density_g_cm3`: given, it must be a density, `null` included, as the handler+/// checks it whenever the key is there; left out, the material keeps its density.+fn some_density<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Density>, D::Error> {+ Density::deserialize(d).map(Some)+}++/// `opacity`: 0 (clear) to 1 (opaque), as `materials::look` reads it whenever the key is there,+/// with its message for anything else, `null` included.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Opacity(pub f64);++impl<'de> Deserialize<'de> for Opacity {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ Value::deserialize(d)?+ .as_f64()+ .filter(|o| o.is_finite() && (0.0..=1.0).contains(o))+ .map(Opacity)+ .ok_or_else(|| D::Error::custom(whole("`opacity` must be 0…1")))+ }+}++impl JsonSchema for Opacity {+ fn schema_name() -> Cow<'static, str> {+ "Opacity".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({"description": "0 (clear) to 1 (opaque).", "type": "number", "minimum": 0, "maximum": 1})+ }+}++fn some_opacity<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Opacity>, D::Error> {+ Opacity::deserialize(d).map(Some)+}++/// `color`: a colour, or `null` to clear the look; the handler tells the two apart, so `null`+/// isn't read as left out.+fn color_or_clear<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Option<ColorParam>>, D::Error> {+ Option::<ColorParam>::deserialize(d).map(Some)+}++fn color_schema(generator: &mut SchemaGenerator) -> Schema {+ let color = generator.subschema_for::<ColorParam>();+ json_schema!({+ "description": "The look's colour, `\"#rrggbb\"` or [r, g, b] (0–255), not with `appearance`. `null` clears the material's look, so its bodies show the default.",+ "anyOf": [color, {"type": "null"}]+ })+}++/// `pbr`: the look's opaque PBR response, or `null` for scalar shading; it needs `appearance` or+/// `color`. `null` and left out differ for a library appearance (left out keeps its own).+fn pbr_or_scalar<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Option<PbrParam>>, D::Error> {+ Option::<PbrParam>::deserialize(d).map(Some)+}++fn pbr_schema(generator: &mut SchemaGenerator) -> Schema {+ let pbr = generator.subschema_for::<PbrParam>();+ json_schema!({+ "description": "The look's opaque PBR response; it needs `appearance` or `color`, and an opaque look. `null` selects scalar shading. Left out, a library appearance keeps its own response.",+ "anyOf": [pbr, {"type": "null"}]+ })+}++/// `physical_card`: the handler checks the card itself (`ValidatedCard::from_value`), with its+/// messages, so the contract takes any value here and describes it.+fn card_or_clear<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Value>, D::Error> {+ Value::deserialize(d).map(Some)+}++fn card_schema(generator: &mut SchemaGenerator) -> Schema {+ let card = super::material_properties::card_schema(generator);+ json_schema!({+ "description": "A validated physical material card in SI units (see docs/physical-material-cards.md). The card's density never changes the assigned density. `null`: no card (an edit clears it). Left out: none for a new material; an edit keeps the current one.",+ "anyOf": [card, {"type": "null"}]+ })+}++/// Define a physical material in this design: a name, a density and an optional default look+/// and physical card. Assign it with `material.assign`. One undo step.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct MaterialCreateParams {+ /// The new material's name: 1 to 128 characters, not a built-in material's or another of the+ /// design's (letter case doesn't matter). Spaces at either end are dropped.+ pub name: String,+ pub density_g_cm3: Density,+ /// The look, a library appearance by name (see `appearance.library`). Not with `color`.+ #[serde(default)]+ pub appearance: Option<String>,+ #[serde(default, deserialize_with = "color_or_clear")]+ #[schemars(schema_with = "color_schema")]+ pub color: Option<Option<ColorParam>>,+ /// The look's opacity: needs `appearance` or `color`. Default: 1, or the appearance's own.+ #[serde(default, deserialize_with = "some_opacity")]+ #[schemars(with = "Opacity")]+ pub opacity: Option<Opacity>,+ #[serde(default, deserialize_with = "pbr_or_scalar")]+ #[schemars(schema_with = "pbr_schema")]+ pub pbr: Option<Option<PbrParam>>,+ #[serde(default, deserialize_with = "card_or_clear")]+ #[schemars(schema_with = "card_schema")]+ pub physical_card: Option<Value>,+}++/// Change a physical material this design defines: its name (its bodies and configuration cells+/// follow), its density, its look or its card. A key left out keeps what the material has; with+/// no look key at all, the whole look is kept. One undo step.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct MaterialEditParams {+ /// The material, one this design defines; built-in materials can't be changed.+ pub material: MaterialRef,+ /// Its new name, as for `material.create`.+ #[serde(default)]+ pub name: Option<String>,+ /// Its new density.+ #[serde(default, deserialize_with = "some_density")]+ #[schemars(with = "Density")]+ pub density_g_cm3: Option<Density>,+ /// The new look, a library appearance by name. Not with `color`.+ #[serde(default)]+ pub appearance: Option<String>,+ #[serde(default, deserialize_with = "color_or_clear")]+ #[schemars(schema_with = "color_schema")]+ pub color: Option<Option<ColorParam>>,+ /// The new look's opacity: needs `appearance` or `color`.+ #[serde(default, deserialize_with = "some_opacity")]+ #[schemars(with = "Opacity")]+ pub opacity: Option<Opacity>,+ #[serde(default, deserialize_with = "pbr_or_scalar")]+ #[schemars(schema_with = "pbr_schema")]+ pub pbr: Option<Option<PbrParam>>,+ #[serde(default, deserialize_with = "card_or_clear")]+ #[schemars(schema_with = "card_schema")]+ pub physical_card: Option<Value>,+}++/// Read a material, built-in or this design's: its density, default look and physical card,+/// with the card's check and how its density compares. The design doesn't change.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct MaterialInspectParams {+ /// A built-in material or one this design defines.+ pub material: MaterialRef,+}++/// Delete a physical material this design defines. One undo step.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct MaterialDeleteParams {+ /// The material, one this design defines.+ pub material: MaterialRef,+ /// Another material, built-in or this design's, for the bodies and configuration cells that+ /// use the deleted one. Without it, a material in use is refused.+ #[serde(default)]+ pub replace: Option<String>,+}++/// What `material.create` and `material.edit` return: the material as the design now defines it.+#[derive(Debug, Serialize, JsonSchema)]+pub struct MaterialReply {+ pub name: String,+ /// The assigned density (g/cm³), the one masses use.+ pub density_g_cm3: f64,+ /// The default look; `null` when it has none.+ pub appearance: Option<LookReply>,+ /// Always true: a material this design defines.+ pub user: bool,+ /// Its physical card, when it has one.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub physical_card: Option<Value>,+ /// The card's check, when it has a card.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub physical_validation: Option<CardValidation>,+ /// How the card's measured density compares with the assigned one, when the card gives one.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub density_comparison: Option<DensityComparison>,+ /// After an edit: the bodies the material is assigned to.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub bodies: Option<Vec<String>>,+ /// In the warn parameter-check mode: what the call's parameters got wrong.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub param_warnings: Vec<String>,+}++/// What `material.inspect` returns. Unlike [`MaterialReply`], `physical_card` is always there,+/// `null` without a card.+#[derive(Debug, Serialize, JsonSchema)]+pub struct MaterialInspected {+ pub name: String,+ /// The assigned density (g/cm³), the one masses use.+ pub density_g_cm3: f64,+ /// The default look; `null` when it has none.+ pub appearance: Option<LookReply>,+ /// Whether this design defines it (`false`: a built-in material).+ pub user: bool,+ /// Its physical card; `null` when it has none.+ pub physical_card: Option<Value>,+ /// The card's check, when it has a card.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub physical_validation: Option<CardValidation>,+ /// How the card's measured density compares with the assigned one, when the card gives one.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub density_comparison: Option<DensityComparison>,+ /// In the warn parameter-check mode: what the call's parameters got wrong.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub param_warnings: Vec<String>,+}++/// A card's measured density against the material's assigned one.+#[derive(Debug, Serialize, JsonSchema)]+pub struct DensityComparison {+ pub assigned_density_kg_m3: f64,+ pub card_density_kg_m3: f64,+ /// Their difference as a share of the larger.+ pub relative_difference: f64,+ /// Whether they agree within `relative_tolerance`.+ pub matches_within_relative_tolerance: bool,+ /// Always 1e-9.+ pub relative_tolerance: f64,+}++/// What `material.delete` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct MaterialDeleted {+ /// The deleted material's name.+ pub deleted: String,+ /// The material its bodies and configuration cells now use; `null` when it wasn't in use.+ pub replaced_by: Option<String>,+ /// The bodies that used it.+ pub bodies: Vec<String>,+ /// In the warn parameter-check mode: what the call's parameters got wrong.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub param_warnings: Vec<String>,+}++#[cfg(test)]+#[path = "materials_tests.rs"]+mod tests;diff --git a/crates/engine/src/schema/materials_tests.rs b/crates/engine/src/schema/materials_tests.rsnew file mode 100644index 0000000000..0ac110eb2a--- /dev/null+++ b/crates/engine/src/schema/materials_tests.rs@@ -0,0 +1,133 @@+use serde_json::{Value, json};++use super::{+ MaterialCreateParams, MaterialDeleteParams, MaterialDeleted, MaterialEditParams, MaterialInspectParams, MaterialInspected, MaterialReply,+};+use crate::Session;+use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};+use crate::schema::{ParamCheck, input_schema_for, output_schema_for};++/// An original synthetic physical card, as `cmd/material_card_persistence_tests.rs` uses: a+/// density and an isotropic elasticity.+fn card() -> Value {+ json!({"schema_version":1,"designation":"Original synthetic card, not design data","family":"other",+ "sources":[{"id":"fixture","title":"Original analytic constants","kind":"illustrative","license":"MIT OR Apache-2.0"}],+ "properties":[{"source_id":"fixture","conditions":{"temperature_k":293.15,"state":"synthetic"},+ "data":{"kind":"density","kg_m3":700.0}},+ {"source_id":"fixture","data":{"kind":"elasticity","model":{+ "symmetry":"isotropic","young_modulus_pa":12.25e9,"poisson_ratio":0.25}}}]})+}++/// A design with a box, `Specimen`, and a material of its own, `Timber`, assigned to it, at+/// the parameter-check level `level`.+fn with_timber(level: ParamCheck) -> Session {+ let mut s = Session { param_check: level, ..Session::default() };+ for (id, p) in [+ ("solid.box", json!({"body_name": "Specimen", "length": 10, "width": 20, "height": 5})),+ ("material.create", json!({"name": "Timber", "density_g_cm3": 0.7, "color": "#b47846"})),+ ("material.assign", json!({"bodies": ["Specimen"], "material": "Timber"})),+ ] {+ s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));+ }+ s+}++#[test]+fn schemas_and_the_key_check_agree() {+ assert_keys(input_schema_for::<MaterialCreateParams>(), &["appearance", "color", "density_g_cm3", "name", "opacity", "pbr", "physical_card"]);+ assert_keys(+ input_schema_for::<MaterialEditParams>(),+ &["appearance", "color", "density_g_cm3", "material", "name", "opacity", "pbr", "physical_card"],+ );+ assert_keys(input_schema_for::<MaterialInspectParams>(), &["material"]);+ assert_keys(input_schema_for::<MaterialDeleteParams>(), &["material", "replace"]);+}++/// Calls that fail today get the same message in strict: the contract's readers give the+/// handler's own message (`density_g_cm3`, `opacity`, `color`, `material`), and the handler+/// refuses the rest.+#[test]+fn strict_keeps_todays_errors() {+ let new = |extra: Value| {+ let mut p = json!({"name": "Resin", "density_g_cm3": 1.2});+ if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) {+ p.extend(extra.clone());+ }+ p+ };+ assert_strict_keeps_todays_errors(&[+ ("material.create", new(json!({"name": " "}))),+ ("material.create", new(json!({"name": "Steel"}))),+ ("material.create", new(json!({"density_g_cm3": 0}))),+ ("material.create", new(json!({"density_g_cm3": "light"}))),+ ("material.create", new(json!({"density_g_cm3": null}))),+ ("material.create", new(json!({"color": "#zzzzzz"}))),+ ("material.create", new(json!({"color": "#808080", "opacity": 2}))),+ ("material.create", new(json!({"color": "#808080", "opacity": null}))),+ ("material.create", new(json!({"opacity": 0.5}))),+ ("material.create", new(json!({"appearance": "Nope"}))),+ ("material.create", new(json!({"appearance": "Steel", "color": "#808080"}))),+ ("material.create", new(json!({"pbr": {"metallic": 0, "roughness": 0.4, "dielectric_ior": 1.5}}))),+ ("material.create", new(json!({"color": "#808080", "pbr": {"metallic": 2, "roughness": 0.4, "dielectric_ior": 1.5}}))),+ ("material.create", new(json!({"physical_card": {}}))),+ ("material.inspect", json!({"material": "Unobtanium"})),+ ("material.inspect", json!({"material": 5})),+ ]);+ // Edit and delete need a material of the design's own, and one in use.+ let cases = [+ ("material.edit", json!({"material": "Nope"})),+ ("material.edit", json!({"material": 5})),+ ("material.edit", json!({"material": "Timber", "density_g_cm3": null})),+ ("material.edit", json!({"material": "Timber", "name": "Aluminum"})),+ ("material.edit", json!({"material": "Timber", "opacity": 0.5})),+ ("material.delete", json!({"material": "Timber"})),+ ("material.delete", json!({"material": "Timber", "replace": "timber"})),+ ("material.delete", json!({"material": "Timber", "replace": "Nope"})),+ ];+ for (id, p) in &cases {+ let error = |level: ParamCheck| with_timber(level).execute(id, p).err().map(|e| e.to_string());+ let off = error(ParamCheck::Off);+ assert!(off.is_some(), "{id} {p} should fail today");+ assert_eq!(error(ParamCheck::Strict), off, "{id} {p}");+ }+}++/// #11862: creating, inspecting, editing and deleting materials reply as the output schemas say,+/// in Warn without warnings: with a card (its check and density comparison) and without, a+/// built-in material, a look cleared with `color: null`, and a deletion that moves the bodies to+/// a built-in material. A misspelt key gets `param_warnings` in Warn, since the handlers ignore+/// unknown keys, and is refused in Strict.+#[test]+fn material_commands_reply_with_their_schemas() {+ let (material, inspected, deleted) =+ (output_schema_for::<MaterialReply>(), output_schema_for::<MaterialInspected>(), output_schema_for::<MaterialDeleted>());+ let mut s = with_timber(ParamCheck::Warn);+ let run = |s: &mut Session, schema: &schemars::Schema, id: &str, p: Value| {+ let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));+ let schema = schema.as_value();+ assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}");+ assert!(r.get("param_warnings").is_none(), "{r}");+ r+ };+ let p = json!({"name": "Resin", "density_g_cm3": 1.2, "color": [40, 90, 200], "opacity": 1,+ "pbr": {"metallic": 0, "roughness": 0.4, "dielectric_ior": 1.5}, "physical_card": card()});+ let r = run(&mut s, &material, "material.create", p);+ assert!(r["physical_validation"].is_object() && r["density_comparison"].is_object() && r.get("bodies").is_none(), "{r}");+ run(&mut s, &material, "material.create", json!({"name": "Plaster", "density_g_cm3": 0.9, "appearance": "Steel - Satin"}));+ assert!(run(&mut s, &inspected, "material.inspect", json!({"material": "resin"}))["physical_card"].is_object());+ let r = run(&mut s, &inspected, "material.inspect", json!({"material": "Steel"}));+ assert!(r["user"] == false && r["physical_card"].is_null(), "a built-in material: {r}");+ let p = json!({"material": "Timber", "name": "Larch", "density_g_cm3": 0.75, "color": null, "physical_card": null});+ let r = run(&mut s, &material, "material.edit", p);+ assert!(r["appearance"].is_null() && r["bodies"] == json!(["Specimen"]), "{r}");+ let r = run(&mut s, &deleted, "material.delete", json!({"material": "Larch", "replace": "Steel"}));+ assert!(r["replaced_by"] == "Steel" && r["bodies"] == json!(["Specimen"]), "{r}");+ let r = run(&mut s, &deleted, "material.delete", json!({"material": "Plaster"}));+ assert!(r["replaced_by"].is_null(), "{r}");+ let r = s.execute("material.inspect", &json!({"material": "Resin", "materal": "Resin"})).unwrap_or_else(|e| panic!("{e}"));+ let warnings = r["param_warnings"].to_string();+ assert!(warnings.contains("materal"), "{r}");+ let mut strict = with_timber(ParamCheck::Strict);+ let error = strict.execute("material.inspect", &json!({"material": "Timber", "materal": "Timber"})).err().map(|e| e.to_string());+ assert!(error.is_some_and(|e| e.contains("`materal`")), "strict refuses the misspelt key");+}diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rsindex fff9aca88f..c62c165729 100644--- a/crates/engine/src/schema/mod.rs+++ b/crates/engine/src/schema/mod.rs@@ -71,6 +71,7 @@ pub mod joints;pub mod libraries;pub mod mass_properties;pub mod material_properties;+pub mod materials;pub mod metadata;pub mod motion;pub mod panels;diff --git a/crates/engine/src/schema/types.rs b/crates/engine/src/schema/types.rsindex 94b93e02dc..b0c50cad40 100644--- a/crates/engine/src/schema/types.rs+++ b/crates/engine/src/schema/types.rs@@ -42,7 +42,7 @@ pub(crate) const WHITESPACE: [(char, char); 10] = [];/// [`WHITESPACE`] as the inside of a regex character class.-fn whitespace_class() -> String {+pub(crate) fn whitespace_class() -> String {let u = |c: char| format!("\\u{:04x}", c as u32);WHITESPACE.iter().map(|&(a, b)| if a == b { u(a) } else { format!("{}-{}", u(a), u(b)) }).collect()}diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txtindex 81243679d3..fbcedc2d54 100644--- a/crates/engine/src/schema/unconverted.txt+++ b/crates/engine/src/schema/unconverted.txt@@ -85,10 +85,6 @@ joint.screwjoint.solvejoint.sweepmaterial.assign-material.create-material.delete-material.edit-material.inspectmaterial.listmesh.convertmotion.delete