Skip to main content

brep_kernel/feature_pipeline/
part_mount.rs

1//! A part's MOUNT FRAME: how the part sits on its footprint, kept beside its
2//! features rather than in them.
3//!
4//! The part document's top-level `mount` block is a rigid pose in the shape an
5//! ACOMP `transform` takes, `{translate (mm), rotateEulerDeg (intrinsic XYZ)}`.
6//! It maps the part's model coordinates to its footprint's:
7//! `p_footprint = M · p_model`. The footprint frame is the board's: top copper at
8//! z = 0, millimetres with y up.
9//!
10//! The mount always moves the WHOLE part (every solid, every connection point
11//! and its seat). Nothing selects what it applies to. It is applied in ONE
12//! place: the ACOMP feature poses an instance's members, ports and nested
13//! poses by M before the instance pose. So a part has one frame wherever it is
14//! placed, and the instance's own pose is still exactly the one it was given.
15//! The solver writes that pose back, so it must never carry M.
16//!
17//! No block means identity. An identity mount is never written
18//! (`mount_block_of` says `None` for it), so a part with no mount and every
19//! KiCad import stay byte-identical.
20
21use serde_json::Value;
22
23use crate::AffineTransform;
24
25/// The part document's top-level key for its mount frame.
26pub const MOUNT_BLOCK: &str = "mount";
27
28/// How far from identity a mount must be to be written at all: a millionth of
29/// a millimetre in translation, a millionth in each rotation entry.
30const IDENTITY_TOLERANCE: f64 = 1e-6;
31
32/// The mount frame `document` declares, `None` when it has none.
33///
34/// A block that is not a rigid pose is an error that names what is wrong:
35/// an unknown key, a value that is not three numbers, or a non-finite number.
36/// A mount that silently read as identity would put the part back in the wrong
37/// frame with no word said.
38pub fn part_mount(document: &Value) -> Result<Option<AffineTransform>, String> {
39    let Some(block) = document.get(MOUNT_BLOCK).filter(|block| !block.is_null()) else {
40        return Ok(None);
41    };
42    mount_from_block(block).map(Some)
43}
44
45/// Read one `mount` block as the rigid pose it is.
46pub fn mount_from_block(block: &Value) -> Result<AffineTransform, String> {
47    let object = block
48        .as_object()
49        .ok_or("mount: must be an object {translate, rotateEulerDeg}")?;
50    if let Some(key) = object.keys().find(|key| !matches!(key.as_str(), "translate" | "rotateEulerDeg")) {
51        return Err(format!("mount: unknown key '{key}' (a mount has translate and rotateEulerDeg)"));
52    }
53    for key in ["translate", "rotateEulerDeg"] {
54        let Some(value) = object.get(key) else { continue };
55        let numbers = value.as_array().filter(|values| values.len() == 3);
56        let finite = numbers.is_some_and(|values| values.iter().all(|v| v.as_f64().is_some_and(f64::is_finite)));
57        if !finite {
58            return Err(format!("mount: {key} must be three finite numbers, found {value}"));
59        }
60    }
61    super::assembly::pose_params_to_transform(block)
62}
63
64/// The `mount` block to store for `transform`: `None` for identity (the key is
65/// then removed, never written as a default), otherwise the pose in the
66/// shape [`part_mount`] reads back.
67pub fn mount_block_of(transform: &AffineTransform) -> Option<Value> {
68    if is_identity(transform) {
69        return None;
70    }
71    Some(super::assembly::transform_to_pose_params(transform))
72}
73
74/// Whether `transform` is the identity, to `IDENTITY_TOLERANCE` (1e-6).
75pub fn is_identity(transform: &AffineTransform) -> bool {
76    transform
77        .elements
78        .iter()
79        .enumerate()
80        .all(|(index, value)| (value - if index % 5 == 0 { 1.0 } else { 0.0 }).abs() <= IDENTITY_TOLERANCE)
81}
82
83fn translation(x: f64, y: f64, z: f64) -> AffineTransform {
84    AffineTransform { elements: [1.0, 0.0, 0.0, x, 0.0, 1.0, 0.0, y, 0.0, 0.0, 1.0, z, 0.0, 0.0, 0.0, 1.0] }
85}
86
87fn identity() -> AffineTransform {
88    translation(0.0, 0.0, 0.0)
89}
90
91/// `v` moved by `transform`'s linear part (a direction, not a point).
92fn linear(transform: &AffineTransform, v: [f64; 3]) -> [f64; 3] {
93    let e = &transform.elements;
94    [0, 1, 2].map(|row| e[row * 4] * v[0] + e[row * 4 + 1] * v[1] + e[row * 4 + 2] * v[2])
95}
96
97/// The SHORTEST rotation taking direction `n` to −z, about the origin; a
98/// half turn about x when `n` is straight up. `None` for no direction.
99fn turn_down(n: [f64; 3]) -> Option<AffineTransform> {
100    let length = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
101    if !(length.is_finite() && length > 1e-12) {
102        return None;
103    }
104    let n = n.map(|c| c / length);
105    // Rotation taking n to d = (0, 0, -1): axis n × d, cos = n · d.
106    let (axis, cos) = ([-n[1], n[0], 0.0], -n[2]);
107    let sin = (axis[0] * axis[0] + axis[1] * axis[1]).sqrt();
108    Some(if sin <= 1e-12 && cos > 0.0 {
109        identity()
110    } else if sin <= 1e-12 {
111        AffineTransform { elements: [1.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 1.0] }
112    } else {
113        let k = axis.map(|c| c / sin);
114        let v = 1.0 - cos;
115        let r = |i: usize, j: usize| {
116            let cross = match (i, j) {
117                (0, 1) => -k[2],
118                (1, 0) => k[2],
119                (0, 2) => k[1],
120                (2, 0) => -k[1],
121                (1, 2) => -k[0],
122                (2, 1) => k[0],
123                _ => 0.0,
124            };
125            (if i == j { cos } else { 0.0 }) + sin * cross + v * k[i] * k[j]
126        };
127        AffineTransform {
128            elements: [r(0, 0), r(0, 1), r(0, 2), 0.0, r(1, 0), r(1, 1), r(1, 2), 0.0, r(2, 0), r(2, 1), r(2, 2), 0.0, 0.0, 0.0, 0.0, 1.0],
129        }
130    })
131}
132
133/// The mount `current` (identity when `None`) moved IN THE FOOTPRINT'S PLANE
134/// so that `point` (model coordinates) lands on the footprint origin. Its
135/// height is left alone: that is the seating plane's to say.
136pub fn mount_origin_to(current: Option<&AffineTransform>, point: [f64; 3]) -> Result<AffineTransform, String> {
137    let current = current.copied().unwrap_or_else(identity);
138    let at = current.point(crate::Vec3::new(point[0], point[1], point[2]));
139    translation(-at.x, -at.y, 0.0).compose(&current)
140}
141
142/// The mount `current` (identity when `None`) turned and lifted so the plane
143/// through `origin` with OUTWARD normal `normal` (both model coordinates) is
144/// the seating plane: the normal points down (−z) and the plane is at z = 0.
145///
146/// The turn is the SHORTEST one taking the mounted normal to −z, about the
147/// footprint origin, so a face that is already nearly down keeps the part's
148/// in-plane angle. A face facing straight up turns a half turn about x.
149pub fn mount_seated_on(
150    current: Option<&AffineTransform>,
151    origin: [f64; 3],
152    normal: [f64; 3],
153) -> Result<AffineTransform, String> {
154    let current = current.copied().unwrap_or_else(identity);
155    let rotation = turn_down(linear(&current, normal)).ok_or("the picked face has no normal to seat on")?;
156    let turned = rotation.compose(&current)?;
157    let at = turned.point(crate::Vec3::new(origin[0], origin[1], origin[2]));
158    translation(0.0, 0.0, -at.z).compose(&turned)
159}
160
161/// The plane a picked name stands for, against the scene `prefix` builds:
162/// `(origin, outward unit normal)`. A PLANAR face gives its own plane, its
163/// normal pointing out of the material; a datum plane gives its frame's z.
164/// Anything else is refused by name: a seating plane must be a plane.
165pub fn reference_plane(prefix: &[crate::feature_pipeline::FeatureResult], name: &str) -> Result<([f64; 3], [f64; 3]), String> {
166    use crate::feature_pipeline::pmi::resolve::resolve_reference;
167    use crate::{resolve_face_selection, SelectionGeometry};
168    let name = name.trim();
169    if name.is_empty() {
170        return Err("nothing was picked".into());
171    }
172    let mut scene = crate::feature_pipeline::SceneMap::default();
173    for result in prefix {
174        scene.apply(result);
175    }
176    let geometry = match scene.resolve_face(name) {
177        Some(face) => crate::with_registered_solid_str(face.handle, |solid| {
178            resolve_face_selection(solid, face.face_id).map_err(|error| format!("face '{name}': {error:?}"))
179        })?,
180        None => resolve_reference(&scene, name)?,
181    };
182    match geometry {
183        SelectionGeometry::Plane { origin, normal } => {
184            let out = ([origin.x, origin.y, origin.z], [normal.x, normal.y, normal.z]);
185            match out.0.iter().chain(out.1.iter()).all(|c| c.is_finite()) {
186                true => Ok(out),
187                false => Err(format!("'{name}' did not evaluate to a finite plane")),
188            }
189        }
190        _ => Err(format!("'{name}' is not flat: pick a planar face (the part's seating face) or a datum plane")),
191    }
192}
193
194/// Wire directions further than this from the pins' mean do not agree on a
195/// seating plane.
196const ALIGN_TILT_AGREEMENT_DEG: f64 = 5.0;
197/// A proper fit leaving less than this (RMS, mm) is never second-guessed by
198/// the mirrored one.
199const ALIGN_MIRROR_FLOOR: f64 = 0.05;
200
201/// One seated pcb point for [`mount_aligned_to_footprint`], in MODEL
202/// coordinates as the part builds it.
203#[derive(Debug, Clone, PartialEq)]
204pub struct AlignSeat {
205    /// The pin number (the point's name), which picks its pads.
206    pub pin: String,
207    /// Where the point resolved (the ports report's position).
208    pub position: [f64; 3],
209    /// The way its wire leaves the part, which is into the board.
210    pub direction: [f64; 3],
211    /// Its contact body's points (a display mesh's vertices), whose lowest
212    /// is the pin's bottom; empty for a point seated by reference, whose
213    /// bottom is its position.
214    pub support: Vec<[f64; 3]>,
215}
216
217/// One pad for [`mount_aligned_to_footprint`]: its number and centre in the
218/// footprint frame (mm, y up), and whether it is surface mount (no drill).
219#[derive(Debug, Clone, PartialEq)]
220pub struct AlignPad {
221    pub number: String,
222    pub at: [f64; 2],
223    pub smd: bool,
224}
225
226/// What Align to footprint did: the new mount, the leftover, and what it
227/// wants said (a rotation it kept, a height it could not set, a mirror).
228#[derive(Debug, Clone)]
229pub struct AlignReport {
230    pub mount: AffineTransform,
231    /// The largest and the RMS pin-to-pad distance in the board's plane, mm.
232    pub largest: f64,
233    pub rms: f64,
234    /// The pin with the largest distance.
235    pub worst: String,
236    /// How many seats were measured for the leftover.
237    pub pins: usize,
238    pub notes: Vec<String>,
239}
240
241/// Whether `transform` turns the model's z out of the board's z: a tilt
242/// someone asked for (a face pick, Y up → Z up), not a turn in the plane.
243fn has_tilt(transform: &AffineTransform) -> bool {
244    let z = linear(transform, [0.0, 0.0, 1.0]);
245    (z[0] * z[0] + z[1] * z[1]).sqrt() > IDENTITY_TOLERANCE || z[2] < 0.0
246}
247
248/// The rigid 2D fit (rotation forced proper) of `from` onto `to`, with its
249/// summed square leftover: `(angle, translation, squares)`. With one pair it
250/// is a translation only.
251fn fit_2d(from: &[[f64; 2]], to: &[[f64; 2]]) -> (f64, [f64; 2], f64) {
252    let n = from.len() as f64;
253    let centre = |points: &[[f64; 2]]| {
254        let sum = points.iter().fold([0.0, 0.0], |s, p| [s[0] + p[0], s[1] + p[1]]);
255        [sum[0] / n, sum[1] / n]
256    };
257    let (p, q) = (centre(from), centre(to));
258    let (mut dot, mut cross) = (0.0, 0.0);
259    for (a, b) in from.iter().zip(to) {
260        let (a, b) = ([a[0] - p[0], a[1] - p[1]], [b[0] - q[0], b[1] - q[1]]);
261        dot += a[0] * b[0] + a[1] * b[1];
262        cross += a[0] * b[1] - a[1] * b[0];
263    }
264    let angle = if from.len() < 2 { 0.0 } else { cross.atan2(dot) };
265    let (s, c) = angle.sin_cos();
266    let t = [q[0] - (c * p[0] - s * p[1]), q[1] - (s * p[0] + c * p[1])];
267    let squares = from
268        .iter()
269        .zip(to)
270        .map(|(a, b)| {
271            let (x, y) = (c * a[0] - s * a[1] + t[0] - b[0], s * a[0] + c * a[1] + t[1] - b[1]);
272            x * x + y * y
273        })
274        .sum();
275    (angle, t, squares)
276}
277
278/// Align to footprint: the mount `current` (identity when `None`) refitted so
279/// the part's seats land on their pads, as one rigid move, with the leftover.
280///
281/// 1. The seating plane. A mount that already tilts the part (a face pick,
282///    Y up → Z up) keeps its plane. Otherwise the pins' wire directions give
283///    the tilt, turned to −z; they must agree within 5° or Align refuses and
284///    names the pins that do not. The height is then the lowest point of the
285///    surface-mount pins (their contact bodies, or their seats), at z = 0; a
286///    part with only through-hole pins keeps its height and is told to pick
287///    its seating face.
288/// 2. The fit in the board's plane, pins matched to pads by number. A pin with
289///    one pad drives the fit; a pin with several pads of its number is matched
290///    afterwards to the nearest. One driving pin moves the part and keeps its
291///    rotation; none is refused. A mirrored fit that would leave a clearly
292///    smaller leftover is said, and never applied.
293pub fn mount_aligned_to_footprint(
294    current: Option<&AffineTransform>,
295    seats: &[AlignSeat],
296    pads: &[AlignPad],
297) -> Result<AlignReport, String> {
298    let current = current.copied().unwrap_or_else(identity);
299    let pads_of = |pin: &str| pads.iter().filter(|pad| pad.number.trim() == pin.trim()).collect::<Vec<_>>();
300    let seats: Vec<(&AlignSeat, Vec<&AlignPad>)> = seats
301        .iter()
302        .map(|seat| (seat, pads_of(&seat.pin)))
303        .filter(|(_, pads)| !pads.is_empty())
304        .collect();
305    if seats.is_empty() {
306        return Err("no seated pcb point has a pad of its number: seat the pins first".into());
307    }
308    let mut notes = Vec::new();
309
310    // 1. The seating plane.
311    let planed = if has_tilt(&current) {
312        current
313    } else {
314        let directions: Vec<[f64; 3]> = seats
315            .iter()
316            .map(|(seat, _)| {
317                let d = linear(&current, seat.direction);
318                let length = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
319                d.map(|c| c / length)
320            })
321            .collect();
322        let sum = directions.iter().fold([0.0; 3], |s, d| [s[0] + d[0], s[1] + d[1], s[2] + d[2]]);
323        let length = (sum[0] * sum[0] + sum[1] * sum[1] + sum[2] * sum[2]).sqrt();
324        if !(length.is_finite() && length > 1e-9) {
325            return Err("the pins' wire directions give no seating plane: pick its seating face".into());
326        }
327        let mean = sum.map(|c| c / length);
328        let cos_limit = ALIGN_TILT_AGREEMENT_DEG.to_radians().cos();
329        let mut apart: Vec<&str> = seats
330            .iter()
331            .zip(&directions)
332            .filter(|(_, d)| !(d[0] * mean[0] + d[1] * mean[1] + d[2] * mean[2] >= cos_limit))
333            .map(|((seat, _), _)| seat.pin.trim())
334            .collect();
335        apart.dedup();
336        if !apart.is_empty() {
337            return Err(format!(
338                "pins {} leave the part more than {ALIGN_TILT_AGREEMENT_DEG}° away from the others, so they give no seating plane: pick its seating face",
339                apart.join(", ")
340            ));
341        }
342        let turn = turn_down(mean).ok_or("the pins' wire directions give no seating plane")?;
343        let turned = turn.compose(&current)?;
344        let lowest = seats
345            .iter()
346            .filter(|(_, pads)| pads.iter().all(|pad| pad.smd))
347            .flat_map(|(seat, _)| if seat.support.is_empty() { vec![seat.position] } else { seat.support.clone() })
348            .map(|p| turned.point(crate::Vec3::new(p[0], p[1], p[2])).z)
349            .fold(f64::INFINITY, f64::min);
350        if lowest.is_finite() {
351            translation(0.0, 0.0, -lowest).compose(&turned)?
352        } else {
353            notes.push("its pins are all through-hole, so its height was not set: pick its seating face".to_string());
354            turned
355        }
356    };
357
358    // 2. The fit in the board's plane.
359    let flat = |transform: &AffineTransform, seat: &AlignSeat| {
360        let p = transform.point(crate::Vec3::new(seat.position[0], seat.position[1], seat.position[2]));
361        [p.x, p.y]
362    };
363    let driving: Vec<(&AlignSeat, [f64; 2])> =
364        seats.iter().filter(|(_, pads)| pads.len() == 1).map(|(seat, pads)| (*seat, pads[0].at)).collect();
365    if driving.is_empty() {
366        return Err("every seated pin has several pads of its number, so none fixes where the part goes".into());
367    }
368    let from: Vec<[f64; 2]> = driving.iter().map(|(seat, _)| flat(&planed, seat)).collect();
369    let to: Vec<[f64; 2]> = driving.iter().map(|(_, at)| *at).collect();
370    let (angle, t, squares) = fit_2d(&from, &to);
371    if driving.len() == 1 {
372        notes.push(format!("only pin {} has a single pad, so the part was moved and its rotation kept", driving[0].0.pin.trim()));
373    } else {
374        let mirrored: Vec<[f64; 2]> = from.iter().map(|p| [-p[0], p[1]]).collect();
375        let (_, _, mirror_squares) = fit_2d(&mirrored, &to);
376        let n = driving.len() as f64;
377        let (proper, mirror) = ((squares / n).sqrt(), (mirror_squares / n).sqrt());
378        if proper > ALIGN_MIRROR_FLOOR && mirror < 0.5 * proper {
379            notes.push(format!(
380                "a mirrored fit would leave {mirror:.3} mm RMS instead of {proper:.3} mm: the part may be modelled mirrored (Align never mirrors it)"
381            ));
382        }
383    }
384    let (s, c) = angle.sin_cos();
385    let in_plane = AffineTransform { elements: [c, -s, 0.0, t[0], s, c, 0.0, t[1], 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0] };
386    let mount = in_plane.compose(&planed)?;
387
388    // 3. The leftover, every seat against its nearest pad of its number.
389    let mut squares = 0.0;
390    let (mut largest, mut worst) = (0.0_f64, String::new());
391    for (seat, pads) in &seats {
392        let at = flat(&mount, seat);
393        let distance = pads
394            .iter()
395            .map(|pad| ((at[0] - pad.at[0]).powi(2) + (at[1] - pad.at[1]).powi(2)).sqrt())
396            .fold(f64::INFINITY, f64::min);
397        squares += distance * distance;
398        if distance > largest || worst.is_empty() {
399            largest = distance.max(largest);
400            worst = seat.pin.trim().to_string();
401        }
402    }
403    Ok(AlignReport { mount, largest, rms: (squares / seats.len() as f64).sqrt(), worst, pins: seats.len(), notes })
404}
405