Skip to main content

brep_instructions/
source.rs

1//! Reading a wizard [`Level`] straight from an assembly document's JSON.
2//!
3//! An assembly document lists its placements as `ACOMP` features
4//! (`inputParams.id`, `partName`, `isFixed`, `bom.Find_Number`), embeds each
5//! placed part in its `partsLibrary` (with `sourceSignature` and the part's own
6//! document, whose `partAttributes` say `Fastener`, `Torque` and
7//! `Serial_Tracked`), keeps its mates in `assembly.constraints` (each naming
8//! entities by `elements`), and its exploded views as PMI views with `explode`
9//! rows. A placed part whose own document has placements is a sub-assembly,
10//! read the same way one level down.
11
12use crate::model::{FASTENER_ATTRIBUTE, SERIAL_TRACKED_ATTRIBUTE, TORQUE_ATTRIBUTE};
13use crate::wizard::{Component, Level};
14use serde_json::Value;
15
16/// How deep sub-assemblies are read.
17pub const MAX_DEPTH: usize = 16;
18
19/// The level of `document`, its placements' paths under `prefix`
20/// (`"ACOMP1"` when the document is placed as `ACOMP1`, `""` at the top), the
21/// level itself at `path` (`""` for the target assembly).
22pub fn level_from_document(document: &Value, prefix: &str, path: &str, name: &str) -> Level {
23    read_level(document, prefix, path, name, 0)
24}
25
26fn read_level(document: &Value, prefix: &str, path: &str, name: &str, depth: usize) -> Level {
27    let library = &document["partsLibrary"];
28    let mut components = Vec::new();
29    let mut ids = Vec::new();
30    let mut first = true;
31    for feature in document["features"].as_array().into_iter().flatten() {
32        let kind = feature["type"].as_str().unwrap_or_default();
33        if !matches!(kind, "ACOMP" | "ASSEMBLY COMPONENT") || feature["suppressed"].as_bool() == Some(true) {
34            continue;
35        }
36        let params = &feature["inputParams"];
37        let Some(id) = params["id"].as_str() else { continue };
38        let part = params["partName"].as_str().unwrap_or_default().to_string();
39        // The kernel's rule: an explicit isFixed wins, else the first
40        // placement is grounded.
41        let grounded = params["isFixed"].as_bool().unwrap_or(first);
42        first = false;
43        let entry = &library[part.as_str()];
44        let part_document = &entry["document"];
45        let attributes = &part_document["partAttributes"];
46        let component_path = join(prefix, id);
47        let children = (depth + 1 < MAX_DEPTH && has_placements(part_document))
48            .then(|| Box::new(read_level(part_document, &component_path, &component_path, &part, depth + 1)));
49        components.push(Component {
50            path: component_path,
51            part_id: entry["sourceKey"].as_str().and_then(plm_part_id),
52            part,
53            signature: entry["sourceSignature"].as_str().unwrap_or_default().to_string(),
54            find_number: text(&params["bom"]["Find_Number"]),
55            grounded,
56            fastener: truthy(&attributes[FASTENER_ATTRIBUTE]),
57            serial_tracked: truthy(&attributes[SERIAL_TRACKED_ATTRIBUTE]),
58            torque: Some(text(&attributes[TORQUE_ATTRIBUTE])).filter(|t| !t.is_empty()),
59            children,
60        });
61        ids.push(id.to_string());
62    }
63    let owner = |element: &str| -> Option<String> {
64        let head = element.split(':').next()?;
65        ids.iter().any(|id| id == head).then(|| join(prefix, head))
66    };
67    let mut mates = Vec::new();
68    for constraint in document["assembly"]["constraints"].as_array().into_iter().flatten() {
69        if constraint["enabled"].as_bool() == Some(false) {
70            continue;
71        }
72        let owners: Vec<String> = constraint["inputParams"]["elements"]
73            .as_array()
74            .into_iter()
75            .flatten()
76            .filter_map(Value::as_str)
77            .filter_map(owner)
78            .collect();
79        for pair in owners.windows(2) {
80            if pair[0] != pair[1] {
81                mates.push((pair[0].clone(), pair[1].clone()));
82            }
83        }
84    }
85    let mut exploded_order: Vec<String> = Vec::new();
86    for view in document["pmi"]["views"].as_array().into_iter().flatten() {
87        let rows: Vec<&Value> = view["annotations"]
88            .as_array()
89            .into_iter()
90            .flatten()
91            .filter(|a| a["type"].as_str() == Some("explode") && a["enabled"].as_bool() != Some(false))
92            .collect();
93        if rows.is_empty() {
94            continue;
95        }
96        for row in rows {
97            for target in references(&row["inputParams"]["targets"]) {
98                if let Some(owner) = owner(&target) {
99                    if !exploded_order.contains(&owner) {
100                        exploded_order.push(owner);
101                    }
102                }
103            }
104        }
105        // The first exploded view seeds the order.
106        break;
107    }
108    Level { path: path.to_string(), name: name.to_string(), components, mates, exploded_order }
109}
110
111/// The PLM part id a library entry's source key names: `part/<id>/rev/<rev>`
112/// (a PLM session's key) or the explorer's path form of it
113/// (`/models/part/<id>/rev/<rev>.nbrep`); `None` for a file's key.
114pub fn plm_part_id(key: &str) -> Option<String> {
115    let rest = key.find("part/").map(|at| &key[at + "part/".len()..])?;
116    let (id, _) = rest.split_once("/rev/")?;
117    (!id.is_empty() && !id.contains('/')).then(|| id.to_string())
118}
119
120/// Whether a document places parts (is an assembly).
121pub fn has_placements(document: &Value) -> bool {
122    document["features"]
123        .as_array()
124        .is_some_and(|features| features.iter().any(|f| matches!(f["type"].as_str(), Some("ACOMP" | "ASSEMBLY COMPONENT"))))
125}
126
127fn join(prefix: &str, id: &str) -> String {
128    if prefix.is_empty() {
129        id.to_string()
130    } else {
131        format!("{prefix}:{id}")
132    }
133}
134
135/// A reference field: one name or an array of names.
136fn references(value: &Value) -> Vec<String> {
137    match value {
138        Value::String(name) if !name.trim().is_empty() => vec![name.trim().to_string()],
139        Value::Array(items) => items.iter().filter_map(Value::as_str).map(str::to_string).collect(),
140        _ => Vec::new(),
141    }
142}
143
144fn text(value: &Value) -> String {
145    match value {
146        Value::String(s) => s.trim().to_string(),
147        Value::Number(n) => n.to_string(),
148        _ => String::new(),
149    }
150}
151
152/// An attribute's yes: `true`, or text `true` / `yes` / `1` / `y` (any case).
153fn truthy(value: &Value) -> bool {
154    match value {
155        Value::Bool(b) => *b,
156        Value::Number(n) => n.as_f64().is_some_and(|v| v != 0.0),
157        Value::String(s) => matches!(s.trim().to_ascii_lowercase().as_str(), "true" | "yes" | "1" | "y"),
158        _ => false,
159    }
160}
161