1use 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
53const TUBES: [&str; 3] = ["innertube", "tubecoupler", "engineblock"];
55
56pub 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
81const MOST_INSTANCES: u32 = 64;
89
90fn nested(element: &Element) -> usize {
93 subcomponents(element).map(|child| 1 + nested(child)).sum()
94}
95
96fn 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#[derive(Debug, Clone)]
115pub(super) struct Unread {
116 pub(super) tag: String,
118 pub(super) lean: Lean,
120 pub(super) parts: usize,
122}
123
124impl Unread {
125 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#[derive(Debug, Clone, Copy)]
137pub(super) struct Parent<'p> {
138 pub(super) part: &'p Part,
142 pub(super) auto: &'p [AutoDimension],
145 pub(super) covered: &'p Covered,
148}
149
150fn 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
164fn sized_from(child: &Element, ring: bool) -> bool {
167 ring && TUBES.contains(&child.name.as_str())
168}
169
170fn 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
186pub(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 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 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
233fn 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 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 _ => return None,
266 }?;
267
268 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 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 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 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 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 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
442fn 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 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 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 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 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 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 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 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 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 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 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 if pods.is_empty() && (overrides != Overrides::default() || drag_override.is_some()) {
701 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 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 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 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
777fn 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 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 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 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 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 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
877const INNER_TUBE_UNRESOLVED_M: f64 = 0.0095;
884
885fn 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 (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
915fn 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
966pub(crate) fn cluster_pattern(name: &str) -> Option<Vec<[f64; 2]>> {
974 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 "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
1013fn 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 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 Some(match outer_radius_m {
1068 Some(radius_m) => thickness_m.min(radius_m),
1069 None => thickness_m,
1070 })
1071}
1072
1073fn 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
1105fn 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 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 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
1147pub(super) const ROOT_PIECES: u32 = 64;
1151
1152fn 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 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 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
1277fn 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
1338fn 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
1356fn 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 "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 Some(FinTab {
1402 height_m,
1403 length_m,
1404 offset_m,
1405 })
1406}
1407
1408const MOST_TUBE_FINS: u32 = 8;
1411
1412fn 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 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
1455fn 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 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
1488fn 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
1505fn 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
1513fn 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
1525fn 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
1535fn 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
1544const PACKED_LENGTH_M: f64 = 0.025;
1555
1556const PACKED_RADIUS_M: f64 = 0.0125;
1559
1560fn 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
1585fn 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
1595fn 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
1622fn 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
1634fn 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
1649fn 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
1672fn 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 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
1728fn 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
1760const REGULAR_PAINT_M: f64 = 60e-6;
1763
1764pub(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
1832fn 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 #[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 #[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 (
1937 Position::Top { aft_offset_m: 0.1 },
1938 Position::Top {
1939 aft_offset_m: 0.095,
1940 },
1941 ),
1942 (
1944 Position::Middle { aft_offset_m: 0.0 },
1945 Position::Middle { aft_offset_m: 0.05 },
1946 ),
1947 (
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 #[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}