Skip to main content

hpr_io/ork/
attached.rs

1//! The parts on and inside the body: what hangs off a `.ork` design's spine.
2//!
3//! [`super::component`] reads the spine: the stages and the body components stacked in them.
4//! Everything else in a design hangs off that trunk, and this module reads it: the tubes, couplers,
5//! rings and bulkheads **inside** a body component, the fins, tube fins, launch lugs and rail
6//! buttons **on** it, and the mass objects, parachutes, streamers and shock cords **packed** in it.
7//!
8//! Three things run through all of them.
9//!
10//! - **Where a part sits** is an offset along its parent and the end it is measured from, which is
11//!   [`Position`]. OpenRocket writes the end under `method` on the newer tag name and `type` on the
12//!   older one, with the same five words.
13//! - **What a part takes from its parent** is an automatic dimension: a coupler's outer radius is
14//!   the tube's bore, a ring's is too, a ring's own bore is the motor tube inside it, and a packed
15//!   part fills whatever room is left. None of that is worked out here:
16//!   [`hpr_design::Rocket::layout`] does it, once, for every reader ([Loft lesson L60][lessons]:
17//!   Loft resolved these as it walked, so the answer depended on the order the siblings were
18//!   written in, and a bulkhead inside a coupler came out as `NaN`).
19//! - **Angles are degrees in the file and radians in `hpr-design`**, which is easy to miss because
20//!   nothing in the file says so: read as radians, `<angleoffset>180</angleoffset>` is more than
21//!   twenty-eight turns instead of half of one. Of the 188 angles in the reference corpus that are
22//!   not zero, 178 are larger than 2π, so they cannot be radians.
23//!
24//! A part this reader cannot give `hpr-design` an honest shape for is **left out with a warning**
25//! rather than guessed at, so the rest of the design still opens. The guide lists every such rule:
26//! [OpenRocket `.ork` design files][guide].
27//!
28//! [guide]: https://hpr.fusionspace.co/format/ork.html
29//! [lessons]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/research/loft-lessons.md
30
31use hpr_design::fins::{FinCrossSection, FinFillet, FinPlanform, FinSet, FinTab, TubeFinSet};
32use hpr_design::parts::{
33    CenteringRing, InnerTube, LaunchLug, MassComponent, Packing, Parachute, PodSet, RailButton,
34    ShockCord, Streamer,
35};
36use hpr_design::tree::{
37    AddedMass, AutoDimension, Component, Overrides, ParallelStage, Part, Position, Stage,
38    StageOverrideRule,
39};
40use hpr_design::{Finish, MotorMount, Wall};
41
42use super::component::{
43    BODY_TAGS, Ids, UNNAMED_RAIL_BUTTON, body, material, material_or, overrides, stage_overrides,
44    stated_radius, subcomponents,
45};
46use super::document::Element;
47use super::left_out::{Around, Counted, Covered, Lean, NOTHING_DEPENDS, spoken};
48use super::motors;
49use super::recovery;
50use super::value::{AXIAL_OFFSET, Dimension, INSTANCE_COUNT, OVERRIDE_FLAGS, Values};
51use super::warning::{Warning, WarningKind};
52
53/// The tags that hang off the spine and hold another part inside them.
54const TUBES: [&str; 3] = ["innertube", "tubecoupler", "engineblock"];
55
56/// Every tag this module knows how to read. A tag outside it belongs to a later milestone, and is
57/// tallied by the caller rather than warned about one by one.
58///
59/// A slice, not an array: this list grows every time a milestone reads another kind of part, and
60/// its length should not be part of the public API.
61pub const ATTACHED_TAGS: &[&str] = &[
62    "innertube",
63    "tubecoupler",
64    "engineblock",
65    "centeringring",
66    "bulkhead",
67    "trapezoidfinset",
68    "ellipticalfinset",
69    "freeformfinset",
70    "tubefinset",
71    "launchlug",
72    "railbutton",
73    "masscomponent",
74    "parachute",
75    "streamer",
76    "shockcord",
77    "podset",
78    "parallelstage",
79];
80
81/// How many of one part a design may say there are.
82///
83/// `hpr-design` builds one body per instance and adds them up, so a count is an allocation: a file
84/// saying `<fincount>4000000000</fincount>` would ask for hundreds of gigabytes, and running out
85/// of memory is an abort rather than an error. The reader is the boundary with a file it did not
86/// write, so the bound lives here, beside the unpacking and nesting limits the container and the
87/// document already carry. The most instanced part in the reference library is a set of 8 fins.
88const MOST_INSTANCES: u32 = 64;
89
90/// How many parts are nested inside `element`, at any depth. A part left out takes them with it,
91/// and a warning that does not say so is a mass quietly missing.
92fn nested(element: &Element) -> usize {
93    subcomponents(element).map(|child| 1 + nested(child)).sum()
94}
95
96/// What follows "it was left out" for `element`, with `around` around it: `", and the 2 parts
97/// inside it"`, or nothing when there are none, then what that leaves out of the numbers
98/// ([`Lean::sentence`]).
99fn and_what_was_inside(element: &Element, around: &Around) -> String {
100    let nested = nested(element);
101    let inside = match nested {
102        0 => String::new(),
103        1 => ", and the one part inside it".to_owned(),
104        many => format!(", and the {many} parts inside it"),
105    };
106    format!(
107        "{inside}.{}",
108        Lean::new(Counted::of_element(element), around).sentence(nested > 0)
109    )
110}
111
112/// A part a reader left out by its tag, which no milestone reads yet, and what leaving it out
113/// does to the numbers: the caller tallies them in one warning.
114#[derive(Debug, Clone)]
115pub(super) struct Unread {
116    /// The tag.
117    pub(super) tag: String,
118    /// What leaving it out, and everything inside it, does.
119    pub(super) lean: Lean,
120    /// How many parts that is: it and everything inside it.
121    pub(super) parts: usize,
122}
123
124impl Unread {
125    /// `element`, left out with `around` around it.
126    pub(super) fn new(element: &Element, around: &Around) -> Self {
127        Self {
128            tag: element.name.clone(),
129            lean: Lean::new(Counted::of_element(element), around),
130            parts: 1 + nested(element),
131        }
132    }
133}
134
135/// What a part's parent passes down to the parts in it.
136#[derive(Debug, Clone, Copy)]
137pub(super) struct Parent<'p> {
138    /// What the parent was read as, which decides two things a child cannot decide for itself:
139    /// whether an external part may attach here at all, and whether an automatic radius has a
140    /// bore to take.
141    pub(super) part: &'p Part,
142    /// Which of its dimensions were automatic, which a pod set's distance from the axis needs to
143    /// know ([`pod_set`]).
144    pub(super) auto: &'p [AutoDimension],
145    /// What the overrides on it and above it set for everything in it, which a warning leaving a
146    /// part out says stays as it was ([`Covered`]).
147    pub(super) covered: &'p Covered,
148}
149
150/// Whether some part among `siblings` takes a size from a tube beside it: a centering ring whose
151/// bore is automatic takes the widest inner tube beside it ([`AutoDimension::InnerRadius`]), so
152/// without the tube the ring can close. Worked out once per list of siblings, so that a list of
153/// many tubes costs one pass, not one per tube.
154fn sizes_a_ring(siblings: &[&Element]) -> bool {
155    siblings.iter().any(|sibling| {
156        sibling.name == "centeringring"
157            && sibling
158                .child("innerradius")
159                .and_then(|radius| Dimension::parse(&radius.text()))
160                .is_some_and(Dimension::is_automatic)
161    })
162}
163
164/// Whether a part beside `child` takes a size from it, `ring` saying whether a ring beside it
165/// takes its bore from a tube ([`sizes_a_ring`]).
166fn sized_from(child: &Element, ring: bool) -> bool {
167    ring && TUBES.contains(&child.name.as_str())
168}
169
170/// Whether the part after `siblings[index]` is placed after it, so that it moves when that part
171/// goes.
172fn placed_after(siblings: &[&Element], index: usize) -> bool {
173    siblings.get(index + 1).is_some_and(|next| {
174        AXIAL_OFFSET
175            .iter()
176            .find_map(|name| next.child(name))
177            .and_then(|offset| {
178                offset
179                    .attribute("method")
180                    .or_else(|| offset.attribute("type"))
181            })
182            == Some("after")
183    })
184}
185
186/// Reads everything in `element`'s `<subcomponents>` that belongs to a body component or a tube.
187///
188/// `parent` is what the parent passes down ([`Parent`]). Anything left out is counted into
189/// `skipped` or warned about, never dropped in silence.
190pub(super) fn children(
191    element: &Element,
192    parent: Parent<'_>,
193    at: &str,
194    ids: &mut Ids,
195    skipped: &mut Vec<Unread>,
196    warnings: &mut Vec<Warning>,
197) -> Vec<Component> {
198    let mut components = Vec::new();
199    let siblings: Vec<&Element> = subcomponents(element).collect();
200    let ring = sizes_a_ring(&siblings);
201    for (index, &child) in siblings.iter().enumerate() {
202        let at = format!("{at}/{}[{index}]", child.name);
203        let around = Around {
204            covered: parent.covered.clone(),
205            sizes: sized_from(child, ring),
206            places: placed_after(&siblings, index),
207        };
208        let read = if child.name == "podset" {
209            pod_set(child, parent, &around, &at, ids, skipped, warnings).map(|(pods, _)| pods)
210        } else if child.name == "parallelstage" {
211            // A stage of its own, beside this tube: the stage reader takes it from `ids`.
212            if let Some(stage) = parallel_stage(child, parent, &at, ids, skipped, warnings) {
213                ids.parallel.push(stage);
214            }
215            continue;
216        } else {
217            one(child, parent, &around, &at, ids, skipped, warnings)
218        };
219        match read {
220            Some(component) => components.push(component),
221            // A part this module knows and could not read has already said so, with its reason;
222            // only a tag no milestone reads yet goes into the tally.
223            None => {
224                if !ATTACHED_TAGS.contains(&child.name.as_str()) {
225                    skipped.push(Unread::new(child, &around));
226                }
227            }
228        }
229    }
230    components
231}
232
233/// Reads one attached part, or leaves it out.
234fn one(
235    element: &Element,
236    above: Parent<'_>,
237    around: &Around,
238    at: &str,
239    ids: &mut Ids,
240    skipped: &mut Vec<Unread>,
241    warnings: &mut Vec<Warning>,
242) -> Option<Component> {
243    let (parent, parent_auto) = (above.part, above.auto);
244    let mut auto = Vec::new();
245    let mut values = Values::new(element, at, warnings);
246    // What a warning that leaves this part out says next: the parts inside it, and what that
247    // leaves out of the numbers.
248    let left_out = and_what_was_inside(element, around);
249    let part = match element.name.as_str() {
250        tag if TUBES.contains(&tag) => inner_tube(tag, &mut values, &mut auto, &left_out),
251        "centeringring" => ring(&mut values, &mut auto, true, &left_out),
252        "bulkhead" => ring(&mut values, &mut auto, false, &left_out),
253        "trapezoidfinset" | "ellipticalfinset" | "freeformfinset" => {
254            fin_set(element, &mut values, &left_out)
255        }
256        "tubefinset" => tube_fins(&mut values, &mut auto, &left_out),
257        "launchlug" => launch_lug(&mut values, &left_out),
258        "railbutton" => rail_button(&mut values, &left_out),
259        "masscomponent" => mass_component(&mut values, &mut auto),
260        "parachute" => parachute(&mut values, &mut auto),
261        "streamer" => streamer(&mut values, &mut auto),
262        "shockcord" => shock_cord(&mut values, &mut auto),
263        // A pod set is read by `pod_set` and a parallel stage by `parallel_stage`, before this;
264        // anything else is a tag this reader has never seen, counted by the caller.
265        _ => return None,
266    }?;
267
268    // `hpr-design` attaches fins, tube fins, lugs and rail buttons to a body tube, and a fin set to
269    // a nose cone or a transition too, its root along the surface ([`follow_the_body`]).
270    // OpenRocket lets the others sit on a nose cone or a transition, where their root is not a
271    // straight line; reading one onto a tube would put it on a body it does not have.
272    let on_a_surface = matches!(part, Part::FinSet(_))
273        && matches!(parent, Part::NoseCone(_) | Part::Transition(_));
274    if part.is_external() && !matches!(parent, Part::BodyTube(_)) && !on_a_surface {
275        values.warn_at(
276            WarningKind::Skipped,
277            format!(
278                "a {} sits on a {}, and HPR Sim attaches one only to a body tube; it was left out{}",
279                spoken(&part),
280                spoken(parent),
281                left_out
282            ),
283        );
284        return None;
285    }
286    // An automatic outer or packed radius is the parent's bore. A hollow nose cone's or
287    // transition's bore narrows along it, and the layout takes an outer radius at the part's
288    // narrower end, as OpenRocket 24.12 does (ADR-096); a packed radius in one, or anything
289    // automatic in a solid one or any other part, has no bore to take. The layout would refuse the
290    // whole design over it, so the part goes instead. A part in a hollow nose whose bore narrows
291    // to nothing at its end (at the tip) stays, and the layout refuses the design: OpenRocket
292    // weighs it as nothing, which hpr does not yet do (ADR-096). A ring's automatic *bore* is not in this
293    // list: it comes from the ring's siblings, and is zero when none of them is a motor tube, so
294    // it needs nothing of the parent.
295    let hollow = |wall: &Wall| matches!(wall, Wall::Shell { .. });
296    let bore_along = match parent {
297        Part::BodyTube(_) | Part::InnerTube(_) => true,
298        Part::NoseCone(nose) => hollow(&nose.wall),
299        Part::Transition(transition) => hollow(&transition.wall),
300        _ => false,
301    };
302    // A tube fin set's automatic radius comes from the body it rings, not a bore; it sits on a body
303    // tube, whose `bore_along` is true, or was left out above.
304    let needs_a_bore = auto.iter().any(|dimension| match dimension {
305        AutoDimension::OuterRadius => !bore_along,
306        AutoDimension::PackedRadius => !matches!(parent, Part::BodyTube(_) | Part::InnerTube(_)),
307        _ => false,
308    });
309    if needs_a_bore {
310        values.warn_at(
311            WarningKind::Skipped,
312            format!(
313                "the {} takes an automatic radius from its parent's bore, and a {} has none; it \
314                 was left out{}",
315                spoken(&part),
316                spoken(parent),
317                left_out
318            ),
319        );
320        return None;
321    }
322
323    // OpenRocket places a part inside an inner tube from that tube's axis; `hpr-design` measures
324    // every part's offset from the body's axis, and this reader does not compose the two yet
325    // (#181). Nothing in the reference library does this, so it is said out loud.
326    let [x, y] = parent.axis_offset_m();
327    if !part.is_external() && (x != 0.0 || y != 0.0) {
328        values.warn_at(
329            WarningKind::Unusual,
330            format!(
331                "the {} sits inside a {} {} m off the body's axis{}. OpenRocket places it from that \
332                 tube's axis, and HPR Sim from the body's axis (issue #181)",
333                spoken(&part),
334                spoken(parent),
335                x.hypot(y),
336                match nested(element) {
337                    0 => String::new(),
338                    1 => "; so is the one part inside it".to_owned(),
339                    many => format!("; so are the {many} parts inside it"),
340                }
341            ),
342        );
343    }
344
345    let name = values.word(&["name"]).unwrap_or_default();
346    let position = match &part {
347        Part::RailButton(button) => centered_on_its_position(position(&mut values), button),
348        _ => position(&mut values),
349    };
350    let part = match follow_the_body(part, parent, parent_auto, position) {
351        Ok(part) => part,
352        Err(why) => {
353            values.warn_at(WarningKind::Skipped, format!("{why}{left_out}"));
354            return None;
355        }
356    };
357    let outside = matches!(
358        part,
359        Part::FinSet(_) | Part::TubeFinSet(_) | Part::LaunchLug(_) | Part::RailButton(_)
360    );
361    let finish = finish(&mut values, outside);
362    let (overrides, include_children, drag_override) = overrides(&mut values);
363    radial_offset_on_the_surface(&mut values, &part);
364    // Only a tube holds other parts. `hpr-design` says the same, so anything written inside
365    // another kind is said out loud here rather than tallied with the parallel stages, whose tally
366    // carries a message about a spine of their own. Nothing in the reference library does this.
367    // Everything inside this part is covered by what covers it, and by its own override when that
368    // covers what it holds.
369    let covered = above
370        .covered
371        .within(&spoken(&part), &overrides, include_children, drag_override);
372    let children = if matches!(part, Part::InnerTube(_)) {
373        let inside = Parent {
374            part: &part,
375            auto: &auto,
376            covered: &covered,
377        };
378        children(element, inside, at, ids, skipped, warnings)
379    } else {
380        if subcomponents(element).next().is_some() {
381            let kind = spoken(&part);
382            let (what, many) = match nested(element) {
383                1 => ("the one part inside it was".to_owned(), false),
384                many => (format!("the {many} parts inside it were"), true),
385            };
386            // They go together, and the part that held them stays: nothing beside them changes.
387            let counted = subcomponents(element)
388                .map(Counted::of_element)
389                .fold(Counted::NOTHING, std::ops::BitOr::bitor);
390            let around = Around {
391                covered,
392                ..Around::default()
393            };
394            values.warn_at(
395                WarningKind::Skipped,
396                format!(
397                    "a {kind} holds no parts in HPR Sim, so {what} left out.{}",
398                    Lean::new(counted, &around).sentence(many)
399                ),
400            );
401        }
402        Vec::new()
403    };
404    let mount = match part {
405        Part::InnerTube(_) => motors::mount(element, at, warnings),
406        _ => None,
407    };
408    let device = match part {
409        Part::Parachute(_) | Part::Streamer(_) => Some(recovery::device(element, at, warnings)),
410        _ => None,
411    };
412    let id = ids.take(
413        &mut Values::new(element, at, warnings),
414        &element.name.clone(),
415    );
416    let motor_mount = mount.map(|mount| {
417        let spec = MotorMount {
418            overhang_m: mount.overhang_m,
419        };
420        ids.mounts.push((id.clone(), mount));
421        spec
422    });
423    if let Some(device) = device {
424        ids.devices.push((id.clone(), device));
425    }
426    ids.read.insert(at.to_owned());
427    Some(Component {
428        id,
429        name,
430        part,
431        position: Some(position),
432        auto,
433        motor_mount,
434        finish,
435        overrides,
436        overrides_include_children: include_children,
437        drag_override,
438        children,
439    })
440}
441
442/// Reads one pod set (ADR-089, ADR-090), or leaves it out with a warning.
443///
444/// A pod set holds pods beside its body tube, each the stack of nose cones, body tubes and
445/// transitions written inside it, with everything on and in them; `hpr-design`'s
446/// [`PodSet`] repeats that stack `instancecount` times around the axis. Its roll angle is the
447/// `angleoffset` read as every angle is ([`roll_angle`]); the angle's `method` changes nothing for
448/// a pod set on a body tube, which sits on the axis.
449///
450/// **The distance from the axis** is not in any document. OpenRocket 24.12 was asked, as an
451/// external oracle, on probes (`validation/oracles/openrocket/pods.py`, recorded in
452/// `validation/fixtures/ork/openrocket-pods.json`), and puts a pod's axis at
453///
454/// | `radiusoffset` method | distance of each pod's axis from the body's |
455/// | --- | --- |
456/// | `relative` | `R + ρ + v` |
457/// | `surface` | `R + ρ`, the number ignored |
458/// | `free` | `v` |
459///
460/// for the tube's outer radius `R`, the written number `v`, and `ρ` the **widest** radius of the
461/// pod's own body components: a probe whose widest tube is aft of a stated narrower nose and tube,
462/// and ahead of another narrower tube, puts the pod at the widest radius, which neither the first
463/// part, the first tube nor the last part gives. An automatic radius in a pod can only take a
464/// radius stated in the pod, so `ρ` is the widest stated one, and a pod with none is left out.
465/// `hpr-design` holds a pod set at a fixed distance, so when the tube's radius is automatic, the
466/// number OpenRocket cached for it is taken, and said; with none cached, the pod set is left out.
467///
468/// **A parallel stage** is read here too, as the pod set it is laid out as. Its overrides are a
469/// stage's, read by a stage's rule ([`stage_overrides`]): one that covers its parts is the whole
470/// stage's, and a mass that doesn't is the stage's added mass, returned beside the pod set. A
471/// pod set carries no added mass, so for one the second value is `None`.
472fn pod_set(
473    element: &Element,
474    above: Parent<'_>,
475    around: &Around,
476    at: &str,
477    ids: &mut Ids,
478    skipped: &mut Vec<Unread>,
479    warnings: &mut Vec<Warning>,
480) -> Option<(Component, Option<AddedMass>)> {
481    let (parent, parent_auto) = (above.part, above.auto);
482    let left_out = and_what_was_inside(element, around);
483    let mut values = Values::new(element, at, warnings);
484    let Part::BodyTube(tube) = parent else {
485        values.warn_at(
486            WarningKind::Skipped,
487            format!(
488                "a pod set hangs from a {}, and HPR Sim hangs one only from a body tube; it was left \
489                 out{}",
490                spoken(parent),
491                left_out
492            ),
493        );
494        return None;
495    };
496    // The path names every pod set and parallel stage above this one, and this one: one inside a
497    // pod would multiply its copies by the outer set's, and `hpr-design` refuses it.
498    if at.matches("/podset[").count() + at.matches("/parallelstage[").count() > 1 {
499        values.warn_at(
500            WarningKind::Skipped,
501            format!(
502                "a pod set inside a pod, which HPR Sim does not nest; it was left out{}",
503                left_out
504            ),
505        );
506        return None;
507    }
508    let count = instances(&mut values, "pod set", &left_out)?;
509    let name = values.word(&["name"]).unwrap_or_default();
510    let position = position(&mut values);
511    // A parallel stage's two overrides each say whether they cover its parts, as an axial
512    // stage's do, and OpenRocket 24.12 weighs them the same way (ADR-341). A pod set weighs
513    // nothing of its own, so its override can only cover its pods (below).
514    let (mut overrides, include_children, added_mass, mut drag_override) =
515        if element.name == "parallelstage" {
516            let (overrides, added_mass, drag_override) = stage_overrides(&mut values);
517            (overrides, true, added_mass, drag_override)
518        } else {
519            let (overrides, include_children, drag_override) = overrides(&mut values);
520            (overrides, include_children, None, drag_override)
521        };
522    let angle_rad = roll_angle(&mut values);
523    let method = values
524        .element(&["radiusoffset"])
525        .map(|offset| offset.attribute("method").unwrap_or("relative").to_owned());
526    let number = values.number(&["radiusoffset"]);
527    let id = ids.take(&mut Values::new(element, at, warnings), &element.name);
528    // A pod set weighs nothing of its own, so its override always covers its pods (below).
529    let kind = if element.name == "parallelstage" {
530        "parallel stage"
531    } else {
532        "pod set"
533    };
534    let covered = around.covered.within(kind, &overrides, true, drag_override);
535
536    let mut pods = Vec::new();
537    for (index, child) in subcomponents(element).enumerate() {
538        let at = format!("{at}/{}[{index}]", child.name);
539        if BODY_TAGS.contains(&child.name.as_str()) {
540            pods.push(body(child, &at, ids, skipped, warnings, &covered).0);
541        } else {
542            let left_out = and_what_was_inside(
543                child,
544                &Around {
545                    covered: covered.clone(),
546                    ..Around::default()
547                },
548            );
549            let tag = child.name.clone();
550            Values::new(child, &at, warnings).warn_at(
551                WarningKind::Skipped,
552                format!(
553                    "a `{tag}` directly inside a pod set, where HPR Sim's pod is a stack of nose \
554                     cones, body tubes and transitions. It was left out{left_out}"
555                ),
556            );
557        }
558    }
559    let mut values = Values::new(element, at, warnings);
560    // OpenRocket draws a pod of a tube with no length, radius or wall (its "phantom body") to hang
561    // fins or a lug off the axis, and `hpr-design` weighs such a tube as nothing. A nose cone or a
562    // transition of no length, or a part of negative length, is no shape `hpr-design` has, so
563    // that pod set goes rather than the whole design.
564    if pods.iter().any(|pod| {
565        let length_m = pod.part.length_m();
566        length_m < 0.0 || (length_m == 0.0 && !matches!(pod.part, Part::BodyTube(_)))
567    }) {
568        values.warn_at(
569            WarningKind::Skipped,
570            format!(
571                "a pod with a nose cone or transition of no length, or a part of negative length, \
572                 which HPR Sim cannot lay out. The pod set was left out{}",
573                left_out
574            ),
575        );
576        return None;
577    }
578    // A tube of no length has no room inside it.
579    let flat = |pod: &Component| pod.part.length_m() == 0.0;
580    if pods
581        .iter()
582        .any(|pod| flat(pod) && pod.children.iter().any(|c| !c.part.is_external()))
583    {
584        values.warn_at(
585            WarningKind::Skipped,
586            format!(
587                "a pod's tube of no length with a part inside it, where it has no room; the pod set \
588                 was left out{}",
589                left_out
590            ),
591        );
592        return None;
593    }
594    // The widest stated radius of the pod: an automatic one can only take a stated one in the pod.
595    let mut widest: Option<f64> = None;
596    for pod in &pods {
597        let radii: &[(f64, AutoDimension)] = match &pod.part {
598            Part::NoseCone(nose) => &[(nose.base_radius_m, AutoDimension::BaseRadius)],
599            Part::BodyTube(tube) => &[(tube.outer_radius_m, AutoDimension::OuterRadius)],
600            Part::Transition(t) => &[
601                (t.fore_radius_m, AutoDimension::ForeRadius),
602                (t.aft_radius_m, AutoDimension::AftRadius),
603            ],
604            _ => &[],
605        };
606        for &(radius_m, dimension) in radii {
607            if !pod.auto.contains(&dimension) {
608                widest = Some(widest.map_or(radius_m, |w: f64| w.max(radius_m)));
609            }
610        }
611    }
612    // A pod set that holds nothing weighs nothing, and its radius is no matter.
613    let Some(pod_radius_m) = widest.or(pods.is_empty().then_some(0.0)) else {
614        values.warn_at(
615            WarningKind::Skipped,
616            format!(
617                "a pod whose radii are all automatic, with no fixed radius in the pod to take; \
618                 the pod set was left out{}",
619                left_out
620            ),
621        );
622        return None;
623    };
624    let tube_radius_m = tube.outer_radius_m;
625    let method = method.unwrap_or_else(|| {
626        values.warn_at(
627            WarningKind::Unusual,
628            "no `radiusoffset`, so the pods were read touching the tube",
629        );
630        "surface".to_owned()
631    });
632    // `relative` and `surface` with no number are the pods touching the tube; `free` with none is
633    // no place at all.
634    let Some(number) = number.or((method != "free").then_some(0.0)) else {
635        values.warn_at(
636            WarningKind::Skipped,
637            format!(
638                "a `free` `radiusoffset` with no number, so where the pods sit is not known; the \
639                 pod set was left out{}",
640                left_out
641            ),
642        );
643        return None;
644    };
645    let radial_offset_m = match method.as_str() {
646        "relative" => tube_radius_m + pod_radius_m + number,
647        "surface" => tube_radius_m + pod_radius_m,
648        "free" => number,
649        other => {
650            values.warn_at(
651                WarningKind::Unusual,
652                format!(
653                    "a `radiusoffset` measured by `{other}`, which this reader does not know; it \
654                     was read as `relative`, from the tube's surface to the pod's"
655                ),
656            );
657            // The design holds a distance from the axis, not this word: kept as written.
658            values.forget(&["radiusoffset"]);
659            tube_radius_m + pod_radius_m + number
660        }
661    };
662    if method != "free" && parent_auto.contains(&AutoDimension::OuterRadius) {
663        if tube_radius_m <= 0.0 {
664            values.warn_at(
665                WarningKind::Skipped,
666                format!(
667                    "the tube's radius is automatic with no number cached, and HPR Sim places pods at \
668                     a fixed distance from the axis. So where they sit is not known. The pod set \
669                     was left out{}",
670                    left_out
671                ),
672            );
673            return None;
674        }
675        values.warn_at(
676            WarningKind::Unusual,
677            format!(
678                "the tube's radius is automatic, and HPR Sim places pods at a fixed distance from the \
679                 axis. They were placed {radial_offset_m} m from it, by the tube radius OpenRocket \
680                 cached, {tube_radius_m} m"
681            ),
682        );
683        // The design holds the distance this cached radius gives, where the file says the pods
684        // follow the tube: the file's offset is kept as written.
685        values.forget(&["radiusoffset"]);
686    }
687    if !(radial_offset_m >= 0.0 && radial_offset_m.is_finite()) {
688        values.warn_at(
689            WarningKind::Skipped,
690            format!(
691                "the pods would sit {radial_offset_m} m from the axis, which is no distance; the \
692                 pod set was left out{}",
693                left_out
694            ),
695        );
696        return None;
697    }
698
699    // Only now that the pod set is read: what is dropped from it next.
700    if pods.is_empty() && (overrides != Overrides::default() || drag_override.is_some()) {
701        // OpenRocket 24.12 puts an override on a pod set that holds nothing at the rocket's tip,
702        // on the axis (`pods.py`), which no design means.
703        overrides = Overrides::default();
704        drag_override = None;
705        values.warn_at(
706            WarningKind::Dropped,
707            "an override on a pod set that holds nothing, which OpenRocket weighs at the rocket's \
708             tip. It was left out, and the pod set's own figures are used: no mass and no drag",
709        );
710        values.forget(&["overridemass", "overridecg", "overridecd"]);
711        values.forget(&OVERRIDE_FLAGS);
712    } else if overrides != Overrides::default() && !include_children {
713        // A pod set weighs nothing of its own, so an override on it can only be its pods' total,
714        // as a stage's is; `hpr-design` refuses one that does not say it covers them.
715        values.warn_at(
716            WarningKind::Dropped,
717            "an override on a pod set that does not cover its pods. A pod set weighs nothing of \
718             its own, so it was read as covering them",
719        );
720        values.forget(&OVERRIDE_FLAGS);
721    }
722    // A tube of no length has no wall for a fin's tab to sit in either: the tab would reach below
723    // the tube's radius.
724    for pod in pods.iter_mut().filter(|pod| flat(pod)) {
725        let radius_m = match &pod.part {
726            Part::BodyTube(tube) => tube.outer_radius_m,
727            _ => 0.0,
728        };
729        // The tab is part of the fins' own mass, so their own override covers it.
730        let pod_covered = covered.within_component(pod);
731        for child in &mut pod.children {
732            let tab_covered = pod_covered.within("fin set", &child.overrides, true, None);
733            if let Part::FinSet(fins) = &mut child.part
734                && fins.tab.as_ref().is_some_and(|tab| tab.height_m > radius_m)
735            {
736                fins.tab = None;
737                let around = Around {
738                    covered: tab_covered,
739                    ..Around::default()
740                };
741                values.warn_at(
742                    WarningKind::Dropped,
743                    format!(
744                        "a tab on the fins `{}` on a pod's tube of no length, deeper than the \
745                         tube's radius ({radius_m} m). The tab was left out.{}",
746                        child.id,
747                        Lean::new(Counted::MASS, &around).sentence(false)
748                    ),
749                );
750            }
751        }
752    }
753
754    ids.read.insert(at.to_owned());
755    Some((
756        Component {
757            id,
758            name,
759            part: Part::PodSet(PodSet {
760                count,
761                radial_offset_m,
762                angle_rad,
763            }),
764            position: Some(position),
765            auto: Vec::new(),
766            motor_mount: None,
767            finish: None,
768            overrides,
769            overrides_include_children: true,
770            drag_override,
771            children: pods,
772        },
773        added_mass,
774    ))
775}
776
777/// Reads one parallel stage (ADR-171), or leaves it out with a warning: a stage of its own,
778/// strapped beside the body tube it is written in, as boosters are.
779///
780/// OpenRocket's parallel stage places its copies as a pod set places its pods, by the same
781/// `instancecount`, `angleoffset`, `radiusoffset` and axial offset, so it is read by [`pod_set`]'s
782/// rules, its warnings saying "parallel stage". It becomes a [`Stage`] with
783/// [`ParallelStage`] set, its body components the pod's stack, its overrides and added mass the
784/// stage's, read as an axial stage's are and weighed with its parts left in place as OpenRocket
785/// 24.12 weighs them (`added_mass_placement.py`'s probes, ADR-341), and its
786/// separation read as a stage's is; the tube's id, taken after its children are read, is filled
787/// in by [`body`]. The stage reader puts it right after the stage it hangs on, which is where
788/// OpenRocket numbers it on a rocket of one axial stage. On a rocket of several, inside a pod or
789/// another parallel stage, with no body component in it, or placed after the part before it, it
790/// is left out.
791fn parallel_stage(
792    element: &Element,
793    parent: Parent<'_>,
794    at: &str,
795    ids: &mut Ids,
796    skipped: &mut Vec<Unread>,
797    warnings: &mut Vec<Warning>,
798) -> Option<Stage> {
799    // A stage of its own: `hpr-design` places it beside the tube, so no override on the tube or
800    // above it covers it, and no part beside it is placed after it (one placed after the part
801    // before it is left out below).
802    let around = Around::default();
803    let parent = Parent {
804        covered: &around.covered,
805        ..parent
806    };
807    let leave_out = |why: &str, warnings: &mut Vec<Warning>| {
808        Values::new(element, at, warnings).warn_at(
809            WarningKind::Skipped,
810            format!(
811                "a parallel stage {why}, which HPR Sim does not read yet; it was left out{}",
812                and_what_was_inside(element, &around)
813            ),
814        );
815    };
816    if !ids.parallel_stages_read {
817        leave_out("on a rocket of more than one axial stage", warnings);
818        return None;
819    }
820    if at.matches("/podset[").count() + at.matches("/parallelstage[").count() > 1 {
821        leave_out("inside a pod or another parallel stage", warnings);
822        return None;
823    }
824    // A stage is a stack of at least one body component (`hpr-design`).
825    if !subcomponents(element).any(|child| BODY_TAGS.contains(&child.name.as_str())) {
826        leave_out("with no nose cone, body tube or transition in it", warnings);
827        return None;
828    }
829    // Looked at before anything inside it is read, so a stage left out leaves no mount behind;
830    // `pod_set` reads the position again, and says what it says about it then.
831    let mut scratch = Vec::new();
832    if matches!(
833        position(&mut Values::new(element, at, &mut scratch)),
834        Position::After { .. }
835    ) {
836        leave_out("placed after the part before it", warnings);
837        return None;
838    }
839    let first = warnings.len();
840    let pods = pod_set(element, parent, &around, at, ids, skipped, warnings);
841    for warning in &mut warnings[first..] {
842        if warning.at == at {
843            warning.message = warning.message.replace("pod set", "parallel stage");
844        }
845    }
846    let (pods, added_mass) = pods?;
847    let Part::PodSet(set) = pods.part else {
848        unreachable!("`pod_set` reads a pod set")
849    };
850    // `pod_set` always places what it reads, and not after a sibling, as looked at above.
851    let position = pods.position.unwrap_or(Position::Top { aft_offset_m: 0.0 });
852    if let Some(separation) = recovery::separation(element, at, warnings) {
853        ids.separations.push((pods.id.clone(), separation));
854    }
855    Some(Stage {
856        id: pods.id,
857        name: pods.name,
858        components: pods.children,
859        // As an axial stage's (`stage` in `component`): OpenRocket 24.12 leaves a parallel
860        // stage's parts where they are under an override that covers them too.
861        override_rule: if pods.overrides.is_empty() {
862            StageOverrideRule::Rescaled
863        } else {
864            StageOverrideRule::PartsInPlace
865        },
866        overrides: pods.overrides,
867        added_mass,
868        drag_override: pods.drag_override,
869        parallel: Some(ParallelStage {
870            on: String::new(),
871            position,
872            pods: set,
873        }),
874    })
875}
876
877/// The radius OpenRocket 24.12 gives an `innertube` whose outer radius is written `auto`: its
878/// inner tube has no automatic radius, so it keeps the 9.5 mm it starts with, in a body tube or a
879/// nose cone alike, where a coupler or an engine block fills its parent. Measured on probe designs
880/// (`validation/oracles/openrocket/conventions.py`, [ADR-096][adr-096]).
881///
882/// [adr-096]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-096-fin-fillets-and-an-automatic-radius-inside-a-nose-cone-read-as-openrocket-reads-them-2026-09-28
883const INNER_TUBE_UNRESOLVED_M: f64 = 0.0095;
884
885/// An inner tube, tube coupler or engine block: all three are a tube inside another one.
886fn inner_tube(
887    tag: &str,
888    values: &mut Values<'_>,
889    auto: &mut Vec<AutoDimension>,
890    left_out: &str,
891) -> Option<Part> {
892    let length_m = values.number(&["length"]).unwrap_or_default();
893    let (mut stated_m, mut outer_radius_m) =
894        stated_radius(values, &["outerradius"], AutoDimension::OuterRadius, auto);
895    if tag == "innertube" && auto.contains(&AutoDimension::OuterRadius) {
896        auto.retain(|dimension| *dimension != AutoDimension::OuterRadius);
897        // OpenRocket's own reading, measured, so no warning: one would keep the design from
898        // flying (ADR-055) for a part read exactly as OpenRocket reads it.
899        (stated_m, outer_radius_m) = (Some(INNER_TUBE_UNRESOLVED_M), INNER_TUBE_UNRESOLVED_M);
900    }
901    let thickness_m = tube_wall(values, stated_m, left_out)?;
902    let angle_rad = roll_angle(values);
903    let cluster_m = cluster(values, outer_radius_m, angle_rad);
904    Some(Part::InnerTube(InnerTube {
905        length_m,
906        outer_radius_m,
907        thickness_m,
908        radial_offset_m: values.number(&["radialposition"]).unwrap_or_default(),
909        angle_rad,
910        material: material(values, &["material"], "bulk"),
911        cluster_m,
912    }))
913}
914
915/// A clustered tube's places ([`InnerTube::cluster_m`]), or none for one tube.
916///
917/// `clusterconfiguration` names one of OpenRocket's patterns ([`cluster_pattern`]), whose points
918/// are in units of the separation between neighboring tubes' axes: `2 R s`, for the tube's outer
919/// radius `R` and `clusterscale` `s` (1 unless written), so tubes of scale 1 touch. The pattern is
920/// turned by the tube's roll angle `θ` less `clusterrotation` `ρ` (degrees, as every `.ork` angle):
921///
922/// `[x, y]ₖ = 2 R s · Rot(θ − ρ) · pₖ`
923///
924/// with OpenRocket's `(y, z)` read as HPR Sim's `(x, y)`, as the roll angle is ([`roll_angle`]). No
925/// document gives the patterns or this rule; OpenRocket 24.12 was asked, as an external oracle, on
926/// probes of every pattern, of a scale, a rotation, a radial offset and all three at once
927/// (`validation/oracles/openrocket/clusters.py`), and `hpr_validate`'s tests hold every tube of
928/// its record to this reading. A name OpenRocket has no pattern for, it reads as one tube; so does
929/// this reader, with a warning.
930fn cluster(values: &mut Values<'_>, outer_radius_m: f64, angle_rad: f64) -> Vec<[f64; 2]> {
931    let Some(name) = values.word(&["clusterconfiguration"]) else {
932        return Vec::new();
933    };
934    let Some(points) = cluster_pattern(&name) else {
935        values.warn_at(
936            WarningKind::Dropped,
937            format!(
938                "`{name}` is not one of OpenRocket's cluster patterns, so the tube is read as one \
939                 tube, as OpenRocket reads it"
940            ),
941        );
942        values.forget(&["clusterconfiguration"]);
943        return Vec::new();
944    };
945    let scale = values.number(&["clusterscale"]).unwrap_or(1.0);
946    let rotation_rad = values
947        .number(&["clusterrotation"])
948        .unwrap_or_default()
949        .to_radians();
950    if name == "single" {
951        return Vec::new();
952    }
953    let separation_m = 2.0 * outer_radius_m * scale;
954    let (sin, cos) = (angle_rad - rotation_rad).sin_cos();
955    points
956        .iter()
957        .map(|&[u, v]| {
958            [
959                separation_m * (u * cos - v * sin),
960                separation_m * (u * sin + v * cos),
961            ]
962        })
963        .collect()
964}
965
966/// OpenRocket's cluster pattern called `name` in a `.ork`: each tube's place in units of the
967/// separation between neighboring tubes' axes, in the order OpenRocket lists them. These are the
968/// points OpenRocket 24.12 gives, as measured by `validation/oracles/openrocket/clusters.py`
969/// (`validation/fixtures/ork/openrocket-clusters.json`), written as the figures they are: rows
970/// one apart, a triangle and a square of side one, rings of radius one round a center tube (the
971/// stars), a pentagon of side one, and a grid and an eight-ring of spacing 1.4. `None` for a name
972/// OpenRocket has no pattern for.
973pub(crate) fn cluster_pattern(name: &str) -> Option<Vec<[f64; 2]>> {
974    // `n` places on a circle of radius `r`, the first at `start` degrees, running clockwise.
975    let ring = |n: u32, r: f64, start: f64| -> Vec<[f64; 2]> {
976        (0..n)
977            .map(|k| {
978                let (sin, cos) = (start - 360.0 * f64::from(k) / f64::from(n))
979                    .to_radians()
980                    .sin_cos();
981                [r * cos, r * sin]
982            })
983            .collect()
984    };
985    let star = |mut points: Vec<[f64; 2]>| {
986        points.insert(0, [0.0, 0.0]);
987        points
988    };
989    let third = 3.0_f64.sqrt() / 6.0;
990    Some(match name {
991        "single" => vec![[0.0, 0.0]],
992        "double" => vec![[-0.5, 0.0], [0.5, 0.0]],
993        "3-row" => vec![[-1.0, 0.0], [0.0, 0.0], [1.0, 0.0]],
994        "3-ring" => vec![[-0.5, -third], [0.5, -third], [0.0, 2.0 * third]],
995        "3-star" => star(ring(3, 1.0, 90.0)),
996        "4-row" => vec![[-1.5, 0.0], [-0.5, 0.0], [0.5, 0.0], [1.5, 0.0]],
997        "4-ring" => vec![[-0.5, 0.5], [0.5, 0.5], [0.5, -0.5], [-0.5, -0.5]],
998        "4-star" => star(ring(4, 1.0, 135.0)),
999        // A pentagon of side one has circumradius 1 / (2 sin 36°).
1000        "5-ring" => ring(5, 0.5 / 36.0_f64.to_radians().sin(), 90.0),
1001        "5-star" => star(ring(5, 1.0, 90.0)),
1002        "6-ring" => ring(6, 1.0, 90.0),
1003        "6-star" => star(ring(6, 1.0, 90.0)),
1004        "9-grid" => [1.4, 0.0, -1.4]
1005            .into_iter()
1006            .flat_map(|y| [-1.4, 0.0, 1.4].map(|x| [x, y]))
1007            .collect(),
1008        "9-star" => star(ring(8, 1.4, 0.0)),
1009        _ => return None,
1010    })
1011}
1012
1013/// A tube's wall, in meters, or `None` when the tube cannot be read at all, with a warning that
1014/// ends in `left_out` ([`and_what_was_inside`]).
1015///
1016/// A tube of **no** wall thickness is read as exactly that, and carries no mass: OpenRocket 24.12
1017/// gives an inner tube, a coupler and a lug of no wall no mass either, measured on a probe design
1018/// ([ADR-061][adr-061]), so it is read as written and not warned of. Reading it as solid would
1019/// invent the mass: a solid coupler filling a 50 mm airframe for 180 mm is a few hundred grams the
1020/// design never had. Seven tube couplers in the reference corpus are written this way, three of
1021/// them in two of OpenRocket's own example designs, and four launch lugs say the same of
1022/// themselves.
1023///
1024/// [adr-061]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-061-what-a-ork-leaves-unsaid-read-as-openrocket-reads-it-overrides-measured-two-departures-kept-2026-09-21
1025fn tube_wall(values: &mut Values<'_>, outer_radius_m: Option<f64>, left_out: &str) -> Option<f64> {
1026    if values.word(&["thickness"]).as_deref() == Some("filled") {
1027        return match outer_radius_m {
1028            Some(radius_m) => Some(radius_m),
1029            None => {
1030                values.warn_at(
1031                    WarningKind::Skipped,
1032                    format!(
1033                        "a filled tube whose outer radius is automatic; there is no radius to fill \
1034                         until the layout resolves one, so it was left out{left_out}"
1035                    ),
1036                );
1037                None
1038            }
1039        };
1040    }
1041    let Some(thickness_m) = values.number(&["thickness"]) else {
1042        // A *stated* zero is OpenRocket saying the bore reaches the rim. A missing tag says
1043        // nothing at all. OpenRocket 24.12 gives it a wall of its own: on the probe design, 0.5 mm
1044        // for a 20 mm inner tube, 1 mm for a 5 mm lug, and none for a coupler (ADR-061). One size
1045        // each does not say whether that wall follows the radius, and nothing in the reference
1046        // library omits it, so it is read as a tube of no wall, out loud, and the test
1047        // `hpr_validate::openrocket::tests` pins the difference.
1048        values.warn_at(
1049            WarningKind::Dropped,
1050            "a tube with no wall thickness at all. It was read as a tube of no wall, which \
1051             carries no mass, rather than as the solid rod a filled one would be",
1052        );
1053        return Some(0.0);
1054    };
1055    if thickness_m == 0.0 {
1056        return Some(0.0);
1057    }
1058    if thickness_m < 0.0 {
1059        values.warn_at(
1060            WarningKind::Skipped,
1061            format!("a tube of negative wall thickness; it was left out{left_out}"),
1062        );
1063        return None;
1064    }
1065    // A wall thicker than the tube is the tube solid. With an automatic radius there is no number
1066    // to compare against yet, so the wall stands as written and the layout decides.
1067    Some(match outer_radius_m {
1068        Some(radius_m) => thickness_m.min(radius_m),
1069        None => thickness_m,
1070    })
1071}
1072
1073/// A centering ring, or a bulkhead, which is a ring with no bore.
1074fn ring(
1075    values: &mut Values<'_>,
1076    auto: &mut Vec<AutoDimension>,
1077    bored: bool,
1078    left_out: &str,
1079) -> Option<Part> {
1080    let length_m = values.number(&["length"]).unwrap_or_default();
1081    let (_, outer_radius_m) =
1082        stated_radius(values, &["outerradius"], AutoDimension::OuterRadius, auto);
1083    let inner_radius_m = if bored {
1084        stated_radius(values, &["innerradius"], AutoDimension::InnerRadius, auto).1
1085    } else {
1086        0.0
1087    };
1088    if inner_radius_m > outer_radius_m && !auto.contains(&AutoDimension::OuterRadius) {
1089        values.warn_at(
1090            WarningKind::Skipped,
1091            format!("a ring whose bore is wider than the ring; it was left out{left_out}"),
1092        );
1093        return None;
1094    }
1095    instanced_once(values, "ring");
1096    off_the_axis(values, "ring");
1097    Some(Part::CenteringRing(CenteringRing {
1098        length_m,
1099        outer_radius_m,
1100        inner_radius_m,
1101        material: material(values, &["material"], "bulk"),
1102    }))
1103}
1104
1105/// A fin set of any of the three outlines OpenRocket writes.
1106fn fin_set(element: &Element, values: &mut Values<'_>, left_out: &str) -> Option<Part> {
1107    let planform = match element.name.as_str() {
1108        "trapezoidfinset" => FinPlanform::Trapezoidal {
1109            root_chord_m: values.number(&["rootchord"]).unwrap_or_default(),
1110            tip_chord_m: values.number(&["tipchord"]).unwrap_or_default(),
1111            span_m: values.number(&["height"]).unwrap_or_default(),
1112            sweep_m: values.number(&["sweeplength"]).unwrap_or_default(),
1113        },
1114        "ellipticalfinset" => FinPlanform::Elliptical {
1115            root_chord_m: values.number(&["rootchord"]).unwrap_or_default(),
1116            span_m: values.number(&["height"]).unwrap_or_default(),
1117        },
1118        _ => outline(values, left_out)?,
1119    };
1120    let count = instances(values, "fin set", left_out)?;
1121    // Fillets weigh what OpenRocket 24.12 weighs them, in their own material, which is cardboard
1122    // when none is named, as for any solid part (ADR-096).
1123    let fillet = values
1124        .number(&["filletradius"])
1125        .filter(|radius_m| *radius_m > 0.0)
1126        .map(|radius_m| FinFillet {
1127            radius_m,
1128            material: material(values, &["filletmaterial"], "bulk"),
1129        });
1130    Some(Part::FinSet(FinSet {
1131        count,
1132        thickness_m: values.number(&["thickness"]).unwrap_or_default(),
1133        cross_section: cross_section(values),
1134        tab: tab(values, planform.root_chord_m()),
1135        fillet,
1136        // Degrees, like every other angle in the file (see `roll_angle`). The corpus's two
1137        // non-zero cants are 1.0 and -3.98, which as radians would be 57° and 228°: a fin turned
1138        // more than half a turn from the airflow, which is not a cant anyone builds and which
1139        // OpenRocket's own roll model (Niskanen eq. 3.10, `δ` small) would not mean.
1140        cant_rad: values.number(&["cant"]).unwrap_or_default().to_radians(),
1141        base_angle_rad: roll_angle(values),
1142        material: material(values, &["material"], "bulk"),
1143        planform,
1144    }))
1145}
1146
1147/// How many straight pieces [`follow_the_body`] reads a fin's root along a nose cone or a
1148/// transition as. On the *Pods--airframes and winglets* example's cockpit, an ogive's last 50 mm,
1149/// the chord of each piece stands at most 0.14 µm inside the curve.
1150pub(super) const ROOT_PIECES: u32 = 64;
1151
1152/// A fin set's root, read where it sits ([ADR-166][adr-166]).
1153///
1154/// OpenRocket measures a fin's points from the body's surface at the root leading edge and runs
1155/// the root along the surface, so on a body tube the outline ends at `h = 0`, and on a nose cone or
1156/// a transition it ends on the surface: `h = r(x_LE + c) − r(x_LE)`. On a body tube an outline that
1157/// ends anywhere else is a fin whose trailing edge stands clear of the body, and there is no honest
1158/// way to read it as a fin that touches: closing it along the root would add planform the design
1159/// does not have. On a nose cone or a transition the root is drawn through [`ROOT_PIECES`] − 1
1160/// points on the surface, and checked as `hpr-design`'s layout checks it
1161/// ([`FinSet::root_radius_on`]), so a root this reads never fails the layout. Only a freeform fin
1162/// set placed from its parent's ends or middle, with no tab or fillet, on a body of stated radii
1163/// that does not narrow along its root, is read there; anything else says why. An automatic
1164/// radius is the layout's to resolve from the parts around it, after this reader has drawn the
1165/// root: a root drawn on the radius OpenRocket cached could stand off the surface the layout
1166/// settles on.
1167///
1168/// [adr-166]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0166-a-fin-root-that-follows-the-body.md
1169fn follow_the_body(
1170    part: Part,
1171    parent: &Part,
1172    parent_auto: &[AutoDimension],
1173    position: Position,
1174) -> Result<Part, String> {
1175    let Part::FinSet(mut fins) = part else {
1176        return Ok(part);
1177    };
1178    let surface = match parent {
1179        Part::NoseCone(nose) => nose.profile(),
1180        Part::Transition(transition) => transition.profile(),
1181        _ => {
1182            return match fins.check_level_root() {
1183                Ok(()) => Ok(Part::FinSet(fins)),
1184                Err(_) => Err(
1185                    "a freeform fin outline that does not run from the root leading \
1186                     edge to the root trailing edge. It was left out rather than closed along a \
1187                     root it never touches"
1188                        .to_owned(),
1189                ),
1190            };
1191        }
1192    };
1193    let on = spoken(parent);
1194    let automatic = parent_auto.iter().any(|dimension| {
1195        matches!(
1196            dimension,
1197            AutoDimension::BaseRadius | AutoDimension::ForeRadius | AutoDimension::AftRadius
1198        )
1199    });
1200    if automatic {
1201        return Err(format!(
1202            "a fin set on a {on} of automatic radius, whose surface the layout settles only after \
1203             this reader draws the root; it was left out"
1204        ));
1205    }
1206    let surface = surface.map_err(|e| {
1207        format!("a fin set on a {on} whose surface is unreadable ({e}); it was left out")
1208    })?;
1209    if fins.tab.is_some() || fins.fillet.is_some() {
1210        return Err(format!(
1211            "a fin set with a tab or a fillet on a {on}, which HPR Sim models only on a body tube; it \
1212             was left out"
1213        ));
1214    }
1215    let chord = fins.planform.root_chord_m();
1216    let FinPlanform::Freeform { points_m, root_m } = &mut fins.planform else {
1217        return Err(format!(
1218            "a {} fin set on a {on}. OpenRocket runs its root along the surface, which HPR Sim reads \
1219             only from a freeform outline. It was left out",
1220            match fins.planform {
1221                FinPlanform::Trapezoidal { .. } => "trapezoidal",
1222                FinPlanform::Elliptical { .. } => "elliptical",
1223                _ => "non-freeform",
1224            }
1225        ));
1226    };
1227    let length = surface.length_m();
1228    let fore = match position {
1229        Position::Top { aft_offset_m } => aft_offset_m,
1230        Position::Middle { aft_offset_m } => 0.5 * (length - chord) + aft_offset_m,
1231        Position::Bottom { aft_offset_m } => length - chord + aft_offset_m,
1232        Position::After { .. } | Position::Absolute { .. } => {
1233            return Err(format!(
1234                "a fin set on a {on} placed after its sibling or at an absolute station, where this \
1235                 reader can't find the surface its root follows. It was left out"
1236            ));
1237        }
1238    };
1239    // The layout's own slack: `length − chord + chord` can round a ulp past the end.
1240    let slack = FinSet::ROOT_ON_SURFACE_M;
1241    if !(fore >= -slack && fore + chord <= length + slack) {
1242        return Err(format!(
1243            "a fin set whose root runs past the ends of the {on} it sits on; it was left out"
1244        ));
1245    }
1246    let base = surface.radius_m(fore);
1247    let rise = |x: f64| surface.radius_m(fore + x) - base;
1248    let pieces = f64::from(ROOT_PIECES);
1249    let stations = (1..=ROOT_PIECES).map(|i| chord * f64::from(i) / pieces);
1250    if stations.clone().any(|x| rise(x) < 0.0) {
1251        return Err(format!(
1252            "a fin set on a {on} that narrows along its root, which HPR Sim reads only where the body \
1253             holds or grows. It was left out"
1254        ));
1255    }
1256    let end = points_m.last().copied().unwrap_or_default();
1257    let miss = end[1] - rise(chord);
1258    if miss.abs() > FinSet::ROOT_ON_SURFACE_M {
1259        return Err(format!(
1260            "a freeform fin outline on a {on} that ends {miss} m off its surface, where \
1261             OpenRocket's root ends; it was left out"
1262        ));
1263    }
1264    *root_m = stations
1265        .take(ROOT_PIECES as usize - 1)
1266        .map(|x| [x, rise(x)])
1267        .collect();
1268    root_m.reverse();
1269    // The layout's check, so that what this reads lays out: a root's slivers across the curve,
1270    // and anything the checks above did not foresee.
1271    fins.root_radius_on(&surface, fore).map_err(|e| {
1272        format!("a fin set on a {on} whose root can't be drawn on it ({e}); it was left out")
1273    })?;
1274    Ok(Part::FinSet(fins))
1275}
1276
1277/// A freeform fin's outline, as `[x, h]` from the root leading edge, ending at the root trailing
1278/// edge, which [`follow_the_body`] checks against the body the fin sits on.
1279fn outline(values: &mut Values<'_>, left_out: &str) -> Option<FinPlanform> {
1280    let Some(points) = values.element(&["finpoints"]) else {
1281        values.warn_at(
1282            WarningKind::Skipped,
1283            format!("a freeform fin set with no outline; it was left out{left_out}"),
1284        );
1285        return None;
1286    };
1287    let mut points_m = Vec::new();
1288    super::reads::note(points, "point");
1289    for point in points.elements().filter(|point| point.name == "point") {
1290        let read = |name: &str| {
1291            point
1292                .attribute(name)
1293                .and_then(|text| text.parse::<f64>().ok())
1294                .filter(|value| value.is_finite())
1295        };
1296        match (read("x"), read("y")) {
1297            (Some(x), Some(h)) => points_m.push([x, h]),
1298            _ => {
1299                values.warn_at(
1300                    WarningKind::Skipped,
1301                    format!(
1302                        "a freeform fin outline with a point that is not two numbers; it was left \
1303                         out{left_out}"
1304                    ),
1305                );
1306                return None;
1307            }
1308        }
1309    }
1310    if points_m.len() < 3 {
1311        values.warn_at(
1312            WarningKind::Skipped,
1313            format!(
1314                "a freeform fin outline of fewer than three points, which encloses no fin; it was \
1315                 left out{left_out}"
1316            ),
1317        );
1318        return None;
1319    }
1320    let ends_aft = matches!(points_m.last(), Some(last) if last[0] > 0.0);
1321    if points_m.first() != Some(&[0.0, 0.0]) || !ends_aft {
1322        values.warn_at(
1323            WarningKind::Skipped,
1324            format!(
1325                "a freeform fin outline that does not run from the root leading edge to the root \
1326                 trailing edge. It was left out rather than closed along a root it never \
1327                 touches{left_out}"
1328            ),
1329        );
1330        return None;
1331    }
1332    Some(FinPlanform::Freeform {
1333        points_m,
1334        root_m: Vec::new(),
1335    })
1336}
1337
1338/// The section shape along a fin's chord.
1339fn cross_section(values: &mut Values<'_>) -> FinCrossSection {
1340    match values.word(&["crosssection"]).as_deref() {
1341        Some("rounded") => FinCrossSection::Rounded,
1342        Some("airfoil") => FinCrossSection::Airfoil,
1343        None | Some("square") => FinCrossSection::Square,
1344        Some(other) => {
1345            let other = other.to_owned();
1346            values.warn_at(
1347                WarningKind::Unusual,
1348                format!("`{other}` is not a fin section this reader knows; it was read as square"),
1349            );
1350            values.forget(&["crosssection"]);
1351            FinCrossSection::Square
1352        }
1353    }
1354}
1355
1356/// The tab below a fin's root, if it has one.
1357///
1358/// OpenRocket measures the tab from the fin's front, its center or its end, saying which in
1359/// `relativeto`; `hpr-design` states one thing, the distance from the root leading edge aft to the
1360/// tab's leading edge.
1361///
1362/// **What each word measures from is read off the corpus, not a specification.** `center` is taken
1363/// as center-to-center, which is the only reading under which the corpus's eight non-zero offsets
1364/// land inside their root chords. Any other puts some of those tabs past an end of their root.
1365/// `end` is the mirror of `front` and appears in no file at all, so
1366/// that arm rests on symmetry alone.
1367fn tab(values: &mut Values<'_>, root_chord_m: f64) -> Option<FinTab> {
1368    let height_m = values.number(&["tabheight"])?;
1369    let length_m = values.number(&["tablength"]).unwrap_or_default();
1370    if height_m <= 0.0 || length_m <= 0.0 {
1371        return None;
1372    }
1373    let element = values.element(&["tabposition"]);
1374    let relative_to = element
1375        .and_then(|element| element.attribute("relativeto"))
1376        .unwrap_or("front")
1377        .to_owned();
1378    let offset_m = values.number(&["tabposition"]).unwrap_or_default();
1379    let offset_m = match relative_to.as_str() {
1380        // OpenRocket writes `<tabposition>` twice, the newer name's frame first. The older
1381        // vocabulary is the same three places under the names the axial offset uses, and across
1382        // the reference library the two elements always carry the same number, so either spelling
1383        // means the same tab.
1384        "front" | "top" => offset_m,
1385        "center" | "middle" => 0.5 * (root_chord_m - length_m) + offset_m,
1386        "end" | "bottom" => root_chord_m - length_m + offset_m,
1387        other => {
1388            values.warn_at(
1389                WarningKind::Unusual,
1390                format!(
1391                    "a fin tab measured from `{other}`, which this reader does not know; it was \
1392                     read from the root leading edge"
1393                ),
1394            );
1395            values.forget(&["tabposition"]);
1396            offset_m
1397        }
1398    };
1399    // A tab past either end of the root is read as the file states it, as OpenRocket 24.12
1400    // weighs it (ADR-309).
1401    Some(FinTab {
1402        height_m,
1403        length_m,
1404        offset_m,
1405    })
1406}
1407
1408/// OpenRocket 24.12 reads a tube fin set of more than this many tubes as this many, whether its
1409/// radius is stated or `auto`: 9, 12, 20 and 100 all read as 8 on its probes (ADR-098).
1410const MOST_TUBE_FINS: u32 = 8;
1411
1412/// A ring of tubes around the body. An `auto` radius is the one at which the tubes close the ring
1413/// around the body tube, which the layout resolves (`AutoDimension::OuterRadius`, ADR-098).
1414fn tube_fins(
1415    values: &mut Values<'_>,
1416    auto: &mut Vec<AutoDimension>,
1417    left_out: &str,
1418) -> Option<Part> {
1419    let (stated_m, outer_radius_m) =
1420        stated_radius(values, &["radius"], AutoDimension::OuterRadius, auto);
1421    let thickness_m = tube_wall(values, stated_m, left_out)?;
1422    // The count is read once, and capped before `MOST_INSTANCES` could leave the set out, so that
1423    // a count past it reads as 8 too, as OpenRocket reads 100 on its probe.
1424    let count = match values.count(&INSTANCE_COUNT).unwrap_or(1) {
1425        0 => {
1426            values.warn_at(
1427                WarningKind::Skipped,
1428                format!("a tube fin set of none; it was left out, and {NOTHING_DEPENDS}"),
1429            );
1430            return None;
1431        }
1432        written if written > MOST_TUBE_FINS => {
1433            values.warn_at(
1434                WarningKind::Dropped,
1435                format!(
1436                    "a tube fin set of {written} tubes; OpenRocket 24.12 reads at most \
1437                     {MOST_TUBE_FINS}, so it was read as {MOST_TUBE_FINS}"
1438                ),
1439            );
1440            values.forget(&INSTANCE_COUNT);
1441            MOST_TUBE_FINS
1442        }
1443        written => written,
1444    };
1445    Some(Part::TubeFinSet(TubeFinSet {
1446        count,
1447        length_m: values.number(&["length"]).unwrap_or_default(),
1448        outer_radius_m,
1449        thickness_m,
1450        base_angle_rad: roll_angle(values),
1451        material: material(values, &["material"], "bulk"),
1452    }))
1453}
1454
1455/// A launch lug, or a row of them.
1456fn launch_lug(values: &mut Values<'_>, left_out: &str) -> Option<Part> {
1457    let mut auto = Vec::new();
1458    let (stated_m, outer_radius_m) =
1459        stated_radius(values, &["radius"], AutoDimension::OuterRadius, &mut auto);
1460    if stated_m.is_none() {
1461        // A lug has no automatic radius in `hpr-design`, and the number OpenRocket cached is the
1462        // rod it last had, which may not be this one's. Reading it would put a stated radius where
1463        // the file says "work it out", and a bare `auto` would leave a lug of no radius that the
1464        // layout refuses, taking the whole design with it. No lug in the reference library is
1465        // written this way.
1466        values.warn_at(
1467            WarningKind::Skipped,
1468            format!(
1469                "a launch lug whose radius OpenRocket works out for itself; HPR Sim does not \
1470                 resolve that, so it was left out{left_out}"
1471            ),
1472        );
1473        return None;
1474    }
1475    let thickness_m = tube_wall(values, stated_m, left_out)?;
1476    let (count, spacing_m) = row(values, "row of launch lugs", left_out)?;
1477    Some(Part::LaunchLug(LaunchLug {
1478        length_m: values.number(&["length"]).unwrap_or_default(),
1479        outer_radius_m,
1480        thickness_m,
1481        angle_rad: roll_angle(values),
1482        count,
1483        spacing_m,
1484        material: material(values, &["material"], "bulk"),
1485    }))
1486}
1487
1488/// A rail button, or a row of them.
1489fn rail_button(values: &mut Values<'_>, left_out: &str) -> Option<Part> {
1490    let (count, spacing_m) = row(values, "row of rail buttons", left_out)?;
1491    Some(Part::RailButton(RailButton {
1492        outer_diameter_m: values.number(&["outerdiameter"]).unwrap_or_default(),
1493        inner_diameter_m: values.number(&["innerdiameter"]).unwrap_or_default(),
1494        height_m: values.number(&["height"]).unwrap_or_default(),
1495        base_height_m: values.number(&["baseheight"]).unwrap_or_default(),
1496        flange_height_m: values.number(&["flangeheight"]).unwrap_or_default(),
1497        screw_height_m: values.number(&["screwheight"]).unwrap_or_default(),
1498        angle_rad: roll_angle(values),
1499        count,
1500        spacing_m,
1501        material: material_or(values, &["material"], "bulk", UNNAMED_RAIL_BUTTON),
1502    }))
1503}
1504
1505/// A lump of mass with no geometry of its own beyond how it is packed.
1506fn mass_component(values: &mut Values<'_>, auto: &mut Vec<AutoDimension>) -> Option<Part> {
1507    Some(Part::MassComponent(MassComponent {
1508        mass_kg: values.number(&["mass"]).unwrap_or_default(),
1509        packing: packing(values, auto),
1510    }))
1511}
1512
1513/// A parachute: a canopy of fabric on a set of shroud lines, packed into the body.
1514fn parachute(values: &mut Values<'_>, auto: &mut Vec<AutoDimension>) -> Option<Part> {
1515    Some(Part::Parachute(Parachute {
1516        diameter_m: values.number(&["diameter"]).unwrap_or_default(),
1517        canopy_material: material(values, &["material"], "surface"),
1518        line_count: values.count(&["linecount"]).unwrap_or_default(),
1519        line_length_m: values.number(&["linelength"]).unwrap_or_default(),
1520        line_material: material(values, &["linematerial"], "line"),
1521        packing: packing(values, auto),
1522    }))
1523}
1524
1525/// A streamer: a strip of fabric, packed into the body.
1526fn streamer(values: &mut Values<'_>, auto: &mut Vec<AutoDimension>) -> Option<Part> {
1527    Some(Part::Streamer(Streamer {
1528        length_m: values.number(&["striplength"]).unwrap_or_default(),
1529        width_m: values.number(&["stripwidth"]).unwrap_or_default(),
1530        material: material(values, &["material"], "surface"),
1531        packing: packing(values, auto),
1532    }))
1533}
1534
1535/// A shock cord, packed into the body.
1536fn shock_cord(values: &mut Values<'_>, auto: &mut Vec<AutoDimension>) -> Option<Part> {
1537    Some(Part::ShockCord(ShockCord {
1538        length_m: values.number(&["cordlength"]).unwrap_or_default(),
1539        material: material(values, &["material"], "line"),
1540        packing: packing(values, auto),
1541    }))
1542}
1543
1544/// The packed length OpenRocket 24.12 gives a mass component, parachute, streamer or shock cord
1545/// whose file writes no `packedlength`, in meters: 25 mm.
1546///
1547/// No document states it, so it was measured ([ADR-063][adr-063]): on probe designs of each kind
1548/// written with no packed size, and a parachute written with only one of the two, OpenRocket's
1549/// center of mass and inertias are those of a solid cylinder this long, from the part's position
1550/// aft, and [`PACKED_RADIUS_M`] in radius, whichever of the two is missing
1551/// (`validation/oracles/openrocket/conventions.py`).
1552///
1553/// [adr-063]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-063-packed-parts-read-and-weighed-as-openrocket-packs-them-2026-09-21
1554const PACKED_LENGTH_M: f64 = 0.025;
1555
1556/// The packed radius OpenRocket 24.12 gives a packed part whose file writes no `packedradius`, in
1557/// meters: 12.5 mm, a fixed number, not the tube's bore. Measured as [`PACKED_LENGTH_M`] is.
1558const PACKED_RADIUS_M: f64 = 0.0125;
1559
1560/// How a mass object or a recovery part is packed: the cylinder it takes up inside the body. A size
1561/// the file does not write is OpenRocket's ([`PACKED_LENGTH_M`], [`PACKED_RADIUS_M`]), read with no
1562/// warning, as [ADR-061][adr-061] reads what else a file leaves unsaid (a wall of no thickness, no
1563/// material): that is what the file means, not a guess.
1564///
1565/// [adr-061]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-061-what-a-ork-leaves-unsaid-read-as-openrocket-reads-it-overrides-measured-two-departures-kept-2026-09-21
1566fn packing(values: &mut Values<'_>, auto: &mut Vec<AutoDimension>) -> Packing {
1567    let radius_m = if values.element(&["packedradius"]).is_none() {
1568        PACKED_RADIUS_M
1569    } else {
1570        stated_radius(values, &["packedradius"], AutoDimension::PackedRadius, auto).1
1571    };
1572    let length_m = if values.element(&["packedlength"]).is_none() {
1573        PACKED_LENGTH_M
1574    } else {
1575        values.number(&["packedlength"]).unwrap_or_default()
1576    };
1577    Packing {
1578        length_m,
1579        radius_m,
1580        radial_offset_m: values.number(&["radialposition"]).unwrap_or_default(),
1581        angle_rad: roll_angle(values),
1582    }
1583}
1584
1585/// How many of an instanced part there are, and how far apart they sit along the body. `None` when
1586/// the file asks for more than [`MOST_INSTANCES`].
1587fn row(values: &mut Values<'_>, what: &str, left_out: &str) -> Option<(u32, f64)> {
1588    let count = instances(values, what, left_out)?;
1589    Some((
1590        count.max(1),
1591        values.number(&["instanceseparation"]).unwrap_or_default(),
1592    ))
1593}
1594
1595/// How many of a part the file says there are, refusing a count no rocket has and a file could
1596/// only give by accident or on purpose, with a warning that ends in `left_out`
1597/// ([`and_what_was_inside`]). See [`MOST_INSTANCES`].
1598fn instances(values: &mut Values<'_>, what: &str, left_out: &str) -> Option<u32> {
1599    let count = values.count(&INSTANCE_COUNT).unwrap_or(1);
1600    if count == 0 {
1601        let what = what.to_owned();
1602        values.warn_at(
1603            WarningKind::Skipped,
1604            format!("a {what} of none; it was left out, and {NOTHING_DEPENDS}"),
1605        );
1606        return None;
1607    }
1608    if count > MOST_INSTANCES {
1609        let what = what.to_owned();
1610        values.warn_at(
1611            WarningKind::Skipped,
1612            format!(
1613                "a {what} of {count}, where HPR Sim builds each one and adds them up; it was left \
1614                 out rather than asked for{left_out}"
1615            ),
1616        );
1617        return None;
1618    }
1619    Some(count)
1620}
1621
1622/// Says so when a part is written more than once and `hpr-design` models one of it.
1623fn instanced_once(values: &mut Values<'_>, what: &str) {
1624    if values.count(&INSTANCE_COUNT).is_some_and(|count| count > 1) {
1625        let what = what.to_owned();
1626        values.warn_at(
1627            WarningKind::Dropped,
1628            format!("a row of more than one {what} was read as the one it is written as"),
1629        );
1630        values.forget(&INSTANCE_COUNT);
1631    }
1632}
1633
1634/// Says so when a part that `hpr-design` keeps on the axis is written off it.
1635fn off_the_axis(values: &mut Values<'_>, what: &str) {
1636    if values
1637        .number(&["radialposition"])
1638        .is_some_and(|offset| offset != 0.0)
1639    {
1640        let what = what.to_owned();
1641        values.warn_at(
1642            WarningKind::Dropped,
1643            format!("a {what} off the body axis was read on it; HPR Sim keeps one on the axis"),
1644        );
1645        values.forget(&["radialposition"]);
1646    }
1647}
1648
1649/// Says so when an external part is written standing off the body's surface.
1650///
1651/// OpenRocket measures a fin's or a lug's radius from the surface (`method="surface"`), or, for
1652/// tube fins, from the body it wraps (`"coaxial"`). `hpr-design` sits every external part on the
1653/// surface, so any offset but zero is a standoff it does not model. Every one of the 95 written in
1654/// the reference corpus is zero.
1655fn radial_offset_on_the_surface(values: &mut Values<'_>, part: &Part) {
1656    if !part.is_external() {
1657        return;
1658    }
1659    if values
1660        .number(&["radiusoffset"])
1661        .is_some_and(|offset| offset != 0.0)
1662    {
1663        let kind = spoken(part);
1664        values.warn_at(
1665            WarningKind::Dropped,
1666            format!("a {kind} standing off the body was read sitting on it"),
1667        );
1668        values.forget(&["radiusoffset"]);
1669    }
1670}
1671
1672/// Where a part sits along its parent.
1673///
1674/// The offset and the end it is measured from are one tag: `<axialoffset method="bottom">` on the
1675/// newer name, `<position type="bottom">` on the older, with the same five words. A part with
1676/// neither is read flush with its parent's forward end, which is what OpenRocket's own default is
1677/// for everything but a fin set; one tube coupler in the reference corpus is written that way.
1678fn position(values: &mut Values<'_>) -> Position {
1679    let Some(element) = values.element(&AXIAL_OFFSET) else {
1680        values.warn_at(
1681            WarningKind::Unusual,
1682            "no axial offset at all; the part was read flush with its parent's forward end",
1683        );
1684        return Position::Top { aft_offset_m: 0.0 };
1685    };
1686    let from = element
1687        .attribute("method")
1688        .or_else(|| element.attribute("type"))
1689        .unwrap_or("top")
1690        .to_owned();
1691    // From the element already found, not a second lookup: asking `Values` again would run the
1692    // two-name comparison a second time and warn twice about one disagreement.
1693    let text = element.text();
1694    let aft_offset_m = match text.trim().parse::<f64>() {
1695        Ok(value) if value.is_finite() => value,
1696        _ => {
1697            let (name, text) = (element.name.clone(), text.trim().to_owned());
1698            values.warn_at(
1699                WarningKind::Dropped,
1700                format!("`{name}` says `{text}`, which is not a number; it was read as zero"),
1701            );
1702            values.forget(&AXIAL_OFFSET);
1703            0.0
1704        }
1705    };
1706    match from.as_str() {
1707        "top" => Position::Top { aft_offset_m },
1708        "middle" => Position::Middle { aft_offset_m },
1709        "bottom" => Position::Bottom { aft_offset_m },
1710        "after" => Position::After { aft_offset_m },
1711        "absolute" => Position::Absolute {
1712            station_m: aft_offset_m,
1713        },
1714        other => {
1715            values.warn_at(
1716                WarningKind::Unusual,
1717                format!(
1718                    "an axial offset measured from `{other}`, which this reader does not know; it \
1719                     was read from the parent's forward end"
1720                ),
1721            );
1722            values.forget(&AXIAL_OFFSET);
1723            Position::Top { aft_offset_m }
1724        }
1725    }
1726}
1727
1728/// Where `hpr-design` must put a rail button's forward edge for its center to be where OpenRocket
1729/// puts it.
1730///
1731/// OpenRocket 24.12 gives a rail button no length, so it places the button's center where a part of
1732/// no length would sit, from whichever end the offset is measured, and a row's first button there,
1733/// the rest following aft (#151; measured on `validation/oracles/openrocket/conventions.py`'s
1734/// probes: from the top, the middle and the bottom, one button and a row of two). `hpr-design`
1735/// puts a part's forward edge, middle or aft edge on the position (from the top, after a part or
1736/// absolute; the middle; the bottom) and gives a row the length from the first button's forward
1737/// edge to the last one's aft edge, so the offset moves by the difference.
1738fn centered_on_its_position(position: Position, button: &RailButton) -> Position {
1739    let radius_m = 0.5 * button.outer_diameter_m;
1740    let row_m = button.spacing_m * f64::from(button.count.saturating_sub(1));
1741    match position {
1742        Position::Top { aft_offset_m } => Position::Top {
1743            aft_offset_m: aft_offset_m - radius_m,
1744        },
1745        Position::Middle { aft_offset_m } => Position::Middle {
1746            aft_offset_m: aft_offset_m + 0.5 * row_m,
1747        },
1748        Position::Bottom { aft_offset_m } => Position::Bottom {
1749            aft_offset_m: aft_offset_m + radius_m + row_m,
1750        },
1751        Position::After { aft_offset_m } => Position::After {
1752            aft_offset_m: aft_offset_m - radius_m,
1753        },
1754        Position::Absolute { station_m } => Position::Absolute {
1755            station_m: station_m - radius_m,
1756        },
1757    }
1758}
1759
1760/// OpenRocket's regular paint, `normal`, and its finish for an outside part that states none, in
1761/// meters ([`finish`]).
1762const REGULAR_PAINT_M: f64 = 60e-6;
1763
1764/// The surface finish, as a roughness height.
1765///
1766/// OpenRocket writes one of five words. What each is worth in micrometers is not in the file
1767/// format documentation; the numbers below are from the program's author, on The Rocketry Forum
1768/// (thread "Open Rocket Finishes", post #6, 22 August 2013):
1769///
1770/// | word | OpenRocket's name for it | roughness |
1771/// | --- | --- | --- |
1772/// | `rough` | Rough | 500 µm |
1773/// | `unfinished` | Unfinished | 150 µm |
1774/// | `normal` | Regular paint | 60 µm |
1775/// | `smooth` | Smooth paint | 20 µm |
1776/// | `polished` | Polished | 2 µm |
1777///
1778/// The default, `normal`, is confirmed twice over: the [OpenRocket technical documentation][doc]
1779/// section 6 says "the 'regular paint' finish was selected, which corresponds to an average
1780/// surface roughness of 60 µm", and the user guide's body-tube dialog reads "Regular paint
1781/// (2.36 mil)", which is 59.9 µm. The guide's [`.ork` page][guide] has the rest, including what is
1782/// not settled about `polished`.
1783///
1784/// **An outside part with no finish, or one of a word not in the table, is read as regular paint,
1785/// 60 µm,** as OpenRocket reads it ([issue #216][216]). Run on its 17 bundled example designs with
1786/// every `<finish>` taken out (`validation/oracles/openrocket/finish.py`, run 2026-10-25; it
1787/// writes nothing), OpenRocket 24.12 reports `Regular paint (60 µm)` and a roughness of
1788/// `6e-05` m (`getFinish`, `getRoughnessSize`) for all 134 outside parts: nose cones, body tubes,
1789/// transitions, the three kinds of fin set, tube fins, launch lugs and rail buttons. With the word
1790/// `gilt` in place of each finish it reports the same. The parts inside the body have no finish in
1791/// OpenRocket, and are left without one here. The 60 µm is OpenRocket's choice, not a measured
1792/// hobby finish ([finish roughness note][note]).
1793///
1794/// [doc]: https://openrocket.sourceforge.net/techdoc.pdf
1795/// [guide]: https://hpr.fusionspace.co/format/ork.html
1796/// [216]: https://github.com/nrdptel/fusionspace-eridanus/issues/216
1797/// [note]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/research/hobby-finish-roughness.md
1798pub(super) fn finish(values: &mut Values<'_>, outside: bool) -> Option<Finish> {
1799    let default = outside.then_some(Finish::Custom {
1800        roughness_m: REGULAR_PAINT_M,
1801    });
1802    let Some(word) = values.word(&["finish"]) else {
1803        return default;
1804    };
1805    let roughness_m = match word.as_str() {
1806        "rough" => 500e-6,
1807        "unfinished" => 150e-6,
1808        "normal" => REGULAR_PAINT_M,
1809        "smooth" => 20e-6,
1810        "polished" => 2e-6,
1811        other => {
1812            let other = other.to_owned();
1813            values.warn_at(
1814                WarningKind::Unusual,
1815                format!(
1816                    "`{other}` is not a surface finish this reader has a roughness for; the part \
1817                     took {}",
1818                    if outside {
1819                        "OpenRocket's, regular paint (60 µm)"
1820                    } else {
1821                        "none"
1822                    }
1823                ),
1824            );
1825            values.forget(&["finish"]);
1826            return default;
1827        }
1828    };
1829    Some(Finish::Custom { roughness_m })
1830}
1831
1832/// A part's roll angle around the body, in radians.
1833///
1834/// **`.ork` angles are degrees.** Nothing in the file says so, and every length beside them is in
1835/// meters, so reading one as radians is an easy mistake: `<angleoffset>180</angleoffset>` would be
1836/// more than twenty-eight turns instead of half of one. The corpus settles it. Of the 993 angles
1837/// written in it, 188 are not zero, and **178 of those are larger than 2π**: more than a whole
1838/// turn, which no component is written at. The values themselves are 180, 90, 45, 30 and 120, with
1839/// float dust (`119.99999999999999`) from a conversion that went through radians and back.
1840/// `cargo xtask ork` prints all three counts.
1841///
1842/// OpenRocket writes the angle under a newer name, `angleoffset`, and an older one: `rotation` on
1843/// a fin set, `radialdirection` on everything else. Those are **not** read as one tag by
1844/// [`Values::element`]: the newer name carries a `method` attribute that the older never does, and
1845/// [ADR-052][adr] left the pair alone for want of a source saying what the older name's frame is.
1846/// What settles it here is narrower than that question and enough for it: on the 95 fin sets and
1847/// 26 other parts of the reference corpus that carry both names, the two agree on the **number**
1848/// every time, so which one is read cannot change an angle. The frames (`relative` to the parent
1849/// and `fixed` in the rocket) are the same angle for every parent this reader builds, because all
1850/// of them sit on the rocket's own axis. A pod set hangs from a body tube, on the axis too, and
1851/// OpenRocket 24.12 places its pods alike for `relative`, `fixed` and `mirror_xy` ([`pod_set`]).
1852///
1853/// **Which way the angle turns is assumed, not sourced.** `docs/physics/frames.md` measures a roll
1854/// angle from `x_B` toward `y_B`, right-handed about `+z_B`, which points at the nose; OpenRocket's
1855/// technical documentation (§3.1.4) puts its own `+x` along the centerline pointing *aft* and
1856/// leaves the other two axes unstated. A right-handed angle about an aft-pointing axis is a
1857/// left-handed one about `+z_B`, so if OpenRocket means that, every angle read here is mirrored:
1858/// a mass object at 90° sits on the other side, and a canted fin set rolls the other way. Nothing
1859/// in the corpus can settle it, because a mirrored design is still a valid design; one asymmetric
1860/// design through the OpenRocket oracle (M2.2) will. Until then this reader takes the number
1861/// unchanged, and the guide lists it among the readings that are not settled.
1862///
1863/// [adr]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md
1864fn roll_angle(values: &mut Values<'_>) -> f64 {
1865    let newer = values.number(&["angleoffset"]);
1866    let older = values
1867        .number(&["rotation"])
1868        .or_else(|| values.number(&["radialdirection"]));
1869    if let (Some(newer), Some(older)) = (newer, older)
1870        && newer != older
1871    {
1872        values.warn_at(
1873            WarningKind::Dropped,
1874            format!(
1875                "`angleoffset` says `{newer}` and the older name says `{older}`; they are two \
1876                 names for one angle, so `angleoffset` was taken"
1877            ),
1878        );
1879        values.forget(&["rotation", "radialdirection"]);
1880    }
1881    newer.or(older).unwrap_or_default().to_radians()
1882}
1883
1884#[cfg(test)]
1885mod tests {
1886    use super::*;
1887    use hpr_design::Material;
1888
1889    /// Each of OpenRocket's fourteen cluster patterns, written here as the figure it is, is the
1890    /// list of points OpenRocket 24.12 gives for it, in its order, to 1e-15; and there is no other
1891    /// (`validation/fixtures/ork/openrocket-clusters.json`).
1892    #[test]
1893    fn cluster_patterns_are_openrocket_s_points() {
1894        let text = include_str!("../../../../validation/fixtures/ork/openrocket-clusters.json");
1895        let record: serde_json::Value = serde_json::from_str(text).unwrap();
1896        let patterns = record["patterns"].as_object().unwrap();
1897        assert_eq!(patterns.len(), 14);
1898        for (name, pattern) in patterns {
1899            let theirs: Vec<f64> = pattern["points"]
1900                .as_array()
1901                .unwrap()
1902                .iter()
1903                .map(|v| v.as_f64().unwrap())
1904                .collect();
1905            let ours = cluster_pattern(name).unwrap_or_else(|| panic!("no pattern {name}"));
1906            assert_eq!(pattern["count"].as_u64(), Some(ours.len() as u64), "{name}");
1907            assert_eq!(theirs.len(), 2 * ours.len(), "{name}");
1908            for (k, [x, y]) in ours.iter().enumerate() {
1909                let apart = (x - theirs[2 * k]).hypot(y - theirs[2 * k + 1]);
1910                assert!(apart <= 1e-15, "{name} point {k}: {x}, {y}");
1911            }
1912        }
1913        assert_eq!(cluster_pattern("4-square"), None);
1914    }
1915
1916    /// A row of two 10 mm buttons 0.1 m apart: its first button's center must land where OpenRocket
1917    /// puts it, a part of no length placed by the same words, whichever end the offset is from.
1918    /// hpr's row runs from the first button's forward edge, 5 mm ahead of its center, and is
1919    /// 0.11 m long.
1920    #[test]
1921    fn a_rail_button_row_is_placed_by_its_first_center() {
1922        let button = RailButton {
1923            outer_diameter_m: 0.01,
1924            inner_diameter_m: 0.006,
1925            height_m: 0.008,
1926            base_height_m: 0.002,
1927            flange_height_m: 0.002,
1928            screw_height_m: 0.0,
1929            angle_rad: 0.0,
1930            count: 2,
1931            spacing_m: 0.1,
1932            material: Material::bulk("Probe", 1000.0),
1933        };
1934        let cases = [
1935            // top 0.1: the forward edge 5 mm ahead.
1936            (
1937                Position::Top { aft_offset_m: 0.1 },
1938                Position::Top {
1939                    aft_offset_m: 0.095,
1940                },
1941            ),
1942            // middle 0: the first center on the middle, so the row's middle 0.05 m aft of it.
1943            (
1944                Position::Middle { aft_offset_m: 0.0 },
1945                Position::Middle { aft_offset_m: 0.05 },
1946            ),
1947            // bottom −0.1: the first center 0.1 m above the end, the row's aft edge 5 mm past
1948            // the last center, which is 0.1 m further aft.
1949            (
1950                Position::Bottom { aft_offset_m: -0.1 },
1951                Position::Bottom {
1952                    aft_offset_m: 0.005,
1953                },
1954            ),
1955            (
1956                Position::After { aft_offset_m: 0.02 },
1957                Position::After {
1958                    aft_offset_m: 0.015,
1959                },
1960            ),
1961            (
1962                Position::Absolute { station_m: 1.0 },
1963                Position::Absolute { station_m: 0.995 },
1964            ),
1965        ];
1966        for (read, placed) in cases {
1967            let found = centered_on_its_position(read, &button);
1968            let offset = |position: &Position| match *position {
1969                Position::Top { aft_offset_m }
1970                | Position::Middle { aft_offset_m }
1971                | Position::Bottom { aft_offset_m }
1972                | Position::After { aft_offset_m } => aft_offset_m,
1973                Position::Absolute { station_m } => station_m,
1974            };
1975            assert_eq!(
1976                std::mem::discriminant(&found),
1977                std::mem::discriminant(&placed),
1978                "{read:?}"
1979            );
1980            assert!(
1981                (offset(&found) - offset(&placed)).abs() < 1e-15,
1982                "{read:?}: {found:?}"
1983            );
1984        }
1985    }
1986
1987    /// A tube is sized from only when a centering ring beside it takes its bore automatically,
1988    /// and a ring with a bore of its own sizes nothing. Which ring sizes from a tube is settled
1989    /// once for the list of siblings, and each part then asks only whether it is a tube
1990    /// (`sized_from` takes no siblings), so a list of many tubes beside a ring costs one pass over
1991    /// it, not one per tube (#952).
1992    #[test]
1993    fn a_tube_is_sized_from_only_beside_a_ring_with_an_automatic_bore() {
1994        let sized = |inside: &str| {
1995            let text = format!(
1996                r#"<openrocket version="1.10"><subcomponents>{inside}</subcomponents></openrocket>"#
1997            );
1998            let root = super::super::document::Document::parse(&text)
1999                .expect("the test text parses")
2000                .value
2001                .root;
2002            let siblings: Vec<&Element> = subcomponents(&root).collect();
2003            let ring = sizes_a_ring(&siblings);
2004            let sized: Vec<bool> = siblings
2005                .iter()
2006                .map(|child| sized_from(child, ring))
2007                .collect();
2008            (ring, sized)
2009        };
2010        let tubes = "<innertube/><tubecoupler/><engineblock/><masscomponent/>";
2011        assert_eq!(
2012            sized(&format!(
2013                "{tubes}<centeringring><innerradius>auto</innerradius></centeringring>"
2014            )),
2015            (true, vec![true, true, true, false, false])
2016        );
2017        assert_eq!(
2018            sized(&format!(
2019                "{tubes}<centeringring><innerradius>0.01</innerradius></centeringring>"
2020            )),
2021            (false, vec![false; 5])
2022        );
2023        assert_eq!(
2024            sized(&format!(
2025                "{tubes}<bulkhead><innerradius>auto</innerradius></bulkhead>"
2026            )),
2027            (false, vec![false; 5])
2028        );
2029        assert_eq!(sized(tubes), (false, vec![false; 4]));
2030    }
2031}