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            attributes: attribute_texts(attributes),
60            children,
61        });
62        ids.push(id.to_string());
63    }
64    let owner = |element: &str| -> Option<String> {
65        let head = element.split(':').next()?;
66        ids.iter().any(|id| id == head).then(|| join(prefix, head))
67    };
68    let mut mates = Vec::new();
69    for constraint in document["assembly"]["constraints"].as_array().into_iter().flatten() {
70        if constraint["enabled"].as_bool() == Some(false) {
71            continue;
72        }
73        let owners: Vec<String> = constraint["inputParams"]["elements"]
74            .as_array()
75            .into_iter()
76            .flatten()
77            .filter_map(Value::as_str)
78            .filter_map(owner)
79            .collect();
80        for pair in owners.windows(2) {
81            if pair[0] != pair[1] {
82                mates.push((pair[0].clone(), pair[1].clone()));
83            }
84        }
85    }
86    let mut exploded_order: Vec<String> = Vec::new();
87    for view in document["pmi"]["views"].as_array().into_iter().flatten() {
88        let rows: Vec<&Value> = view["annotations"]
89            .as_array()
90            .into_iter()
91            .flatten()
92            .filter(|a| a["type"].as_str() == Some("explode") && a["enabled"].as_bool() != Some(false))
93            .collect();
94        if rows.is_empty() {
95            continue;
96        }
97        for row in rows {
98            for target in references(&row["inputParams"]["targets"]) {
99                if let Some(owner) = owner(&target) {
100                    if !exploded_order.contains(&owner) {
101                        exploded_order.push(owner);
102                    }
103                }
104            }
105        }
106        // The first exploded view seeds the order.
107        break;
108    }
109    Level { path: path.to_string(), name: name.to_string(), components, mates, exploded_order }
110}
111
112/// The PLM part id a library entry's source key names: `part/<id>/rev/<rev>`
113/// (a PLM session's key) or the explorer's path form of it
114/// (`/models/part/<id>/rev/<rev>.nbrep`); `None` for a file's key.
115pub fn plm_part_id(key: &str) -> Option<String> {
116    let rest = key.find("part/").map(|at| &key[at + "part/".len()..])?;
117    let (id, _) = rest.split_once("/rev/")?;
118    (!id.is_empty() && !id.contains('/')).then(|| id.to_string())
119}
120
121/// Whether a document places parts (is an assembly).
122pub fn has_placements(document: &Value) -> bool {
123    document["features"]
124        .as_array()
125        .is_some_and(|features| features.iter().any(|f| matches!(f["type"].as_str(), Some("ACOMP" | "ASSEMBLY COMPONENT"))))
126}
127
128fn join(prefix: &str, id: &str) -> String {
129    if prefix.is_empty() {
130        id.to_string()
131    } else {
132        format!("{prefix}:{id}")
133    }
134}
135
136/// A reference field: one name or an array of names.
137fn references(value: &Value) -> Vec<String> {
138    match value {
139        Value::String(name) if !name.trim().is_empty() => vec![name.trim().to_string()],
140        Value::Array(items) => items.iter().filter_map(Value::as_str).map(str::to_string).collect(),
141        _ => Vec::new(),
142    }
143}
144
145fn text(value: &Value) -> String {
146    match value {
147        Value::String(s) => s.trim().to_string(),
148        Value::Number(n) => n.to_string(),
149        _ => String::new(),
150    }
151}
152
153/// A part's attributes as display text: every text, number or yes/no value
154/// that is not empty, in the order the JSON map holds them (an object or a
155/// list is not a detail a reader can read, and is left out), save the
156/// fastener, torque and serial-tracking attributes the component carries as
157/// its own fields.
158fn attribute_texts(attributes: &Value) -> Vec<(String, String)> {
159    attributes
160        .as_object()
161        .into_iter()
162        .flatten()
163        .filter(|(key, _)| ![FASTENER_ATTRIBUTE, SERIAL_TRACKED_ATTRIBUTE, TORQUE_ATTRIBUTE].contains(&key.trim()))
164        .filter_map(|(key, value)| {
165            let shown = match value {
166                Value::Bool(true) => "Yes".to_string(),
167                Value::Bool(false) => "No".to_string(),
168                other => text(other),
169            };
170            (!key.trim().is_empty() && !shown.is_empty()).then(|| (key.trim().to_string(), shown))
171        })
172        .collect()
173}
174
175/// An attribute's yes: `true`, or text `true` / `yes` / `1` / `y` (any case).
176fn truthy(value: &Value) -> bool {
177    match value {
178        Value::Bool(b) => *b,
179        Value::Number(n) => n.as_f64().is_some_and(|v| v != 0.0),
180        Value::String(s) => matches!(s.trim().to_ascii_lowercase().as_str(), "true" | "yes" | "1" | "y"),
181        _ => false,
182    }
183}
184