Skip to main content

brep_instructions/
wizard.rs

1//! The step-order wizard: proposes the step tree from an assembly's
2//! occurrence tree and mate graph.
3//!
4//! The order, per assembly level:
5//! 1. every sub-assembly is one step of its parent's level whose children are
6//!    its own parts' steps: they build it first, then the step places it;
7//! 2. the grounded components come first, then mate order: the next component
8//!    is the one mated to what is already placed, earliest in the assembly's
9//!    own order. When the assembly already has an exploded view, its steps
10//!    seed the order instead (an exploded view lists parts coming OFF, so it
11//!    reads backwards);
12//! 3. fasteners come last, one step per fastener part, in the order of the
13//!    parts they fasten, with the torque taken from the part's attribute.
14//!
15//! One step per component or sub-assembly. The author merges, splits and
16//! reorders afterwards ([`crate::edit`]).
17
18use crate::model::{Add, Instructions, Step, Torque};
19use std::collections::{HashMap, HashSet};
20
21/// One assembly level: its components and the mates between them.
22#[derive(Debug, Clone, Default, PartialEq)]
23pub struct Level {
24    /// The occurrence path of this assembly; `""` for the target itself.
25    pub path: String,
26    /// The assembly's part name.
27    pub name: String,
28    /// Components in the assembly's own (history) order.
29    pub components: Vec<Component>,
30    /// Mates, as pairs of component paths of THIS level. A mate between parts
31    /// inside two sub-assemblies is given as the two sub-assembly paths.
32    pub mates: Vec<(String, String)>,
33    /// Component paths in the order the assembly's exploded view moves them
34    /// out; empty when it has none.
35    pub exploded_order: Vec<String>,
36}
37
38#[derive(Debug, Clone, Default, PartialEq)]
39pub struct Component {
40    /// Occurrence path relative to the instructions document (`ACOMP1:ACOMP3`).
41    pub path: String,
42    /// The part's name (titles, the display name).
43    pub part: String,
44    /// The PLM part id when the part was placed from a PLM revision
45    /// (`part/<id>/rev/<rev>`): what an add's `part` names then.
46    pub part_id: Option<String>,
47    /// The placed part's content signature (re-target compares it).
48    pub signature: String,
49    pub find_number: String,
50    pub grounded: bool,
51    pub fastener: bool,
52    pub serial_tracked: bool,
53    /// The fastener's `Torque` attribute text.
54    pub torque: Option<String>,
55    /// A sub-assembly's own level.
56    pub children: Option<Box<Level>>,
57}
58
59/// Propose the steps for `root` into `block`, replacing its step tree.
60pub fn propose(block: &mut Instructions, root: &Level) {
61    block.steps.clear();
62    block.steps = level_steps(block, root);
63}
64
65/// The steps that build `level`, in proposed order; a sub-assembly's step
66/// holds the steps that build it as its children.
67pub fn level_steps(block: &mut Instructions, level: &Level) -> Vec<Step> {
68    let mut steps = Vec::new();
69    for group in order(level) {
70        let mut step = step_for(block, &group);
71        if let Some(children) = &group[0].children {
72            step.steps = level_steps(block, children);
73        }
74        steps.push(step);
75    }
76    steps
77}
78
79/// The level's components grouped into steps, in proposed order. Every group
80/// but a fastener group holds one component.
81pub fn order(level: &Level) -> Vec<Vec<&Component>> {
82    let parts: Vec<&Component> = level.components.iter().filter(|c| !c.fastener).collect();
83    let mut placed: Vec<&Component> = Vec::new();
84    let mut placed_set: HashSet<&str> = HashSet::new();
85    let neighbours = adjacency(level);
86    let seed: HashMap<&str, usize> =
87        level.exploded_order.iter().rev().enumerate().map(|(i, p)| (p.as_str(), i)).collect();
88
89    // Grounded first, in assembly order; with none grounded, the first part.
90    for c in parts.iter().filter(|c| c.grounded) {
91        placed.push(c);
92        placed_set.insert(c.path.as_str());
93    }
94    if placed.is_empty() && seed.is_empty() {
95        if let Some(first) = parts.first() {
96            placed.push(first);
97            placed_set.insert(first.path.as_str());
98        }
99    }
100    while placed.len() < parts.len() {
101        let remaining = parts.iter().filter(|c| !placed_set.contains(c.path.as_str()));
102        let next = if !seed.is_empty() {
103            // The exploded view's reverse order; parts it does not move go
104            // after, in mate order.
105            remaining
106                .clone()
107                .filter(|c| seed.contains_key(c.path.as_str()))
108                .min_by_key(|c| seed[c.path.as_str()])
109                .copied()
110                .or_else(|| mated_first(remaining.clone(), &neighbours, &placed_set))
111        } else {
112            mated_first(remaining.clone(), &neighbours, &placed_set)
113        };
114        let next = next.or_else(|| remaining.clone().next().copied()).expect("a remaining part");
115        placed.push(next);
116        placed_set.insert(next.path.as_str());
117    }
118
119    let mut groups: Vec<Vec<&Component>> = placed.into_iter().map(|c| vec![c]).collect();
120
121    // Fasteners: one group per part, ordered by the latest placed part each
122    // one is mated to (unmated ones last, in assembly order).
123    let position: HashMap<&str, usize> = groups.iter().enumerate().map(|(i, g)| (g[0].path.as_str(), i)).collect();
124    let mut fastener_groups: Vec<(usize, usize, Vec<&Component>)> = Vec::new();
125    for (index, c) in level.components.iter().enumerate().filter(|(_, c)| c.fastener) {
126        let after = neighbours
127            .get(c.path.as_str())
128            .into_iter()
129            .flatten()
130            .filter_map(|n| position.get(n).copied())
131            .max()
132            .unwrap_or(usize::MAX);
133        match fastener_groups.iter_mut().find(|(_, _, g)| g[0].part == c.part) {
134            Some((rank, _, group)) => {
135                *rank = (*rank).max(after);
136                group.push(c);
137            }
138            None => fastener_groups.push((after, index, vec![c])),
139        }
140    }
141    fastener_groups.sort_by_key(|(rank, index, _)| (*rank, *index));
142    groups.extend(fastener_groups.into_iter().map(|(_, _, g)| g));
143    groups
144}
145
146/// The remaining part mated to something placed, earliest in assembly order.
147fn mated_first<'a, 'b>(
148    mut remaining: impl Iterator<Item = &'b &'a Component>,
149    neighbours: &HashMap<&str, Vec<&str>>,
150    placed: &HashSet<&str>,
151) -> Option<&'a Component>
152where
153    'a: 'b,
154{
155    remaining
156        .find(|c| neighbours.get(c.path.as_str()).is_some_and(|n| n.iter().any(|p| placed.contains(p))))
157        .copied()
158}
159
160fn adjacency(level: &Level) -> HashMap<&str, Vec<&str>> {
161    let mut map: HashMap<&str, Vec<&str>> = HashMap::new();
162    for (a, b) in &level.mates {
163        if a == b {
164            continue;
165        }
166        map.entry(a.as_str()).or_default().push(b.as_str());
167        map.entry(b.as_str()).or_default().push(a.as_str());
168    }
169    map
170}
171
172/// The step that adds `group`.
173pub fn step_for(block: &mut Instructions, group: &[&Component]) -> Step {
174    let first = group[0];
175    let quantity = group.len();
176    let subassembly = first.children.is_some();
177    let title = match (subassembly, quantity) {
178        (true, _) => format!("Install sub-assembly {}", first.part),
179        (false, 1) => format!("Install {}", first.part),
180        (false, n) => format!("Install {n} × {}", first.part),
181    };
182    let torque = if first.fastener { first.torque.as_deref().and_then(Torque::from_attribute) } else { None };
183    Step {
184        id: block.next_id("MS"),
185        title,
186        adds: vec![Add {
187            find_number: first.find_number.clone(),
188            subassembly,
189            fastener: first.fastener,
190            serial_tracked: first.serial_tracked,
191            ..Add::named(group.iter().map(|c| c.path.clone()).collect(), first.part_key(), &first.part)
192        }],
193        torque,
194        ..Step::default()
195    }
196}
197
198impl Component {
199    /// What an add's `part` names for this component: the PLM part id, else
200    /// the name.
201    pub fn part_key(&self) -> &str {
202        self.part_id.as_deref().unwrap_or(&self.part)
203    }
204}
205
206/// Every component of `level` and its sub-assemblies, depth first, each with
207/// the path of the level that holds it.
208pub fn flatten(level: &Level) -> Vec<(&str, &Component)> {
209    let mut out = Vec::new();
210    fn walk<'a>(level: &'a Level, out: &mut Vec<(&'a str, &'a Component)>) {
211        for c in &level.components {
212            out.push((level.path.as_str(), c));
213            if let Some(children) = &c.children {
214                walk(children, out);
215            }
216        }
217    }
218    walk(level, &mut out);
219    out
220}
221
222/// The level at `path` inside `root` (`""` is the root).
223pub fn find_level<'a>(root: &'a Level, path: &str) -> Option<&'a Level> {
224    if root.path == path {
225        return Some(root);
226    }
227    root.components.iter().filter_map(|c| c.children.as_deref()).find_map(|l| find_level(l, path))
228}
229