Skip to main content
← Back to kicad-monkey Rust Docs kicad-monkey Rust Crate API Reference

kicad_monkey_fab/
pose.rs

1//! Canonical KiCad 3D model pose math and HLR-to-board coordinate mapping.
2//!
3//! Matches KiCad's STEP exporter, Python `KiCadFabView` / `fab/virtual/_assembly.py`,
4//! `kicad_cruncher_pcb_model_pose.py`, and `pcbe` `typed_model_resources.rs`.
5
6use crate::geom::{CoordNm, LayerSide, mm_to_nm};
7use serde::{Deserialize, Serialize};
8
9/// Models sit this far above the board surface, as KiCad draws them.
10pub const BOARD_MODEL_Z_OFFSET_MM: f64 = 0.05;
11
12/// Row-major 4x4 homogeneous transform matrix in millimetres.
13pub type Matrix4 = [[f64; 4]; 4];
14
15/// One 3D model attachment extracted onto [`crate::FabViewData`].
16#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
17pub struct FabBody3D {
18    pub component_id: String,
19    pub path: String,
20    pub side: LayerSide,
21    pub offset_mm: [f64; 3],
22    pub rotate_deg: [f64; 3],
23    pub scale: [f64; 3],
24    pub hidden: bool,
25}
26
27/// Normalize zero or non-finite scales to `1.0` (matching KiCad STEP export and `pcbe`).
28#[must_use]
29pub fn normalize_scale(raw: [f64; 3]) -> [f64; 3] {
30    [
31        if !raw[0].is_finite() || raw[0] == 0.0 {
32            1.0
33        } else {
34            raw[0]
35        },
36        if !raw[1].is_finite() || raw[1] == 0.0 {
37            1.0
38        } else {
39            raw[1]
40        },
41        if !raw[2].is_finite() || raw[2] == 0.0 {
42            1.0
43        } else {
44            raw[2]
45        },
46    ]
47}
48
49/// Compute a 3D model's footprint-local 4x4 matrix on a board centred on `z = 0`.
50///
51/// Order: `[Rx(pi) if bottom] * T(offset_x, offset_y, offset_z + 0.05 + t/2)
52/// * Rz(-rz) * Ry(-ry) * Rx(-rx) * S(scale)`.
53#[must_use]
54pub fn local_pose_matrix(
55    offset_mm: [f64; 3],
56    rotate_deg: [f64; 3],
57    scale_xyz: [f64; 3],
58    board_thickness_mm: f64,
59    is_bottom: bool,
60) -> Matrix4 {
61    let mut matrix = identity();
62    if is_bottom {
63        matrix = multiply(matrix, rotation_x(std::f64::consts::PI));
64    }
65    matrix = multiply(
66        matrix,
67        translation(
68            offset_mm[0],
69            offset_mm[1],
70            offset_mm[2] + BOARD_MODEL_Z_OFFSET_MM + board_thickness_mm / 2.0,
71        ),
72    );
73    matrix = multiply(matrix, rotation_z(-rotate_deg[2].to_radians()));
74    matrix = multiply(matrix, rotation_y(-rotate_deg[1].to_radians()));
75    matrix = multiply(matrix, rotation_x(-rotate_deg[0].to_radians()));
76    multiply(matrix, scale(normalize_scale(scale_xyz)))
77}
78
79/// Compute `Rz(fp_angle_deg) * local_pose_matrix(...)`: the turned pose before XY placement.
80#[must_use]
81pub fn turned_pose_matrix(
82    offset_mm: [f64; 3],
83    rotate_deg: [f64; 3],
84    scale_xyz: [f64; 3],
85    board_thickness_mm: f64,
86    is_bottom: bool,
87    fp_angle_deg: f64,
88) -> Matrix4 {
89    let local = local_pose_matrix(
90        offset_mm,
91        rotate_deg,
92        scale_xyz,
93        board_thickness_mm,
94        is_bottom,
95    );
96    multiply(rotation_z(fp_angle_deg.to_radians()), local)
97}
98
99/// Map a Geometer local HLR point in millimetres (`+Y` up camera) into `+Y`-up board nanometres.
100///
101/// For top views (`dir = +Z, up = +Y`), camera right is `+X`.
102/// For bottom views (`dir = -Z, up = +Y`), camera right is `-X`, so `lx_mm` is negated
103/// before applying the footprint's board rotation and origin translation.
104#[must_use]
105pub fn local_hlr_mm_to_board_nm(
106    lx_mm: f64,
107    ly_mm: f64,
108    origin_nm: CoordNm,
109    comp_rot_deg: f64,
110    is_bottom: bool,
111) -> CoordNm {
112    let ux = if is_bottom { -lx_mm } else { lx_mm };
113    let uy = ly_mm;
114    let (sin_t, cos_t) = comp_rot_deg.to_radians().sin_cos();
115    let dx_mm = ux * cos_t - uy * sin_t;
116    let dy_mm = ux * sin_t + uy * cos_t;
117    CoordNm::new(
118        origin_nm.x.saturating_add(mm_to_nm(dx_mm)),
119        origin_nm.y.saturating_add(mm_to_nm(dy_mm)),
120    )
121}
122
123/// Flatten a row-major 4x4 matrix into 16 scalars.
124#[must_use]
125pub fn flatten_row_major(matrix: &Matrix4) -> [f64; 16] {
126    [
127        matrix[0][0],
128        matrix[0][1],
129        matrix[0][2],
130        matrix[0][3],
131        matrix[1][0],
132        matrix[1][1],
133        matrix[1][2],
134        matrix[1][3],
135        matrix[2][0],
136        matrix[2][1],
137        matrix[2][2],
138        matrix[2][3],
139        matrix[3][0],
140        matrix[3][1],
141        matrix[3][2],
142        matrix[3][3],
143    ]
144}
145
146#[must_use]
147pub const fn identity() -> Matrix4 {
148    [
149        [1.0, 0.0, 0.0, 0.0],
150        [0.0, 1.0, 0.0, 0.0],
151        [0.0, 0.0, 1.0, 0.0],
152        [0.0, 0.0, 0.0, 1.0],
153    ]
154}
155
156#[must_use]
157pub const fn translation(x: f64, y: f64, z: f64) -> Matrix4 {
158    let mut result = identity();
159    result[0][3] = x;
160    result[1][3] = y;
161    result[2][3] = z;
162    result
163}
164
165#[must_use]
166pub const fn scale(value: [f64; 3]) -> Matrix4 {
167    [
168        [value[0], 0.0, 0.0, 0.0],
169        [0.0, value[1], 0.0, 0.0],
170        [0.0, 0.0, value[2], 0.0],
171        [0.0, 0.0, 0.0, 1.0],
172    ]
173}
174
175#[must_use]
176pub fn rotation_x(angle_rad: f64) -> Matrix4 {
177    let (sin, cos) = angle_rad.sin_cos();
178    [
179        [1.0, 0.0, 0.0, 0.0],
180        [0.0, cos, -sin, 0.0],
181        [0.0, sin, cos, 0.0],
182        [0.0, 0.0, 0.0, 1.0],
183    ]
184}
185
186#[must_use]
187pub fn rotation_y(angle_rad: f64) -> Matrix4 {
188    let (sin, cos) = angle_rad.sin_cos();
189    [
190        [cos, 0.0, sin, 0.0],
191        [0.0, 1.0, 0.0, 0.0],
192        [-sin, 0.0, cos, 0.0],
193        [0.0, 0.0, 0.0, 1.0],
194    ]
195}
196
197#[must_use]
198pub fn rotation_z(angle_rad: f64) -> Matrix4 {
199    let (sin, cos) = angle_rad.sin_cos();
200    [
201        [cos, -sin, 0.0, 0.0],
202        [sin, cos, 0.0, 0.0],
203        [0.0, 0.0, 1.0, 0.0],
204        [0.0, 0.0, 0.0, 1.0],
205    ]
206}
207
208#[must_use]
209pub fn multiply(left: Matrix4, right: Matrix4) -> Matrix4 {
210    let mut out = [[0.0; 4]; 4];
211    for (r, out_row) in out.iter_mut().enumerate() {
212        for (c, cell) in out_row.iter_mut().enumerate() {
213            *cell = left[r][0] * right[0][c]
214                + left[r][1] * right[1][c]
215                + left[r][2] * right[2][c]
216                + left[r][3] * right[3][c];
217        }
218    }
219    out
220}
221
222#[cfg(test)]
223mod tests {
224    use super::*;
225
226    #[test]
227    fn offset_on_rotated_inductor_maps_onto_board_without_shift() {
228        // Mirrors L11 on speedy_processing_module_C: offset=(0, -1.35, 1.2), fp_rot=90 deg.
229        let m = local_pose_matrix(
230            [0.0, -1.35, 1.2],
231            [0.0, 0.0, 0.0],
232            [1.0, 1.0, 1.0],
233            1.6,
234            false,
235        );
236        // Point (0, 1.35, 0) in model space sits at local (0, 0) after offset (0, -1.35).
237        let lx = m[0][0] * 0.0 + m[0][1] * 1.35 + m[0][3];
238        let ly = m[1][0] * 0.0 + m[1][1] * 1.35 + m[1][3];
239        assert!(lx.abs() < 1e-12);
240        assert!(ly.abs() < 1e-12);
241        let origin = CoordNm::new(90_770_000, -104_470_000);
242        let pt = local_hlr_mm_to_board_nm(lx, ly, origin, 90.0, false);
243        assert_eq!(pt, origin);
244    }
245
246    #[test]
247    fn bottom_pose_flips_y_offset_and_hlr_x_consistently() {
248        let m = local_pose_matrix(
249            [0.5, -1.35, 1.2],
250            [0.0, 0.0, 0.0],
251            [1.0, 1.0, 1.0],
252            1.6,
253            true,
254        );
255        // Model point (1, 2, 0) -> T(0.5, -1.35) -> (1.5, 0.65) -> Rx(pi) -> (1.5, -0.65).
256        let wx = m[0][0] * 1.0 + m[0][1] * 2.0 + m[0][3];
257        let wy = m[1][0] * 1.0 + m[1][1] * 2.0 + m[1][3];
258        assert!((wx - 1.5).abs() < 1e-12);
259        assert!((wy + 0.65).abs() < 1e-12);
260        // Bottom Geometer camera (dir=-Z, up=+Y) sees lx = -wx, ly = wy.
261        let origin = CoordNm::new(10_000_000, -20_000_000);
262        let board = local_hlr_mm_to_board_nm(-wx, wy, origin, 90.0, true);
263        // Rz(90) * (1.5, -0.65) = (0.65, 1.5) -> (10.65, -18.5) mm.
264        assert_eq!(board, CoordNm::new(10_650_000, -18_500_000));
265    }
266}