Skip to main content

hpr_design/
checks.rs

1//! Structural design checks: typed findings about a design that resolves but can't be built or
2//! flown as described.
3//!
4//! A finding is an [`Severity::Error`] when the design is physically impossible and a simulation of
5//! it would be wrong, usually on the flattering side: a motor wider than its mount (Loft reported
6//! +69% apogee for one), or fins whose root touches no part of the tube they belong to. A
7//! [`Severity::Warning`] marks something unusual that can be real, such as a motor mount that
8//! sticks out of the airframe. Callers that simulate should refuse designs with errors.
9//!
10//! Lengths are compared with [`LENGTH_TOLERANCE_M`] of slack, so round-off never raises a finding.
11//!
12//! See `docs/physics/design.md`.
13
14use serde::{Deserialize, Serialize};
15
16use crate::config::{Configuration, LaidOut};
17use crate::error::DesignError;
18use crate::solids::Wall;
19use crate::tree::{LENGTH_TOLERANCE_M, Layout, Part, PlacedComponent, Rocket};
20
21/// The tolerance of a three-place inch dimension on AeroTech's RMS dimensional drawings, m:
22/// 0.005 in (0.127 mm), the `.XXX` entry of their title blocks.
23pub const DRAWING_TOLERANCE_M: f64 = 0.005 * 0.0254;
24
25/// ISO 2768-1:1989, table 1, tolerance class *c* (coarse): the permissible deviation of a linear
26/// dimension with no tolerance of its own. Each entry is `(upper size, ± deviation)`, m, for sizes
27/// above the previous entry's and up to and including this one's; the first band starts at
28/// 0.5 mm, included, below which the standard sets none. The standard is for machined parts; HPR Sim borrows
29/// its coarse class for hobby airframe parts, which no standard covers.
30pub const COARSE_GENERAL_TOLERANCE_M: [(f64, f64); 8] = [
31    (0.003, 0.0002),
32    (0.006, 0.0003),
33    (0.030, 0.0005),
34    (0.120, 0.0008),
35    (0.400, 0.0012),
36    (1.000, 0.002),
37    (2.000, 0.003),
38    (4.000, 0.004),
39];
40
41/// How far an internal part may reach past the room in its parent and still be a fit, m: the
42/// coarse general tolerance ([`COARSE_GENERAL_TOLERANCE_M`]) of the room's diameter. A part
43/// drawn that much wider than a bore of that size, both made to the tolerance, can be made as a
44/// fit: the bore at `+t` and the part at `−t` close a diametral interference of `2t`, a radial one
45/// of `t`. 0.5 mm for a bore of 6 to 30 mm, 0.8 mm for 30 to 120 mm, 1.2 mm for 120 to 400 mm;
46/// none below 0.5 mm, and 4 mm past 4 m.
47pub fn fit_tolerance_m(room_m: f64) -> f64 {
48    let diameter_m = 2.0 * room_m;
49    // A room that isn't a number gets no tolerance.
50    if diameter_m.is_nan() || diameter_m < 0.0005 {
51        return 0.0;
52    }
53    COARSE_GENERAL_TOLERANCE_M
54        .iter()
55        .find(|(upto, _)| diameter_m <= *upto)
56        .map_or(0.004, |(_, t)| *t)
57}
58
59/// The nominal motor sizes whose cases are narrower than their names, with the largest case
60/// outside diameter, m: AeroTech's RMS dimensional drawings (RMS-18/20, RMS-24/40, RMS-29/40-120
61/// and HP RMS-29/120, archived from aerotech-rocketry.com in 2005; inches, `.XXX` to
62/// [`DRAWING_TOLERANCE_M`]) give the cases as 0.698, 0.938 and 1.125 in across, so at most 0.703,
63/// 0.943 and 1.130 in. Each entry is `(nominal size, largest case)`. ThrustCurve.org and RASP
64/// files carry the nominal size, so a "29 mm" motor is 29 mm in HPR Sim, and an AeroTech RMS-29 case
65/// at most 28.70 mm in the hand; other makers' cases may differ. The same drawings give 38, 54,
66/// 75 and 98 mm cases as 1.500, 2.125, 2.965 and 3.870 in, so at the +0.005 in limit each is at
67/// least as wide as its name, and those sizes get no slack.
68pub const NARROWER_THAN_NOMINAL_M: [(f64, f64); 3] = [
69    (0.018, 0.698 * 0.0254 + DRAWING_TOLERANCE_M),
70    (0.024, 0.938 * 0.0254 + DRAWING_TOLERANCE_M),
71    (0.029, 1.125 * 0.0254 + DRAWING_TOLERANCE_M),
72];
73
74/// How much wider than its mount's bore a motor's diameter may be and only warn, m: for a nominal
75/// size in [`NARROWER_THAN_NOMINAL_M`], how much wider the name is than the largest case
76/// (0.144 mm at 18 mm, 0.048 mm at 24 mm, 0.298 mm at 29 mm, so a 29 mm motor fits a 1.140 in
77/// bore); for any other diameter, none.
78pub fn motor_fit_slack_m(diameter_m: f64) -> f64 {
79    NARROWER_THAN_NOMINAL_M
80        .iter()
81        .find(|(nominal, _)| (diameter_m - nominal).abs() <= LENGTH_TOLERANCE_M)
82        .map_or(0.0, |(nominal, case)| nominal - case)
83}
84
85/// How serious a finding is.
86#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
87#[serde(rename_all = "snake_case")]
88pub enum Severity {
89    /// Unusual, but it can be built and flown.
90    Warning,
91    /// Impossible as described; a simulation would be wrong.
92    Error,
93}
94
95/// A problem found in a design. Serialized with a `kind` tag.
96#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
97#[serde(tag = "kind", rename_all = "snake_case")]
98#[non_exhaustive]
99pub enum Finding {
100    /// The motor case is wider than the mount's inside diameter by more than
101    /// [`motor_fit_slack_m`] allows (error).
102    MotorWiderThanMount {
103        /// Configuration id.
104        configuration: String,
105        /// Mount id.
106        mount: String,
107        /// Motor case diameter, m.
108        motor_diameter_m: f64,
109        /// Mount inside diameter, m.
110        mount_inner_diameter_m: f64,
111    },
112    /// The motor's nominal diameter is wider than the mount's inside diameter, but by no more than
113    /// [`motor_fit_slack_m`] allows: the real case fits, such as a 29 mm motor in a 1.140 in
114    /// (28.956 mm) bore (warning).
115    MotorTightInMount {
116        /// Configuration id.
117        configuration: String,
118        /// Mount id.
119        mount: String,
120        /// The motor's nominal diameter, m.
121        motor_diameter_m: f64,
122        /// Mount inside diameter, m.
123        mount_inner_diameter_m: f64,
124    },
125    /// The motor case doesn't overlap its mount along the axis at all, such as an overhang typed
126    /// in millimeters as meters (error).
127    MotorOutsideMount {
128        /// Configuration id.
129        configuration: String,
130        /// Mount id.
131        mount: String,
132    },
133    /// The motor case reaches forward past the mount's forward end (warning).
134    MotorPastMountTop {
135        /// Configuration id.
136        configuration: String,
137        /// Mount id.
138        mount: String,
139        /// How far past, m.
140        excess_m: f64,
141    },
142    /// The motor case reaches forward past the aft face of a part inside its mount whose bore is
143    /// narrower than the case: an engine block, a forward thrust ring or a bulkhead, which the
144    /// `.ork` reader reads as an inner tube or a ring attached to the mount (warning). Of several,
145    /// the aftmost, where a case slid in from aft stops. A real case stops at the part's aft face,
146    /// `excess_m` further aft than drawn.
147    MotorIntoBlock {
148        /// Configuration id.
149        configuration: String,
150        /// Mount id.
151        mount: String,
152        /// The blocking part's id.
153        block: String,
154        /// The part's bore, m: 0 for a bulkhead.
155        block_bore_m: f64,
156        /// The motor case's diameter, m.
157        motor_diameter_m: f64,
158        /// How far the case reaches forward past the part's aft face, m.
159        excess_m: f64,
160    },
161    /// An external part (fin root, tube fins, lug, rail button or pod set) doesn't overlap the body
162    /// tube it is attached to at all (error). A pod set of no length touches its tube when it sits
163    /// between the tube's ends, and a part on a pod's tube of no length when it spans the tube's
164    /// station.
165    AttachmentOffBody {
166        /// Component id.
167        component: String,
168        /// Body tube id.
169        body: String,
170    },
171    /// An external part runs past an end of its body tube (warning). Pods are exempt: a pod hangs
172    /// from a pylon and often runs past its tube. So is a part on a pod's tube of no length, which
173    /// has no length to run past.
174    AttachmentPastBodyEnd {
175        /// Component id.
176        component: String,
177        /// Body tube id.
178        body: String,
179        /// How far past, m.
180        excess_m: f64,
181    },
182    /// An internal part lies wholly forward of the nose tip or aft of the rocket's end, and touches
183    /// none of the parts it hangs from (a motor mount may stick out) (error).
184    PartOutsideRocket {
185        /// Component id.
186        component: String,
187    },
188    /// An internal part runs past an end of its parent (warning).
189    InternalPartPastParentEnd {
190        /// Component id.
191        component: String,
192        /// Parent id.
193        parent: String,
194        /// How far past, m.
195        excess_m: f64,
196    },
197    /// An internal part reaches farther from its parent's axis than the parent has room, a tube's
198    /// bore or a nose cone's or transition's inside radius along the part (for a rigid part the
199    /// most room along it, for a packed part the least), by more than
200    /// [`fit_tolerance_m`] (error). A centering ring that wraps its parent inner tube, on the
201    /// tube's axis with its bore at least the tube's outside, is measured against what holds the
202    /// tube instead.
203    InternalPartWiderThanParent {
204        /// Component id.
205        component: String,
206        /// The id of the part whose room it needs: its parent, or what holds the tube it wraps.
207        parent: String,
208        /// How far the part reaches from the parent's axis, m.
209        reach_m: f64,
210        /// The room in the parent, m.
211        room_m: f64,
212    },
213    /// An internal part reaches past the room in its parent by no more than [`fit_tolerance_m`]: a
214    /// fit to sand. The mass where it crosses its parent's wall counts twice (warning). A ring
215    /// wrapping its parent tube is measured as for [`Finding::InternalPartWiderThanParent`].
216    InternalPartTightInParent {
217        /// Component id.
218        component: String,
219        /// The id of the part whose room it needs: its parent, or what holds the tube it wraps.
220        parent: String,
221        /// How far the part reaches from the parent's axis, m.
222        reach_m: f64,
223        /// The room in the parent, m.
224        room_m: f64,
225    },
226    /// An internal part other than a packed part fits inside a nose cone or transition where the
227    /// profile is widest along the part, to [`fit_tolerance_m`], but reaches into the wall where
228    /// the profile narrows, past that tolerance: as drawn it can't slide that far in (warning,
229    /// #313). It flies where it is drawn, so its mass sits a little nearer the narrow end than it
230    /// could.
231    InternalPartWedgedInParent {
232        /// Component id.
233        component: String,
234        /// Parent id.
235        parent: String,
236        /// How far the part reaches from the parent's axis, m.
237        reach_m: f64,
238        /// The room where the profile is narrowest along the part, m.
239        room_m: f64,
240        /// The room where the profile is widest along the part, m.
241        widest_room_m: f64,
242    },
243    /// A packed part (a mass component, parachute, streamer or shock cord) reaches past the room
244    /// in its parent, its center inside the room (warning). Its width is how it is packed, which
245    /// sets only its own share of the rocket's inertia; its mass, length and station fly as drawn.
246    PackedPartWiderThanParent {
247        /// Component id.
248        component: String,
249        /// Parent id.
250        parent: String,
251        /// How far the part reaches from the parent's axis, m.
252        reach_m: f64,
253        /// The room in the parent, m.
254        room_m: f64,
255        /// Whether the parent has more room aft of the part than along it, as a nose cone or a
256        /// shoulder does: the part's mass can sit only farther aft than drawn, so its center of
257        /// gravity flies forward of where it can be and the stability margin may read high
258        /// ([issue #367](https://github.com/nrdptel/fusionspace-eridanus/issues/367)). Read as `false` from a
259        /// finding saved before it was kept.
260        #[serde(default)]
261        room_widens_aft: bool,
262    },
263    /// A centering ring or bulkhead wider than its parent's room, past [`fit_tolerance_m`], sits
264    /// at one of its parent's end faces and fits what holds its parent, to that tolerance: a cap
265    /// glued against the end, such as a bulkhead sized to the airframe on a coupler's end. The
266    /// mass where it crosses its parent's wall counts twice (warning).
267    RingAgainstParentEnd {
268        /// The ring's id.
269        ring: String,
270        /// Parent id.
271        parent: String,
272        /// How far the ring reaches from the axis of what holds its parent, m.
273        reach_m: f64,
274        /// The room in what holds its parent, m.
275        room_m: f64,
276    },
277    /// Two tubes of a cluster are closer than a tube's diameter, so they cross: the mass where they
278    /// cross is counted twice and their motors would not fit (warning).
279    ClusterTubesOverlap {
280        /// Inner tube id.
281        tube: String,
282        /// The distance between the closest two tubes' axes, m.
283        apart_m: f64,
284        /// The tube's outer diameter, m.
285        diameter_m: f64,
286    },
287    /// A centering ring overlaps an inner tube beside it, so the mass where they cross is counted
288    /// twice; an automatic inner radius only clears on-axis tubes (warning).
289    RingOverlapsInnerTube {
290        /// The ring's id.
291        ring: String,
292        /// The tube's id.
293        tube: String,
294    },
295    /// A stage with an axial center-of-mass override (`cg_aft_m`), its own or a component's, has
296    /// its center forward of the nose tip or aft of the rocket's end although every internal part
297    /// in it is on the rocket, such as a center typed in millimeters as meters (error). Written
298    /// before the move to US spelling as `centre_outside_rocket`, which is still read and never written.
299    #[serde(alias = "centre_outside_rocket")]
300    CenterOutsideRocket {
301        /// The stage's id.
302        stage: String,
303        /// The center's station, m.
304        station_m: f64,
305    },
306    /// Adjacent body components' radii differ where they meet (warning).
307    RadiusStep {
308        /// The forward component's id.
309        fore: String,
310        /// The aft component's id.
311        aft: String,
312        /// The forward component's aft radius, m.
313        fore_radius_m: f64,
314        /// The aft component's forward radius, m.
315        aft_radius_m: f64,
316    },
317    /// The first body component is not a nose cone (warning).
318    NoNoseCone {
319        /// The first component's id.
320        component: String,
321    },
322}
323
324impl Finding {
325    /// The finding's severity.
326    pub fn severity(&self) -> Severity {
327        match self {
328            Self::MotorWiderThanMount { .. }
329            | Self::MotorOutsideMount { .. }
330            | Self::AttachmentOffBody { .. }
331            | Self::PartOutsideRocket { .. }
332            | Self::InternalPartWiderThanParent { .. }
333            | Self::CenterOutsideRocket { .. } => Severity::Error,
334            Self::MotorTightInMount { .. }
335            | Self::MotorPastMountTop { .. }
336            | Self::MotorIntoBlock { .. }
337            | Self::AttachmentPastBodyEnd { .. }
338            | Self::InternalPartPastParentEnd { .. }
339            | Self::InternalPartTightInParent { .. }
340            | Self::InternalPartWedgedInParent { .. }
341            | Self::PackedPartWiderThanParent { .. }
342            | Self::RingAgainstParentEnd { .. }
343            | Self::ClusterTubesOverlap { .. }
344            | Self::RingOverlapsInnerTube { .. }
345            | Self::RadiusStep { .. }
346            | Self::NoNoseCone { .. } => Severity::Warning,
347        }
348    }
349
350    /// The finding as a sentence, without its severity: the parts by `name`, which is given a
351    /// component's, stage's or configuration's id; sizes in millimeters.
352    ///
353    /// ```
354    /// use hpr_design::checks::Finding;
355    ///
356    /// let finding = Finding::InternalPartPastParentEnd {
357    ///     component: "c1".to_owned(),
358    ///     parent: "c2".to_owned(),
359    ///     excess_m: 0.0508,
360    /// };
361    /// let name = |id: &str| if id == "c1" { "Shock cord" } else { "Body tube" }.to_owned();
362    /// assert_eq!(
363    ///     finding.describe(&name),
364    ///     "Shock cord runs 50.8 mm past an end of Body tube, which holds it"
365    /// );
366    /// ```
367    pub fn describe(&self, name: &dyn Fn(&str) -> String) -> String {
368        match self {
369            Self::MotorWiderThanMount {
370                configuration,
371                mount,
372                motor_diameter_m,
373                mount_inner_diameter_m,
374            } => {
375                let (motor, bore) = mm_pair(*motor_diameter_m, *mount_inner_diameter_m);
376                format!(
377                    "the motor in {} is {motor} wide, wider than the mount's {bore} bore by more \
378                     than a real case's slack (configuration {})",
379                    name(mount),
380                    name(configuration)
381                )
382            }
383            Self::MotorTightInMount {
384                configuration,
385                mount,
386                motor_diameter_m,
387                mount_inner_diameter_m,
388            } => {
389                let (motor, bore) = mm_pair(*motor_diameter_m, *mount_inner_diameter_m);
390                format!(
391                    "the motor in {} is nominally {motor} wide in a {bore} bore: it fits, as real \
392                     cases run under their nominal size (configuration {})",
393                    name(mount),
394                    name(configuration)
395                )
396            }
397            Self::MotorOutsideMount {
398                configuration,
399                mount,
400            } => format!(
401                "the motor in {} lies wholly outside the mount along its length, such as an \
402                 overhang typed in millimeters as meters (configuration {})",
403                name(mount),
404                name(configuration)
405            ),
406            Self::MotorPastMountTop {
407                configuration,
408                mount,
409                excess_m,
410            } => format!(
411                "the motor in {} reaches {} past the mount's forward end (configuration {}). The \
412                 mass, CG and margin are for the motor as drawn: where a ring or bulkhead closes \
413                 the mount there, the real case sits that much further aft",
414                name(mount),
415                mm(*excess_m),
416                name(configuration)
417            ),
418            Self::MotorIntoBlock {
419                configuration,
420                mount,
421                block,
422                block_bore_m,
423                motor_diameter_m,
424                excess_m,
425            } => format!(
426                "the motor in {} reaches {} forward of the aft face of {}, whose {} bore can't \
427                 pass the {} case (configuration {}). The mass, CG and margin are for the motor \
428                 as drawn: a real case stops at the part, that much further aft",
429                name(mount),
430                mm(*excess_m),
431                name(block),
432                mm(*block_bore_m),
433                mm(*motor_diameter_m),
434                name(configuration)
435            ),
436            Self::AttachmentOffBody { component, body } => format!(
437                "{} doesn't touch {}, the body tube it is attached to",
438                name(component),
439                name(body)
440            ),
441            Self::AttachmentPastBodyEnd {
442                component,
443                body,
444                excess_m,
445            } => format!(
446                "{} runs {} past an end of {}, the body tube it is attached to",
447                name(component),
448                mm(*excess_m),
449                name(body)
450            ),
451            Self::PartOutsideRocket { component } => format!(
452                "{} lies wholly forward of the nose tip or aft of the rocket's end",
453                name(component)
454            ),
455            Self::InternalPartPastParentEnd {
456                component,
457                parent,
458                excess_m,
459            } => format!(
460                "{} runs {} past an end of {}, which holds it",
461                name(component),
462                mm(*excess_m),
463                name(parent)
464            ),
465            Self::InternalPartWiderThanParent {
466                component,
467                parent,
468                reach_m,
469                room_m,
470            } => {
471                let (reach, room) = mm_pair(*reach_m, *room_m);
472                format!(
473                    "{} reaches {reach} from the axis of {}, which has {room} of room: too wide \
474                     to fit, past the fit tolerance",
475                    name(component),
476                    name(parent)
477                )
478            }
479            Self::InternalPartTightInParent {
480                component,
481                parent,
482                reach_m,
483                room_m,
484            } => {
485                let (reach, room) = mm_pair(*reach_m, *room_m);
486                format!(
487                    "{} reaches {reach} from the axis of {}, which has {room} of room. That is a \
488                     fit to sand, and the mass where it crosses the wall counts twice",
489                    name(component),
490                    name(parent)
491                )
492            }
493            Self::InternalPartWedgedInParent {
494                component,
495                parent,
496                reach_m,
497                room_m,
498                widest_room_m,
499            } => {
500                let (reach, room) = mm_pair(*reach_m, *room_m);
501                let (_, widest) = mm_pair(*reach_m, *widest_room_m);
502                format!(
503                    "{} reaches {reach} from the axis of {}, which narrows to {room} of room \
504                     along it ({widest} where widest). It can't slide in that far as drawn, and \
505                     flies where it is drawn",
506                    name(component),
507                    name(parent)
508                )
509            }
510            Self::PackedPartWiderThanParent {
511                component,
512                parent,
513                reach_m,
514                room_m,
515                room_widens_aft,
516            } => {
517                let (reach, room) = mm_pair(*reach_m, *room_m);
518                let mut text = format!(
519                    "{} is packed to reach {reach} from the axis of {}, which has {room} of \
520                     room. It can't go in as drawn. Its mass, length and station fly as drawn, and \
521                     its width sets only its own inertia",
522                    name(component),
523                    name(parent)
524                );
525                if *room_widens_aft {
526                    text.push_str(
527                        ". The room widens aft of it, so its mass can sit only farther aft. The \
528                         center of gravity flies forward of where it can be, and the stability \
529                         margin may read high (issue #367, \
530                         https://github.com/nrdptel/fusionspace-eridanus/issues/367)",
531                    );
532                }
533                text
534            }
535            Self::RingAgainstParentEnd {
536                ring,
537                parent,
538                reach_m,
539                room_m,
540            } => {
541                let (reach, room) = mm_pair(*reach_m, *room_m);
542                format!(
543                    "{} reaches {reach} from the axis, wider than {}, and caps its end, in \
544                     {room} of room around it. The mass where it crosses the wall counts twice",
545                    name(ring),
546                    name(parent)
547                )
548            }
549            Self::ClusterTubesOverlap {
550                tube,
551                apart_m,
552                diameter_m,
553            } => {
554                let (apart, diameter) = mm_pair(*apart_m, *diameter_m);
555                format!(
556                    "the cluster of {} has tubes {apart} apart, closer than their {diameter} \
557                     diameter, so they cross. The mass where they cross counts twice and their \
558                     motors would not fit",
559                    name(tube)
560                )
561            }
562            Self::RingOverlapsInnerTube { ring, tube } => format!(
563                "{} overlaps {} beside it, so the mass where they cross counts twice",
564                name(ring),
565                name(tube)
566            ),
567            Self::CenterOutsideRocket { stage, station_m } => format!(
568                "the center of mass set for {} is {} {} the nose tip, outside the rocket, such \
569                 as a center typed in millimeters as meters",
570                name(stage),
571                mm(station_m.abs()),
572                if *station_m < 0.0 {
573                    "forward of"
574                } else {
575                    "aft of"
576                }
577            ),
578            Self::RadiusStep {
579                fore,
580                aft,
581                fore_radius_m,
582                aft_radius_m,
583            } => {
584                let (fore_radius, aft_radius) = mm_pair(*fore_radius_m, *aft_radius_m);
585                format!(
586                    "{} ends {fore_radius} in radius where {} begins {aft_radius}: a step in the \
587                     body's outline",
588                    name(fore),
589                    name(aft)
590                )
591            }
592            Self::NoNoseCone { component } => format!(
593                "the rocket's first body part, {}, is not a nose cone",
594                name(component)
595            ),
596        }
597    }
598}
599
600/// A length in millimeters: to a tenth, or under 1 mm to a hundredth, or under 0.1 mm to a
601/// thousandth.
602fn mm(length_m: f64) -> String {
603    let mm = length_m * 1000.0;
604    format!("{mm:.prec$} mm", prec = decimals(mm))
605}
606
607/// The decimals [`mm`] gives a size in millimeters.
608fn decimals(mm: f64) -> usize {
609    match mm.abs() {
610        size if size >= 1.0 || size == 0.0 => 1,
611        size if size >= 0.1 => 2,
612        _ => 3,
613    }
614}
615
616/// Two lengths a sentence compares, in millimeters, to as many decimals as tell them apart, up to
617/// a ten-thousandth (0.1 µm): a 29 mm motor in a 28.956 mm bore is `29.00 mm` in a `28.96 mm`,
618/// not `29.0 mm` in a `29.0 mm`.
619fn mm_pair(a_m: f64, b_m: f64) -> (String, String) {
620    let (a, b) = (a_m * 1000.0, b_m * 1000.0);
621    // The finer of the two, so a small size beside a large one keeps its digits.
622    let mut prec = decimals(a).max(decimals(b));
623    while prec < 4 && format!("{a:.prec$}") == format!("{b:.prec$}") {
624        prec += 1;
625    }
626    (format!("{a:.prec$} mm"), format!("{b:.prec$} mm"))
627}
628
629/// Every check on a design and all its configurations.
630///
631/// # Errors
632///
633/// As [`Rocket::layout`], [`Rocket::check_configuration_ids`] and [`Layout::place_motors`]: a
634/// design that doesn't resolve can't be checked.
635pub fn check(rocket: &Rocket) -> Result<Vec<Finding>, DesignError> {
636    rocket.check_configuration_ids()?;
637    check_on(rocket, &rocket.layout()?)
638}
639
640impl LaidOut {
641    /// As [`check`], on this layout.
642    ///
643    /// # Errors
644    ///
645    /// As [`Layout::place_motors`].
646    pub fn check(&self) -> Result<Vec<Finding>, DesignError> {
647        check_on(self.rocket(), self.layout())
648    }
649}
650
651/// Every check on `rocket`, whose layout is `layout`.
652fn check_on(rocket: &Rocket, layout: &Layout) -> Result<Vec<Finding>, DesignError> {
653    let mut findings = check_layout(layout);
654    for configuration in &rocket.configurations {
655        findings.extend(check_configuration(layout, configuration)?);
656    }
657    Ok(findings)
658}
659
660/// Whether any finding is an error.
661pub fn has_errors(findings: &[Finding]) -> bool {
662    findings.iter().any(|f| f.severity() == Severity::Error)
663}
664
665/// How far, m, a motor case may reach forward past the aft face of an engine block or thrust ring
666/// inside its mount without a finding ([`Finding::MotorIntoBlock`]): a whole millimeter, the step
667/// most of the bundled catalog's case lengths are stated to, so a case drawn to its catalog length
668/// can reach past a block it really meets by up to half of it.
669pub const BLOCK_OVERLAP_TOLERANCE_M: f64 = 0.001;
670
671/// The overlap of `[a0, a1]` and `[b0, b1]`, m (negative when they are apart).
672fn overlap(a0: f64, a1: f64, b0: f64, b1: f64) -> f64 {
673    a1.min(b1) - a0.max(b0)
674}
675
676/// How far `[fore, aft]` runs past `[parent_fore, parent_aft]`, m, or `None` when the two don't
677/// overlap at all.
678fn excess(fore: f64, aft: f64, parent_fore: f64, parent_aft: f64) -> Option<f64> {
679    if overlap(fore, aft, parent_fore, parent_aft) <= 0.0 {
680        return None;
681    }
682    Some((parent_fore - fore).max(aft - parent_aft).max(0.0))
683}
684
685/// The checks on the structure alone.
686///
687/// The stage-center check reads the `center_overridden` flags that [`crate::Rocket::layout`] sets;
688/// a layout built by hand without them never raises [`Finding::CenterOutsideRocket`].
689pub fn check_layout(layout: &Layout) -> Vec<Finding> {
690    let mut findings = Vec::new();
691    let body: Vec<_> = layout.body().collect();
692    if let Some(first) = body.first()
693        && !matches!(first.part, Part::NoseCone(_))
694    {
695        findings.push(Finding::NoNoseCone {
696            component: first.id.clone(),
697        });
698    }
699    for pair in body.windows(2) {
700        let (fore, aft) = (pair[0], pair[1]);
701        if let (Some(a), Some(b)) = (fore.part.aft_radius_m(), aft.part.fore_radius_m())
702            && (a - b).abs() > LENGTH_TOLERANCE_M
703        {
704            findings.push(Finding::RadiusStep {
705                fore: fore.id.clone(),
706                aft: aft.id.clone(),
707                fore_radius_m: a,
708                aft_radius_m: b,
709            });
710        }
711    }
712    // Internal parts wholly off the rocket and off every part they hang from, and the components
713    // holding one.
714    let length = layout.length_m;
715    // A part that only touches a span at an end face is on it, within round-off.
716    let apart = |c: &PlacedComponent, fore: f64, aft: f64| {
717        overlap(c.fore_station_m, c.aft_station_m(), fore, aft) < -LENGTH_TOLERANCE_M
718    };
719    let off_rocket: Vec<bool> = layout
720        .components
721        .iter()
722        .map(|c| {
723            // A pod's body components are outside the airframe, like the pod set they hang from.
724            if c.parent.is_none()
725                || c.part.is_external()
726                || c.part.is_body()
727                || !apart(c, 0.0, length)
728            {
729                return false;
730            }
731            let mut ancestor = c.parent;
732            for _ in 0..layout.components.len() {
733                let Some(a) = ancestor.and_then(|i| layout.components.get(i)) else {
734                    break;
735                };
736                if !apart(c, a.fore_station_m, a.aft_station_m()) {
737                    return false;
738                }
739                ancestor = a.parent;
740            }
741            true
742        })
743        .collect();
744    let mut holds_off = off_rocket.clone();
745    for (index, component) in layout.components.iter().enumerate().rev() {
746        if holds_off[index]
747            && let Some(flag) = component.parent.and_then(|p| holds_off.get_mut(p))
748        {
749            *flag = true;
750        }
751    }
752    for (k, stage) in layout.stages.iter().enumerate() {
753        let station = -stage.mass.cg_m.z;
754        let in_stage = || {
755            layout
756                .components
757                .iter()
758                .enumerate()
759                .filter(|(_, c)| c.stage == k)
760        };
761        let holds = in_stage().any(|(i, _)| holds_off[i]);
762        let overridden = stage.center_overridden || in_stage().any(|(_, c)| c.center_overridden);
763        if overridden
764            && !holds
765            && stage.mass.mass_kg > 0.0
766            && !(-LENGTH_TOLERANCE_M..=length + LENGTH_TOLERANCE_M).contains(&station)
767        {
768            findings.push(Finding::CenterOutsideRocket {
769                stage: stage.id.clone(),
770                station_m: station,
771            });
772        }
773    }
774    for (index, component) in layout.components.iter().enumerate() {
775        let Some(parent) = component.parent.and_then(|i| layout.components.get(i)) else {
776            continue;
777        };
778        attached_findings(component, parent, off_rocket[index], layout, &mut findings);
779    }
780    findings
781}
782
783/// Interior stations at which [`room_m`] samples a profile across a part's span, besides the
784/// span's two ends.
785const ROOM_SAMPLES: usize = 31;
786
787/// The room for internal parts in a parent, m, along a part's span.
788#[derive(Debug, Clone, Copy)]
789struct Room {
790    /// Where the parent is narrowest along the part.
791    least_m: f64,
792    /// Where the parent is widest along the part.
793    most_m: f64,
794}
795
796/// The room for an internal part spanning stations `[fore, aft]` in `part`: a tube's bore, or a
797/// nose cone's or transition's inside radius along the part (#313). That is the profile's outer
798/// radius less its wall (none when filled, and none where the wall closes in at a tip), its least
799/// and most over the part's span within the profile: the span's two ends and [`ROOM_SAMPLES`]
800/// stations between them. Every profile HPR Sim draws is concave (its radius never dips between two
801/// stations), so the least is at an end; the samples guard that claim. The wall is measured
802/// normal to the surface, so outer less wall overstates the inside radius by `t (1/cos θ − 1)` on
803/// a slope `θ`: 1% of the wall at 8°, 0.1 mm of a 3 mm wall at 15°. An automatic radius in a
804/// profile is its inside radius at the part's narrower end ([ADR-096][adr-096]), so it fits by
805/// this measure.
806///
807/// A part that runs past the profile's ends is measured over the part of it inside them (the
808/// rest is [`Finding::InternalPartPastParentEnd`]). One wholly outside them, or with length that
809/// only touches an end from outside, is measured against
810/// the profile's largest outer radius, as before #313: where it sits is not in the profile, and
811/// the past-the-end finding already names it. `None` for a part with no room for internal parts,
812/// or a profile that can't be drawn.
813///
814/// [adr-096]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0096-fin-fillets-and-an-automatic-radius-inside-a.md
815fn room_m(part: &PlacedComponent, fore: f64, aft: f64) -> Option<Room> {
816    let both = |room_m: f64| Room {
817        least_m: room_m,
818        most_m: room_m,
819    };
820    if let Some(bore) = part.part.inner_radius_m() {
821        return Some(both(bore));
822    }
823    let (profile, wall) = match &part.part {
824        Part::NoseCone(nose) => (nose.profile().ok()?, nose.wall),
825        Part::Transition(transition) => (transition.profile().ok()?, transition.wall),
826        _ => return None,
827    };
828    let length = part.length_m;
829    let (x0, x1) = (fore - part.fore_station_m, aft - part.fore_station_m);
830    // Outside: no length of the part inside the profile. A part of no length at an end is inside,
831    // at that end: at a nose's tip it has no room.
832    let inside_m = x1.min(length) - x0.max(0.0);
833    if x1 < -LENGTH_TOLERANCE_M
834        || x0 > length + LENGTH_TOLERANCE_M
835        || (x1 - x0 > LENGTH_TOLERANCE_M && inside_m <= LENGTH_TOLERANCE_M)
836    {
837        return Some(both(profile.max_radius_m()));
838    }
839    let wall_m = match wall {
840        Wall::Filled {} => return Some(both(0.0)),
841        Wall::Shell { thickness_m } => thickness_m,
842    };
843    let (x0, x1) = (x0.clamp(0.0, length), x1.clamp(0.0, length));
844    let (least, most) = (0..=ROOM_SAMPLES + 1)
845        .map(|i| {
846            let x = x0 + (x1 - x0) * (i as f64) / ((ROOM_SAMPLES + 1) as f64);
847            profile.radius_m(x)
848        })
849        .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), r| {
850            (lo.min(r), hi.max(r))
851        });
852    Some(Room {
853        least_m: (least - wall_m).max(0.0),
854        most_m: (most - wall_m).max(0.0),
855    })
856}
857
858/// What surrounds a centering ring that wraps `tube` over the ring's span `[fore, aft]`: out from
859/// the tube, the first part with room for parts whose span overlaps the ring's, if it holds the
860/// whole ring; `None` when one holds only part of it or none overlaps it, and the ring is measured
861/// in the tube.
862fn wrapped_ring_container<'a>(
863    fore: f64,
864    aft: f64,
865    tube: &PlacedComponent,
866    layout: &'a Layout,
867) -> Option<&'a PlacedComponent> {
868    let mut next = tube.parent;
869    while let Some(part) = next.and_then(|i| layout.components.get(i)) {
870        if room_m(part, fore, aft).is_some()
871            && let Some(e) = excess(fore, aft, part.fore_station_m, part.aft_station_m())
872        {
873            return (e <= LENGTH_TOLERANCE_M).then_some(part);
874        }
875        next = part.parent;
876    }
877    None
878}
879
880/// The checks on one attached part.
881fn attached_findings(
882    component: &PlacedComponent,
883    parent: &PlacedComponent,
884    off_rocket: bool,
885    layout: &Layout,
886    findings: &mut Vec<Finding>,
887) {
888    // A pod's body components stack along it, so they span the pod set exactly.
889    if component.part.is_body() {
890        return;
891    }
892    let (fore, aft) = (component.fore_station_m, component.aft_station_m());
893    // Whether `[a0, a1]` holds the station `x`, to round-off.
894    let holds =
895        |a0: f64, a1: f64, x: f64| a0 - LENGTH_TOLERANCE_M <= x && x <= a1 + LENGTH_TOLERANCE_M;
896    // Fins or a lug on a pod's body tube of no length hang off the airframe on that pod, as
897    // OpenRocket draws winglets: they touch the tube if they span its station, and there is no
898    // length for them to run past.
899    if component.part.is_external() && parent.part.is_body() && parent.length_m == 0.0 {
900        if !holds(fore, aft, parent.fore_station_m) {
901            findings.push(Finding::AttachmentOffBody {
902                component: component.id.clone(),
903                body: parent.id.clone(),
904            });
905        }
906        return;
907    }
908    let span = if component.length_m == 0.0 && matches!(component.part, Part::PodSet(_)) {
909        // A pod set of no length (empty, or a pod of no length) is a point on its tube: it
910        // touches the tube if it sits within the tube's ends.
911        holds(parent.fore_station_m, parent.aft_station_m(), fore).then_some(0.0)
912    } else {
913        excess(fore, aft, parent.fore_station_m, parent.aft_station_m())
914    };
915    if component.part.is_external() {
916        match span {
917            None => findings.push(Finding::AttachmentOffBody {
918                component: component.id.clone(),
919                body: parent.id.clone(),
920            }),
921            // A pod is held by its pylon, not along its length: outboard pods often run past the
922            // tube they hang from.
923            Some(_) if matches!(component.part, Part::PodSet(_)) => {}
924            Some(e) if e > LENGTH_TOLERANCE_M => {
925                findings.push(Finding::AttachmentPastBodyEnd {
926                    component: component.id.clone(),
927                    body: parent.id.clone(),
928                    excess_m: e,
929                });
930            }
931            Some(_) => {}
932        }
933        return;
934    }
935    // An internal part entirely outside its parent runs past it by at least its own length.
936    let e =
937        span.unwrap_or_else(|| (parent.fore_station_m - fore).max(aft - parent.aft_station_m()));
938    if off_rocket {
939        findings.push(Finding::PartOutsideRocket {
940            component: component.id.clone(),
941        });
942    } else if e > LENGTH_TOLERANCE_M {
943        findings.push(Finding::InternalPartPastParentEnd {
944            component: component.id.clone(),
945            parent: parent.id.clone(),
946            excess_m: e,
947        });
948    }
949    let holder = parent.parent.and_then(|i| layout.components.get(i));
950    // A ring shares its parent's axis when the parent is neither a cluster nor off the axis: a
951    // cluster's tubes or an off-axis tube sit beside the ring, not around it.
952    let concentric = parent.part.axis_offset_m() == component.part.axis_offset_m()
953        && !matches!(&parent.part, Part::InnerTube(tube) if !tube.cluster_m.is_empty());
954    // A centering ring whose bore takes its parent tube's outside wraps that tube, as OpenRocket's
955    // pods examples draw the rings on their motor tubes: it sits in whatever surrounds the tube at
956    // the ring's own station, so that is where it needs room.
957    let wraps = concentric
958        && matches!((&component.part, &parent.part), (Part::CenteringRing(ring), Part::InnerTube(tube))
959            if ring.inner_radius_m >= tube.outer_radius_m - LENGTH_TOLERANCE_M);
960    let container = if wraps {
961        wrapped_ring_container(fore, aft, parent, layout).unwrap_or(parent)
962    } else {
963        parent
964    };
965    if let (Some(reach_m), Some(room)) = (
966        component.part.reach_from_m(container.part.axis_offset_m()),
967        room_m(container, fore, aft),
968    ) && reach_m > room.least_m + LENGTH_TOLERANCE_M
969    {
970        let Room { least_m, most_m } = room;
971        let fits = |room_m: f64| reach_m <= room_m + fit_tolerance_m(room_m) + LENGTH_TOLERANCE_M;
972        // A ring at its parent's end face can sit against it, so it needs room in what holds its
973        // parent instead. It covers one end face, not both, and shares its parent's axis.
974        // A ring that wraps its tube is around it, not over its end face, so it is never a cap.
975        let at_end = matches!(component.part, Part::CenteringRing(_))
976            && concentric
977            && !wraps
978            && holds(fore, aft, parent.fore_station_m) != holds(fore, aft, parent.aft_station_m());
979        let cap = holder.filter(|_| at_end).and_then(|holder| {
980            let reach_m = component.part.reach_from_m(holder.part.axis_offset_m())?;
981            let room_m = room_m(holder, fore, aft)?.most_m;
982            (reach_m <= room_m + fit_tolerance_m(room_m) + LENGTH_TOLERANCE_M)
983                .then_some((reach_m, room_m))
984        });
985        // A packed part's width is how it is packed: it sets only the part's own share of the
986        // rocket's inertia, so a packed part drawn too wide still flies as drawn while its
987        // center is in the room. It has no fit tolerance, and centered past the room it is an
988        // error (ADR-170). In a profile the room is the narrowest along the part.
989        let packed_center_inside = component
990            .part
991            .packing()
992            .map(|packing| reach_m - packing.radius_m <= least_m + LENGTH_TOLERANCE_M);
993        let rigid = packed_center_inside.is_none();
994        findings.push(if packed_center_inside == Some(true) {
995            // Room anywhere aft of the part, to the container's end, that is more than the least
996            // along it: the part could fit only farther aft (#367). A NaN room counts.
997            // A part that runs past the container's aft end is measured at that end.
998            let end = container.aft_station_m();
999            let room_widens_aft = room_m(container, aft.min(end), end).is_none_or(|aft_room| {
1000                let most_m = aft_room.most_m;
1001                most_m.is_nan() || least_m.is_nan() || most_m > least_m + LENGTH_TOLERANCE_M
1002            });
1003            Finding::PackedPartWiderThanParent {
1004                component: component.id.clone(),
1005                parent: container.id.clone(),
1006                reach_m,
1007                room_m: least_m,
1008                room_widens_aft,
1009            }
1010        } else if rigid && fits(least_m) {
1011            Finding::InternalPartTightInParent {
1012                component: component.id.clone(),
1013                parent: container.id.clone(),
1014                reach_m,
1015                room_m: least_m,
1016            }
1017        } else if rigid && fits(most_m) {
1018            // In a nose cone or transition: it fits where the profile is widest along it, and
1019            // runs into the wall where the profile narrows (#313).
1020            Finding::InternalPartWedgedInParent {
1021                component: component.id.clone(),
1022                parent: container.id.clone(),
1023                reach_m,
1024                room_m: least_m,
1025                widest_room_m: most_m,
1026            }
1027        } else if let Some((reach_m, room_m)) = cap {
1028            Finding::RingAgainstParentEnd {
1029                ring: component.id.clone(),
1030                parent: parent.id.clone(),
1031                reach_m,
1032                room_m,
1033            }
1034        } else {
1035            Finding::InternalPartWiderThanParent {
1036                component: component.id.clone(),
1037                parent: container.id.clone(),
1038                reach_m,
1039                room_m: if rigid { most_m } else { least_m },
1040            }
1041        });
1042    }
1043    if let Part::InnerTube(inner) = &component.part {
1044        let apart_m = inner
1045            .cluster_m
1046            .iter()
1047            .enumerate()
1048            .flat_map(|(i, &[x, y])| {
1049                inner.cluster_m[i + 1..]
1050                    .iter()
1051                    .map(move |&[u, v]| (x - u).hypot(y - v))
1052            })
1053            .fold(f64::INFINITY, f64::min);
1054        let diameter_m = 2.0 * inner.outer_radius_m;
1055        if apart_m < diameter_m - LENGTH_TOLERANCE_M {
1056            findings.push(Finding::ClusterTubesOverlap {
1057                tube: component.id.clone(),
1058                apart_m,
1059                diameter_m,
1060            });
1061        }
1062    }
1063    if let Part::CenteringRing(ring) = &component.part {
1064        // A ring that wraps its tube sits beside the tubes in what surrounds it too.
1065        let around = (container.id != parent.id)
1066            .then(|| layout.find(&container.id))
1067            .flatten()
1068            .map(|(i, _)| i);
1069        for tube in layout.components.iter().filter(|c| {
1070            (c.parent == component.parent || around.is_some_and(|i| c.parent == Some(i)))
1071                && c.id != component.id
1072                && c.id != parent.id
1073        }) {
1074            let Part::InnerTube(inner) = &tube.part else {
1075                continue;
1076            };
1077            // Each tube (every tube of a cluster) covers radii [d − R, d + R] about the ring's
1078            // (the body) axis.
1079            let [x, y] = tube.part.axis_offset_m();
1080            let tubes = if inner.cluster_m.is_empty() {
1081                &[[0.0, 0.0]][..]
1082            } else {
1083                inner.cluster_m.as_slice()
1084            };
1085            let radial = tubes
1086                .iter()
1087                .map(|&[u, v]| {
1088                    let d = (x + u).hypot(y + v);
1089                    (d + inner.outer_radius_m).min(ring.outer_radius_m)
1090                        - (d - inner.outer_radius_m).max(ring.inner_radius_m)
1091                })
1092                .fold(f64::NEG_INFINITY, f64::max);
1093            if overlap(fore, aft, tube.fore_station_m, tube.aft_station_m()) > LENGTH_TOLERANCE_M
1094                && radial > LENGTH_TOLERANCE_M
1095            {
1096                findings.push(Finding::RingOverlapsInnerTube {
1097                    ring: component.id.clone(),
1098                    tube: tube.id.clone(),
1099                });
1100            }
1101        }
1102    }
1103}
1104
1105/// The checks on one configuration's motors in `layout`. The configuration need not be one of the
1106/// rocket's own, so a candidate motor can be checked before it is stored.
1107///
1108/// # Errors
1109///
1110/// As [`Layout::place_motors`].
1111pub fn check_configuration(
1112    layout: &Layout,
1113    configuration: &Configuration,
1114) -> Result<Vec<Finding>, DesignError> {
1115    let mut findings = Vec::new();
1116    // Every tube of a cluster holds the same motor the same way along the axis, so its first tube
1117    // speaks for the mount and each finding is made once.
1118    let placed = layout.place_motors(configuration)?;
1119    for motor in placed.into_iter().filter(|motor| motor.tube == 0) {
1120        let Some((_, mount)) = layout.find(&motor.mount) else {
1121            continue;
1122        };
1123        if let Some(inner) = mount.part.inner_radius_m() {
1124            let inner_diameter = 2.0 * inner;
1125            let motor_diameter_m = motor.mounted.diameter_m;
1126            let slack_m = motor_fit_slack_m(motor_diameter_m);
1127            if motor_diameter_m > inner_diameter + slack_m + LENGTH_TOLERANCE_M {
1128                findings.push(Finding::MotorWiderThanMount {
1129                    configuration: configuration.id.clone(),
1130                    mount: mount.id.clone(),
1131                    motor_diameter_m,
1132                    mount_inner_diameter_m: inner_diameter,
1133                });
1134            } else if motor_diameter_m > inner_diameter + LENGTH_TOLERANCE_M {
1135                findings.push(Finding::MotorTightInMount {
1136                    configuration: configuration.id.clone(),
1137                    mount: mount.id.clone(),
1138                    motor_diameter_m,
1139                    mount_inner_diameter_m: inner_diameter,
1140                });
1141            }
1142        }
1143        let (fore, nozzle) = (motor.fore_station_m(), motor.nozzle_station_m());
1144        if overlap(fore, nozzle, mount.fore_station_m, mount.aft_station_m()) <= 0.0 {
1145            findings.push(Finding::MotorOutsideMount {
1146                configuration: configuration.id.clone(),
1147                mount: mount.id.clone(),
1148            });
1149            continue;
1150        }
1151        let past = mount.fore_station_m - fore;
1152        if past > LENGTH_TOLERANCE_M {
1153            findings.push(Finding::MotorPastMountTop {
1154                configuration: configuration.id.clone(),
1155                mount: mount.id.clone(),
1156                excess_m: past,
1157            });
1158        }
1159        // An engine block, forward thrust ring or bulkhead: a part attached to the mount whose
1160        // bore the case can't pass, with its aft face between the case's ends. A case slid in from
1161        // aft stops at the aftmost such face, so that part alone is the block.
1162        let mount_index = layout.find(&motor.mount).map(|(index, _)| index);
1163        let radius_m = motor.mounted.diameter_m / 2.0;
1164        let block = layout
1165            .components
1166            .iter()
1167            .filter(|part| part.parent.is_some() && part.parent == mount_index)
1168            .filter_map(|part| {
1169                let bore_radius_m = match &part.part {
1170                    Part::InnerTube(tube) => tube.outer_radius_m - tube.thickness_m,
1171                    Part::CenteringRing(ring) => ring.inner_radius_m,
1172                    _ => return None,
1173                };
1174                let aft_m = part.fore_station_m + part.length_m;
1175                (bore_radius_m < radius_m - LENGTH_TOLERANCE_M
1176                    && aft_m - fore > BLOCK_OVERLAP_TOLERANCE_M
1177                    && aft_m < nozzle - LENGTH_TOLERANCE_M)
1178                    .then_some((part, bore_radius_m, aft_m))
1179            })
1180            .max_by(|(_, _, a), (_, _, b)| a.total_cmp(b));
1181        if let Some((block, bore_radius_m, aft_m)) = block {
1182            findings.push(Finding::MotorIntoBlock {
1183                configuration: configuration.id.clone(),
1184                mount: mount.id.clone(),
1185                block: block.id.clone(),
1186                block_bore_m: 2.0 * bore_radius_m.max(0.0),
1187                motor_diameter_m: motor.mounted.diameter_m,
1188                excess_m: aft_m - fore,
1189            });
1190        }
1191    }
1192    Ok(findings)
1193}
1194
1195#[cfg(test)]
1196mod tests {
1197    use super::*;
1198    use crate::testing::{
1199        attached, body, bottom, inner_tube, mass_component, ring, rocket, stage, three_fin_rocket,
1200        top, tube,
1201    };
1202    use crate::{AutoDimension, MotorMount};
1203    use crate::{Part, Position};
1204
1205    /// Every finding's sentence names its parts by `name`, never by id, and gives its sizes in
1206    /// millimeters.
1207    #[test]
1208    fn describe_names_parts_and_sizes_in_millimeters() {
1209        let id = |s: &str| s.to_owned();
1210        let findings = [
1211            Finding::MotorWiderThanMount {
1212                configuration: id("cfg"),
1213                mount: id("mt"),
1214                motor_diameter_m: 0.038,
1215                mount_inner_diameter_m: 0.029,
1216            },
1217            Finding::MotorTightInMount {
1218                configuration: id("cfg"),
1219                mount: id("mt"),
1220                motor_diameter_m: 0.029,
1221                mount_inner_diameter_m: 0.028_956,
1222            },
1223            Finding::MotorOutsideMount {
1224                configuration: id("cfg"),
1225                mount: id("mt"),
1226            },
1227            Finding::MotorPastMountTop {
1228                configuration: id("cfg"),
1229                mount: id("mt"),
1230                excess_m: 0.012,
1231            },
1232            Finding::AttachmentOffBody {
1233                component: id("fin"),
1234                body: id("bt"),
1235            },
1236            Finding::AttachmentPastBodyEnd {
1237                component: id("fin"),
1238                body: id("bt"),
1239                excess_m: 0.0004,
1240            },
1241            Finding::PartOutsideRocket {
1242                component: id("mass"),
1243            },
1244            Finding::InternalPartPastParentEnd {
1245                component: id("cord"),
1246                parent: id("bt"),
1247                excess_m: 0.050_800_000_000_000_01,
1248            },
1249            Finding::InternalPartWiderThanParent {
1250                component: id("ring"),
1251                parent: id("bt"),
1252                reach_m: 0.04,
1253                room_m: 0.035,
1254            },
1255            Finding::InternalPartTightInParent {
1256                component: id("ring"),
1257                parent: id("bt"),
1258                reach_m: 0.035_05,
1259                room_m: 0.035,
1260            },
1261            Finding::PackedPartWiderThanParent {
1262                component: id("payload"),
1263                parent: id("bt"),
1264                reach_m: 0.0125,
1265                room_m: 0.0105,
1266                room_widens_aft: false,
1267            },
1268            Finding::RingAgainstParentEnd {
1269                ring: id("ring"),
1270                parent: id("cp"),
1271                reach_m: 0.04,
1272                room_m: 0.0399,
1273            },
1274            Finding::ClusterTubesOverlap {
1275                tube: id("it"),
1276                apart_m: 0.02,
1277                diameter_m: 0.025,
1278            },
1279            Finding::RingOverlapsInnerTube {
1280                ring: id("ring"),
1281                tube: id("it"),
1282            },
1283            Finding::CenterOutsideRocket {
1284                stage: id("st"),
1285                station_m: -0.25,
1286            },
1287            Finding::RadiusStep {
1288                fore: id("nose"),
1289                aft: id("bt"),
1290                fore_radius_m: 0.0205,
1291                aft_radius_m: 0.0207,
1292            },
1293            Finding::NoNoseCone {
1294                component: id("bt"),
1295            },
1296            Finding::InternalPartWedgedInParent {
1297                component: id("coupler"),
1298                parent: id("nose"),
1299                reach_m: 0.0245,
1300                room_m: 0.0115,
1301                widest_room_m: 0.025,
1302            },
1303            Finding::MotorIntoBlock {
1304                configuration: id("cfg"),
1305                mount: id("mt"),
1306                block: id("block"),
1307                block_bore_m: 0.025,
1308                motor_diameter_m: 0.038,
1309                excess_m: 0.012,
1310            },
1311        ];
1312        let name = |id: &str| format!("<{id}>");
1313        let sentences: Vec<String> = findings.iter().map(|f| f.describe(&name)).collect();
1314        for (finding, sentence) in findings.iter().zip(&sentences) {
1315            // Every id the finding carries is named, as `name` gives it.
1316            let value = serde_json::to_value(finding).unwrap();
1317            for (key, field) in value.as_object().unwrap() {
1318                if let Some(text) = field.as_str().filter(|_| key != "kind") {
1319                    assert!(sentence.contains(&format!("<{text}>")), "{key}: {sentence}");
1320                }
1321            }
1322            assert!(
1323                !sentence.contains('{') && !sentence.contains('_'),
1324                "{sentence}"
1325            );
1326        }
1327        assert_eq!(
1328            sentences[0],
1329            "the motor in <mt> is 38.0 mm wide, wider than the mount's 29.0 mm bore by more \
1330             than a real case's slack (configuration <cfg>)"
1331        );
1332        assert!(sentences[5].contains(" 0.40 mm past "), "{}", sentences[5]);
1333        assert!(sentences[7].contains(" 50.8 mm past "), "{}", sentences[7]);
1334        assert!(
1335            sentences[3].contains(
1336                "reaches 12.0 mm past the mount's forward end (configuration <cfg>). The mass, CG \
1337                 and margin are for the motor as drawn"
1338            ),
1339            "{}",
1340            sentences[3]
1341        );
1342        assert_eq!(
1343            sentences.last().map(String::as_str),
1344            Some(
1345                "the motor in <mt> reaches 12.0 mm forward of the aft face of <block>, whose 25.0 mm \
1346                 bore can't pass the 38.0 mm case (configuration <cfg>). The mass, CG and margin \
1347                 are for the motor as drawn: a real case stops at the part, that much further aft"
1348            )
1349        );
1350        assert!(sentences[14].contains(" 250.0 mm forward of the nose tip"));
1351        assert_eq!(mm(0.000_05), "0.050 mm");
1352        // Two sizes a sentence compares never print alike.
1353        assert!(
1354            sentences[1].contains(" is nominally 29.00 mm wide in a 28.96 mm bore"),
1355            "{}",
1356            sentences[1]
1357        );
1358        assert!(
1359            sentences[9].contains(" reaches 35.05 mm from the axis of <bt>, which has 35.00 mm")
1360        );
1361        assert!(sentences[10].contains(
1362            "<payload> is packed to reach 12.5 mm from the axis of <bt>, which has 10.5 mm of room"
1363        ));
1364        assert!(
1365            sentences[17].contains(
1366                "<coupler> reaches 24.5 mm from the axis of <nose>, which narrows to 11.5 mm of \
1367                 room along it (25.0 mm where widest)"
1368            ),
1369            "{}",
1370            sentences[17]
1371        );
1372        assert!(sentences[11].contains(
1373            " reaches 40.0 mm from the axis, wider than <cp>, and caps its end, in 39.9 mm"
1374        ));
1375        assert!(sentences[15].contains(" ends 20.5 mm in radius where <bt> begins 20.7 mm"));
1376        assert_eq!(
1377            mm_pair(0.038, 0.037_97),
1378            ("38.00 mm".to_owned(), "37.97 mm".to_owned())
1379        );
1380        assert_eq!(
1381            mm_pair(0.040, 0.000_049),
1382            ("40.000 mm".to_owned(), "0.049 mm".to_owned())
1383        );
1384        assert_eq!(
1385            mm_pair(0.025, 0.024_98),
1386            ("25.00 mm".to_owned(), "24.98 mm".to_owned())
1387        );
1388        assert_eq!(
1389            mm_pair(0.020_5, 0.020_500_01),
1390            ("20.5000 mm".to_owned(), "20.5000 mm".to_owned())
1391        );
1392        assert_eq!(mm(0.0005), "0.50 mm");
1393        assert_eq!(mm(0.0), "0.0 mm");
1394    }
1395
1396    fn kinds(findings: &[Finding]) -> Vec<(String, Severity)> {
1397        findings
1398            .iter()
1399            .map(|f| {
1400                let tag = serde_json::to_value(f).unwrap()["kind"]
1401                    .as_str()
1402                    .unwrap()
1403                    .to_owned();
1404                (tag, f.severity())
1405            })
1406            .collect()
1407    }
1408
1409    #[test]
1410    fn sample_rocket_passes_every_check() {
1411        let findings = check(&three_fin_rocket()).unwrap();
1412        assert!(findings.is_empty(), "{findings:?}");
1413    }
1414
1415    /// Loft lesson L50: a 54 mm motor in a 38 mm mount flew, and flew high. Here it is an error, a
1416    /// motor exactly as wide as the bore is not, and a case longer than the mount only warns.
1417    #[test]
1418    fn motor_wider_than_mount_is_rejected() {
1419        let mut design = three_fin_rocket();
1420        design.configurations[0].motors[0] = crate::testing::motor("mmt", 0.054, 0.2);
1421        let findings = check(&design).unwrap();
1422        assert_eq!(
1423            findings,
1424            vec![Finding::MotorWiderThanMount {
1425                configuration: "main".to_owned(),
1426                mount: "mmt".to_owned(),
1427                motor_diameter_m: 0.054,
1428                mount_inner_diameter_m: 2.0 * (0.020 - 0.001),
1429            }]
1430        );
1431        assert_eq!(findings[0].severity(), Severity::Error);
1432        assert!(has_errors(&findings));
1433        // A cluster of three such tubes is still one finding: the motor is named once.
1434        if let Part::InnerTube(tube) = &mut design.stages[0].components[1].children[0].part {
1435            tube.cluster_m = vec![[0.0, 0.0], [0.04, 0.0], [-0.04, 0.0]];
1436        }
1437        let findings = check(&design).unwrap();
1438        let wider = findings
1439            .iter()
1440            .filter(|f| matches!(f, Finding::MotorWiderThanMount { .. }))
1441            .count();
1442        assert_eq!(wider, 1, "{findings:?}");
1443
1444        // The sample's 38 mm motor fills its 38 mm bore exactly: no finding.
1445        let exact = three_fin_rocket();
1446        assert!(check(&exact).unwrap().is_empty());
1447        // Wider by more than round-off is an error again.
1448        let mut design = three_fin_rocket();
1449        design.configurations[0].motors[0] = crate::testing::motor("mmt", 0.038 + 1e-6, 0.2);
1450        assert!(has_errors(&check(&design).unwrap()));
1451
1452        // A 0.35 m case in a 0.3 m mount with 0.01 m of overhang reaches 0.04 m past its top.
1453        let mut design = three_fin_rocket();
1454        design.configurations[0].motors[0] = crate::testing::motor("mmt", 0.038, 0.35);
1455        let findings = check(&design).unwrap();
1456        let [Finding::MotorPastMountTop { excess_m, .. }] = findings[..] else {
1457            panic!("{findings:?}")
1458        };
1459        assert!((excess_m - 0.04).abs() < 1e-12);
1460        assert!(!has_errors(&findings));
1461    }
1462
1463    /// Issue #1261: an engine block, forward thrust ring or bulkhead attached to the mount, with a
1464    /// bore the case can't pass and its aft face between the case's ends, is found, with how much
1465    /// further aft the case stops; of several, the aftmost alone. One the case clears, ends at,
1466    /// reaches past by no more than the 1 mm tolerance, or whose aft face is past the nozzle,
1467    /// isn't.
1468    #[test]
1469    fn a_motor_into_an_engine_block_is_found() {
1470        // The tests' mount: 0.3 m long, 38 mm bore, its motor 0.01 m past its aft end.
1471        let with_motor = |block: Part, at_m: f64, motor_diameter_m: f64, motor_length_m: f64| {
1472            let mut design = three_fin_rocket();
1473            let mount = &mut design.stages[0].components[1].children[0];
1474            assert_eq!(mount.id, "mmt");
1475            mount.children = vec![attached("block", block, top(at_m))];
1476            design.configurations[0].motors[0] =
1477                crate::testing::motor("mmt", motor_diameter_m, motor_length_m);
1478            check(&design).unwrap()
1479        };
1480        let with_block = |block: Part, at_m: f64, motor_length_m: f64| {
1481            with_motor(block, at_m, 0.038, motor_length_m)
1482        };
1483        // A 20 mm block of 28 mm bore at the mount's top: a 0.2 m case ends 0.11 m aft of it.
1484        let block = || inner_tube(0.02, 0.019, 0.005);
1485        assert!(with_block(block(), 0.0, 0.2).is_empty());
1486        // A 0.3 m case reaches 0.01 m aft of the mount's top, 0.01 m into the block: it stops 0.01
1487        // m further aft.
1488        let findings = with_block(block(), 0.0, 0.3);
1489        let [
1490            Finding::MotorIntoBlock {
1491                block: ref blocker,
1492                block_bore_m,
1493                motor_diameter_m,
1494                excess_m,
1495                ..
1496            },
1497        ] = findings[..]
1498        else {
1499            panic!("{findings:?}")
1500        };
1501        assert_eq!(blocker, "block");
1502        assert!((block_bore_m - 0.028).abs() < 1e-12, "{block_bore_m}");
1503        assert_eq!(motor_diameter_m, 0.038);
1504        assert!((excess_m - 0.01).abs() < 1e-12, "{excess_m}");
1505        assert_eq!(findings[0].severity(), Severity::Warning);
1506        // A case ending exactly at the block's aft face touches it, no more: 0.28 m + 0.01 m out.
1507        assert!(with_block(block(), 0.0, 0.29).is_empty());
1508        // Up to a millimeter into it is the catalog's rounding of the case's length; past it, not.
1509        assert!(with_block(block(), 0.0, 0.291).is_empty());
1510        let findings = with_block(block(), 0.0, 0.291 + 1e-6);
1511        assert!(
1512            matches!(findings[..], [Finding::MotorIntoBlock { .. }]),
1513            "{findings:?}"
1514        );
1515        // A thrust ring lower down stops the case at its own aft face: 0.03 m aft of the top.
1516        let findings = with_block(block(), 0.01, 0.3);
1517        let [Finding::MotorIntoBlock { excess_m, .. }] = findings[..] else {
1518            panic!("{findings:?}")
1519        };
1520        assert!((excess_m - 0.02).abs() < 1e-12, "{excess_m}");
1521        // A bulkhead, as a ring with no bore, 8 mm down, stops it 4 mm further aft; its bore is 0.
1522        let findings = with_block(ring(0.006, 0.019, 0.0), 0.008, 0.3);
1523        let [
1524            Finding::MotorIntoBlock {
1525                block_bore_m,
1526                excess_m,
1527                ..
1528            },
1529        ] = findings[..]
1530        else {
1531            panic!("{findings:?}")
1532        };
1533        assert_eq!(block_bore_m, 0.0);
1534        assert!((excess_m - 0.004).abs() < 1e-12, "{excess_m}");
1535        // A case the block's bore passes, 28 mm across, isn't stopped by it.
1536        assert!(with_motor(block(), 0.0, 0.028, 0.3).is_empty());
1537        // A bulkhead 0.8 mm thick, 0.1 m down, wholly inside the case's span: the case reaches
1538        // 100.8 mm - 10 mm = 90.8 mm past its aft face, though it overlaps it by 0.8 mm alone.
1539        let findings = with_block(ring(0.0008, 0.019, 0.0), 0.1, 0.3);
1540        let [Finding::MotorIntoBlock { excess_m, .. }] = findings[..] else {
1541            panic!("{findings:?}")
1542        };
1543        assert!((excess_m - 0.0908).abs() < 1e-12, "{excess_m}");
1544        // A ring across the nozzle's station, its aft face aft of it (a retainer's lip drawn
1545        // there), isn't a block: the case sits 10 mm up the mount, its nozzle at 290 mm, and the
1546        // ring spans 286 to 292 mm.
1547        let mut design = three_fin_rocket();
1548        let mount = &mut design.stages[0].components[1].children[0];
1549        mount.motor_mount = Some(MotorMount { overhang_m: -0.01 });
1550        mount.children = vec![attached("lip", ring(0.006, 0.019, 0.0), top(0.286))];
1551        design.configurations[0].motors[0] = crate::testing::motor("mmt", 0.038, 0.25);
1552        let findings = check(&design).unwrap();
1553        assert!(findings.is_empty(), "{findings:?}");
1554        // Two blocks: the aftmost is where the case stops, and the one finding names it.
1555        let mut design = three_fin_rocket();
1556        let mount = &mut design.stages[0].components[1].children[0];
1557        mount.children = vec![
1558            attached("top-block", block(), top(0.0)),
1559            attached("ring", ring(0.006, 0.019, 0.0), top(0.05)),
1560        ];
1561        design.configurations[0].motors[0] = crate::testing::motor("mmt", 0.038, 0.3);
1562        let findings = check(&design).unwrap();
1563        let [
1564            Finding::MotorIntoBlock {
1565                block: ref binding,
1566                excess_m,
1567                ..
1568            },
1569        ] = findings[..]
1570        else {
1571            panic!("{findings:?}")
1572        };
1573        assert_eq!(binding, "ring");
1574        assert!((excess_m - 0.046).abs() < 1e-12, "{excess_m}");
1575        // A case past the mount's top and into the block: both, the block's the further aft.
1576        let findings = with_block(block(), 0.0, 0.35);
1577        let excesses: Vec<f64> = findings
1578            .iter()
1579            .map(|finding| match finding {
1580                Finding::MotorPastMountTop { excess_m, .. }
1581                | Finding::MotorIntoBlock { excess_m, .. } => *excess_m,
1582                _ => panic!("{findings:?}"),
1583            })
1584            .collect();
1585        assert_eq!(excesses.len(), 2, "{findings:?}");
1586        assert!((excesses[0] - 0.04).abs() < 1e-12 && (excesses[1] - 0.06).abs() < 1e-12);
1587    }
1588
1589    /// Issue #280: a nominal 29 mm motor in LOC's 1.140 in (28.956 mm) tube only warns, as
1590    /// AeroTech's 29 mm case is at most 1.130 in (28.702 mm) across; a hair past that, and the
1591    /// Loft demo's 28.0 mm bore, are errors. Sizes whose cases are as wide as their names get no
1592    /// slack, and neither does a diameter that isn't a nominal size.
1593    #[test]
1594    fn a_nominal_motor_in_its_matching_tube_only_warns() {
1595        let fitted = |motor_m: f64, bore_m: f64| {
1596            let mut design = three_fin_rocket();
1597            let Part::InnerTube(tube) = &mut design.stages[0].components[1].children[0].part else {
1598                panic!("the tests' rocket's mount is an inner tube");
1599            };
1600            tube.outer_radius_m = bore_m / 2.0 + tube.thickness_m;
1601            design.configurations[0].motors[0] = crate::testing::motor("mmt", motor_m, 0.2);
1602            check(&design).unwrap()
1603        };
1604        let findings = fitted(0.029, 0.028956);
1605        let [
1606            Finding::MotorTightInMount {
1607                motor_diameter_m,
1608                mount_inner_diameter_m,
1609                ..
1610            },
1611        ] = findings[..]
1612        else {
1613            panic!("{findings:?}")
1614        };
1615        assert_eq!(motor_diameter_m, 0.029);
1616        assert!((mount_inner_diameter_m - 0.028956).abs() < 1e-12);
1617        assert_eq!(findings[0].severity(), Severity::Warning);
1618        assert!(!has_errors(&findings));
1619        // The slack is the name less the largest case: 0.298, 0.0478 and 0.1438 mm.
1620        assert!((motor_fit_slack_m(0.029) - 0.000_298).abs() < 1e-12);
1621        assert!((motor_fit_slack_m(0.024) - 0.000_047_8).abs() < 1e-12);
1622        assert!((motor_fit_slack_m(0.018) - 0.000_143_8).abs() < 1e-12);
1623        assert_eq!(motor_fit_slack_m(0.038), 0.0);
1624        assert!(!has_errors(&fitted(0.029, 0.028702 + 1e-7)));
1625        for (motor_m, bore_m) in [
1626            (0.029, 0.028702 - 1e-6),
1627            (0.029, 0.028),
1628            (0.024, 0.023952 - 1e-6),
1629            (0.038, 0.038 - 1e-6),
1630            (0.054, 0.054 - 1e-6),
1631            // Not a nominal size: compared as it is.
1632            (0.0289, 0.0289 - 1e-6),
1633        ] {
1634            // A 54 mm mount is wider than the tests' airframe, so only the motor's findings count.
1635            let findings: Vec<_> = fitted(motor_m, bore_m)
1636                .into_iter()
1637                .filter(|f| {
1638                    matches!(
1639                        f,
1640                        Finding::MotorWiderThanMount { .. } | Finding::MotorTightInMount { .. }
1641                    )
1642                })
1643                .collect();
1644            assert!(
1645                matches!(&findings[..], [Finding::MotorWiderThanMount { .. }]),
1646                "{motor_m} in {bore_m}: {findings:?}"
1647            );
1648        }
1649    }
1650
1651    /// A pod of no length (fins or a lug on a pod's tube of length 0, as OpenRocket draws
1652    /// winglets) and an empty pod set raise no finding where they sit on their tube, though they
1653    /// have no length to overlap it with; a pod set of no length beyond the tube's end is still
1654    /// off it (M1.13b2).
1655    #[test]
1656    fn a_pod_set_of_no_length_touches_its_tube_where_it_sits() {
1657        let podded = |children: Vec<crate::Component>, position: Position| {
1658            let mut design = three_fin_rocket();
1659            let mut pods = attached(
1660                "pods",
1661                Part::PodSet(crate::parts::PodSet {
1662                    count: 2,
1663                    radial_offset_m: 0.06,
1664                    angle_rad: 0.0,
1665                }),
1666                position,
1667            );
1668            pods.children = children;
1669            design.stages[0].components[1].children.push(pods);
1670            check(&design).unwrap()
1671        };
1672        let mut phantom = body("phantom", tube(0.0, 0.0, 0.0));
1673        phantom.children = vec![attached(
1674            "wings",
1675            crate::testing::fins(0.05, 0.03),
1676            bottom(0.0),
1677        )];
1678        let base = check(&three_fin_rocket()).unwrap();
1679        assert_eq!(podded(vec![phantom.clone()], top(0.1)), base);
1680        assert_eq!(podded(Vec::new(), top(0.1)), base);
1681        // At the tube's aft end, and just past it.
1682        assert_eq!(podded(Vec::new(), bottom(0.0)), base);
1683        let off = podded(vec![phantom], bottom(0.01));
1684        assert!(
1685            off.contains(&Finding::AttachmentOffBody {
1686                component: "pods".to_owned(),
1687                body: "airframe".to_owned(),
1688            }),
1689            "{off:?}"
1690        );
1691        assert_eq!(off.len(), base.len() + 1, "{off:?}");
1692
1693        // Fins that don't reach their tube of no length are off it, as any fins are.
1694        let mut far = body("phantom", tube(0.0, 0.0, 0.0));
1695        far.children = vec![attached(
1696            "wings",
1697            crate::testing::fins(0.05, 0.03),
1698            top(0.01),
1699        )];
1700        let off = podded(vec![far], top(0.1));
1701        assert_eq!(
1702            off.iter()
1703                .filter(
1704                    |f| matches!(f, Finding::AttachmentOffBody { component, body }
1705                    if component == "wings" && body == "phantom")
1706                )
1707                .count(),
1708            1,
1709            "{off:?}"
1710        );
1711        assert_eq!(off.len(), base.len() + 1, "{off:?}");
1712    }
1713
1714    /// Loft lesson L50: fins could sit off the airframe. A fin root that touches none of its body
1715    /// tube is an error; one that runs past the tube's end warns.
1716    #[test]
1717    fn fin_root_must_touch_body() {
1718        let with_fins = |offset: f64| {
1719            let mut design = three_fin_rocket();
1720            design.stages[0].components[1].children[3].position = Some(bottom(offset));
1721            check(&design).unwrap()
1722        };
1723        // Root chord 0.1 m; the tube ends at station 1.0.
1724        let off = with_fins(0.15);
1725        assert_eq!(
1726            off,
1727            vec![Finding::AttachmentOffBody {
1728                component: "fins".to_owned(),
1729                body: "airframe".to_owned(),
1730            }]
1731        );
1732        assert!(has_errors(&off));
1733        // Touching only at the tube's end is still off the body.
1734        assert!(has_errors(&with_fins(0.1)));
1735        let past = with_fins(0.04);
1736        let [
1737            Finding::AttachmentPastBodyEnd {
1738                ref component,
1739                excess_m,
1740                ..
1741            },
1742        ] = past[..]
1743        else {
1744            panic!("{past:?}")
1745        };
1746        assert_eq!(component, "fins");
1747        assert!((excess_m - 0.04).abs() < 1e-12);
1748        assert!(!has_errors(&past));
1749        assert!(with_fins(0.0).is_empty());
1750        // Forward of the tube too.
1751        let mut design = three_fin_rocket();
1752        design.stages[0].components[1].children[3].position = Some(top(-0.2));
1753        assert!(has_errors(&check(&design).unwrap()));
1754    }
1755
1756    #[test]
1757    fn internal_parts_radius_steps_and_a_missing_nose_are_found() {
1758        let mut airframe = body("airframe", tube(0.5, 0.03, 0.001));
1759        airframe.children = vec![
1760            // 1 mm wider than the 29 mm bore, 0.5 mm past its fit tolerance.
1761            attached("wide-ring", ring(0.005, 0.03, 0.01), top(0.1)),
1762            // Hanging 0.05 m out of the tube's aft end.
1763            attached("long-mmt", inner_tube(0.2, 0.01, 0.001), bottom(0.05)),
1764            // Entirely forward of the tube.
1765            attached("lost", mass_component(0.1, 0.05, 0.01), top(-0.2)),
1766            // 0.5 mm wider than the bore: a tight fit.
1767            attached("tight-ring", ring(0.005, 0.0295, 0.01), top(0.2)),
1768        ];
1769        let mut mount = airframe.children[1].clone();
1770        mount.motor_mount = Some(MotorMount::default());
1771        airframe.children[1] = mount;
1772        let design = rocket(vec![stage(
1773            "s",
1774            vec![airframe, body("tail", tube(0.1, 0.02, 0.001))],
1775        )]);
1776        let findings = check(&design).unwrap();
1777        assert_eq!(
1778            kinds(&findings),
1779            vec![
1780                ("no_nose_cone".to_owned(), Severity::Warning),
1781                ("radius_step".to_owned(), Severity::Warning),
1782                (
1783                    "internal_part_wider_than_parent".to_owned(),
1784                    Severity::Error
1785                ),
1786                (
1787                    "internal_part_past_parent_end".to_owned(),
1788                    Severity::Warning
1789                ),
1790                // Wholly forward of the nose tip: one error, not also a warning.
1791                ("part_outside_rocket".to_owned(), Severity::Error),
1792                (
1793                    "internal_part_tight_in_parent".to_owned(),
1794                    Severity::Warning
1795                ),
1796            ]
1797        );
1798
1799        // A ring left solid across the motor mount counts their mass twice.
1800        let mut design = three_fin_rocket();
1801        design.stages[0].components[1].children[1].auto = vec![AutoDimension::OuterRadius];
1802        assert_eq!(
1803            check(&design).unwrap(),
1804            vec![Finding::RingOverlapsInnerTube {
1805                ring: "ring-fore".to_owned(),
1806                tube: "mmt".to_owned(),
1807            }]
1808        );
1809    }
1810
1811    /// Radial room is measured about the parent's own axis: a block centered in an off-axis pod
1812    /// fits, and a mass on the body axis attached to the pod doesn't. Rings in a cluster warn.
1813    #[test]
1814    fn internal_parts_are_measured_from_their_parents_axis() {
1815        let offset = |part: Part, r: f64| match part {
1816            Part::InnerTube(mut t) => {
1817                t.radial_offset_m = r;
1818                Part::InnerTube(t)
1819            }
1820            Part::MassComponent(mut m) => {
1821                m.packing.radial_offset_m = r;
1822                Part::MassComponent(m)
1823            }
1824            other => other,
1825        };
1826        let mut pod = attached(
1827            "pod",
1828            offset(inner_tube(0.3, 0.02, 0.001), 0.025),
1829            bottom(0.0),
1830        );
1831        pod.children = vec![attached(
1832            "block",
1833            offset(inner_tube(0.01, 0.019, 0.003), 0.025),
1834            top(0.0),
1835        )];
1836        let mut airframe = body("airframe", tube(0.8, 0.05, 0.002));
1837        airframe.children = vec![pod, attached("ring", ring(0.005, 0.048, 0.0), bottom(-0.1))];
1838        let design = rocket(vec![stage(
1839            "s",
1840            vec![body("nose", crate::testing::nose(0.2, 0.05)), airframe],
1841        )]);
1842        assert_eq!(
1843            check(&design).unwrap(),
1844            vec![Finding::RingOverlapsInnerTube {
1845                ring: "ring".to_owned(),
1846                tube: "pod".to_owned(),
1847            }]
1848        );
1849
1850        let mut design = design;
1851        design.stages[0].components[1].children[0].children[0] =
1852            attached("on-axis", mass_component(0.1, 0.05, 0.004), top(0.1));
1853        let findings = check(&design).unwrap();
1854        let wide = findings
1855            .iter()
1856            .find_map(|f| match f {
1857                Finding::InternalPartWiderThanParent {
1858                    component,
1859                    reach_m,
1860                    room_m,
1861                    ..
1862                } if component == "on-axis" => Some((*reach_m, *room_m)),
1863                _ => None,
1864            })
1865            .unwrap();
1866        assert!(
1867            (wide.0 - 0.029).abs() < 1e-15 && (wide.1 - 0.019).abs() < 1e-15,
1868            "{wide:?}"
1869        );
1870    }
1871
1872    /// A packed part drawn wider than its parent's bore warns, by any amount, while its center is
1873    /// in the bore: OpenRocket's *Deployable payload* packs a 25 mm payload into a 21 mm bore. Its
1874    /// width sets only its own inertia. A ring as wide is an error, and so is a packed part whose
1875    /// center is past the bore (ADR-170).
1876    #[test]
1877    fn a_packed_part_wider_than_its_bore_warns_while_its_center_is_inside() {
1878        // The airframe's bore is 0.0255 m; its fit tolerance (51 mm) is 0.8 mm.
1879        let room = 0.0255;
1880        let placed = |part: Part, offset_m: f64| {
1881            let part = match part {
1882                Part::MassComponent(mut m) => {
1883                    m.packing.radial_offset_m = offset_m;
1884                    Part::MassComponent(m)
1885                }
1886                Part::Parachute(mut p) => {
1887                    p.packing.radial_offset_m = offset_m;
1888                    Part::Parachute(p)
1889                }
1890                other => other,
1891            };
1892            let mut design = three_fin_rocket();
1893            design.stages[0].components[1]
1894                .children
1895                .push(attached("packed", part, top(0.2)));
1896            check(&design).unwrap()
1897        };
1898        let packed = |reach_m: f64| {
1899            vec![Finding::PackedPartWiderThanParent {
1900                component: "packed".to_owned(),
1901                parent: "airframe".to_owned(),
1902                reach_m,
1903                room_m: room,
1904                // A tube's bore is as wide aft of it: the part's center of gravity is no less
1905                // possible where it is drawn (#367).
1906                room_widens_aft: false,
1907            }]
1908        };
1909        // 5 mm too wide, or within the fit tolerance: a warning, not a fit to sand.
1910        for radius_m in [0.0305, 0.026] {
1911            assert_eq!(
1912                placed(mass_component(0.1, 0.05, radius_m), 0.0),
1913                packed(radius_m)
1914            );
1915        }
1916        let mut chute = three_fin_rocket().stages[0].components[1].children[4]
1917            .part
1918            .clone();
1919        if let Part::Parachute(p) = &mut chute {
1920            p.packing.radius_m = 0.03;
1921        }
1922        assert_eq!(placed(chute, 0.0), packed(0.03));
1923        // Its center on the bore's edge still warns; 0.1 µm past it, the part is an error.
1924        let reach = room + 0.002;
1925        assert_eq!(
1926            placed(mass_component(0.1, 0.05, 0.002), room),
1927            packed(reach)
1928        );
1929        assert_eq!(
1930            placed(mass_component(0.1, 0.05, 0.002), room + 1e-7),
1931            vec![Finding::InternalPartWiderThanParent {
1932                component: "packed".to_owned(),
1933                parent: "airframe".to_owned(),
1934                reach_m: room + 1e-7 + 0.002,
1935                room_m: room,
1936            }]
1937        );
1938        // A thin part centered in the wall, reaching past the bore by less than the fit
1939        // tolerance, is no fit to sand: packed parts have no tolerance.
1940        for (radius_m, offset_m) in [(0.0002, room + 0.0002), (0.0001, room + 0.0005)] {
1941            assert_eq!(
1942                placed(mass_component(0.1, 0.05, radius_m), offset_m),
1943                vec![Finding::InternalPartWiderThanParent {
1944                    component: "packed".to_owned(),
1945                    parent: "airframe".to_owned(),
1946                    reach_m: offset_m + radius_m,
1947                    room_m: room,
1948                }]
1949            );
1950        }
1951        // A centering ring as wide is not packed: an error.
1952        let findings = placed(ring(0.005, 0.0305, 0.0), 0.0);
1953        assert!(
1954            matches!(&findings[..], [Finding::InternalPartWiderThanParent { component, .. }]
1955                if component == "packed"),
1956            "{findings:?}"
1957        );
1958    }
1959
1960    /// A part drawn wider than its parent's bore by up to the coarse general tolerance of the
1961    /// bore's diameter (ISO 2768-1 class c) is a fit and warns; 0.1 µm past that is an error. A
1962    /// bulkhead sized to the airframe's bore at a coupler's end, as OpenRocket's two-stage example
1963    /// draws its own, is a cap and warns; the same bulkhead inside the coupler, or one too wide
1964    /// for the airframe too, is an error.
1965    #[test]
1966    fn a_part_wider_than_its_parent_warns_only_as_a_fit_or_a_cap() {
1967        // The airframe: 0.027 m outside, 0.0255 m bore; the coupler's bore is 0.0245 m, a
1968        // diameter of 49 mm, whose tolerance is 0.8 mm.
1969        let fitted = |radius_m: f64, at: Position| {
1970            let mut design = three_fin_rocket();
1971            let mut coupler = attached("coupler", inner_tube(0.1, 0.0255, 0.001), top(0.1));
1972            coupler.children = vec![attached("bulkhead", ring(0.005, radius_m, 0.0), at)];
1973            design.stages[0].components[1].children.push(coupler);
1974            check(&design).unwrap()
1975        };
1976        let room = 0.0255 - 0.001;
1977        let tight = room + 0.0008;
1978        assert_eq!(
1979            fitted(tight, top(0.02)),
1980            vec![Finding::InternalPartTightInParent {
1981                component: "bulkhead".to_owned(),
1982                parent: "coupler".to_owned(),
1983                reach_m: tight,
1984                room_m: room,
1985            }]
1986        );
1987        assert_eq!(
1988            fitted(tight + 1e-7, top(0.02)),
1989            vec![Finding::InternalPartWiderThanParent {
1990                component: "bulkhead".to_owned(),
1991                parent: "coupler".to_owned(),
1992                reach_m: tight + 1e-7,
1993                room_m: room,
1994            }]
1995        );
1996        // At either end face, inside or outside the coupler, a bulkhead as wide as the airframe's
1997        // bore, or wider by its tolerance (0.8 mm for 51 mm), is a cap.
1998        let capped = 0.0255 + 0.0008;
1999        for (radius_m, at) in [
2000            (0.0255, top(0.0)),
2001            (0.0255, top(-0.005)),
2002            (0.0255, bottom(0.0)),
2003            (capped, bottom(0.005)),
2004        ] {
2005            let findings = fitted(radius_m, at);
2006            assert!(!has_errors(&findings));
2007            // One forward of the coupler's top also runs past its end, which only warns.
2008            let findings: Vec<_> = findings
2009                .into_iter()
2010                .filter(|f| !matches!(f, Finding::InternalPartPastParentEnd { .. }))
2011                .collect();
2012            assert_eq!(
2013                findings,
2014                vec![Finding::RingAgainstParentEnd {
2015                    ring: "bulkhead".to_owned(),
2016                    parent: "coupler".to_owned(),
2017                    reach_m: radius_m,
2018                    room_m: 0.0255,
2019                }],
2020                "{radius_m} at {at:?}"
2021            );
2022        }
2023        // Inside the coupler, away from its ends, or too wide for the airframe: an error.
2024        for (radius_m, at) in [(0.0255, top(0.02)), (capped + 1e-7, top(0.0))] {
2025            let findings = fitted(radius_m, at);
2026            assert!(
2027                matches!(&findings[..], [Finding::InternalPartWiderThanParent { component, .. }]
2028                    if component == "bulkhead"),
2029                "{radius_m} at {at:?}: {findings:?}"
2030            );
2031        }
2032        // A ring at the end of a clustered or off-axis tube sits beside it, not around it, and a
2033        // ring as long as its parent covers both ends: neither is a cap.
2034        for (cluster, offset_m, length_m) in [
2035            (vec![[0.018, 0.0], [-0.018, 0.0]], 0.0, 0.005),
2036            (Vec::new(), 0.018, 0.005),
2037            (Vec::new(), 0.0, 0.1),
2038        ] {
2039            let mut design = three_fin_rocket();
2040            let mut tube = inner_tube(0.1, 0.007, 0.001);
2041            if let Part::InnerTube(inner) = &mut tube {
2042                inner.cluster_m = cluster.clone();
2043                inner.radial_offset_m = offset_m;
2044            }
2045            let mut holder = attached("holder", tube, top(0.1));
2046            holder.children = vec![attached("ring", ring(length_m, 0.012, 0.0), top(0.0))];
2047            design.stages[0].components[1].children.push(holder);
2048            let findings = check(&design).unwrap();
2049            assert!(
2050                findings.iter().any(|f| matches!(f,
2051                    Finding::InternalPartWiderThanParent { component, .. } if component == "ring")),
2052                "{cluster:?} {offset_m} {length_m}: {findings:?}"
2053            );
2054        }
2055        // A tube is no cap, even at its parent's end.
2056        let mut design = three_fin_rocket();
2057        let mut coupler = attached("coupler", inner_tube(0.1, 0.0255, 0.001), top(0.1));
2058        coupler.children = vec![attached(
2059            "sleeve",
2060            inner_tube(0.01, 0.0255, 0.001),
2061            top(0.0),
2062        )];
2063        design.stages[0].components[1].children.push(coupler);
2064        assert!(matches!(
2065            &check(&design).unwrap()[..],
2066            [Finding::InternalPartWiderThanParent { component, .. }] if component == "sleeve"
2067        ));
2068    }
2069
2070    /// A centering ring drawn as a child of the motor tube it wraps, as OpenRocket's pods examples
2071    /// draw theirs, needs room in the airframe around the tube, not in the tube's bore: it fits,
2072    /// warns as a fit or errs by the airframe's room. A ring whose bore is 1 µm short of the
2073    /// tube's outside, or whose tube is off the axis or a cluster, is still measured in the tube.
2074    #[test]
2075    fn a_ring_around_its_motor_tube_needs_room_in_the_airframe() {
2076        // The airframe's bore is 0.0255 m (a 51 mm diameter, tolerance 0.8 mm); the motor tube is
2077        // 0.020 m outside with a 0.019 m bore.
2078        let wrapped = |outer_m: f64, inner_m: f64, offset_m: f64, cluster: Vec<[f64; 2]>| {
2079            let mut design = three_fin_rocket();
2080            let mount = &mut design.stages[0].components[1].children[0];
2081            if let Part::InnerTube(tube) = &mut mount.part {
2082                tube.radial_offset_m = offset_m;
2083                tube.cluster_m = cluster;
2084            }
2085            mount.children = vec![attached("wrap", ring(0.003, outer_m, inner_m), top(0.1))];
2086            check(&design).unwrap()
2087        };
2088        let (outer, bore, airframe) = (0.020, 0.019, 0.0255);
2089        assert_eq!(wrapped(airframe, outer, 0.0, Vec::new()), vec![]);
2090        // A bore wider than the tube still sits on it.
2091        assert_eq!(wrapped(airframe, outer + 0.001, 0.0, Vec::new()), vec![]);
2092        let tight = airframe + 0.0008;
2093        assert_eq!(
2094            wrapped(tight, outer, 0.0, Vec::new()),
2095            vec![Finding::InternalPartTightInParent {
2096                component: "wrap".to_owned(),
2097                parent: "airframe".to_owned(),
2098                reach_m: tight,
2099                room_m: airframe,
2100            }]
2101        );
2102        assert_eq!(
2103            wrapped(tight + 1e-7, outer, 0.0, Vec::new()),
2104            vec![Finding::InternalPartWiderThanParent {
2105                component: "wrap".to_owned(),
2106                parent: "airframe".to_owned(),
2107                reach_m: tight + 1e-7,
2108                room_m: airframe,
2109            }]
2110        );
2111        // Not wrapping the tube: inside it, so measured against its bore, an error.
2112        let in_tube = |findings: Vec<Finding>| {
2113            findings.iter().any(|f| {
2114                matches!(f, Finding::InternalPartWiderThanParent { component, parent, room_m, .. }
2115                    if component == "wrap" && parent == "mmt" && *room_m == bore)
2116            })
2117        };
2118        assert!(in_tube(wrapped(airframe, outer - 1e-6, 0.0, Vec::new())));
2119        assert!(in_tube(wrapped(airframe, outer, 0.002, Vec::new())));
2120        assert!(in_tube(wrapped(
2121            airframe,
2122            outer,
2123            0.0,
2124            vec![[0.0, 0.0], [0.05, 0.0]]
2125        )));
2126        // The tube's outside less the round-off tolerance still wraps.
2127        assert_eq!(wrapped(airframe, outer - 5e-10, 0.0, Vec::new()), vec![]);
2128
2129        // With the motor tube 50 mm out of the airframe's aft end, a ring wholly aft of the
2130        // airframe, or across its end, has nothing around it that holds it: it is measured in
2131        // the tube, an error, and no cap at the tube's end.
2132        let overhung = |at: Position| {
2133            let mut design = three_fin_rocket();
2134            let mount = &mut design.stages[0].components[1].children[0];
2135            mount.position = Some(bottom(0.05));
2136            mount.children = vec![attached("wrap", ring(0.003, airframe, outer), at)];
2137            check(&design).unwrap()
2138        };
2139        assert!(in_tube(overhung(bottom(0.0))));
2140        assert!(in_tube(overhung(bottom(-0.048))));
2141        assert_eq!(
2142            overhung(top(0.1))
2143                .into_iter()
2144                .filter(
2145                    |f| matches!(f, Finding::InternalPartWiderThanParent { component, .. }
2146                    | Finding::InternalPartTightInParent { component, .. } if component == "wrap")
2147                )
2148                .count(),
2149            0
2150        );
2151
2152        // A tube beside the wrapped one in the airframe, crossing the ring, overlaps it.
2153        let mut design = three_fin_rocket();
2154        let airframe_part = &mut design.stages[0].components[1];
2155        airframe_part.children[0].children =
2156            vec![attached("wrap", ring(0.003, airframe, outer), top(0.1))];
2157        let mut side = inner_tube(0.04, 0.004, 0.0005);
2158        if let Part::InnerTube(tube) = &mut side {
2159            tube.radial_offset_m = 0.021;
2160        }
2161        airframe_part
2162            .children
2163            .push(attached("side", side, top(0.58)));
2164        assert_eq!(
2165            check(&design).unwrap(),
2166            vec![Finding::RingOverlapsInnerTube {
2167                ring: "wrap".to_owned(),
2168                tube: "side".to_owned(),
2169            }]
2170        );
2171    }
2172
2173    /// ISO 2768-1's coarse class by the room's diameter, each band up to and including its upper
2174    /// size; none below 0.5 mm or for a room that isn't a number.
2175    #[test]
2176    fn the_fit_tolerance_is_the_coarse_general_tolerance_of_the_bore() {
2177        for (diameter_m, tolerance_m) in [
2178            (0.0004, 0.0),
2179            (0.0005, 0.0002),
2180            (0.002, 0.0002),
2181            (0.006, 0.0003),
2182            (0.0061, 0.0005),
2183            (0.030, 0.0005),
2184            (0.0301, 0.0008),
2185            (0.120, 0.0008),
2186            (0.150, 0.0012),
2187            (5.0, 0.004),
2188        ] {
2189            assert_eq!(
2190                fit_tolerance_m(diameter_m / 2.0),
2191                tolerance_m,
2192                "{diameter_m}"
2193            );
2194        }
2195        assert_eq!(fit_tolerance_m(f64::NAN), 0.0);
2196    }
2197
2198    /// A motor that isn't in its mount at all is an error, whichever way it missed.
2199    #[test]
2200    fn motor_outside_its_mount_is_rejected() {
2201        for overhang in [5.0, 0.2, -0.3] {
2202            let mut design = three_fin_rocket();
2203            design.stages[0].components[1].children[0].motor_mount = Some(MotorMount {
2204                overhang_m: overhang,
2205            });
2206            let findings = check(&design).unwrap();
2207            assert_eq!(
2208                findings,
2209                vec![Finding::MotorOutsideMount {
2210                    configuration: "main".to_owned(),
2211                    mount: "mmt".to_owned(),
2212                }],
2213                "{overhang}"
2214            );
2215            assert!(has_errors(&findings));
2216        }
2217    }
2218
2219    /// Parts wholly off the rocket are errors, and a stage center moved off it by an override too.
2220    #[test]
2221    fn parts_and_centers_off_the_rocket_are_rejected() {
2222        let mut design = three_fin_rocket();
2223        design.stages[0].components[1].children[4].position = Some(top(2.0));
2224        assert_eq!(
2225            check(&design).unwrap(),
2226            vec![Finding::PartOutsideRocket {
2227                component: "chute".to_owned(),
2228            }]
2229        );
2230        let mut design = three_fin_rocket();
2231        design.stages[0].overrides.cg_aft_m = Some(350.0);
2232        let findings = check(&design).unwrap();
2233        assert!(
2234            matches!(&findings[..], [Finding::CenterOutsideRocket { stage, station_m }]
2235                if stage == "sustainer" && *station_m == 350.0),
2236            "{findings:?}"
2237        );
2238        // An added mass at such a station drags the stage's center out with it.
2239        let mut design = three_fin_rocket();
2240        design.stages[0].added_mass = Some(crate::AddedMass {
2241            mass_kg: 1.0,
2242            cg_aft_m: Some(350.0),
2243        });
2244        let findings = check(&design).unwrap();
2245        assert!(
2246            matches!(&findings[..], [Finding::CenterOutsideRocket { stage, station_m }]
2247                if stage == "sustainer" && *station_m > 100.0),
2248            "{findings:?}"
2249        );
2250        // One with no station sits among the parts, and is not a center anyone set.
2251        design.stages[0].added_mass = Some(crate::AddedMass {
2252            mass_kg: 1.0,
2253            cg_aft_m: None,
2254        });
2255        assert_eq!(check(&design).unwrap(), Vec::new());
2256        // A retainer on a motor mount sticking out past the airframe is on the rocket.
2257        let mut design = three_fin_rocket();
2258        let mount = &mut design.stages[0].components[1].children[0];
2259        mount.position = Some(bottom(0.012));
2260        mount.children = vec![attached(
2261            "retainer",
2262            mass_component(0.05, 0.01, 0.015),
2263            bottom(0.0),
2264        )];
2265        let findings = check(&design).unwrap();
2266        assert!(
2267            matches!(&findings[..], [Finding::InternalPartPastParentEnd { component, .. }]
2268                if component == "mmt"),
2269            "{findings:?}"
2270        );
2271        // So is one flush against the mount's aft end, wholly behind the airframe.
2272        let mut flush = design.clone();
2273        flush.stages[0].components[1].children[0].children[0].position = Some(top(0.3));
2274        let layout = flush.layout().unwrap();
2275        let (_, retainer) = layout.find("retainer").unwrap();
2276        assert!(
2277            retainer.fore_station_m >= layout.length_m,
2278            "the test needs it behind"
2279        );
2280        let findings = check(&flush).unwrap();
2281        assert!(
2282            findings
2283                .iter()
2284                .all(|f| !matches!(f, Finding::PartOutsideRocket { .. })),
2285            "{findings:?}"
2286        );
2287        assert!(!has_errors(&findings), "{findings:?}");
2288        // But one clear of the mount is off the rocket.
2289        let mut clear = design.clone();
2290        clear.stages[0].components[1].children[0].children[0].position = Some(top(0.35));
2291        assert_eq!(
2292            check(&clear).unwrap(),
2293            vec![
2294                Finding::InternalPartPastParentEnd {
2295                    component: "mmt".to_owned(),
2296                    parent: "airframe".to_owned(),
2297                    excess_m: check(&design)
2298                        .unwrap()
2299                        .iter()
2300                        .find_map(|f| match f {
2301                            Finding::InternalPartPastParentEnd { excess_m, .. } => Some(*excess_m),
2302                            _ => None,
2303                        })
2304                        .unwrap(),
2305                },
2306                Finding::PartOutsideRocket {
2307                    component: "retainer".to_owned(),
2308                },
2309            ]
2310        );
2311        // Fins trailing far past a light stage's end move its center off the rocket, but with no
2312        // override that is geometry, not a typo.
2313        let mut can = body("can", tube(0.3, 0.03, 0.0005));
2314        let mut fins = attached("trailing-fins", crate::testing::fins(0.2, 0.1), bottom(0.0));
2315        if let Part::FinSet(set) = &mut fins.part {
2316            set.planform = crate::FinPlanform::Trapezoidal {
2317                root_chord_m: 0.2,
2318                tip_chord_m: 0.2,
2319                span_m: 0.1,
2320                sweep_m: 0.4,
2321            };
2322        }
2323        can.children = vec![fins];
2324        let design = rocket(vec![stage("s", vec![can])]);
2325        let layout = design.layout().unwrap();
2326        assert!(
2327            -layout.stages[0].mass.cg_m.z > layout.length_m,
2328            "the test needs it off"
2329        );
2330        assert!(!has_errors(&check(&design).unwrap()));
2331        // A mass override can't move a center past its parts, so it doesn't arm the check.
2332        let mut heavier = design.clone();
2333        heavier.stages[0].components[0].children[0]
2334            .overrides
2335            .mass_kg = Some(1.0);
2336        assert!(!has_errors(&check(&heavier).unwrap()));
2337        // Nor can a sideways center override.
2338        let mut sideways = design.clone();
2339        sideways.stages[0].components[0].children[0]
2340            .overrides
2341            .cg_xy_m = Some([0.0, 0.0]);
2342        assert!(!has_errors(&check(&sideways).unwrap()));
2343        // A component's axial center override arms it.
2344        let mut moved = design.clone();
2345        moved.stages[0].components[0].children[0].overrides.cg_aft_m = Some(50.0);
2346        let findings = check(&moved).unwrap();
2347        assert!(
2348            matches!(&findings[..], [Finding::NoNoseCone { .. }, Finding::CenterOutsideRocket { stage, .. }] if stage == "s"),
2349            "{findings:?}"
2350        );
2351        // A point mass at the rocket's end is on it, whatever the round-off in the length
2352        // (0.1 + 0.7 is 0.7999999999999999).
2353        let mut design = rocket(vec![stage(
2354            "s",
2355            vec![
2356                body("nose", crate::testing::nose(0.1, 0.03)),
2357                body("airframe", tube(0.7, 0.03, 0.001)),
2358            ],
2359        )]);
2360        design.stages[0].components[1].children = vec![attached(
2361            "tail-weight",
2362            mass_component(0.05, 0.0, 0.01),
2363            Position::Absolute { station_m: 0.8 },
2364        )];
2365        assert!(design.layout().unwrap().length_m < 0.8);
2366        assert!(check(&design).unwrap().is_empty());
2367        // And a part flush behind the rocket's end is on it, however its length adds up
2368        // (0.1 + 0.2 is 0.30000000000000004, 0.15 + 0.15 is 0.3).
2369        for (nose, tube_length) in [(0.1, 0.2), (0.15, 0.15)] {
2370            let mut design = rocket(vec![stage(
2371                "s",
2372                vec![
2373                    body("nose", crate::testing::nose(nose, 0.03)),
2374                    body("airframe", tube(tube_length, 0.03, 0.001)),
2375                ],
2376            )]);
2377            design.stages[0].components[1].children = vec![attached(
2378                "tail-block",
2379                mass_component(0.05, 0.05, 0.01),
2380                Position::Absolute { station_m: 0.3 },
2381            )];
2382            let findings = check(&design).unwrap();
2383            assert!(
2384                matches!(&findings[..], [Finding::InternalPartPastParentEnd { component, .. }]
2385                    if component == "tail-block"),
2386                "{nose} + {tube_length}: {findings:?}"
2387            );
2388        }
2389        // Ballast wider than a nose cone, measured against the cone's inside where it sits: packed,
2390        // so a warning while its center is in the cone (ADR-170).
2391        let mut design = three_fin_rocket();
2392        design.stages[0].components[0].children = vec![attached(
2393            "ballast",
2394            mass_component(0.1, 0.02, 0.2),
2395            bottom(0.0),
2396        )];
2397        assert!(matches!(
2398            &check(&design).unwrap()[..],
2399            [Finding::PackedPartWiderThanParent { component, .. }] if component == "ballast"
2400        ));
2401        // A check of a layout with a bad parent index skips it instead of panicking.
2402        let mut layout = three_fin_rocket().layout().unwrap();
2403        layout.components[2].parent = Some(999);
2404        let _ = check_layout(&layout);
2405    }
2406
2407    /// #367: a packed mass too wide for a transition's room where it is drawn could sit only
2408    /// where the transition is wider. Where that is aft (a shoulder, widening aft) its drawn
2409    /// center of gravity is forward of where it can be, the flattering side, and the warning
2410    /// names #367; where it is forward (a boattail, narrowing aft) it is the safe side, and the
2411    /// warning doesn't.
2412    #[test]
2413    fn a_packed_part_names_367_only_where_the_room_widens_aft_of_it() {
2414        let widens = |fore_radius_m: f64, aft_radius_m: f64, position: Option<Position>| {
2415            let transition = Part::Transition(crate::Transition {
2416                shape: crate::NoseShape::Conical {},
2417                clipped: false,
2418                length_m: 0.2,
2419                fore_radius_m,
2420                aft_radius_m,
2421                wall: crate::Wall::Shell { thickness_m: 0.002 },
2422                fore_shoulder: None,
2423                aft_shoulder: None,
2424                material: crate::Material::bulk("PLA", 1240.0),
2425            });
2426            let mut middle = body("transition", transition);
2427            // A 30 mm long, 20 mm radius mass, 10 mm from the transition's 15 mm end: 13.75 mm
2428            // of room or less along it, 23 mm at the other end.
2429            let position = position.unwrap_or(if fore_radius_m < aft_radius_m {
2430                top(0.01)
2431            } else {
2432                bottom(-0.01)
2433            });
2434            middle.children = vec![attached("mass", mass_component(0.05, 0.03, 0.02), position)];
2435            let design = rocket(vec![stage(
2436                "sustainer",
2437                vec![
2438                    body("nose", crate::testing::nose(0.2, fore_radius_m)),
2439                    middle,
2440                    body("airframe", tube(0.6, aft_radius_m, 0.0015)),
2441                ],
2442            )]);
2443            let findings = check(&design).unwrap();
2444            let packed: Vec<_> = findings
2445                .iter()
2446                .filter_map(|finding| match finding {
2447                    Finding::PackedPartWiderThanParent {
2448                        component,
2449                        room_widens_aft,
2450                        ..
2451                    } if component == "mass" => Some((
2452                        *room_widens_aft,
2453                        finding.describe(&|id: &str| id.to_owned()),
2454                    )),
2455                    _ => None,
2456                })
2457                .collect();
2458            assert_eq!(packed.len(), 1, "{findings:?}");
2459            let (flag, text) = packed[0].clone();
2460            assert_eq!(flag, text.contains("issue #367"), "{text}");
2461            flag
2462        };
2463        assert!(widens(0.015, 0.025, None), "a shoulder widens aft");
2464        assert!(!widens(0.025, 0.015, None), "a boattail narrows aft");
2465        // Run 10 mm past a boattail's aft end, it is measured at that end, not by the room the
2466        // profile gives outside it (found in review).
2467        assert!(
2468            !widens(0.025, 0.015, Some(bottom(0.01))),
2469            "past a boattail's end"
2470        );
2471    }
2472
2473    /// #313: a part in a nose cone is measured against the cone's inside where it sits, not its
2474    /// base: the outer radius less the 2 mm wall over the part's span. The 0.2 m conical nose of
2475    /// 27 mm base radius has `r(x) = 0.135 x` outside, so `0.135 x − 0.002` inside.
2476    #[test]
2477    fn a_part_in_a_nose_cone_needs_room_where_it_sits() {
2478        let findings = |part: Part, position: Position| {
2479            let mut nose = body("nose", crate::testing::nose(0.2, 0.027));
2480            nose.children = vec![attached("part", part, position)];
2481            let design = rocket(vec![stage(
2482                "sustainer",
2483                vec![nose, body("airframe", tube(0.6, 0.027, 0.0015))],
2484            )]);
2485            check(&design).unwrap()
2486        };
2487        let room = |x_m: f64| (0.135 * x_m - 0.002_f64).max(0.0);
2488        // A 20 mm bulkhead at the tip has no room at all there, nor 10 mm aft: an error, measured
2489        // where the cone is widest along it. Before #313 the cone's 27 mm base let it pass.
2490        let bulkhead = || ring(0.01, 0.02, 0.0);
2491        let tip = findings(bulkhead(), top(0.0));
2492        assert!(
2493            matches!(&tip[..], [Finding::InternalPartWiderThanParent { component, parent, reach_m, room_m }]
2494                if component == "part" && parent == "nose" && *reach_m == 0.02 && *room_m == 0.0),
2495            "{tip:?}"
2496        );
2497        // At the base it fits: 23.65 mm of room at its fore face.
2498        assert_eq!(findings(bulkhead(), bottom(0.0)), vec![]);
2499        // So does a 20 mm mass there.
2500        assert_eq!(
2501            findings(mass_component(0.05, 0.01, 0.02), bottom(0.0)),
2502            vec![]
2503        );
2504        // A 20 mm mass at the tip is packed: a warning while its center is in the room
2505        // (ADR-170), here on the axis where the wall closes in.
2506        let packed = findings(mass_component(0.05, 0.03, 0.02), top(0.0));
2507        assert!(
2508            matches!(&packed[..], [Finding::PackedPartWiderThanParent { component, room_m, room_widens_aft, .. }]
2509                if component == "part" && *room_m == 0.0 && *room_widens_aft),
2510            "{packed:?}"
2511        );
2512        // The cone widens aft of it, so its mass can sit only farther aft: the margin may read
2513        // high, and the warning names #367.
2514        let text = packed[0].describe(&|id: &str| id.to_owned());
2515        assert!(text.contains("issue #367"), "{text}");
2516        assert!(text.contains("margin may read high"), "{text}");
2517        // Off the axis by 5 mm its center is out of that room: an error.
2518        let mut off_axis = mass_component(0.05, 0.03, 0.02);
2519        if let Part::MassComponent(mass) = &mut off_axis {
2520            mass.packing.radial_offset_m = 0.005;
2521        }
2522        let off = findings(off_axis, top(0.0));
2523        assert!(
2524            matches!(&off[..], [Finding::InternalPartWiderThanParent { component, reach_m, room_m, .. }]
2525                if component == "part" && (*reach_m - 0.025).abs() < 1e-15 && *room_m == 0.0),
2526            "{off:?}"
2527        );
2528        // A mass of no packed length at the tip is in the cone, where it has no room: a warning
2529        // centered, an error off the axis (found in review: it once counted as past the tip).
2530        let point = findings(mass_component(0.05, 0.0, 0.02), top(0.0));
2531        assert!(
2532            matches!(&point[..], [Finding::PackedPartWiderThanParent { room_m, room_widens_aft, .. }]
2533                if *room_m == 0.0 && *room_widens_aft),
2534            "{point:?}"
2535        );
2536        let mut point_off_axis = mass_component(0.05, 0.0, 0.02);
2537        if let Part::MassComponent(mass) = &mut point_off_axis {
2538            mass.packing.radial_offset_m = 0.005;
2539        }
2540        let point_off = findings(point_off_axis, top(0.0));
2541        assert!(
2542            matches!(&point_off[..], [Finding::InternalPartWiderThanParent { room_m, .. }] if *room_m == 0.0),
2543            "{point_off:?}"
2544        );
2545        // A 24.5 mm tube over the cone's aft 100 mm fits at the base (25 mm of room) and runs into
2546        // the wall forward, where the cone has 11.5 mm: wedged, a warning.
2547        let wedged = findings(inner_tube(0.1, 0.0245, 0.001), bottom(0.0));
2548        match &wedged[..] {
2549            [
2550                Finding::InternalPartWedgedInParent {
2551                    component,
2552                    parent,
2553                    reach_m,
2554                    room_m,
2555                    widest_room_m,
2556                },
2557            ] => {
2558                assert_eq!((component.as_str(), parent.as_str()), ("part", "nose"));
2559                assert_eq!(*reach_m, 0.0245);
2560                assert!((room_m - room(0.1)).abs() < 1e-15, "{room_m}");
2561                assert!((widest_room_m - room(0.2)).abs() < 1e-15, "{widest_room_m}");
2562            }
2563            other => panic!("{other:?}"),
2564        }
2565        // Past fit tolerance even at the base: an error, on the widest room.
2566        let wide = findings(inner_tube(0.1, 0.0265, 0.001), bottom(0.0));
2567        assert!(
2568            matches!(&wide[..], [Finding::InternalPartWiderThanParent { room_m, .. }]
2569                if (room_m - room(0.2)).abs() < 1e-15),
2570            "{wide:?}"
2571        );
2572        // Wholly aft of the base, touching it, a ring is measured as before #313, against the
2573        // cone's largest radius: it is past the cone's end, and that is the finding.
2574        let past = findings(ring(0.006, 0.026, 0.0), bottom(0.006));
2575        assert!(
2576            matches!(&past[..], [Finding::InternalPartPastParentEnd { component, .. }]
2577                if component == "part"),
2578            "{past:?}"
2579        );
2580    }
2581
2582    /// A ring of three 40 mm tubes touches at `40 mm / √3` from the axis and crosses inside it.
2583    #[test]
2584    fn a_cluster_whose_tubes_cross_is_flagged() {
2585        let at = |r: f64| {
2586            let mut design = three_fin_rocket();
2587            if let Part::InnerTube(tube) = &mut design.stages[0].components[1].children[0].part {
2588                tube.cluster_m = [90.0_f64, 210.0, 330.0]
2589                    .iter()
2590                    .map(|a| [r * a.to_radians().cos(), r * a.to_radians().sin()])
2591                    .collect();
2592            }
2593            check(&design)
2594                .unwrap()
2595                .into_iter()
2596                .filter(|f| matches!(f, Finding::ClusterTubesOverlap { .. }))
2597                .collect::<Vec<_>>()
2598        };
2599        assert!(at(0.04 / 3.0_f64.sqrt()).is_empty());
2600        let [
2601            Finding::ClusterTubesOverlap {
2602                tube,
2603                apart_m,
2604                diameter_m,
2605            },
2606        ] = &at(0.02)[..]
2607        else {
2608            panic!("one finding");
2609        };
2610        assert_eq!(tube, "mmt");
2611        assert!((apart_m - 0.02 * 3.0_f64.sqrt()).abs() < 1e-15, "{apart_m}");
2612        assert_eq!(*diameter_m, 0.04);
2613        assert_eq!(at(0.02)[0].severity(), Severity::Warning);
2614    }
2615
2616    /// A finding written before the move to US spelling, `centre_outside_rocket`, reads as the same
2617    /// finding.
2618    #[test]
2619    fn a_finding_with_the_old_uk_kind_reads_the_same() {
2620        let finding = Finding::CenterOutsideRocket {
2621            stage: "sustainer".to_owned(),
2622            station_m: 2.5,
2623        };
2624        let text = serde_json::to_string(&finding).unwrap();
2625        assert!(
2626            text.contains("\"kind\":\"center_outside_rocket\""),
2627            "{text}"
2628        );
2629        let old = text.replace("center_outside_rocket", "centre_outside_rocket");
2630        assert_eq!(serde_json::from_str::<Finding>(&old).unwrap(), finding);
2631    }
2632}