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    /// The part's own `partAttributes` with a text, number or yes/no value
56    /// (description, material, vendor …): what the
57    /// player's parts page lists as the part's details.
58    pub attributes: Vec<(String, String)>,
59    /// A sub-assembly's own level.
60    pub children: Option<Box<Level>>,
61}
62
63/// Propose the steps for `root` into `block`, replacing its step tree.
64pub fn propose(block: &mut Instructions, root: &Level) {
65    block.steps.clear();
66    block.steps = level_steps(block, root);
67}
68
69/// The steps that build `level`, in proposed order; a sub-assembly's step
70/// holds the steps that build it as its children.
71pub fn level_steps(block: &mut Instructions, level: &Level) -> Vec<Step> {
72    let mut steps = Vec::new();
73    for group in order(level) {
74        let mut step = step_for(block, &group);
75        if let Some(children) = &group[0].children {
76            step.steps = level_steps(block, children);
77        }
78        steps.push(step);
79    }
80    steps
81}
82
83/// The level's components grouped into steps, in proposed order. Every group
84/// but a fastener group holds one component.
85pub fn order(level: &Level) -> Vec<Vec<&Component>> {
86    let parts: Vec<&Component> = level.components.iter().filter(|c| !c.fastener).collect();
87    let mut placed: Vec<&Component> = Vec::new();
88    let mut placed_set: HashSet<&str> = HashSet::new();
89    let neighbours = adjacency(level);
90    let seed: HashMap<&str, usize> =
91        level.exploded_order.iter().rev().enumerate().map(|(i, p)| (p.as_str(), i)).collect();
92
93    // Grounded first, in assembly order; with none grounded, the first part.
94    for c in parts.iter().filter(|c| c.grounded) {
95        placed.push(c);
96        placed_set.insert(c.path.as_str());
97    }
98    if placed.is_empty() && seed.is_empty() {
99        if let Some(first) = parts.first() {
100            placed.push(first);
101            placed_set.insert(first.path.as_str());
102        }
103    }
104    while placed.len() < parts.len() {
105        let remaining = parts.iter().filter(|c| !placed_set.contains(c.path.as_str()));
106        let next = if !seed.is_empty() {
107            // The exploded view's reverse order; parts it does not move go
108            // after, in mate order.
109            remaining
110                .clone()
111                .filter(|c| seed.contains_key(c.path.as_str()))
112                .min_by_key(|c| seed[c.path.as_str()])
113                .copied()
114                .or_else(|| mated_first(remaining.clone(), &neighbours, &placed_set))
115        } else {
116            mated_first(remaining.clone(), &neighbours, &placed_set)
117        };
118        let next = next.or_else(|| remaining.clone().next().copied()).expect("a remaining part");
119        placed.push(next);
120        placed_set.insert(next.path.as_str());
121    }
122
123    let mut groups: Vec<Vec<&Component>> = placed.into_iter().map(|c| vec![c]).collect();
124
125    // Fasteners: one group per part, ordered by the latest placed part each
126    // one is mated to (unmated ones last, in assembly order).
127    let position: HashMap<&str, usize> = groups.iter().enumerate().map(|(i, g)| (g[0].path.as_str(), i)).collect();
128    let mut fastener_groups: Vec<(usize, usize, Vec<&Component>)> = Vec::new();
129    for (index, c) in level.components.iter().enumerate().filter(|(_, c)| c.fastener) {
130        let after = neighbours
131            .get(c.path.as_str())
132            .into_iter()
133            .flatten()
134            .filter_map(|n| position.get(n).copied())
135            .max()
136            .unwrap_or(usize::MAX);
137        match fastener_groups.iter_mut().find(|(_, _, g)| g[0].part == c.part) {
138            Some((rank, _, group)) => {
139                *rank = (*rank).max(after);
140                group.push(c);
141            }
142            None => fastener_groups.push((after, index, vec![c])),
143        }
144    }
145    fastener_groups.sort_by_key(|(rank, index, _)| (*rank, *index));
146    groups.extend(fastener_groups.into_iter().map(|(_, _, g)| g));
147    groups
148}
149
150/// The remaining part mated to something placed, earliest in assembly order.
151fn mated_first<'a, 'b>(
152    mut remaining: impl Iterator<Item = &'b &'a Component>,
153    neighbours: &HashMap<&str, Vec<&str>>,
154    placed: &HashSet<&str>,
155) -> Option<&'a Component>
156where
157    'a: 'b,
158{
159    remaining
160        .find(|c| neighbours.get(c.path.as_str()).is_some_and(|n| n.iter().any(|p| placed.contains(p))))
161        .copied()
162}
163
164fn adjacency(level: &Level) -> HashMap<&str, Vec<&str>> {
165    let mut map: HashMap<&str, Vec<&str>> = HashMap::new();
166    for (a, b) in &level.mates {
167        if a == b {
168            continue;
169        }
170        map.entry(a.as_str()).or_default().push(b.as_str());
171        map.entry(b.as_str()).or_default().push(a.as_str());
172    }
173    map
174}
175
176/// The step that adds `group`.
177pub fn step_for(block: &mut Instructions, group: &[&Component]) -> Step {
178    let first = group[0];
179    let quantity = group.len();
180    let subassembly = first.children.is_some();
181    let title = match (subassembly, quantity) {
182        (true, _) => format!("Install sub-assembly {}", first.part),
183        (false, 1) => format!("Install {}", first.part),
184        (false, n) => format!("Install {n} × {}", first.part),
185    };
186    let torque = if first.fastener { first.torque.as_deref().and_then(Torque::from_attribute) } else { None };
187    Step {
188        id: block.next_id("MS"),
189        title,
190        adds: vec![Add {
191            find_number: first.find_number.clone(),
192            subassembly,
193            fastener: first.fastener,
194            serial_tracked: first.serial_tracked,
195            ..Add::named(group.iter().map(|c| c.path.clone()).collect(), first.part_key(), &first.part)
196        }],
197        torque,
198        ..Step::default()
199    }
200}
201
202impl Component {
203    /// What an add's `part` names for this component: the PLM part id, else
204    /// the name.
205    pub fn part_key(&self) -> &str {
206        self.part_id.as_deref().unwrap_or(&self.part)
207    }
208}
209
210/// Every component of `level` and its sub-assemblies, depth first, each with
211/// the path of the level that holds it.
212pub fn flatten(level: &Level) -> Vec<(&str, &Component)> {
213    let mut out = Vec::new();
214    fn walk<'a>(level: &'a Level, out: &mut Vec<(&'a str, &'a Component)>) {
215        for c in &level.components {
216            out.push((level.path.as_str(), c));
217            if let Some(children) = &c.children {
218                walk(children, out);
219            }
220        }
221    }
222    walk(level, &mut out);
223    out
224}
225
226/// The level at `path` inside `root` (`""` is the root).
227pub fn find_level<'a>(root: &'a Level, path: &str) -> Option<&'a Level> {
228    if root.path == path {
229        return Some(root);
230    }
231    root.components.iter().filter_map(|c| c.children.as_deref()).find_map(|l| find_level(l, path))
232}
233