use super::element::{attributes, elements, fn_name, rust_name};
use super::ir::slug;
use super::schema::{describe_issue, validate, with_defaults};
use super::source::Sources;
use super::standards::sized_hole;
use super::{Declared, Family};
pub use super::threed_props::THREED_FEATURES;
pub use super::{fragment, json, El, Json, Value};
use std::sync::OnceLock;
elements! {
part: children;
assembly: children;
parameter: leaf;
plane: leaf;
body: leaf;
slot: leaf;
joint: leaf;
contact: leaf;
mate: leaf;
sheet: leaf;
item: leaf;
assemble: leaf;
product: leaf;
unit: leaf;
capture: leaf;
view: leaf;
check: leaf;
accept: leaf;
permitted: leaf;
fastener: leaf;
tactile: leaf;
port: leaf;
library: leaf;
linear_dimension = "linearDimension": leaf;
radial_dimension = "radialDimension": leaf;
size_dimension = "sizeDimension": leaf;
angular_dimension = "angularDimension": leaf;
note: leaf;
datum_feature = "datumFeature": leaf;
datum_target = "datumTarget": leaf;
feature_control_frame = "featureControlFrame": leaf;
surface_finish = "surfaceFinish": leaf;
feature: leaf;
sketch: children;
extrude: leaf;
revolve: leaf;
sweep: leaf;
curve: leaf;
rod: leaf;
loft: leaf;
fillet: leaf;
chamfer: leaf;
shell: leaf;
box_: leaf;
import: leaf;
external_part = "externalPart": leaf;
cylinder: leaf;
sphere: leaf;
cone: leaf;
make_human = "makeHuman": leaf;
linear_pattern = "linearPattern": leaf;
circular_pattern = "circularPattern": leaf;
path_pattern = "pathPattern": leaf;
mirror: leaf;
datum_plane = "datumPlane": leaf;
datum_axis = "datumAxis": leaf;
datum_point = "datumPoint": leaf;
draft: leaf;
hole: leaf;
thread: leaf;
rib: leaf;
coil: leaf;
combine: leaf;
offset_faces = "offsetFaces": leaf;
thicken: leaf;
trim_surface = "trimSurface": leaf;
untrim_surface = "untrimSurface": leaf;
extend_surface = "extendSurface": leaf;
stitch: leaf;
replace_face = "replaceFace": leaf;
offset_surface = "offsetSurface": leaf;
split: leaf;
scale: leaf;
dome: leaf;
wrap_text = "wrapText": leaf;
delete_face = "deleteFace": leaf;
full_round = "fullRound": leaf;
sheet_metal = "sheetMetal": leaf;
sheet_corner = "sheetCorner": leaf;
sheet_convert = "sheetConvert": leaf;
sheet_refold = "sheetRefold": leaf;
sheet_base = "sheetBase": leaf;
sheet_flange = "sheetFlange": leaf;
sheet_hem = "sheetHem": leaf;
sheet_fold = "sheetFold": leaf;
unfold: leaf;
frame_member = "frameMember": leaf;
end_cap = "endCap": leaf;
copy_body = "copyBody": leaf;
transform: leaf;
subdiv_body = "subdivBody": leaf;
mesh_body = "meshBody": leaf;
mesh_modifier = "meshModifier": leaf;
point_cloud = "pointCloud": leaf;
gaussian_splat = "gaussianSplat": leaf;
skeleton: leaf;
volume: leaf;
molecule: leaf;
graph: leaf;
generate: leaf;
pcb_trace = "pcbTrace": leaf;
copper_pour = "copperPour": leaf;
generate_via = "generateVia": leaf;
plated_hole = "platedHole": leaf;
code: leaf;
point: leaf;
line: leaf;
circle: leaf;
arc: leaf;
spline: leaf;
ellipse: leaf;
ellipse_arc = "ellipseArc": leaf;
constraint: leaf;
projection: leaf;
equation: leaf;
text: leaf;
}
attributes! {
pub trait ThreedAttrs {
a; actuator; african; age; align_to_path; anchor; angle; animation; annotations; area; armatures; asian; assembly;
at; axis; axis_b; b; base; bend_radius; bias; bindings; bodies; body_id; bond_orders; bonds; both_sides;
break_after; builtin; builtin_planes; by; cap; caucasian; cell; center; centreline; chains; closed; collapsed;
colormap; colors; comment; component; conductor; construction; consumes; contours; control_points; corner; count; count2;
cupsize; currency; data; decals; depth; diameter; dims; dir; directed; direction; direction2; distance; distance2;
draft_angle; drill_mm; dynamics; edge; edge_weights; edges; efficiency; electrical; electron; elements; end; engineering; entities;
environment; expression; fabrication; face; faces; factor; fasteners; feature; file_id; file_name; firmness; fixed; fixture; focus; font;
footprint; format; from; gender; graph; groups; head_depth; head_diameter; height; hidden_lines; hole_callouts; home; home_travel; host; id; importer; indices;
input; inputs; instruction; internal; iso; join; k_factor; keep_original; kind; knots; label; layer; layers; length;
level; lib_id; limits; local_placement; material; material_groups; mates; max; members; min; minor_radius; minutes; mode;
model_id; modifier; muscle; name; node_colors; node_groups; node_positions; node_sizes; node_types; normal;
normals; nucleus; nurbs; offset; operation; optimization; order; origin; outward; overall_dimensions; pad; pad_diameter_mm;
pads; paint; params; parents; part; parts; parts_list; path; pin; pitch; placement; planar; plane; point; point_size; points;
polygons; position; positions; profile; profiles; projection; proportions; provenance; pull_direction; qty; quaternion;
radii; radius; radius1; radius2; rate_per_hour; ref_; ref_a; ref_b; reference; refs; regions; render; representation; requires; reverse;
right_handed; rings; rotate_angle; rotate_axis; rotation_deg; rotations; rule; ruled; scale; scale_x_y_z;
scales; scene_constraints; seed_feature; semantic_visibility; sh; sh_degree; side; signature; size; sketch;
skins; source; source_materials; source_uv; spacing; spacing2; standard_parts; start; step; style;
subdivision; suppressed; symmetric; target; terminal; thickness; through; title; token; tools; transform; translate;
travel; turns; type_; u; unit; unit_scale_mm; up_to_face; uv; v; value; views; visible; weight; width; x; x_axis; y;
start_tangent; end_tangent; tangents; tangent_scale;
frame; up; guide; twist;
tolerance;
hole; shaft; intent;
chain; limit; method; samples; seed;
against; min_volume; sweep;
options;
check; body; other; max_volume; reason; region; severity;
compliance; shipping;
device; rotation; channels; tilt_deg = "tilt_deg"; size_mm = "size_mm";
src; captured; licence; credit; terms; devices;
camera; ride;
process; edge_dir;
clamped; receiver; washer; nut; grip; fit; min_engagement; torque; part_number;
along; rows; cols; saturation;
strands; file; section; to; slack; segment; hold; retention; first; ends;
match_; sizes;
collide; friction; restitution; report;
text_at; notes; formats; measure; spherical; of; datum; rim; angle_selection; vertex; text; leader_to; property;
letter; placed; on; characteristic; diameter_zone; datums; modifiers; zone; unequal; projected; per_unit; maximum;
segment_of; roughness; requirement;
base2; edge2; point2; point3; plane2; plane3; surface; thread; thread_depth; thread_kind; tool; tool_body; keep_front; rollback;
}
}
pub(crate) const FAMILY: Family = Family { module: "threed", roots: &["part", "assembly"], declare };
pub fn threed_schema() -> &'static Json {
static SCHEMA: OnceLock<Json> = OnceLock::new();
SCHEMA.get_or_init(|| Json::parse(include_str!("threed_schema.json")).expect("threed_schema.json is JSON"))
}
fn check_feature(el: &El, feature: Json) -> Result<Json, String> {
let schema = threed_schema();
let Some(def) = feature.get("type").and_then(|t| schema.get("roots")?.get(t.as_str()?)).and_then(Json::as_str) else { return Ok(feature) };
let defs = schema.get("$defs").cloned().unwrap_or_else(Json::obj);
let root = Json::obj().with("$ref", format!("#/$defs/{def}"));
let filled = with_defaults(&root, &feature, &defs)?;
let issues = validate(&root, &filled, &defs, "")?;
if issues.is_empty() {
return Ok(filled);
}
Err(format!("{}: {}", at(el), issues.iter().map(describe_issue).collect::<Vec<_>>().join("; ")))
}
fn check_value(el: &El, def: &str, value: &Json, path: &str) -> Result<Json, String> {
let schema = threed_schema();
let defs = schema.get("$defs").cloned().unwrap_or_else(Json::obj);
let root = Json::obj().with("$ref", format!("#/$defs/{def}"));
let filled = with_defaults(&root, value, &defs)?;
let issues = validate(&root, &filled, &defs, path)?;
if issues.is_empty() {
return Ok(filled);
}
Err(format!("{}: {}", at(el), issues.iter().map(describe_issue).collect::<Vec<_>>().join("; ")))
}
fn sheet_view_problems(sheet: &Json) -> Vec<String> {
let Some(Json::Arr(views)) = sheet.get("views") else { return Vec::new() };
let text = |v: &Json, k: &str| v.get(k).and_then(Json::as_str).unwrap_or_default().to_string();
let given = |v: &Json, k: &str| v.get(k).is_some_and(|x| !matches!(x, Json::Null));
let mut out = Vec::new();
for v in views {
let (id, view) = (text(v, "id"), text(v, "view"));
if view == "section" && !given(v, "section") {
out.push(format!("view {id} is a section view with no section: give its cutting plane (point and normal)"));
}
if view != "detail" {
continue;
}
let Some(detail) = v.get("detail").filter(|_| given(v, "detail")) else {
out.push(format!("view {id} is a detail view with no detail: give the view it enlarges, its centre and its radius"));
continue;
};
let of = text(detail, "of");
match views.iter().find(|w| text(w, "id") == of) {
None => out.push(format!("view {id} is a detail of {of}, which is no view of this sheet")),
Some(w) if text(w, "view") == "detail" => out.push(format!("view {id} is a detail of {of}, which is a detail itself")),
Some(_) => {}
}
}
out
}
pub const THREED_LISTS: &[(&str, &str, &str, &str, Option<&str>)] =
&[
("joint", "dynamics", "joints", "DynamicsJoint", None),
("contact", "dynamics", "contacts", "DynamicsContact", None),
("mate", "assembly", "mates", "Mate", None),
("sheet", "drawings", "value", "DrawingSheet", None),
("check", "checks", "value", "DesignCheck", None),
("accept", "accepted", "value", "AcceptedFinding", None),
("permitted", "permitted", "value", "PermittedFinding", None),
("fastener", "fasteners", "value", "FastenerStack", None),
("tactile", "tactile", "value", "TactileSkin", None),
("port", "ports", "value", "Port", None),
("item", "items", "value", "ProductItem", None),
("assemble", "assemblySteps", "value", "AssemblyStep", None),
("library", "library", "value", "LibraryData", None),
("product", "products", "value", "ProductFacts", None),
("unit", "placements", "value", "PlacedUnit", None),
("capture", "captures", "value", "PlacedCapture", None),
("view", "views", "value", "NamedView", None),
("linearDimension", "annotations", "value", "LinearDimension", Some("annotation")),
("radialDimension", "annotations", "value", "RadialDimension", Some("annotation")),
("sizeDimension", "annotations", "value", "SizeDimension", Some("annotation")),
("angularDimension", "annotations", "value", "AngularDimension", Some("annotation")),
("note", "annotations", "value", "Note", Some("annotation")),
("datumFeature", "annotations", "value", "DatumFeature", Some("annotation")),
("datumTarget", "annotations", "value", "DatumTarget", Some("annotation")),
("featureControlFrame", "annotations", "value", "FeatureControlFrame", Some("annotation")),
("surfaceFinish", "annotations", "value", "SurfaceFinish", Some("annotation")),
];
pub const THREED_ANNOTATIONS: &[&str] =
&["linearDimension", "radialDimension", "sizeDimension", "angularDimension", "note", "datumFeature", "datumTarget", "featureControlFrame", "surfaceFinish"];
const NOT_FEATURES: &[&str] = &[
"feature", "part", "assembly", "parameter", "plane", "body", "slot", "joint", "contact", "mate", "sheet", "check", "accept", "permitted", "fastener", "tactile", "port", "item", "assemble", "library", "product", "unit", "capture", "view", "point", "constraint",
"projection", "equation", "text", "line", "circle", "arc", "spline", "ellipse", "ellipseArc", "input", "linearDimension", "radialDimension", "sizeDimension",
"angularDimension", "note", "datumFeature", "datumTarget", "featureControlFrame", "surfaceFinish",
];
pub const SKETCH_SEGMENTS: &[&str] = &["line", "circle", "arc", "spline", "ellipse", "ellipseArc"];
pub const BUILTIN_PLANES: &[(&str, &str, [f64; 3], [f64; 3], [f64; 3], &str)] = &[
("plane_xy", "Top (XY)", [0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0], "XY"),
("plane_xz", "Front (XZ)", [0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0], "XZ"),
("plane_yz", "Right (YZ)", [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], "YZ"),
];
const VIEW_ATTRS: &[&str] = &["semanticVisibility"];
const PARAM_FIELDS: &[&str] = &["value", "expression", "unit", "comment", "min", "max", "step", "tolerance"];
const NOT_SLOTS: &[&str] = &[
"id", "name", "units", "planes", "features", "parameters", "presentation", "isAssembly", "bodyMeta", "semanticVisibility", "drawings", "checks",
"accepted", "permitted", "fasteners", "tactile", "ports", "items", "assemblySteps", "library", "products", "placements", "captures", "views", "annotations",
];
const OBJECT_SLOTS: &[&str] = &["environment", "assembly", "sceneConstraints", "dynamics", "animation", "optimization", "standardParts"];
pub fn is_threed(root: &El) -> bool {
root.tag == "part" || root.tag == "assembly"
}
fn at(el: &El) -> String {
for k in ["id", "name"] {
if let Some(v @ Json::Str(_)) = el.attr_of(k) {
return format!("{}().{k}({})", fn_name(el.tag), v.text());
}
}
format!("{}()", fn_name(el.tag))
}
fn js_number(n: f64) -> String {
if n.is_nan() {
"NaN".into()
} else if n.is_infinite() {
if n > 0.0 { "Infinity".into() } else { "-Infinity".into() }
} else {
Json::Num(n).text()
}
}
fn plain(v: &Json, what: &str) -> Result<(), String> {
match v {
Json::Num(n) if !n.is_finite() => Err(format!("{what} is {}, not a finite number", js_number(*n))),
Json::Arr(items) => items.iter().enumerate().try_for_each(|(i, x)| plain(x, &format!("{what}[{i}]"))),
Json::Obj(entries) => entries.iter().try_for_each(|(k, x)| plain(x, &format!("{what}.{k}"))),
_ => Ok(()),
}
}
fn fields(el: &El, skip: &[&str]) -> Result<Vec<(String, Json)>, String> {
let mut out = Vec::new();
for (k, v) in &el.attrs {
if skip.contains(&k.as_str()) {
continue;
}
plain(v, &format!("{} {}", at(el), rust_name(k)))?;
out.push((k.clone(), v.clone()));
}
Ok(out)
}
fn take(fields: &mut Vec<(String, Json)>, name: &str) -> Option<Json> {
fields.iter().position(|(k, _)| k == name).map(|i| fields.remove(i).1)
}
fn word_char(c: char) -> bool {
c.is_ascii_alphanumeric() || c == '_'
}
fn id_ok(id: &str) -> bool {
id.split('/').all(|part| !part.is_empty() && part.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-')))
}
fn id_of(el: &El) -> Result<String, String> {
match el.attr_of("id") {
Some(Json::Str(id)) if !id.is_empty() => {
if !id_ok(id) {
return Err(format!("{}: an id is letters, digits, _ . - with / between them ({})", at(el), Json::from(id.as_str()).text()));
}
Ok(id.clone())
}
_ => Err(format!("{} needs an id", at(el))),
}
}
fn no_children(el: &El) -> Result<(), String> {
if el.child_elements().next().is_some() {
return Err(format!("{} has no child elements", at(el)));
}
Ok(())
}
fn source_meta(el: &El) -> Option<Json> {
el.source_json().map(|s| Json::obj().with("source", s))
}
fn keys(entries: &[(String, Json)]) -> Json {
Json::Arr(entries.iter().map(|(k, _)| Json::from(k.as_str())).collect())
}
fn sketch_of(el: &El) -> Result<(Json, Sources), String> {
let (mut points, mut segments, mut constraints, mut projections) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
let (mut equations, mut texts): (Vec<(String, Json)>, Vec<(String, Json)>) = (Vec::new(), Vec::new());
let mut sources = Sources::new();
let mut taken: Vec<String> = Vec::new();
for child in el.child_elements() {
let mut claim = |kind: &str| -> Result<String, String> {
let id = id_of(child)?;
if taken.contains(&id) {
return Err(format!("{}: two entities are called {id}", at(el)));
}
taken.push(id.clone());
sources.put(format!("{kind}:{id}"), child);
no_children(child)?;
Ok(id)
};
if child.tag == "point" {
let id = claim("point")?;
let f = fields(child, &[])?;
let num = |k: &str| matches!(f.iter().find(|(n, _)| n == k), Some((_, Json::Num(_))));
if !num("x") || !num("y") {
return Err(format!("{} {}: a point has x and y (mm)", at(el), at(child)));
}
points.push((id, Json::Obj(f)));
} else if SKETCH_SEGMENTS.contains(&child.tag) {
let id = claim("segment")?;
if child.attr_of("type").is_some() {
return Err(format!("{} {}: the tag is the segment's type", at(el), at(child)));
}
let mut s = vec![("id".to_string(), Json::from(id.as_str())), ("type".to_string(), Json::from(child.tag))];
s.extend(fields(child, &["id"])?);
segments.push((id, Json::Obj(s)));
} else if child.tag == "constraint" {
let id = claim("constraint")?;
let f = fields(child, &[])?;
let get = |k: &str| f.iter().find(|(n, _)| n == k).map(|(_, v)| v);
if !matches!(get("kind"), Some(Json::Str(_))) || !matches!(get("entities"), Some(Json::Arr(_))) {
return Err(format!("{} {}: a constraint has a kind and its entities", at(el), at(child)));
}
constraints.push((id, Json::Obj(f)));
} else if child.tag == "projection" {
let id = claim("projection")?;
projections.push((id, Json::Obj(fields(child, &[])?)));
} else if child.tag == "equation" {
let id = claim("equation")?;
let f = fields(child, &[])?;
let get = |k: &str| f.iter().find(|(n, _)| n == k).map(|(_, v)| v);
let num = |k: &str| matches!(get(k), Some(Json::Num(_)));
if !matches!(get("x"), Some(Json::Str(_))) || !matches!(get("y"), Some(Json::Str(_))) || !num("from") || !num("to") || !num("points") {
return Err(format!("{} {}: an equation curve has x and y (arithmetic of t), from, to and points", at(el), at(child)));
}
let mut e = vec![("id".to_string(), Json::from(id.as_str()))];
e.extend(f);
equations.push((id, Json::Obj(e)));
} else if child.tag == "text" {
let id = claim("text")?;
let f = fields(child, &[])?;
let get = |k: &str| f.iter().find(|(n, _)| n == k).map(|(_, v)| v);
if !matches!(get("text"), Some(Json::Str(_))) || !matches!(get("anchor"), Some(Json::Str(_))) || !matches!(get("along"), Some(Json::Str(_))) || !matches!(get("contours"), Some(Json::Arr(_))) {
return Err(format!("{} {}: a text has its words, its anchor and along points and its contours", at(el), at(child)));
}
let mut e = vec![("id".to_string(), Json::from(id.as_str()))];
e.extend(f);
texts.push((id, Json::Obj(e)));
} else {
let segs: Vec<String> = SKETCH_SEGMENTS.iter().map(|s| fn_name(s)).collect();
return Err(format!("{}: {}() is not read in a sketch (point, {}, constraint, projection, equation, text)", at(el), fn_name(child.tag), segs.join(", ")));
}
}
for (id, s) in &segments {
for k in ["a", "b", "center", "start", "end", "focus"] {
if let Some(p) = s.get(k) {
if !p.as_str().is_some_and(|p| points.iter().any(|(q, _)| q == p)) {
return Err(format!("{}: segment {id}'s {k} names no point of the sketch ({})", at(el), p.text()));
}
}
}
}
let mut sketch = Json::obj()
.with("points", Json::Obj(points.clone()))
.with("segments", Json::Obj(segments.clone()))
.with("constraints", Json::Obj(constraints.clone()))
.with("pointOrder", keys(&points))
.with("segmentOrder", keys(&segments))
.with("constraintOrder", keys(&constraints));
if !projections.is_empty() {
sketch.set("projectionOrder", keys(&projections));
if let Json::Obj(entries) = &mut sketch {
let at = entries.len() - 1;
entries.insert(at, ("projections".into(), Json::Obj(projections)));
}
}
for (group, order, list) in [("equations", "equationOrder", equations), ("texts", "textOrder", texts)] {
if list.is_empty() {
continue;
}
if group == "texts" {
for (id, t) in &list {
for k in ["anchor", "along"] {
let p = t.get(k).and_then(|p| p.as_str());
if !p.is_some_and(|p| points.iter().any(|(q, _)| q == p)) {
return Err(format!("{}: text {id}'s {k} names no point of the sketch", at(el)));
}
}
}
}
sketch.set(order, keys(&list));
if let Json::Obj(entries) = &mut sketch {
let at = entries.len() - 1;
entries.insert(at, (group.into(), Json::Obj(list)));
}
}
Ok((sketch, sources))
}
fn builtin_planes_of(root: &El) -> Result<Vec<&'static str>, String> {
let all: Vec<&'static str> = BUILTIN_PLANES.iter().map(|p| p.0).collect();
let Some(v) = root.attr_of("builtinPlanes") else { return Ok(all) };
let refused = || format!("{}: builtin_planes lists built-in planes ({})", at(root), all.join(", "));
let Json::Arr(items) = v else { return Err(refused()) };
let mut out = Vec::new();
for x in items {
let p = x.as_str().and_then(|s| all.iter().find(|a| **a == s).copied()).ok_or_else(refused)?;
if out.contains(&p) {
return Err(format!("{}: builtin_planes names a plane twice", at(root)));
}
out.push(p);
}
Ok(out)
}
fn presentation_of(root: &El, order: Vec<Json>) -> Result<Option<Json>, String> {
let features: Vec<String> = order.iter().filter_map(|j| j.as_str().map(String::from)).collect();
let mut out = Json::obj();
let mut any = false;
if !order.is_empty() {
out.set("order", order);
any = true;
}
if let Some(groups) = root.attr_of("groups") {
let Json::Arr(items) = groups else { return Err(format!("{} groups: a list of {{ id, name, members, collapsed? }}", at(root))) };
let mut made = Vec::new();
for (i, g) in items.iter().enumerate() {
let here = format!("{} groups[{i}]", at(root));
let (Some(Json::Str(id)), Some(Json::Str(name)), Some(Json::Arr(members))) = (g.get("id"), g.get("name"), g.get("members")) else {
return Err(format!("{here}: a group is {{ id, name, members, collapsed? }}"));
};
if id.is_empty() {
return Err(format!("{here}: a group is {{ id, name, members, collapsed? }}"));
}
for m in members {
if !m.as_str().is_some_and(|m| features.iter().any(|f| f == m)) {
return Err(format!("{here}: member {} is not a feature of this document", m.text()));
}
}
let mut group = Json::obj().with("id", id.as_str()).with("name", name.as_str()).with("members", Json::Arr(members.clone()));
if matches!(g.get("collapsed"), Some(Json::Bool(true))) {
group.set("collapsed", true);
}
made.push(group);
}
out.set("groups", Json::Arr(made));
any = true;
}
if let Some(rollback) = root.attr_of("rollback") {
match rollback.as_str() {
Some(r) if features.iter().any(|f| f == r) => {
out.set("rollback", r);
any = true;
}
_ => return Err(format!("{} rollback: {} is not a feature of this document", at(root), rollback.text())),
}
}
Ok(if any { Some(out) } else { None })
}
fn declare(root: El) -> Result<Declared, String> {
declare_threed(&root, &super::source::stem().unwrap_or_else(|| "Part".into())).map(Declared::Graph)
}
pub fn declare_threed(root: &El, fallback_name: &str) -> Result<Json, String> {
if !is_threed(root) {
return Err("a 3D document is one part() or assembly() element".into());
}
for (k, _) in &root.attrs {
if !["name", "id", "builtinPlanes", "groups", "rollback"].contains(&k.as_str()) && !VIEW_ATTRS.contains(&k.as_str()) {
return Err(format!("{}: {} is not read on a 3D document", at(root), rust_name(k)));
}
}
let builtins = builtin_planes_of(root)?;
let name = match root.attr_of("name") {
Some(Json::Str(n)) if !n.is_empty() => n.clone(),
_ => fallback_name.to_string(),
};
let mut nodes: Vec<(String, Json)> = Vec::new();
let mut owner: Vec<(String, String)> = Vec::new();
fn claim(owner: &mut Vec<(String, String)>, id: &str, what: String) -> Result<(), String> {
if let Some((_, prev)) = owner.iter().find(|(o, _)| o == id) {
return Err(format!("the id \"{id}\" is both {prev} and {what}; a node id is used once"));
}
owner.push((id.to_string(), what));
Ok(())
}
let node = |id: &str, kind: &str, label: Option<&str>, inputs: Json, meta: Option<Json>| {
let mut n = Json::obj().with("id", id).with("type", kind);
if let Some(l) = label {
n.set("label", l);
}
n.set("inputs", inputs);
if let Some(m) = meta {
n.set("meta", m);
}
n
};
let mut order: Vec<Json> = Vec::new();
let mut bodies: Vec<(String, Json)> = Vec::new();
let mut body_sources = Sources::new();
let mut declared: Vec<&El> = Vec::new();
let mut lists: Vec<(usize, Vec<Json>, Sources)> = Vec::new();
let mut refused: Vec<String> = Vec::new();
for el in root.child_elements() {
let read = (|| -> Result<(), String> {
match el.tag {
"parameter" => {
no_children(el)?;
let pname = match el.attr_of("name") {
Some(Json::Str(p)) if !p.is_empty() && slug(p) == *p => p.clone(),
_ => return Err(format!("{} needs a name (letters, digits, _ . -)", at(el))),
};
for (k, _) in &el.attrs {
if !["name", "bindings"].contains(&k.as_str()) && !PARAM_FIELDS.contains(&k.as_str()) {
return Err(format!("{}: {} is not read on a parameter", at(el), rust_name(k)));
}
}
if !matches!(el.attr_of("value"), Some(Json::Num(_))) {
return Err(format!("{}: value is a number", at(el)));
}
if let Some(tol) = el.attr_of("tolerance") {
if let Some(problem) = super::tolerances::tolerance_problem(tol) {
return Err(format!("{}: tolerance: {problem}", at(el)));
}
}
claim(&mut owner, &pname, format!("parameter \"{pname}\""))?;
let mut inputs = fields(el, &["name", "bindings"])?;
let bindings = match el.attr_of("bindings") {
None => Json::Arr(Vec::new()),
Some(b) => {
plain(b, &format!("{} bindings", at(el)))?;
b.clone()
}
};
let ok = match &bindings {
Json::Arr(list) => list.iter().all(|b| matches!(b.get("target"), Some(Json::Str(_))) && matches!(b.get("field"), Some(Json::Str(_)))),
_ => false,
};
if !ok {
return Err(format!("{}: bindings are [{{ target, field }}]", at(el)));
}
if matches!(&bindings, Json::Arr(l) if !l.is_empty()) {
inputs.retain(|(k, _)| k != "drives");
inputs.push(("drives".into(), bindings));
}
nodes.push((pname.clone(), node(&pname, "input", Some(&pname), Json::Obj(inputs), source_meta(el))));
}
"plane" => {
no_children(el)?;
let id = id_of(el)?;
claim(&mut owner, &id, format!("plane \"{id}\""))?;
let mut rest = fields(el, &["id"])?;
let label = take(&mut rest, "name");
nodes.push((id.clone(), node(&id, "plane", label.as_ref().and_then(Json::as_str), Json::Obj(rest), source_meta(el))));
}
"body" => {
no_children(el)?;
let id = id_of(el)?;
if bodies.iter().any(|(b, _)| *b == id) {
return Err(format!("two body() elements are called {id}"));
}
let mut body = fields(el, &["id"])?;
for (k, v) in body.iter_mut() {
if k == "engineering" {
*v = check_value(el, "PartEngineering", v, "engineering")?;
}
if k == "material" {
*v = check_value(el, "BodyMaterial", v, "material")?;
}
}
bodies.push((id.clone(), Json::Obj(body)));
body_sources.put(id, el);
}
t if THREED_LISTS.iter().any(|l| l.0 == t) => {
no_children(el)?;
let id = id_of(el)?;
let row = THREED_LISTS.iter().position(|l| l.0 == t).unwrap_or_default();
let (_, node, port, def, kind) = THREED_LISTS[row];
if !lists.iter().any(|l| THREED_LISTS[l.0].1 == node && THREED_LISTS[l.0].2 == port) {
lists.push((row, Vec::new(), Sources::new()));
}
let Some(held) = lists.iter_mut().find(|l| THREED_LISTS[l.0].1 == node && THREED_LISTS[l.0].2 == port) else { return Ok(()) };
if held.1.iter().any(|x| x.get("id").and_then(Json::as_str) == Some(id.as_str())) {
return Err(match kind {
Some(k) => format!("two {k}s are called {id}"),
None => format!("two {}() elements are called {id}", fn_name(t)),
});
}
let mut said = fields(el, &[])?;
if let Some(k) = kind {
if el.attr_of("type").is_some() {
return Err(format!("{}: the tag is the {k}'s type", at(el)));
}
said.insert(0, ("type".into(), Json::from(t)));
}
let item = check_value(el, def, &Json::Obj(said), "")?;
if t == "sheet" {
let problems = sheet_view_problems(&item);
if !problems.is_empty() {
return Err(format!("{}: {}", at(el), problems.join("; ")));
}
}
held.1.push(item);
held.2.put(format!("{}:{id}", kind.unwrap_or(t)), el);
}
"slot" => {
no_children(el)?;
let field = match el.attr_of("name") {
Some(Json::Str(f)) if f.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_') && f.chars().all(word_char) => f.clone(),
_ => return Err(format!("{} needs the name of a document field", at(el))),
};
if NOT_SLOTS.contains(&field.as_str()) {
let tags: Vec<String> = THREED_LISTS.iter().filter(|l| l.1 == field && l.2 == "value").map(|l| format!("{}()", fn_name(l.0))).collect();
let said = if tags.is_empty() { "(it has its own element or attribute)".to_string() } else { format!("(its items are written as their own elements: {})", tags.join(", ")) };
return Err(format!("{}: {field} is not a slot {said}", at(el)));
}
for (k, _) in &el.attrs {
if k != "name" && k != "value" {
return Err(format!("{}: {} is not read on a slot (its value is value)", at(el), rust_name(k)));
}
}
claim(&mut owner, &field, format!("the document's {field}"))?;
let value = el.attr_of("value").cloned();
if let Some(v) = &value {
plain(v, &format!("{} value", at(el)))?;
}
let inputs = if OBJECT_SLOTS.contains(&field.as_str()) {
match &value {
Some(v @ Json::Obj(_)) => {
if let Some(l) = THREED_LISTS.iter().find(|l| l.1 == field && v.get(l.2).is_some()) {
return Err(format!("{}: {} are written as {}() elements", at(el), l.2, fn_name(l.0)));
}
v.clone()
}
_ => return Err(format!("{}: the document's {field} is an object", at(el))),
}
} else {
match value {
Some(v) => Json::obj().with("value", v),
None => Json::obj(),
}
};
nodes.push((field.clone(), node(&field, &format!("3d.{field}"), None, inputs, source_meta(el))));
}
t if THREED_FEATURES.contains(&t) => declared.push(el),
"feature" => {
let t = match el.attr_of("type") {
Some(Json::Str(t))
if t.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_') && t.chars().all(|c| word_char(c) || c == '.' || c == '-') =>
{
t.clone()
}
_ => return Err(format!("{} needs the feature's type", at(el))),
};
if THREED_FEATURES.contains(&t.as_str()) || NOT_FEATURES.contains(&t.as_str()) {
return Err(format!("{}: a {t} is written {}(…)", at(el), fn_name(&t)));
}
declared.push(el);
}
"part" | "assembly" => {
return Err(format!("{}() is a document of its own: place its file with external_part() (file_name, importer \"3d\"; its bodies keep their names under the placement)", fn_name(el.tag)))
}
_ => return Err(format!("{}() is not read in a 3D document (see commandagi::design::threed)", fn_name(el.tag))),
}
Ok(())
})();
if let Err(e) = read {
refused.push(e);
}
}
for el in declared {
let read = (|| -> Result<(), String> {
let id = id_of(el)?;
claim(&mut owner, &id, format!("feature \"{id}\""))?;
let generic = el.tag == "feature";
if !generic && el.attr_of("type").is_some() {
return Err(format!("{}: the tag is the feature's type", at(el)));
}
let kind = if generic { el.attr_of("type").and_then(Json::as_str).unwrap_or_default().to_string() } else { el.tag.to_string() };
let mut rest = fields(el, if generic { &["id", "type"] } else { &["id"] })?;
let label = take(&mut rest, "name");
let suppressed = take(&mut rest, "suppressed");
if suppressed.as_ref().is_some_and(|s| !matches!(s, Json::Bool(_))) {
return Err(format!("{}: suppressed is true or false", at(el)));
}
let mut inputs = rest;
let mut sources = Sources::new();
if el.tag == "sketch" {
if inputs.iter().any(|(k, _)| k == "sketch") {
return Err(format!("{}: a sketch's points, segments and constraints are its child elements", at(el)));
}
let (sketch, s) = sketch_of(el)?;
inputs.push(("sketch".into(), sketch));
sources = s;
}
if el.tag == "hole" && inputs.iter().any(|(k, v)| k == "size" && matches!(v, Json::Str(_))) {
if let Json::Obj(sized) = sized_hole(&Json::Obj(inputs.clone())).map_err(|e| format!("{}: {e}", at(el)))? {
inputs = sized;
}
}
if !generic {
let mut feature = vec![("type".to_string(), Json::from(kind.as_str())), ("id".to_string(), Json::from(id.as_str()))];
feature.push(("name".into(), label.clone().unwrap_or_else(|| Json::from(id.as_str()))));
if let Some(s) = &suppressed {
feature.push(("suppressed".into(), s.clone()));
}
feature.extend(inputs.iter().cloned());
if let Json::Obj(filled) = check_feature(el, Json::Obj(feature))? {
inputs = filled.into_iter().filter(|(k, _)| !matches!(k.as_str(), "type" | "id" | "name" | "suppressed")).collect();
}
}
if el.tag != "sketch" {
no_children(el)?;
if el.tag == "code" {
let code_inputs = take(&mut inputs, "inputs");
if code_inputs.as_ref().is_some_and(|c| !matches!(c, Json::Obj(_))) {
return Err(format!("{}: inputs is an object", at(el)));
}
if let Some((k, _)) = inputs.iter().find(|(k, _)| k != "source" && k != "host" && k != "consumes") {
return Err(format!("{}: a code feature has source, inputs, host and consumes, not {}", at(el), rust_name(k)));
}
if let Some(Json::Obj(entries)) = code_inputs {
for (k, v) in entries {
inputs.retain(|(n, _)| *n != k);
inputs.push((k, v));
}
}
}
}
let mut n = Json::obj().with("id", id.as_str()).with("type", kind.as_str());
n.set("label", match &label {
Some(Json::Str(l)) => l.as_str(),
_ => id.as_str(),
});
if let Some(s) = suppressed {
n.set("disabled", s);
}
n.set("inputs", Json::Obj(inputs));
let mut meta = Json::obj();
if let Some(s) = el.source_json() {
meta.set("source", s);
}
if !sources.is_empty() {
meta.set("sources", sources.json());
}
if meta != Json::obj() {
n.set("meta", meta);
}
nodes.push((id.clone(), n));
order.push(Json::from(id.as_str()));
Ok(())
})();
if let Err(e) = read {
refused.push(e);
}
}
if !refused.is_empty() {
return Err(refused.join("\n"));
}
for (id, label, origin, normal, x_axis, builtin) in BUILTIN_PLANES {
if owner.iter().any(|(o, _)| o == id) || !builtins.contains(id) {
continue;
}
let v3 = |v: &[f64; 3]| Json::Arr(v.iter().map(|n| Json::Num(*n)).collect());
let inputs = Json::obj().with("origin", v3(origin)).with("normal", v3(normal)).with("xAxis", v3(x_axis)).with("builtin", *builtin);
nodes.push((id.to_string(), node(id, "plane", Some(label), inputs, None)));
}
for (row, items, sources) in lists {
let (tag, field, port, _, _) = THREED_LISTS[row];
if !nodes.iter().any(|(id, _)| id == field) {
claim(&mut owner, field, format!("the document's {field} ({}())", fn_name(tag)))?;
nodes.push((field.to_string(), node(field, &format!("3d.{field}"), None, Json::obj(), None)));
}
let Some((_, n)) = nodes.iter_mut().find(|(id, _)| id == field) else { continue };
let mut inputs = n.get("inputs").cloned().unwrap_or_else(Json::obj);
inputs.set(port, Json::Arr(items));
n.set("inputs", inputs);
if !sources.is_empty() {
let mut meta = n.get("meta").cloned().unwrap_or_else(Json::obj);
let mut all = meta.get("sources").cloned().unwrap_or_else(Json::obj);
if let Json::Obj(entries) = sources.json() {
for (k, v) in entries {
all.set(&k, v);
}
}
meta.set("sources", all);
n.set("meta", meta);
}
}
if !bodies.is_empty() {
claim(&mut owner, "bodyMeta", "the bodies (body())".into())?;
let meta = (!body_sources.is_empty()).then(|| Json::obj().with("sources", body_sources.json()));
nodes.push(("bodyMeta".into(), node("bodyMeta", "3d.bodyMeta", None, Json::Obj(bodies), meta)));
}
let mut view = Json::obj().with("name", name.as_str()).with("units", "mm");
for k in VIEW_ATTRS {
if let Some(v) = root.attr_of(k) {
plain(v, &format!("{} {}", at(root), rust_name(k)))?;
view.set(k, v.clone());
}
}
if root.tag == "assembly" {
view.set("isAssembly", true);
}
if let Some(presentation) = presentation_of(root, order)? {
view.set("presentation", presentation);
}
let id = match root.attr_of("id") {
Some(Json::Str(i)) if !i.is_empty() => i.clone(),
_ => format!("3d-{}", slug(&name).to_lowercase()),
};
Ok(Json::obj().with("id", id.as_str()).with("nodes", Json::Obj(nodes)).with("meta", view))
}