* claim: #10994 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Compare Bodies: input and output schemas (#10994) inspect.compare gets a typed contract and reply types in schema/compare.rs and leaves unconverted.txt. Each key reads as the handler reads it, with its message; `color` checks each colour with the handler's own color_param, now pub(crate) and re-exported from cmd. The reply is built from Comparison and its parts, with the same JSON. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Compare: drop the json import the typed reply no longer uses Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Compare schema: colour strings carry the hex pattern Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: bherbruck <brennen.herbruck@gmail.com>
This commit is contained in:
@@ -5,7 +5,7 @@
|
||||
//! well as any; each place's volume, centre and box are then measured exactly, on the pieces of
|
||||
//! the two cuts a − b and b − a that lie there, as `inspect.measure` measures a body.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use serde_json::Value;
|
||||
use solidcore_record::Vec3;
|
||||
use solidcraft_geom::Aabb3;
|
||||
use solidcraft_geom::compare::{self, CompareOptions, Side};
|
||||
@@ -13,9 +13,19 @@ use solidcraft_geom::prelude::*;
|
||||
|
||||
use super::CommandSpec;
|
||||
use crate::params::bad;
|
||||
use crate::schema::compare::{
|
||||
Bounds, CompareParams, CompareSide, Comparison, Deviation, Deviations, Difference, MeasuredBy, Region, Resolution, Sampling, SideTotal,
|
||||
};
|
||||
use crate::schema::{TypedContract, output_schema_for};
|
||||
use crate::{Result, Sel, Session};
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("inspect.compare", "Compare Bodies", compare_bodies).icon("compare").params(
|
||||
const CONTRACT: TypedContract<CompareParams> = TypedContract::new();
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("inspect.compare", "Compare Bodies", crate::checked!("inspect.compare", compare_bodies))
|
||||
.icon("compare")
|
||||
.contract(&CONTRACT)
|
||||
.output(output_schema_for::<Comparison>)
|
||||
.params(
|
||||
"a, b: body names (default: the two selected bodies, or the design's only two), in world placement; tolerance?: mm (0.001 to 10, default 0.01): \
|
||||
surfaces closer than this agree; spacing?: mm (default 0.5): the largest piece of a face sampled as one point, coarser for a body that would need \
|
||||
more than max_points? (default 8 million, up to 50 million) samples; max_regions? (default 50); color?: true | {only_in_a?, only_in_b?: \"#rrggbb\"} \
|
||||
@@ -32,10 +42,10 @@ pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("inspect.compare", "Com
|
||||
const ONLY_IN_A: [u8; 3] = [0xe0, 0x31, 0x31];
|
||||
const ONLY_IN_B: [u8; 3] = [0x2f, 0x9e, 0x44];
|
||||
|
||||
fn side_name(s: Side) -> &'static str {
|
||||
fn side_of(s: Side) -> CompareSide {
|
||||
match s {
|
||||
Side::OnlyInA => "only_in_a",
|
||||
Side::OnlyInB => "only_in_b",
|
||||
Side::OnlyInA => CompareSide::OnlyInA,
|
||||
Side::OnlyInB => CompareSide::OnlyInB,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,21 +115,21 @@ fn v3(v: &Value) -> Option<Vec3> {
|
||||
}
|
||||
|
||||
/// b − a of the two bodies' measures.
|
||||
fn difference(ma: &Value, mb: &Value) -> Value {
|
||||
fn difference(ma: &Value, mb: &Value) -> Difference {
|
||||
let f = |m: &Value, k: &str| m.get(k).and_then(Value::as_f64);
|
||||
let sub = |x: Option<f64>, y: Option<f64>| x.zip(y).map(|(x, y)| y - x);
|
||||
let (va, vb) = (f(ma, "volume_mm3"), f(mb, "volume_mm3"));
|
||||
let com = v3(&ma["center_of_mass"]).zip(v3(&mb["center_of_mass"])).map(|(a, b)| b - a);
|
||||
let corner = |k: &str| v3(&ma["bbox"][k]).zip(v3(&mb["bbox"][k])).map(|(a, b)| b - a);
|
||||
json!({
|
||||
"volume_mm3": sub(va, vb),
|
||||
"volume_percent": va.zip(vb).filter(|(a, _)| a.abs() > 0.0).map(|(a, b)| 100.0 * (b - a) / a),
|
||||
"area_mm2": sub(f(ma, "area_mm2"), f(mb, "area_mm2")),
|
||||
"center_of_mass": com,
|
||||
"center_of_mass_distance_mm": com.map(Vec3::len),
|
||||
"bbox_min": corner("min"),
|
||||
"bbox_max": corner("max"),
|
||||
})
|
||||
let corner = |k: &str| v3(&ma["bbox"][k]).zip(v3(&mb["bbox"][k])).map(|(a, b)| (b - a).into());
|
||||
Difference {
|
||||
volume_mm3: sub(va, vb),
|
||||
volume_percent: va.zip(vb).filter(|(a, _)| a.abs() > 0.0).map(|(a, b)| 100.0 * (b - a) / a),
|
||||
area_mm2: sub(f(ma, "area_mm2"), f(mb, "area_mm2")),
|
||||
center_of_mass: com.map(Into::into),
|
||||
center_of_mass_distance_mm: com.map(Vec3::len),
|
||||
bbox_min: corner("min"),
|
||||
bbox_max: corner("max"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The volume a closed mesh encloses (divergence theorem, about its box's centre).
|
||||
@@ -245,8 +255,8 @@ fn exact_regions(
|
||||
(measured, notes)
|
||||
}
|
||||
|
||||
fn deviation_json(d: &compare::Deviation) -> Value {
|
||||
json!({"max_mm": d.max, "mean_mm": d.mean, "at": d.at, "area_beyond_mm2": d.beyond_area, "area_mm2": d.area, "points": d.points})
|
||||
fn deviation(d: &compare::Deviation) -> Deviation {
|
||||
Deviation { max_mm: d.max, mean_mm: d.mean, at: d.at.into(), area_beyond_mm2: d.beyond_area, area_mm2: d.area, points: d.points }
|
||||
}
|
||||
|
||||
fn compare_bodies(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -308,30 +318,36 @@ fn compare_bodies(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
exact_notes.iter().find(mine).or_else(|| exact_notes.last()).cloned().unwrap_or_else(|| "the exact cut gave no piece here".to_string())
|
||||
};
|
||||
let axis = |k: usize| ["X", "Y", "Z"].get(k).copied().unwrap_or("?");
|
||||
let regions: Vec<Value> = order
|
||||
let regions: Vec<Region> = order
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, &k)| c.regions.get(k).map(|r| (i, k, r)))
|
||||
.map(|(i, k, r)| {
|
||||
let m = measured(k);
|
||||
json!({
|
||||
"index": i + 1,
|
||||
"side": side_name(r.side),
|
||||
"material_of": if r.side == Side::OnlyInA { &na } else { &nb },
|
||||
"volume_mm3": m.map(|m| m.volume),
|
||||
"measured_by": if m.is_some() { "boolean" } else { "not measured" },
|
||||
"not_measured": if m.is_some() { Value::Null } else { json!(reason(k)) },
|
||||
"area_mm2": r.area_a + r.area_b,
|
||||
"area_a_mm2": r.area_a,
|
||||
"area_b_mm2": r.area_b,
|
||||
"max_deviation_mm": r.max_deviation,
|
||||
"at": r.at,
|
||||
"center": m.map(|m| m.center),
|
||||
"bbox": m.map(|m| json!({"min": m.bbox.min, "max": m.bbox.max})).unwrap_or_else(|| json!({"min": r.bbox.min, "max": r.bbox.max})),
|
||||
"faces_a": r.faces_a.iter().map(|x| x.0).collect::<Vec<u32>>(),
|
||||
"faces_b": r.faces_b.iter().map(|x| x.0).collect::<Vec<u32>>(),
|
||||
"resolution": {"along": axis(r.lines.axis), "line_spacing_mm": r.lines.spacing, "lines": r.lines.count, "skipped_lines": r.lines.skipped},
|
||||
})
|
||||
let bbox = m.map_or(r.bbox, |m| m.bbox);
|
||||
Region {
|
||||
index: i + 1,
|
||||
side: side_of(r.side),
|
||||
material_of: if r.side == Side::OnlyInA { na.clone() } else { nb.clone() },
|
||||
volume_mm3: m.map(|m| m.volume),
|
||||
measured_by: if m.is_some() { MeasuredBy::Boolean } else { MeasuredBy::NotMeasured },
|
||||
not_measured: if m.is_some() { None } else { Some(reason(k)) },
|
||||
area_mm2: r.area_a + r.area_b,
|
||||
area_a_mm2: r.area_a,
|
||||
area_b_mm2: r.area_b,
|
||||
max_deviation_mm: r.max_deviation,
|
||||
at: r.at.into(),
|
||||
center: m.map(|m| m.center.into()),
|
||||
bbox: Bounds { min: bbox.min.into(), max: bbox.max.into() },
|
||||
faces_a: r.faces_a.iter().map(|x| x.0).collect(),
|
||||
faces_b: r.faces_b.iter().map(|x| x.0).collect(),
|
||||
resolution: Resolution {
|
||||
along: axis(r.lines.axis).to_string(),
|
||||
line_spacing_mm: r.lines.spacing,
|
||||
lines: r.lines.count,
|
||||
skipped_lines: r.lines.skipped,
|
||||
},
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
// A side's total, or none when one of its regions is not measured.
|
||||
@@ -361,25 +377,28 @@ fn compare_bodies(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !warnings.is_empty() {
|
||||
verdict += &format!(" ({} warning{})", warnings.len(), if warnings.len() == 1 { "" } else { "s" });
|
||||
}
|
||||
let mut out = json!({
|
||||
"a": measure_a,
|
||||
"b": measure_b,
|
||||
"difference": difference(&measure_a, &measure_b),
|
||||
"tolerance_mm": tolerance,
|
||||
"deviation": {"a_to_b": deviation_json(&c.a_to_b), "b_to_a": deviation_json(&c.b_to_a), "max_mm": worst},
|
||||
"identical": identical,
|
||||
"verdict": verdict,
|
||||
"regions": regions,
|
||||
"only_in_a": {"regions": ca, "volume_mm3": va},
|
||||
"only_in_b": {"regions": cb, "volume_mm3": vb},
|
||||
"unlisted_regions": c.unlisted,
|
||||
"warnings": warnings,
|
||||
"sampling": {"spacing_mm": c.spacing, "chord_mm": chord, "triangles_a": mesh_a.triangles.len(), "triangles_b": mesh_b.triangles.len()},
|
||||
});
|
||||
if let Some(colors) = colors {
|
||||
out["colored_faces"] = json!(color_regions(s, &c, [&na, &nb], colors)?);
|
||||
}
|
||||
Ok(out)
|
||||
let colored_faces = match colors {
|
||||
Some(colors) => Some(color_regions(s, &c, [&na, &nb], colors)?),
|
||||
None => None,
|
||||
};
|
||||
let out = Comparison {
|
||||
difference: difference(&measure_a, &measure_b),
|
||||
a: measure_a.as_object().cloned().unwrap_or_default(),
|
||||
b: measure_b.as_object().cloned().unwrap_or_default(),
|
||||
tolerance_mm: tolerance,
|
||||
deviation: Deviations { a_to_b: deviation(&c.a_to_b), b_to_a: deviation(&c.b_to_a), max_mm: worst },
|
||||
identical,
|
||||
verdict,
|
||||
regions,
|
||||
only_in_a: SideTotal { regions: ca, volume_mm3: va },
|
||||
only_in_b: SideTotal { regions: cb, volume_mm3: vb },
|
||||
unlisted_regions: c.unlisted,
|
||||
warnings,
|
||||
sampling: Sampling { spacing_mm: c.spacing, chord_mm: chord, triangles_a: mesh_a.triangles.len(), triangles_b: mesh_b.triangles.len() },
|
||||
colored_faces,
|
||||
param_warnings: Vec::new(),
|
||||
};
|
||||
serde_json::to_value(out).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
|
||||
/// A face is coloured for a region when at least this share of it deviates there.
|
||||
|
||||
@@ -46,6 +46,7 @@ pub(crate) use features::profiles as feature_profiles;
|
||||
pub(crate) use features::{EdgeRefForm, PLANE_FORMS, axis_dir_form, axis_line_object, edge_ref_form, explicit_plane, plane_name_problem, sketch_key};
|
||||
pub use features::{auto_operation, extrude_reach, shown_scope};
|
||||
pub use file::open_steps::OpenSteps;
|
||||
pub(crate) use inspect::color_param;
|
||||
pub use join_pieces::{Addition, addition};
|
||||
pub use parts::part_length_label;
|
||||
pub use sketch::dimension_roles;
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
//! Contract and result types for `inspect.compare` in `cmd/compare.rs` (#10994).
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
|
||||
use serde::de::Error as _;
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use super::check::whole;
|
||||
|
||||
/// Compare two bodies laid over each other, in world placement: measure both, sample each
|
||||
/// surface's distance to the other, and find, measure and (with `color`) colour the places where
|
||||
/// only one of them has material. It works from the two surfaces, without a boolean of the
|
||||
/// bodies, so near-identical bodies compare too.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct CompareParams {
|
||||
/// The first body, by name. Give both `a` and `b`, or neither: then the two selected bodies,
|
||||
/// or the design's only two.
|
||||
#[serde(default, deserialize_with = "body_name")]
|
||||
pub a: Option<String>,
|
||||
/// The second body, by name.
|
||||
#[serde(default, deserialize_with = "body_name")]
|
||||
pub b: Option<String>,
|
||||
/// Surfaces closer than this agree, in mm: 0.001 to 10 (default 0.01).
|
||||
#[serde(default, deserialize_with = "tolerance")]
|
||||
#[schemars(schema_with = "tolerance_schema")]
|
||||
pub tolerance: Option<f64>,
|
||||
/// The largest piece of a face sampled as one point, in mm: 0.01 to 1000 (default 0.5),
|
||||
/// coarser for a body that would need more than `max_points` samples.
|
||||
#[serde(default, deserialize_with = "spacing")]
|
||||
#[schemars(schema_with = "spacing_schema")]
|
||||
pub spacing: Option<f64>,
|
||||
/// The most samples per body: 10 000 to 50 million (default 8 million).
|
||||
#[serde(default, deserialize_with = "max_points")]
|
||||
#[schemars(schema_with = "max_points_schema")]
|
||||
pub max_points: Option<f64>,
|
||||
/// The most regions measured: 1 to 1000 (default 50); more are counted in `unlisted_regions`.
|
||||
#[serde(default, deserialize_with = "max_regions")]
|
||||
#[schemars(schema_with = "max_regions_schema")]
|
||||
pub max_regions: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub color: Option<CompareColor>,
|
||||
}
|
||||
|
||||
/// A body name, with the handler's message for anything else; `null` is none.
|
||||
fn body_name<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::Null => Ok(None),
|
||||
Value::String(s) => Ok(Some(s)),
|
||||
_ => Err(D::Error::custom("must be a body name")),
|
||||
}
|
||||
}
|
||||
|
||||
/// A number in `lo..=hi` with the handler's message, `null` none, for each ranged key.
|
||||
macro_rules! ranged {
|
||||
($read:ident, $schema:ident, $lo:literal, $hi:literal) => {
|
||||
fn $read<'de, D: Deserializer<'de>>(d: D) -> Result<Option<f64>, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::Null => Ok(None),
|
||||
v => v
|
||||
.as_f64()
|
||||
.filter(|x| x.is_finite() && ($lo..=$hi).contains(x))
|
||||
.map(Some)
|
||||
.ok_or_else(|| D::Error::custom(format!("must be a number from {} to {}", $lo, $hi))),
|
||||
}
|
||||
}
|
||||
|
||||
fn $schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({"type": ["number", "null"], "minimum": $lo, "maximum": $hi})
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
ranged!(tolerance, tolerance_schema, 0.001, 10.0);
|
||||
ranged!(spacing, spacing_schema, 0.01, 1000.0);
|
||||
ranged!(max_points, max_points_schema, 1e4, 5e7);
|
||||
ranged!(max_regions, max_regions_schema, 1.0, 1000.0);
|
||||
|
||||
/// Colour the faces that hold a region: `true` for red where only `a` has material and green
|
||||
/// where only `b` has, or `{only_in_a?, only_in_b?}` to choose either colour (`"#rrggbb"` or
|
||||
/// `[r, g, b]`, 0 to 255). `false` colours nothing. One undo step.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct CompareColor(pub Value);
|
||||
|
||||
impl<'de> Deserialize<'de> for CompareColor {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let v = Value::deserialize(d)?;
|
||||
match &v {
|
||||
Value::Bool(_) => {}
|
||||
Value::Object(o) => {
|
||||
if o.keys().any(|k| k != "only_in_a" && k != "only_in_b") {
|
||||
return Err(D::Error::custom("must be true or {only_in_a, only_in_b}"));
|
||||
}
|
||||
for k in ["only_in_a", "only_in_b"] {
|
||||
if o.get(k).is_some_and(|c| !c.is_null() && crate::cmd::color_param(c).is_none()) {
|
||||
return Err(D::Error::custom(whole(format!("`color.{k}` must be \"#rrggbb\" or [r, g, b] with values 0–255"))));
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => return Err(D::Error::custom("must be true or {only_in_a, only_in_b}")),
|
||||
}
|
||||
Ok(CompareColor(v))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for CompareColor {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"CompareColor".into()
|
||||
}
|
||||
fn inline_schema() -> bool {
|
||||
true
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
let color = || {
|
||||
serde_json::json!({
|
||||
"anyOf": [
|
||||
{"description": "\"#rrggbb\": six hex digits, the # optional.", "type": "string", "pattern": "^\\s*#?[0-9a-fA-F]{6}\\s*$"},
|
||||
{"type": "array", "items": {"type": "number", "minimum": 0, "maximum": 255}, "minItems": 3, "maxItems": 3},
|
||||
{"type": "null"}
|
||||
]
|
||||
})
|
||||
};
|
||||
json_schema!({
|
||||
"description": "Colour the faces that hold a region: true for red where only `a` has material and green where only `b` has, or {only_in_a?, only_in_b?} to choose either colour (\"#rrggbb\" or [r, g, b], 0 to 255). false colours nothing.",
|
||||
"anyOf": [
|
||||
{"type": "boolean"},
|
||||
{"type": "object", "properties": {"only_in_a": color(), "only_in_b": color()}, "additionalProperties": false}
|
||||
]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// What `inspect.compare` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct Comparison {
|
||||
/// `a`'s measures, as `inspect.measure` gives a body's.
|
||||
pub a: Map<String, Value>,
|
||||
/// `b`'s measures, as `inspect.measure` gives a body's.
|
||||
pub b: Map<String, Value>,
|
||||
/// `b` less `a`.
|
||||
pub difference: Difference,
|
||||
/// The tolerance used (mm).
|
||||
pub tolerance_mm: f64,
|
||||
/// How far each surface is from the other.
|
||||
pub deviation: Deviations,
|
||||
/// Whether no region differs by more than the tolerance.
|
||||
pub identical: bool,
|
||||
/// The comparison in a sentence.
|
||||
pub verdict: String,
|
||||
/// The regions where only one body has material, largest first.
|
||||
pub regions: Vec<Region>,
|
||||
/// The regions with material only in `a`, and their volume together.
|
||||
pub only_in_a: SideTotal,
|
||||
/// The regions with material only in `b`, and their volume together.
|
||||
pub only_in_b: SideTotal,
|
||||
/// Regions beyond `max_regions`, counted but not measured.
|
||||
pub unlisted_regions: usize,
|
||||
/// What makes the comparison less certain: a body whose surface doesn't enclose what it
|
||||
/// measures, a cut that couldn't be made, a body that encloses no volume.
|
||||
pub warnings: Vec<String>,
|
||||
/// How the surfaces were sampled.
|
||||
pub sampling: Sampling,
|
||||
/// With `color`: how many faces were coloured.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub colored_faces: Option<usize>,
|
||||
/// 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>,
|
||||
}
|
||||
|
||||
/// `b` less `a`; `null` where either has no such measure.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct Difference {
|
||||
pub volume_mm3: Option<f64>,
|
||||
/// The volume difference as a share of `a`'s (%).
|
||||
pub volume_percent: Option<f64>,
|
||||
pub area_mm2: Option<f64>,
|
||||
pub center_of_mass: Option<[f64; 3]>,
|
||||
pub center_of_mass_distance_mm: Option<f64>,
|
||||
pub bbox_min: Option<[f64; 3]>,
|
||||
pub bbox_max: Option<[f64; 3]>,
|
||||
}
|
||||
|
||||
/// How far each surface is from the other.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct Deviations {
|
||||
/// From `a`'s surface to `b`'s.
|
||||
pub a_to_b: Deviation,
|
||||
/// From `b`'s surface to `a`'s.
|
||||
pub b_to_a: Deviation,
|
||||
/// The larger of the two maxima (mm).
|
||||
pub max_mm: f64,
|
||||
}
|
||||
|
||||
/// One surface's distance to the other, over its samples.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct Deviation {
|
||||
pub max_mm: f64,
|
||||
pub mean_mm: f64,
|
||||
/// Where the largest is.
|
||||
pub at: [f64; 3],
|
||||
/// The area further than the tolerance (mm²).
|
||||
pub area_beyond_mm2: f64,
|
||||
/// The area sampled (mm²).
|
||||
pub area_mm2: f64,
|
||||
/// How many samples.
|
||||
pub points: usize,
|
||||
}
|
||||
|
||||
/// Which body alone has a region's material.
|
||||
#[derive(Clone, Copy, Debug, Serialize, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum CompareSide {
|
||||
OnlyInA,
|
||||
OnlyInB,
|
||||
}
|
||||
|
||||
/// A region where only one body has material.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct Region {
|
||||
/// Its number, from 1, largest first.
|
||||
pub index: usize,
|
||||
pub side: CompareSide,
|
||||
/// The body that has the material.
|
||||
pub material_of: String,
|
||||
/// Its volume (mm³), measured exactly on the pieces of the cut on its side (a − b or b − a)
|
||||
/// that lie there; `null` when it isn't measured, never an estimate.
|
||||
pub volume_mm3: Option<f64>,
|
||||
/// `boolean` when the volume, centre and box were measured on the cut, else `not measured`.
|
||||
pub measured_by: MeasuredBy,
|
||||
/// Why it isn't measured (the cut couldn't be made, a body encloses no volume, no piece fell
|
||||
/// here); `null` when it is.
|
||||
pub not_measured: Option<String>,
|
||||
/// Its surface on both bodies (mm²).
|
||||
pub area_mm2: f64,
|
||||
pub area_a_mm2: f64,
|
||||
pub area_b_mm2: f64,
|
||||
/// How far the surfaces are apart there at most (mm).
|
||||
pub max_deviation_mm: f64,
|
||||
/// Where that is.
|
||||
pub at: [f64; 3],
|
||||
/// Its centre of volume, measured with the volume; `null` when it isn't measured.
|
||||
pub center: Option<[f64; 3]>,
|
||||
/// The measured pieces' box, or the box the region was found in when it isn't measured.
|
||||
pub bbox: Bounds,
|
||||
/// The faces of `a` it lies on, by index, as `model.faces` lists them.
|
||||
pub faces_a: Vec<u32>,
|
||||
/// The faces of `b` it lies on.
|
||||
pub faces_b: Vec<u32>,
|
||||
/// The lines through it the surfaces were sampled along.
|
||||
pub resolution: Resolution,
|
||||
}
|
||||
|
||||
/// How a region was measured.
|
||||
#[derive(Clone, Copy, Debug, Serialize, JsonSchema)]
|
||||
pub enum MeasuredBy {
|
||||
/// Exactly, on the pieces of the cut that lie there.
|
||||
#[serde(rename = "boolean")]
|
||||
Boolean,
|
||||
/// Not at all: see `not_measured`.
|
||||
#[serde(rename = "not measured")]
|
||||
NotMeasured,
|
||||
}
|
||||
|
||||
/// A box, by its corners.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct Bounds {
|
||||
pub min: [f64; 3],
|
||||
pub max: [f64; 3],
|
||||
}
|
||||
|
||||
/// The lines through a region the surfaces were sampled along.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct Resolution {
|
||||
/// The axis they run along: `X`, `Y` or `Z`.
|
||||
pub along: String,
|
||||
/// Their spacing across the other two axes (mm).
|
||||
pub line_spacing_mm: [f64; 2],
|
||||
pub lines: usize,
|
||||
/// Lines that crossed a gap in a surface and were left out.
|
||||
pub skipped_lines: usize,
|
||||
}
|
||||
|
||||
/// The regions on one side, and their volume together.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct SideTotal {
|
||||
pub regions: usize,
|
||||
/// Their volume together (mm³); `null` when one of them isn't measured.
|
||||
pub volume_mm3: Option<f64>,
|
||||
}
|
||||
|
||||
/// How the surfaces were sampled.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct Sampling {
|
||||
/// The sample spacing used (mm).
|
||||
pub spacing_mm: f64,
|
||||
/// How closely the meshes follow the surfaces (mm): a quarter of the tolerance.
|
||||
pub chord_mm: f64,
|
||||
pub triangles_a: usize,
|
||||
pub triangles_b: usize,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "compare_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,74 @@
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CompareParams, Comparison};
|
||||
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};
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schemas_and_the_key_check_agree() {
|
||||
assert_keys(input_schema_for::<CompareParams>(), &["a", "b", "color", "max_points", "max_regions", "spacing", "tolerance"]);
|
||||
}
|
||||
|
||||
/// The handler reads the numbers and the colours before it looks for the bodies, so each of
|
||||
/// these fails the same way on a design with none.
|
||||
#[test]
|
||||
fn strict_keeps_todays_errors() {
|
||||
assert_strict_keeps_todays_errors(&[
|
||||
("inspect.compare", json!({"tolerance": 0})),
|
||||
("inspect.compare", json!({"tolerance": "x"})),
|
||||
("inspect.compare", json!({"spacing": 2000})),
|
||||
("inspect.compare", json!({"max_points": 1})),
|
||||
("inspect.compare", json!({"max_regions": 0})),
|
||||
("inspect.compare", json!({"color": 5})),
|
||||
("inspect.compare", json!({"color": "red"})),
|
||||
("inspect.compare", json!({"color": {"only_in_a": "#zz0000"}})),
|
||||
("inspect.compare", json!({"color": {"only_in_b": [1, 2]}})),
|
||||
("inspect.compare", json!({"a": 5})),
|
||||
("inspect.compare", json!({"a": "A"})),
|
||||
("inspect.compare", json!({})),
|
||||
("inspect.compare", json!({"a": "X", "b": "Y"})),
|
||||
]);
|
||||
}
|
||||
|
||||
/// #10994: a comparison replies as its output schema says, in Warn without warnings for good
|
||||
/// calls and with them for a misspelt key: a box and its copy (identical, no regions), and the
|
||||
/// copy with a boss, compared with every key and coloured both ways.
|
||||
#[test]
|
||||
fn a_comparison_replies_with_its_schema() {
|
||||
let schema = output_schema_for::<Comparison>();
|
||||
let matches = |r: &Value, warned: bool| {
|
||||
let schema = schema.as_value();
|
||||
assert!(conforms(schema, schema, r), "{r} doesn't match {schema}");
|
||||
assert_eq!(r.get("param_warnings").is_some(), warned, "{r}");
|
||||
};
|
||||
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10, "body_name": "A"}));
|
||||
run(&mut s, "solid.move", json!({"bodies": ["A"], "translate": [0, 0, 0], "copy": true}));
|
||||
let r = run(&mut s, "inspect.compare", json!({}));
|
||||
matches(&r, false);
|
||||
assert!(r["identical"] == true && r["regions"] == json!([]) && r.get("colored_faces").is_none(), "{r}");
|
||||
run(&mut s, "solid.box", json!({"length": 6, "width": 5, "height": 2, "corner": [5, 5, 10], "operation": "join", "targets": ["A (2)"]}));
|
||||
let r = run(
|
||||
&mut s,
|
||||
"inspect.compare",
|
||||
json!({"a": "A", "b": "A (2)", "tolerance": 0.01, "spacing": 0.5, "max_points": 1e6, "max_regions": 10, "color": true}),
|
||||
);
|
||||
matches(&r, false);
|
||||
assert_eq!((r["regions"][0]["side"].as_str(), r["identical"].as_bool()), (Some("only_in_b"), Some(false)), "{r}");
|
||||
assert!(r["colored_faces"].as_u64().is_some_and(|n| n > 0), "{r}");
|
||||
let r = run(&mut s, "inspect.compare", json!({"a": "A", "b": "A (2)", "color": {"only_in_b": "#123456", "only_in_a": null}}));
|
||||
matches(&r, false);
|
||||
matches(&run(&mut s, "inspect.compare", json!({"a": "A", "b": "A (2)", "color": false, "tolerence": 1})), true);
|
||||
}
|
||||
|
||||
/// A `color` string in the published schema carries the same pattern the handler checks.
|
||||
#[test]
|
||||
fn the_color_string_has_a_pattern() {
|
||||
let schema = serde_json::to_string(&input_schema_for::<CompareParams>()).unwrap();
|
||||
assert!(schema.contains(r"^\\s*#?[0-9a-fA-F]{6}\\s*$"), "{schema}");
|
||||
}
|
||||
@@ -58,6 +58,7 @@ pub mod appearance;
|
||||
pub mod bom;
|
||||
pub mod browser;
|
||||
pub mod clearance;
|
||||
pub mod compare;
|
||||
pub mod component;
|
||||
pub mod config;
|
||||
pub mod construct;
|
||||
|
||||
@@ -75,7 +75,6 @@ frame.member
|
||||
frame.profile.insert
|
||||
frame.profile.list
|
||||
frame.profile.properties
|
||||
inspect.compare
|
||||
inspect.interference
|
||||
inspect.measure
|
||||
inspect.parameter_sweep
|
||||
|
||||
Reference in New Issue
Block a user