hpr_io/ork/component.rs
1//! The spine of a design: its stages and the body components stacked inside them.
2//!
3//! A `.ork` design is a tree. Its trunk is the **spine**: the stages, and inside each of them the
4//! nose cones, body tubes and transitions that stack end to end along the axis. Everything else
5//! hangs off that trunk and is read by [`super::attached`]: the tubes and rings inside the body,
6//! the fins and lugs on it, the recovery gear.
7//!
8//! What this module does is turn the spine into [`hpr_design`] types: a [`Rocket`] of [`Stage`]s of
9//! [`Component`]s, each of them carrying whatever [`super::attached`] read inside and on it. It
10//! resolves nothing itself. Where OpenRocket wrote `auto`, the component carries an
11//! [`AutoDimension`] and [`Rocket::layout`] works the radius out from the neighbors, which is the
12//! one place that rule lives. The one exception is a radius that rule cannot reach (a chain of
13//! automatic radii with no fixed radius anywhere along it), which takes OpenRocket's default,
14//! [`OPENROCKET_DEFAULT_RADIUS_M`], because the design holds no other number for it.
15//!
16//! [roadmap]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/ROADMAP.md
17
18use hpr_design::parts::{BodyTube, NoseCone, Shoulder, Transition};
19use hpr_design::shapes::NoseShape;
20use hpr_design::solids::Wall;
21use hpr_design::tree::{
22 AddedMass, AutoDimension, Component, DragOverride, Overrides, Part, ReferenceDiameter, Rocket,
23 Stage, StageOverrideRule,
24};
25use hpr_design::{Material, MotorMount};
26
27use super::attached::{self, Parent, Unread, finish};
28use super::document::{Document, Element};
29use super::left_out::{Around, Covered, Lean, spoken};
30use super::motors::{self, MountRead};
31use super::recovery::{self, DeviceRead, SeparationRead};
32use super::value::{OVERRIDE_FLAGS, Values};
33use super::warning::{Imported, Warning, WarningKind};
34
35/// The body tags this milestone reads. Anything else in a `<subcomponents>` is counted and left.
36pub(super) const BODY_TAGS: [&str; 3] = ["nosecone", "bodytube", "transition"];
37
38/// A filled tube whose automatic radius cached a number, read as solid to that number.
39const FILLED_TO_CACHE: &str = "a filled tube whose radius is automatic; it was read as solid to \
40 the radius OpenRocket last worked out, which may be stale";
41
42/// A filled tube whose automatic radius cached nothing, so it has no radius to be solid to.
43const FILLED_TO_NOTHING: &str = "a filled tube whose radius is automatic and nothing cached. It \
44 carries no mass, because there is no radius to fill until the \
45 layout resolves one";
46
47/// What a body component was read from: where it is in the file, and for a body tube the wall as
48/// the file wrote it, before any radius was known to judge it against.
49struct BodyRead {
50 at: String,
51 wall: Option<Wall>,
52}
53
54/// The radius OpenRocket gives an automatic body radius that has no fixed radius anywhere along its
55/// chain to take, in meters: its **default radius**, 25 mm.
56///
57/// OpenRocket's maintainers write that such a radius is "the default radius"
58/// ([openrocket#1988](https://github.com/openrocket/openrocket/issues/1988#issuecomment-1397654629))
59/// and that a tube left with nothing to take "reverts to default diameter"
60/// ([#1992](https://github.com/openrocket/openrocket/issues/1992)); a user guesses that default at
61/// "1.969 in" of diameter ([#871](https://github.com/openrocket/openrocket/issues/871)), which is
62/// 50.0 mm. No document states the number, so it was measured: OpenRocket 24.12, run on fifteen
63/// small designs by `validation/oracles/openrocket/automatic_radius.py`, settles every such tube,
64/// lone nose cone and lone transition at 0.025 m and ignores any number cached after `auto`
65/// (`validation/fixtures/ork/openrocket-automatic-radius.json`, [ADR-054][adr-054]).
66///
67/// HPR Sim departs from OpenRocket in one place, on purpose: where a nose cone's base or a transition's
68/// end looks at another automatic radius, OpenRocket 24.12 settles on −1 m, which no geometry can
69/// take. HPR Sim gives it this default too, so the chain is one radius end to end.
70///
71/// [adr-054]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-054-an-automatic-radius-with-nothing-to-take-is-openrockets-default-and-a-rocket-with-no-stage-or-component-holds-no-design-2026-09-20
72pub const OPENROCKET_DEFAULT_RADIUS_M: f64 = 0.025;
73
74/// Reads a design document into a [`Rocket`]: its stages, the body components stacked in them, and
75/// the parts on and inside each of those.
76///
77/// Never fails: a tag it cannot read is left out with a [`Warning`], so a design written by another
78/// program still opens. The result is a [`Rocket`] whose body components are in file order, forward
79/// to aft, with automatic dimensions **marked rather than filled in**: [`Rocket::layout`] resolves
80/// them, and is where a part's mass and station come from.
81///
82/// A body tube or inner tube that holds a motor is marked as a motor mount, but the motors
83/// themselves are not read here, and [`Rocket::configurations`] is left empty:
84/// [`super::design`] reads them. A `<motormount>` it cannot read still warns here.
85///
86/// ```
87/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
88/// let xml = br#"<?xml version="1.0" encoding="UTF-8"?>
89/// <openrocket version="1.10" creator="OpenRocket 24.12">
90/// <rocket><name>Sounder</name><subcomponents><stage><name>Sustainer</name><id>s</id>
91/// <subcomponents>
92/// <nosecone><name>Nose</name><id>nose</id><finish>smooth</finish>
93/// <material type="bulk" density="680.0">Cardboard</material>
94/// <length>0.3</length><thickness>0.002</thickness>
95/// <shape>ogive</shape><shapeparameter>1.0</shapeparameter>
96/// <aftradius>0.05</aftradius></nosecone>
97/// <bodytube><name>Tube</name><id>tube</id>
98/// <material type="bulk" density="680.0">Cardboard</material>
99/// <length>0.6</length><thickness>0.002</thickness><radius>0.05</radius>
100/// <subcomponents>
101/// <centeringring><name>Ring</name><id>ring</id>
102/// <material type="bulk" density="680.0">Plywood</material>
103/// <axialoffset method="bottom">0.0</axialoffset><length>0.005</length>
104/// <outerradius>auto</outerradius><innerradius>0.019</innerradius></centeringring>
105/// </subcomponents></bodytube>
106/// </subcomponents></stage></subcomponents></rocket>
107/// </openrocket>"#;
108///
109/// let read = hpr_io::ork::read(xml)?;
110/// let design = hpr_io::ork::rocket(&read.value.document);
111///
112/// // Anything the reader could not take at face value travels with the result. Nothing here did.
113/// assert!(design.warnings.is_empty(), "{:?}", design.warnings);
114///
115/// // The ring's outer radius says `auto`, so the design carries the dimension, not a number...
116/// use hpr_design::AutoDimension;
117/// let ring = &design.value.stages[0].components[1].children[0];
118/// assert!(ring.auto.contains(&AutoDimension::OuterRadius));
119///
120/// // ...and the layout works it out: the bore of the tube the ring sits in, 0.05 - 0.002.
121/// let layout = design.value.layout()?;
122/// let (_, placed) = layout.find("ring").expect("the ring");
123/// let hpr_design::Part::CenteringRing(ring) = &placed.part else { panic!("a ring") };
124/// assert!((ring.outer_radius_m - 0.048).abs() < 1e-12);
125/// assert!(placed.own.mass_kg > 0.0);
126/// # Ok(())
127/// # }
128/// ```
129pub fn rocket(document: &Document) -> Imported<Rocket> {
130 walk(document).0
131}
132
133/// [`rocket`], and every motor mount, recovery device and stage separation it read, for
134/// [`super::motors::read`] and [`super::recovery::read`].
135pub(super) fn walk(document: &Document) -> (Imported<Rocket>, Walked) {
136 let mut warnings = Vec::new();
137 let mut rocket = Rocket {
138 name: String::new(),
139 stages: Vec::new(),
140 reference_diameter: ReferenceDiameter::default(),
141 configurations: Vec::new(),
142 };
143 let Some(element) = document.root.child("rocket") else {
144 warnings.push(Warning::new(
145 "openrocket",
146 WarningKind::Skipped,
147 "no `rocket` element, so the document holds no design".to_owned(),
148 ));
149 return (
150 Imported {
151 value: rocket,
152 warnings,
153 },
154 Walked::default(),
155 );
156 };
157 let at = "openrocket/rocket";
158 rocket.name = Values::new(element, at, &mut warnings)
159 .word(&["name"])
160 .unwrap_or_default();
161 rocket.reference_diameter = reference_diameter(element, at, &mut warnings);
162 if subcomponents(element).next().is_none() {
163 // A document can carry a rocket's name and stored results and nothing to build: Debrief's
164 // synthesized demonstration file does. There is no design in it to lay out.
165 warnings.push(Warning::new(
166 at,
167 WarningKind::Unusual,
168 "the `rocket` holds no stage or component of any kind, so the document holds no design"
169 .to_owned(),
170 ));
171 }
172
173 let mut ids = Ids {
174 parallel_stages_read: subcomponents(element)
175 .filter(|child| child.name == "stage")
176 .count()
177 == 1,
178 ..Ids::default()
179 };
180 let mut skipped: Vec<Unread> = Vec::new();
181 let mut reads: Vec<Vec<BodyRead>> = Vec::new();
182 for (index, stage_element) in subcomponents(element).enumerate() {
183 if stage_element.name != "stage" {
184 skipped.push(Unread::new(stage_element, &Around::default()));
185 continue;
186 }
187 let mut read = Vec::new();
188 rocket.stages.push(stage(
189 stage_element,
190 index,
191 &mut ids,
192 &mut read,
193 &mut skipped,
194 &mut warnings,
195 ));
196 reads.push(read);
197 // Its parallel stages follow it, as OpenRocket numbers them; their body components
198 // resolve among themselves, as a pod's do, so `default_radii` has nothing to read there.
199 for parallel in std::mem::take(&mut ids.parallel) {
200 rocket.stages.push(parallel);
201 reads.push(Vec::new());
202 }
203 }
204 let tags: Vec<String> = skipped.iter().map(|unread| unread.tag.clone()).collect();
205 let parts: usize = skipped.iter().map(|unread| unread.parts).sum();
206 let lean = skipped
207 .into_iter()
208 .map(|unread| unread.lean)
209 .reduce(Lean::and);
210 if let (Some(note), Some(lean)) = (tally(&tags), lean) {
211 warnings.push(Warning::new(
212 at,
213 WarningKind::Skipped,
214 format!(
215 "{note} {} left out: tags HPR Sim does not read where they are written (a \
216 parallel stage is read only inside a body tube).{}",
217 if tags.len() == 1 { "was" } else { "were" },
218 lean.sentence(parts > 1)
219 ),
220 ));
221 }
222 default_radii(&mut rocket, &reads, &mut warnings);
223 (
224 Imported {
225 value: rocket,
226 warnings,
227 },
228 Walked {
229 mounts: ids.mounts,
230 devices: ids.devices,
231 separations: ids.separations,
232 read: ids.read,
233 },
234 )
235}
236
237/// Gives every automatic body radius that [`Rocket::unresolvable_body_radii`] lists
238/// [`OPENROCKET_DEFAULT_RADIUS_M`], as a fixed radius, with a warning at its tag naming the radius.
239///
240/// A body tube filled that way has its wall judged again, now there is a radius to judge it
241/// against, by the rule a stated radius gets: `filled`, or a wall at least as thick as the radius,
242/// is solid. The warnings that said the radius was not known yet are withdrawn, because it is.
243fn default_radii(rocket: &mut Rocket, reads: &[Vec<BodyRead>], warnings: &mut Vec<Warning>) {
244 let radius_m = OPENROCKET_DEFAULT_RADIUS_M;
245 for filled in rocket.fill_unresolvable_body_radii(radius_m) {
246 let Some(read) = reads
247 .get(filled.stage)
248 .and_then(|stage| stage.get(filled.component))
249 else {
250 continue;
251 };
252 let component = &mut rocket.stages[filled.stage].components[filled.component];
253 if let Part::BodyTube(tube) = &mut component.part {
254 match read.wall {
255 Some(Wall::Filled {}) => tube.thickness_m = radius_m,
256 Some(Wall::Shell { thickness_m }) if thickness_m >= radius_m => {
257 tube.thickness_m = radius_m;
258 }
259 _ => {}
260 }
261 warnings.retain(|warning| {
262 warning.at != read.at
263 || (warning.message != FILLED_TO_CACHE && warning.message != FILLED_TO_NOTHING)
264 });
265 }
266 warnings.push(Warning::new(
267 read.at.clone(),
268 WarningKind::Unusual,
269 format!(
270 "an automatic radius with no fixed radius anywhere along its chain to take, its \
271 `{}`. It was given {:.0} mm, OpenRocket's default radius for a tube with nothing \
272 to take",
273 radius_tag(filled.dimension),
274 radius_m * 1e3
275 ),
276 ));
277 }
278}
279
280/// The tag a body component's radius is written under: a nose cone's base is its `aftradius`.
281fn radius_tag(dimension: AutoDimension) -> &'static str {
282 match dimension {
283 AutoDimension::OuterRadius => "radius",
284 AutoDimension::ForeRadius => "foreradius",
285 AutoDimension::BaseRadius | AutoDimension::AftRadius => "aftradius",
286 other => other.name(),
287 }
288}
289
290/// Reads one `<stage>`, and everything stacked inside it. What each body component was read from
291/// goes into `reads`, in the stage's order, for [`default_radii`].
292fn stage(
293 element: &Element,
294 index: usize,
295 ids: &mut Ids,
296 reads: &mut Vec<BodyRead>,
297 skipped: &mut Vec<Unread>,
298 warnings: &mut Vec<Warning>,
299) -> Stage {
300 let at = format!("openrocket/rocket/stage[{index}]");
301 let mut values = Values::new(element, &at, warnings);
302 let name = values.word(&["name"]).unwrap_or_default();
303 let (overrides, added_mass, drag_override) = stage_overrides(&mut values);
304 let covered = Covered::default().within("stage", &overrides, true, drag_override);
305 let id = ids.take(&mut Values::new(element, &at, warnings), "stage");
306 if let Some(separation) = recovery::separation(element, &at, warnings) {
307 ids.separations.push((id.clone(), separation));
308 }
309 ids.read.insert(at.clone());
310 let mut components = Vec::new();
311 // The index is part of the path so that a warning can be traced back to one part of the 188
312 // body tubes in the reference library, the way a stage's already could (issue #132).
313 for (index, child) in subcomponents(element).enumerate() {
314 if BODY_TAGS.contains(&child.name.as_str()) {
315 let at = format!("{at}/{}[{index}]", child.name);
316 let (component, wall) = body(child, &at, ids, skipped, warnings, &covered);
317 reads.push(BodyRead { at, wall });
318 components.push(component);
319 } else {
320 // Nothing in a stage is placed after a part that isn't a body component.
321 let around = Around {
322 covered: covered.clone(),
323 ..Around::default()
324 };
325 skipped.push(Unread::new(child, &around));
326 }
327 }
328 Stage {
329 id,
330 name,
331 components,
332 // OpenRocket 24.12 leaves a stage's parts where they are under an override that covers
333 // them (ADR-340): the rule changes nothing on a stage with no such override.
334 override_rule: if overrides.is_empty() {
335 StageOverrideRule::Rescaled
336 } else {
337 StageOverrideRule::PartsInPlace
338 },
339 overrides,
340 added_mass,
341 drag_override,
342 parallel: None,
343 }
344}
345
346/// A stage's overrides, as `hpr-design` states them: an override that covers the stage's parts is
347/// the whole stage's ([`Stage::overrides`]), and a mass that doesn't cover them is added to them
348/// ([`AddedMass`]).
349///
350/// This is OpenRocket 24.12's reading, measured on `conventions.py`'s stage probes
351/// ([ADR-335][adr-335]), where a flag not written reads as `false`, and so does the single older
352/// flag saying `false`. A parallel stage's overrides are read by the same table. Its rows with
353/// each flag written, and the mass alone and both overrides with none, are measured on
354/// `added_mass_placement.py`'s
355/// probes ([ADR-341][adr-341]):
356///
357/// | The mass override | The center of gravity override | What the stage weighs |
358/// |---|---|---|
359/// | covers the parts | any, or none | the override's mass, at the override's center if one is given: the whole stage's |
360/// | doesn't cover them | none | the parts and the mass, the mass at the parts' center |
361/// | doesn't cover them | doesn't cover them | the parts and the mass, the mass at the override's station |
362/// | doesn't cover them | covers the parts | the parts and the mass, their center moved to the override's |
363/// | none | covers the parts | the parts, their center moved to the override's |
364/// | none | doesn't cover them | the parts: the override changes nothing |
365///
366/// The last row's override is left out of the design and kept as the file wrote it, so that an
367/// export writes it back. A flag that says neither `true` nor `false` is warned of where it is
368/// read and taken as not written.
369///
370/// [adr-335]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0335-a-stage-s-added-mass-as-openrocket-weighs-it.md
371/// [adr-341]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0341-m2-3d8-in-five-a-parallel-stage-s-added-mass-first.md
372pub(super) fn stage_overrides(
373 values: &mut Values<'_>,
374) -> (Overrides, Option<AddedMass>, Option<DragOverride>) {
375 let read = values.overrides();
376 let drag_override = read.cd.map(|coefficient| DragOverride {
377 coefficient,
378 include_children: read.subcomponents_cd.unwrap_or_default(),
379 });
380 let mass_covers = read.subcomponents_mass.unwrap_or_default();
381 let center_covers = read.subcomponents_cg.unwrap_or_default();
382 let mut overrides = Overrides::default();
383 let mut added_mass = None;
384 match (read.mass_kg, read.cg_m) {
385 (Some(mass_kg), center) if mass_covers => {
386 overrides.mass_kg = Some(mass_kg);
387 overrides.cg_aft_m = center;
388 }
389 (Some(mass_kg), Some(center)) if center_covers => {
390 added_mass = Some(AddedMass {
391 mass_kg,
392 cg_aft_m: None,
393 });
394 overrides.cg_aft_m = Some(center);
395 }
396 (Some(mass_kg), center) => {
397 added_mass = Some(AddedMass {
398 mass_kg,
399 cg_aft_m: center,
400 });
401 }
402 (None, Some(center)) if center_covers => overrides.cg_aft_m = Some(center),
403 (None, Some(_)) => {
404 values.forget(&["overridecg"]);
405 values.forget(&OVERRIDE_FLAGS);
406 }
407 (None, None) => {}
408 }
409 (overrides, added_mass, drag_override)
410}
411
412/// Reads one body component, and everything on and inside it; for a body tube, also the wall as
413/// the file wrote it. A pod's body components are read here too ([`attached::children`]).
414/// `covered` is what the overrides above it set for everything in it ([`Covered`]).
415pub(super) fn body(
416 element: &Element,
417 at: &str,
418 ids: &mut Ids,
419 skipped: &mut Vec<Unread>,
420 warnings: &mut Vec<Warning>,
421 covered: &Covered,
422) -> (Component, Option<Wall>) {
423 let mut auto = Vec::new();
424 let mut values = Values::new(element, at, warnings);
425 let name = values.word(&["name"]).unwrap_or_default();
426 let (overrides, overrides_include_children, drag_override) = overrides(&mut values);
427 // Every body component is an outside part.
428 let finish = finish(&mut values, true);
429 let (part, wall) = match element.name.as_str() {
430 "nosecone" => (nose_cone(element, at, &mut auto, warnings), None),
431 "bodytube" => {
432 let (part, wall) = body_tube(element, at, &mut auto, warnings);
433 (part, Some(wall))
434 }
435 _ => (transition(element, at, &mut auto, warnings), None),
436 };
437 let hung = ids.parallel.len();
438 let covered = covered.within(
439 &spoken(&part),
440 &overrides,
441 overrides_include_children,
442 drag_override,
443 );
444 let inside = Parent {
445 part: &part,
446 auto: &auto,
447 covered: &covered,
448 };
449 let children = attached::children(element, inside, at, ids, skipped, warnings);
450 let mount = match part {
451 Part::BodyTube(_) => motors::mount(element, at, warnings),
452 _ => None,
453 };
454 let id = ids.take(
455 &mut Values::new(element, at, warnings),
456 &element.name.clone(),
457 );
458 let motor_mount = mount.map(|mount| {
459 let spec = MotorMount {
460 overhang_m: mount.overhang_m,
461 };
462 ids.mounts.push((id.clone(), mount));
463 spec
464 });
465 // The parallel stages read among this tube's children hang on it.
466 for stage in &mut ids.parallel[hung..] {
467 if let Some(parallel) = &mut stage.parallel {
468 parallel.on.clone_from(&id);
469 }
470 }
471 ids.read.insert(at.to_owned());
472 let component = Component {
473 id,
474 name,
475 part,
476 position: None,
477 auto,
478 motor_mount,
479 finish,
480 overrides,
481 overrides_include_children,
482 drag_override,
483 children,
484 };
485 (component, wall)
486}
487
488fn nose_cone(
489 element: &Element,
490 at: &str,
491 auto: &mut Vec<AutoDimension>,
492 warnings: &mut Vec<Warning>,
493) -> Part {
494 let mut values = Values::new(element, at, warnings);
495 let length_m = values.number(&["length"]).unwrap_or_default();
496 // A flipped nose cone is a tail cone: its base is forward, so its radius is the fore radius of
497 // a transition that ends in a point, and its shoulder is on that base. With one end a point, a
498 // transition's clipped and unclipped profiles are both the whole nose shape, mirrored
499 // (`hpr_design::shapes`), so the solid is the nose cone's, turned end for end.
500 if values.flag(&["isflipped"]) == Some(true) {
501 let (stated_m, fore_radius_m) =
502 stated_radius(&mut values, &["aftradius"], AutoDimension::ForeRadius, auto);
503 return Part::Transition(Transition {
504 wall: wall(&mut values, stated_m),
505 shape: shape(&mut values),
506 clipped: false,
507 length_m,
508 fore_radius_m,
509 aft_radius_m: 0.0,
510 fore_shoulder: shoulder(&mut values, "aft", AutoDimension::ForeShoulderRadius, auto),
511 aft_shoulder: None,
512 material: material(&mut values, &["material"], "bulk"),
513 });
514 }
515 let (stated_m, base_radius_m) =
516 stated_radius(&mut values, &["aftradius"], AutoDimension::BaseRadius, auto);
517 let wall = wall(&mut values, stated_m);
518 let shape = shape(&mut values);
519 let shoulder = shoulder(&mut values, "aft", AutoDimension::ShoulderRadius, auto);
520 Part::NoseCone(NoseCone {
521 shape,
522 length_m,
523 base_radius_m,
524 wall,
525 shoulder,
526 material: material(&mut values, &["material"], "bulk"),
527 })
528}
529
530fn body_tube(
531 element: &Element,
532 at: &str,
533 auto: &mut Vec<AutoDimension>,
534 warnings: &mut Vec<Warning>,
535) -> (Part, Wall) {
536 let mut values = Values::new(element, at, warnings);
537 let length_m = values.number(&["length"]).unwrap_or_default();
538 let (stated_m, outer_radius_m) =
539 stated_radius(&mut values, &["radius"], AutoDimension::OuterRadius, auto);
540 // A body tube is a wall, not a solid of revolution, so `filled` has to be said as a wall as
541 // thick as the tube. With an automatic radius there is no such number yet: the tube is read as
542 // the wall it caches, and says so.
543 let read = wall(&mut values, stated_m);
544 let thickness_m = match (read, stated_m) {
545 (Wall::Filled {}, Some(radius_m)) => radius_m,
546 (Wall::Filled {}, None) if outer_radius_m > 0.0 => {
547 values.warn_at(WarningKind::Dropped, FILLED_TO_CACHE);
548 outer_radius_m
549 }
550 // Nothing cached either, so there is no number that means "solid" until the layout
551 // resolves one. The tube still has to stand in the stack, so it stands as a wall of
552 // nothing, and that is said as loudly as a part left out, because a solid tube read as an
553 // empty one is a mass quietly missing rather than a design that fails (issue #130).
554 (Wall::Filled {}, None) => {
555 values.warn_at(WarningKind::Skipped, FILLED_TO_NOTHING);
556 // The design holds no `filled`, so the tag is kept for an export to write back.
557 values.forget(&["thickness"]);
558 0.0
559 }
560 (Wall::Shell { thickness_m }, _) => thickness_m,
561 };
562 let part = Part::BodyTube(BodyTube {
563 length_m,
564 outer_radius_m,
565 thickness_m,
566 material: material(&mut values, &["material"], "bulk"),
567 });
568 (part, read)
569}
570
571fn transition(
572 element: &Element,
573 at: &str,
574 auto: &mut Vec<AutoDimension>,
575 warnings: &mut Vec<Warning>,
576) -> Part {
577 let mut values = Values::new(element, at, warnings);
578 let length_m = values.number(&["length"]).unwrap_or_default();
579 let (stated_fore_m, fore_radius_m) = stated_radius(
580 &mut values,
581 &["foreradius"],
582 AutoDimension::ForeRadius,
583 auto,
584 );
585 let (stated_aft_m, aft_radius_m) =
586 stated_radius(&mut values, &["aftradius"], AutoDimension::AftRadius, auto);
587 // Either end may be automatic; a wall is only too thick when it is thicker than both ends that
588 // are known.
589 let known = match (stated_fore_m, stated_aft_m) {
590 (Some(fore_m), Some(aft_m)) => Some(fore_m.max(aft_m)),
591 _ => None,
592 };
593 let wall = wall(&mut values, known);
594 let shape = shape(&mut values);
595 // Only 1 of the 21 transitions in the reference corpus states `shapeclipped`, so the default
596 // matters and no document this project may read states it. Clipped is taken as the default
597 // because it is the shape a transition between two radii needs to reach both of them; the
598 // OpenRocket oracle (M2.2) is what will settle it.
599 let clipped = values.flag(&["shapeclipped"]).unwrap_or(true);
600 Part::Transition(Transition {
601 shape,
602 clipped,
603 length_m,
604 fore_radius_m,
605 aft_radius_m,
606 wall,
607 fore_shoulder: shoulder(&mut values, "fore", AutoDimension::ForeShoulderRadius, auto),
608 aft_shoulder: shoulder(&mut values, "aft", AutoDimension::AftShoulderRadius, auto),
609 material: material(&mut values, &["material"], "bulk"),
610 })
611}
612
613/// The radius, and what it is worth to a reader before the layout resolves it: `None` when the file
614/// says `auto`, whether or not OpenRocket cached a number with it, because the cached number is the
615/// neighbor it last had and may be stale.
616pub(super) fn stated_radius(
617 values: &mut Values<'_>,
618 names: &[&str],
619 dimension: AutoDimension,
620 auto: &mut Vec<AutoDimension>,
621) -> (Option<f64>, f64) {
622 let Some(read) = values.dimension(names) else {
623 // A tag that is there but unreadable has already said so. A tag that is not there at all
624 // is read as zero, which for a radius is a part with no width: a transition with no
625 // `foreradius` lays out as a cone growing from a point, and says nothing unless it says
626 // this (issue #131).
627 if values.element(names).is_none() {
628 let name = names.first().copied().unwrap_or("dimension").to_owned();
629 values.warn_at(
630 WarningKind::Dropped,
631 format!("no `{name}`, so it was read as zero"),
632 );
633 }
634 return (None, 0.0);
635 };
636 if read.is_automatic() {
637 auto.push(dimension);
638 return (None, read.value().unwrap_or_default());
639 }
640 let value = read.value().unwrap_or_default();
641 (Some(value), value)
642}
643
644/// `<thickness>filled</thickness>` is a solid part; anything else is a wall of that thickness.
645///
646/// `outer_radius_m` is the radius the wall sits in, and is `None` when that radius is automatic and
647/// so is not known yet. A wall at least as thick as a known radius is the part filled. It must not
648/// be judged against an unknown radius: the stated thickness would be thrown away whenever the
649/// radius was automatic, which is half of [Loft lesson L61][lessons]: a stated wall dropped
650/// because the outer radius was `auto`.
651///
652/// Two readings are OpenRocket 24.12's, measured on probe designs by
653/// `validation/oracles/openrocket/conventions.py` ([ADR-061][adr-061]):
654///
655/// - a wall of no thickness is a surface with no wall: the part keeps its shape and weighs
656/// nothing, where a filled part is written `filled`;
657/// - a part that writes no thickness at all has OpenRocket's 2 mm wall
658/// ([`DEFAULT_WALL_M`]), whatever its radius.
659///
660/// [lessons]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/research/loft-lessons.md
661/// [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
662fn wall(values: &mut Values<'_>, outer_radius_m: Option<f64>) -> Wall {
663 if values.word(&["thickness"]).as_deref() == Some("filled") {
664 return Wall::Filled {};
665 }
666 match (values.number(&["thickness"]), outer_radius_m) {
667 (Some(thickness_m), Some(radius_m)) if thickness_m >= radius_m => Wall::Filled {},
668 // OpenRocket's 2 mm, in a part no wider than it, is taken to fill the part, as a stated wall
669 // that thick does: an assumption, since no probe is that narrow and no file writes one.
670 (None, Some(radius_m)) if DEFAULT_WALL_M >= radius_m => Wall::Filled {},
671 (Some(thickness_m), _) if thickness_m > 0.0 => Wall::Shell { thickness_m },
672 (Some(0.0), _) => Wall::Shell { thickness_m: 0.0 },
673 (Some(thickness_m), _) => {
674 values.warn_at(
675 WarningKind::Dropped,
676 format!("a wall {thickness_m} m thick is no wall; it was read as none"),
677 );
678 values.forget(&["thickness"]);
679 Wall::Shell { thickness_m: 0.0 }
680 }
681 (None, _) => Wall::Shell {
682 thickness_m: DEFAULT_WALL_M,
683 },
684 }
685}
686
687/// The wall OpenRocket 24.12 gives a nose cone, transition or body tube that writes no thickness,
688/// m: a nose cone and a tube at 50 mm and at 30 mm, and a transition, each weigh what a 2 mm wall
689/// gives ([ADR-061][adr-061]).
690///
691/// [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
692const DEFAULT_WALL_M: f64 = 0.002;
693
694/// A shoulder at one end, if the file gives it a length. A zero-length shoulder is no shoulder.
695fn shoulder(
696 values: &mut Values<'_>,
697 end: &str,
698 dimension: AutoDimension,
699 auto: &mut Vec<AutoDimension>,
700) -> Option<Shoulder> {
701 let length_m = values.number(&[&format!("{end}shoulderlength")])?;
702 if length_m <= 0.0 {
703 return None;
704 }
705 let (known_m, outer_radius_m) =
706 stated_radius(values, &[&format!("{end}shoulderradius")], dimension, auto);
707 // A shoulder with no wall, or none written, weighs nothing in OpenRocket 24.12, capped or not
708 // and whether or not the part it hangs from is filled: measured on probe designs (ADR-061).
709 // So it is read as a tube of no wall, which weighs nothing.
710 // The stated wall is clamped to the radius it sits in, and only when that radius is known:
711 // clamping against an automatic one that has not resolved yet would throw the wall away, which
712 // is half of Loft lesson L61 and what issue #130 found still open on a shoulder.
713 let thickness_m = match values.number(&[&format!("{end}shoulderthickness")]) {
714 Some(stated_m) if stated_m > 0.0 => {
715 known_m.map_or(stated_m, |radius_m| stated_m.min(radius_m))
716 }
717 Some(stated_m) if stated_m < 0.0 => {
718 values.warn_at(
719 WarningKind::Dropped,
720 format!("the {end} shoulder's wall is {stated_m} m thick, which is no wall; it was read as none"),
721 );
722 values.forget(&[&format!("{end}shoulderthickness")]);
723 0.0
724 }
725 _ => 0.0,
726 };
727 Some(Shoulder {
728 length_m,
729 outer_radius_m,
730 thickness_m,
731 // A cap is as thick as the shoulder's wall, so a shoulder of no wall has none; and a solid
732 // shoulder has no bore to close, so a cap on one is nothing either: reading it as a cap
733 // asks `hpr-design` for a disc inside a tube that isn't hollow.
734 capped: thickness_m > 0.0
735 && known_m.is_none_or(|radius_m| thickness_m < radius_m)
736 && values
737 .flag(&[&format!("{end}shouldercapped")])
738 .unwrap_or_default(),
739 })
740}
741
742/// The profile shape and its parameter.
743///
744/// OpenRocket's shape parameter is `κ`, defined in [Niskanen's technical documentation][niskanen],
745/// appendix A. For an ogive it is the ratio of a tangent ogive's radius of curvature to this one's,
746/// `κ = ρ_t/ρ` (equation A.3), so `κ = 1` is a tangent ogive and `κ = 0` an infinite radius, which
747/// is a cone. [`NoseShape::Ogive`] states the same shape the other way up, as `ρ/ρ_t`, so the two
748/// are reciprocals. The power series (A.8) and the parabolic series (A.7) use the same `κ` this
749/// crate's [`NoseShape::PowerSeries`] and [`NoseShape::ParabolicSeries`] do, and the Haack series
750/// (A.9) the same `C`.
751///
752/// [niskanen]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/format/ork.md
753fn shape(values: &mut Values<'_>) -> NoseShape {
754 let name = values.word(&["shape"]).unwrap_or_default();
755 let parameter = values.number(&["shapeparameter"]);
756 match (name.as_str(), parameter) {
757 ("conical", _) => NoseShape::Conical {},
758 ("ellipsoid", _) => NoseShape::Elliptical {},
759 // κ = 0 is the cone, and the reciprocal below would divide by it.
760 ("ogive", Some(kappa)) if kappa <= 0.0 => NoseShape::Conical {},
761 ("ogive", kappa) => NoseShape::Ogive {
762 radius_ratio: 1.0 / kappa.unwrap_or(1.0),
763 },
764 ("power", Some(exponent)) => NoseShape::PowerSeries { exponent },
765 ("parabolic", Some(parameter)) => NoseShape::ParabolicSeries { parameter },
766 ("haack", parameter) => NoseShape::Haack {
767 parameter: parameter.unwrap_or_default(),
768 },
769 // A power or parabolic series is the shape its parameter says it is, and there is no
770 // sourced default for either: OpenRocket's own is in its source, which this project does
771 // not read. So it is read as a cone and the message says why, rather than blaming the
772 // shape's name (issue #131). No nose in the reference corpus omits it.
773 (shape @ ("power" | "parabolic"), None) => {
774 let shape = shape.to_owned();
775 values.warn_at(
776 WarningKind::Unusual,
777 format!(
778 "a `{shape}` nose states no shape parameter, and this reader has no sourced \
779 default for one; it was read as a cone"
780 ),
781 );
782 // The design holds a cone, not the shape named: the name is kept as written.
783 values.forget(&["shape"]);
784 NoseShape::Conical {}
785 }
786 (other, _) => {
787 let other = other.to_owned();
788 values.warn_at(
789 WarningKind::Unusual,
790 format!("`{other}` is not a shape this reader knows; it was read as a cone"),
791 );
792 values.forget(&["shape", "shapeparameter"]);
793 NoseShape::Conical {}
794 }
795 }
796}
797
798/// The material a part is made of. A `.ork` stores the density with the name, so nothing is
799/// looked up.
800///
801/// `want` is the kind of density the part needs: `bulk` for anything solid, `surface` for a
802/// canopy or a streamer, `line` for a shroud line or a shock cord. The file declares a kind of its
803/// own in the `type` attribute, and the number is in that kind's units, so a density declared as
804/// one kind cannot be converted into another: the part is built with the kind it needs and the
805/// disagreement is reported. No material in the reference corpus is declared as a kind its part
806/// does not want.
807///
808/// A part that names no material is made of the one OpenRocket 24.12 gives it, by kind
809/// ([`unnamed_material`]); a rail button's is its own, so it calls [`material_or`].
810pub(super) fn material(values: &mut Values<'_>, names: &[&str], want: &str) -> Material {
811 material_or(values, names, want, unnamed_material(want))
812}
813
814/// The material OpenRocket 24.12 gives a part that names none, by the kind of density it needs:
815/// cardboard, 680 kg/m³, for a solid part; ripstop nylon, 0.067 kg/m², for a canopy or a streamer;
816/// and a 2 mm elastic cord, 0.0018 kg/m, for shroud lines and a shock cord. Each was read from a
817/// probe part of each kind through OpenRocket's public `getMaterial` and `getLineMaterial`
818/// (`validation/oracles/openrocket/conventions.py`, [ADR-061][adr-061]).
819///
820/// [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
821fn unnamed_material(want: &str) -> (&'static str, f64) {
822 match want {
823 "surface" => ("Ripstop nylon", 0.067),
824 "line" => ("Elastic cord (round 2 mm, 1/16 in)", 0.0018),
825 _ => ("Cardboard", 680.0),
826 }
827}
828
829/// The material OpenRocket 24.12 gives a rail button that names none: Delrin, 1,420 kg/m³, measured
830/// as [`unnamed_material`]'s are.
831pub(super) const UNNAMED_RAIL_BUTTON: (&str, f64) = ("Delrin", 1420.0);
832
833/// [`material`], with the material a part that names none is made of.
834pub(super) fn material_or(
835 values: &mut Values<'_>,
836 names: &[&str],
837 want: &str,
838 (unnamed, unnamed_kg): (&str, f64),
839) -> Material {
840 let named = |name: &str, kg: f64| match want {
841 "surface" => Material::surface(name, kg),
842 "line" => Material::line(name, kg),
843 _ => Material::bulk(name, kg),
844 };
845 let Some(element) = values.element(names) else {
846 return named(unnamed, unnamed_kg);
847 };
848 let name = element.text().trim().to_owned();
849 if let Some(declared) = element.attribute("type")
850 && declared != want
851 {
852 let declared = declared.to_owned();
853 values.warn_at(
854 WarningKind::Dropped,
855 format!(
856 "the material `{name}` is declared `{declared}` where a `{want}` density is \
857 needed; its number was taken as a `{want}` one"
858 ),
859 );
860 // The design holds the kind the part needs, so the file's own is kept as written.
861 super::reads::forget_attribute(element, "type");
862 }
863 let density = element
864 .attribute("density")
865 .and_then(|text| text.parse::<f64>().ok())
866 .filter(|density| density.is_finite() && *density >= 0.0);
867 match density {
868 Some(kg) => named(&name, kg),
869 None => {
870 values.warn_at(
871 WarningKind::Dropped,
872 format!("the material `{name}` states no density; it weighs nothing"),
873 );
874 super::reads::forget_attribute(element, "density");
875 named(&name, 0.0)
876 }
877 }
878}
879
880/// The overrides, as `hpr-design` states them, and whether they cover the parts inside this one.
881///
882/// A `.ork` says "covers the children too" once per quantity and `hpr-design` says it once for the
883/// component. A part that overrides only one quantity takes that quantity's flag; OpenRocket 24.12
884/// applies a center-of-gravity override alone to the whole assembly when its flag says so
885/// (measured, ADR-061). A part that overrides both, with flags that disagree, cannot be said in
886/// `hpr-design`: the mass flag decides, because mass is the quantity the flag is written for (95 of
887/// the 104 in the reference corpus are `overridesubcomponentsmass`), and the disagreement is
888/// reported, and the file's flags are kept as written for an export to put back. The drag override
889/// has its own flag, in `hpr-design` as in the file ([`DragOverride`], ADR-167).
890pub(super) fn overrides(values: &mut Values<'_>) -> (Overrides, bool, Option<DragOverride>) {
891 let read = values.overrides();
892 let drag_override = read.cd.map(|coefficient| DragOverride {
893 coefficient,
894 include_children: read.subcomponents_cd.unwrap_or_default(),
895 });
896 let mass_flag = read.subcomponents_mass.unwrap_or_default();
897 let covers_children = match (read.mass_kg, read.cg_m) {
898 (None, Some(_)) => read.subcomponents_cg.unwrap_or_default(),
899 _ => mass_flag,
900 };
901 if read.mass_kg.is_some()
902 && read.cg_m.is_some()
903 && read.subcomponents_cg.unwrap_or_default() != mass_flag
904 {
905 values.warn_at(
906 WarningKind::Dropped,
907 format!(
908 "the mass override covers the parts inside this one ({mass_flag}) and \
909 the center-of-gravity override does not agree. HPR Sim states it once, so \
910 the mass flag was taken"
911 ),
912 );
913 // The flags are kept as written, all together, since their order says which wins.
914 values.forget(&OVERRIDE_FLAGS);
915 }
916 (
917 Overrides {
918 mass_kg: read.mass_kg,
919 cg_aft_m: read.cg_m,
920 cg_xy_m: None,
921 inertia: None,
922 },
923 covers_children,
924 drag_override,
925 )
926}
927
928/// How the reference diameter is chosen. Every design in the reference corpus says `maximum`,
929/// which is OpenRocket's default; anything else is left at that default and reported.
930fn reference_diameter(
931 element: &Element,
932 at: &str,
933 warnings: &mut Vec<Warning>,
934) -> ReferenceDiameter {
935 let word = Values::new(element, at, warnings).word(&["referencetype"]);
936 match word.as_deref() {
937 None | Some("maximum") => ReferenceDiameter::Maximum {},
938 Some(other) => {
939 warnings.push(Warning::new(
940 at,
941 WarningKind::Dropped,
942 format!(
943 "a reference diameter chosen by `{other}` is not read yet; the widest body \
944 component was used"
945 ),
946 ));
947 super::reads::forget(element, "referencetype");
948 ReferenceDiameter::Maximum {}
949 }
950 }
951}
952
953/// The children of an element's `<subcomponents>`, in file order.
954pub(super) fn subcomponents(element: &Element) -> impl Iterator<Item = &Element> {
955 element
956 .child("subcomponents")
957 .into_iter()
958 .flat_map(Element::elements)
959}
960
961/// Unique ids: a `.ork` gives most components one, but not all of them, and `hpr-design` needs
962/// every id to be distinct or it refuses the whole design.
963///
964/// So every id handed out is remembered, whether it came from the file or was invented here. A
965/// file whose own ids repeat, or whose `<id>bodytube-4</id>` collides with the name invented for a
966/// component that has none, gets a number added and a warning rather than a design that will not
967/// open (issue #132).
968#[derive(Debug, Default)]
969pub(super) struct Ids {
970 used: usize,
971 taken: std::collections::BTreeSet<String>,
972 /// Every motor mount read, with the id its component was given, in file order: the walk
973 /// records them here because this is what it carries everywhere, and [`super::motors::read`]
974 /// needs the ids.
975 pub(super) mounts: Vec<(String, MountRead)>,
976 /// Every parachute and streamer read, with its component's id, in file order.
977 pub(super) devices: Vec<(String, DeviceRead)>,
978 /// Every stage that states when it separates, with the stage's id, in file order.
979 pub(super) separations: Vec<(String, SeparationRead)>,
980 /// The path of every stage and component read, for [`super::extensions::read`] to keep the
981 /// rest.
982 pub(super) read: std::collections::BTreeSet<String>,
983 /// The parallel stages read in the stage being read, each to follow it ([`stage`]).
984 pub(super) parallel: Vec<Stage>,
985 /// Whether parallel stages are read: on a rocket of one axial stage, where OpenRocket numbers
986 /// each right after it (ADR-171).
987 pub(super) parallel_stages_read: bool,
988}
989
990/// What the walk read besides the rocket, each with the id it gave its component.
991#[derive(Debug, Default)]
992pub(super) struct Walked {
993 /// The motor mounts.
994 pub mounts: Vec<(String, MountRead)>,
995 /// The parachutes and streamers.
996 pub devices: Vec<(String, DeviceRead)>,
997 /// The stages' separations.
998 pub separations: Vec<(String, SeparationRead)>,
999 /// The path of every stage and component read.
1000 pub read: std::collections::BTreeSet<String>,
1001}
1002
1003impl Ids {
1004 pub(super) fn take(&mut self, values: &mut Values<'_>, kind: &str) -> String {
1005 self.used += 1;
1006 let wanted = values
1007 .word(&["id"])
1008 .filter(|id| !id.is_empty())
1009 .unwrap_or_else(|| format!("{kind}-{}", self.used));
1010 if self.taken.insert(wanted.clone()) {
1011 return wanted;
1012 }
1013 let mut again = 2usize;
1014 let id = loop {
1015 let candidate = format!("{wanted}-{again}");
1016 if self.taken.insert(candidate.clone()) {
1017 break candidate;
1018 }
1019 again += 1;
1020 };
1021 values.warn_at(
1022 WarningKind::Unusual,
1023 format!(
1024 "`{wanted}` is already the id of another component; this one was called `{id}`"
1025 ),
1026 );
1027 // The design holds the new id, so the file's is kept as written.
1028 values.forget(&["id"]);
1029 id
1030 }
1031}
1032
1033/// `["bodytube", "finset", "bodytube"]` as `2 bodytube, 1 finset`.
1034fn tally(names: &[String]) -> Option<String> {
1035 if names.is_empty() {
1036 return None;
1037 }
1038 let mut counts: std::collections::BTreeMap<&str, usize> = std::collections::BTreeMap::new();
1039 for name in names {
1040 *counts.entry(name.as_str()).or_default() += 1;
1041 }
1042 Some(
1043 counts
1044 .into_iter()
1045 .map(|(name, count)| format!("{count} `{name}`"))
1046 .collect::<Vec<_>>()
1047 .join(", "),
1048 )
1049}