1use crate::model::{Add, Instructions, Step, Torque};
19use std::collections::{HashMap, HashSet};
20
21#[derive(Debug, Clone, Default, PartialEq)]
23pub struct Level {
24 pub path: String,
26 pub name: String,
28 pub components: Vec<Component>,
30 pub mates: Vec<(String, String)>,
33 pub exploded_order: Vec<String>,
36}
37
38#[derive(Debug, Clone, Default, PartialEq)]
39pub struct Component {
40 pub path: String,
42 pub part: String,
44 pub part_id: Option<String>,
47 pub signature: String,
49 pub find_number: String,
50 pub grounded: bool,
51 pub fastener: bool,
52 pub serial_tracked: bool,
53 pub torque: Option<String>,
55 pub attributes: Vec<(String, String)>,
59 pub children: Option<Box<Level>>,
61}
62
63pub fn propose(block: &mut Instructions, root: &Level) {
65 block.steps.clear();
66 block.steps = level_steps(block, root);
67}
68
69pub 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
83pub 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 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 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 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
150fn 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
176pub 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 pub fn part_key(&self) -> &str {
206 self.part_id.as_deref().unwrap_or(&self.part)
207 }
208}
209
210pub 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
226pub 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