1use std::collections::{BTreeMap, BTreeSet};
41
42use hpr_core::{DMat3, DVec3};
43use serde::{Deserialize, Serialize};
44
45use crate::config::{Configuration, MotorMount};
46use crate::error::DesignError;
47use crate::finish::Finish;
48use crate::fins::{FinSet, TubeFinSet};
49use crate::mass::{MassProperties, Placement};
50use crate::parts::{
51 BodyTube, CenteringRing, InnerTube, LaunchLug, MassComponent, NoseCone, Packing, Parachute,
52 PodSet, RailButton, ShockCord, Streamer, Transition,
53};
54use crate::shapes::check_dimension;
55use crate::solids::Wall;
56
57pub const LENGTH_TOLERANCE_M: f64 = 1e-9;
60
61#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
64#[serde(deny_unknown_fields)]
65pub struct Rocket {
66 #[serde(default)]
68 pub name: String,
69 pub stages: Vec<Stage>,
72 #[serde(default)]
74 pub reference_diameter: ReferenceDiameter,
75 #[serde(default)]
77 pub configurations: Vec<Configuration>,
78}
79
80#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
83#[serde(deny_unknown_fields)]
84pub struct Stage {
85 pub id: String,
87 #[serde(default)]
89 pub name: String,
90 pub components: Vec<Component>,
92 #[serde(
95 default,
96 skip_serializing_if = "Overrides::is_empty",
97 deserialize_with = "object_only"
98 )]
99 pub overrides: Overrides,
100 #[serde(default, skip_serializing_if = "StageOverrideRule::is_rescaled")]
104 pub override_rule: StageOverrideRule,
105 #[serde(default, skip_serializing_if = "Option::is_none")]
110 pub added_mass: Option<AddedMass>,
111 #[serde(default, skip_serializing_if = "Option::is_none")]
114 pub drag_override: Option<DragOverride>,
115 #[serde(default, skip_serializing_if = "Option::is_none")]
118 pub parallel: Option<ParallelStage>,
119}
120
121#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
133#[serde(deny_unknown_fields)]
134pub struct ParallelStage {
135 pub on: String,
137 pub position: Position,
140 pub pods: PodSet,
142}
143
144fn object_only<'de, D, T>(deserializer: D) -> Result<T, D::Error>
149where
150 D: serde::Deserializer<'de>,
151 T: Deserialize<'de>,
152{
153 struct ObjectOnly<T>(std::marker::PhantomData<T>);
154 impl<'de, T: Deserialize<'de>> serde::de::Visitor<'de> for ObjectOnly<T> {
155 type Value = T;
156 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
157 formatter.write_str("an object")
158 }
159 fn visit_map<A: serde::de::MapAccess<'de>>(self, map: A) -> Result<T, A::Error> {
160 T::deserialize(serde::de::value::MapAccessDeserializer::new(map))
161 }
162 }
163 deserializer.deserialize_map(ObjectOnly(std::marker::PhantomData))
164}
165
166#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
168#[serde(deny_unknown_fields)]
169pub struct Component {
170 pub id: String,
172 #[serde(default)]
174 pub name: String,
175 pub part: Part,
177 #[serde(default, skip_serializing_if = "Option::is_none")]
180 pub position: Option<Position>,
181 #[serde(default, skip_serializing_if = "Vec::is_empty")]
183 pub auto: Vec<AutoDimension>,
184 #[serde(default, skip_serializing_if = "Option::is_none")]
186 pub motor_mount: Option<MotorMount>,
187 #[serde(default, skip_serializing_if = "Option::is_none")]
190 pub finish: Option<Finish>,
191 #[serde(
193 default,
194 skip_serializing_if = "Overrides::is_empty",
195 deserialize_with = "object_only"
196 )]
197 pub overrides: Overrides,
198 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
201 pub overrides_include_children: bool,
202 #[serde(default, skip_serializing_if = "Option::is_none")]
205 pub drag_override: Option<DragOverride>,
206 #[serde(default, skip_serializing_if = "Vec::is_empty")]
208 pub children: Vec<Component>,
209}
210
211impl Component {
212 pub fn length_m(&self) -> f64 {
215 match self.part {
216 Part::PodSet(_) => self
218 .children
219 .iter()
220 .fold(0.0, |length, c| length + c.part.length_m()),
221 _ => self.part.length_m(),
222 }
223 }
224}
225
226#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
228#[serde(rename_all = "snake_case")]
229#[non_exhaustive]
230pub enum Part {
231 NoseCone(NoseCone),
233 BodyTube(BodyTube),
235 Transition(Transition),
237 InnerTube(InnerTube),
239 CenteringRing(CenteringRing),
241 FinSet(FinSet),
243 TubeFinSet(TubeFinSet),
245 LaunchLug(LaunchLug),
247 RailButton(RailButton),
249 PodSet(PodSet),
252 MassComponent(MassComponent),
254 Parachute(Parachute),
256 Streamer(Streamer),
258 ShockCord(ShockCord),
260}
261
262#[derive(Debug, Clone, Copy, PartialEq, Eq)]
264enum Role {
265 Body,
267 External,
269 Internal,
271}
272
273impl Part {
274 pub fn kind_name(&self) -> &'static str {
276 match self {
277 Self::NoseCone(_) => "nose_cone",
278 Self::BodyTube(_) => "body_tube",
279 Self::Transition(_) => "transition",
280 Self::InnerTube(_) => "inner_tube",
281 Self::CenteringRing(_) => "centering_ring",
282 Self::FinSet(_) => "fin_set",
283 Self::TubeFinSet(_) => "tube_fin_set",
284 Self::LaunchLug(_) => "launch_lug",
285 Self::RailButton(_) => "rail_button",
286 Self::PodSet(_) => "pod_set",
287 Self::MassComponent(_) => "mass_component",
288 Self::Parachute(_) => "parachute",
289 Self::Streamer(_) => "streamer",
290 Self::ShockCord(_) => "shock_cord",
291 }
292 }
293
294 fn role(&self) -> Role {
295 match self {
296 Self::NoseCone(_) | Self::BodyTube(_) | Self::Transition(_) => Role::Body,
297 Self::FinSet(_)
298 | Self::TubeFinSet(_)
299 | Self::LaunchLug(_)
300 | Self::RailButton(_)
301 | Self::PodSet(_) => Role::External,
302 Self::InnerTube(_)
303 | Self::CenteringRing(_)
304 | Self::MassComponent(_)
305 | Self::Parachute(_)
306 | Self::Streamer(_)
307 | Self::ShockCord(_) => Role::Internal,
308 }
309 }
310
311 pub fn is_body(&self) -> bool {
313 self.role() == Role::Body
314 }
315
316 pub fn is_external(&self) -> bool {
319 self.role() == Role::External
320 }
321
322 pub fn length_m(&self) -> f64 {
328 let row =
329 |count: u32, one: f64, spacing: f64| one + spacing * f64::from(count.saturating_sub(1));
330 match self {
331 Self::NoseCone(p) => p.length_m,
332 Self::BodyTube(p) => p.length_m,
333 Self::Transition(p) => p.length_m,
334 Self::InnerTube(p) => p.length_m,
335 Self::CenteringRing(p) => p.length_m,
336 Self::FinSet(p) => p.planform.root_chord_m(),
337 Self::TubeFinSet(p) => p.length_m,
338 Self::LaunchLug(p) => row(p.count, p.length_m, p.spacing_m),
339 Self::RailButton(p) => row(p.count, p.outer_diameter_m, p.spacing_m),
340 Self::PodSet(_) => 0.0,
341 Self::MassComponent(p) => p.packing.length_m,
342 Self::Parachute(p) => p.packing.length_m,
343 Self::Streamer(p) => p.packing.length_m,
344 Self::ShockCord(p) => p.packing.length_m,
345 }
346 }
347
348 pub fn packing(&self) -> Option<&Packing> {
350 match self {
351 Self::MassComponent(p) => Some(&p.packing),
352 Self::Parachute(p) => Some(&p.packing),
353 Self::Streamer(p) => Some(&p.packing),
354 Self::ShockCord(p) => Some(&p.packing),
355 _ => None,
356 }
357 }
358
359 pub fn fore_radius_m(&self) -> Option<f64> {
361 match self {
362 Self::NoseCone(_) => Some(0.0),
363 Self::BodyTube(p) => Some(p.outer_radius_m),
364 Self::Transition(p) => Some(p.fore_radius_m),
365 _ => None,
366 }
367 }
368
369 pub fn aft_radius_m(&self) -> Option<f64> {
371 match self {
372 Self::NoseCone(p) => Some(p.base_radius_m),
373 Self::BodyTube(p) => Some(p.outer_radius_m),
374 Self::Transition(p) => Some(p.aft_radius_m),
375 _ => None,
376 }
377 }
378
379 pub fn max_radius_m(&self) -> Result<Option<f64>, DesignError> {
385 Ok(match self {
386 Self::NoseCone(p) => Some(p.profile()?.max_radius_m()),
387 Self::BodyTube(p) => Some(p.outer_radius_m),
388 Self::Transition(p) => Some(p.profile()?.max_radius_m()),
389 _ => None,
390 })
391 }
392
393 pub fn inner_radius_m(&self) -> Option<f64> {
395 match self {
396 Self::BodyTube(p) => Some(p.outer_radius_m - p.thickness_m),
397 Self::InnerTube(p) => Some(p.outer_radius_m - p.thickness_m),
398 _ => None,
399 }
400 }
401
402 pub fn axis_offset_m(&self) -> [f64; 2] {
406 let turned = |r: f64, angle: f64| [r * angle.cos(), r * angle.sin()];
407 match self {
408 Self::InnerTube(p) => turned(p.radial_offset_m, p.angle_rad),
409 Self::MassComponent(p) => turned(p.packing.radial_offset_m, p.packing.angle_rad),
410 Self::Parachute(p) => turned(p.packing.radial_offset_m, p.packing.angle_rad),
411 Self::Streamer(p) => turned(p.packing.radial_offset_m, p.packing.angle_rad),
412 Self::ShockCord(p) => turned(p.packing.radial_offset_m, p.packing.angle_rad),
413 _ => [0.0, 0.0],
414 }
415 }
416
417 pub fn outer_radius_about_axis_m(&self) -> Option<f64> {
420 match self {
421 Self::InnerTube(p) => Some(p.outer_radius_m),
422 Self::CenteringRing(p) => Some(p.outer_radius_m),
423 Self::MassComponent(p) => Some(p.packing.radius_m),
424 Self::Parachute(p) => Some(p.packing.radius_m),
425 Self::Streamer(p) => Some(p.packing.radius_m),
426 Self::ShockCord(p) => Some(p.packing.radius_m),
427 _ => None,
428 }
429 }
430
431 pub fn reach_from_m(&self, axis: [f64; 2]) -> Option<f64> {
434 let [x, y] = self.axis_offset_m();
435 let tubes = match self {
436 Self::InnerTube(tube) if !tube.cluster_m.is_empty() => tube.cluster_m.as_slice(),
437 _ => &[[0.0, 0.0]],
438 };
439 self.outer_radius_about_axis_m().map(|r| {
440 tubes
441 .iter()
442 .map(|&[u, v]| (x + u - axis[0]).hypot(y + v - axis[1]) + r)
443 .fold(f64::NEG_INFINITY, f64::max)
444 })
445 }
446
447 pub fn mass_properties(
455 &self,
456 body_radius_m: Option<f64>,
457 ) -> Result<MassProperties, DesignError> {
458 let body = || {
459 body_radius_m.ok_or_else(|| {
460 DesignError::Geometry(format!(
461 "a {} needs the radius of the body it sits on",
462 self.kind_name()
463 ))
464 })
465 };
466 match self {
467 Self::NoseCone(p) => p.mass_properties(),
468 Self::BodyTube(p) => p.mass_properties(),
469 Self::Transition(p) => p.mass_properties(),
470 Self::InnerTube(p) => p.mass_properties(),
471 Self::CenteringRing(p) => p.mass_properties(),
472 Self::FinSet(p) => p.mass_properties(body()?),
473 Self::TubeFinSet(p) => p.mass_properties(body()?),
474 Self::LaunchLug(p) => p.mass_properties(body()?),
475 Self::RailButton(p) => p.mass_properties(body()?),
476 Self::PodSet(p) => p.pods().map(|_| MassProperties::ZERO),
477 Self::MassComponent(p) => p.mass_properties(),
478 Self::Parachute(p) => p.mass_properties(),
479 Self::Streamer(p) => p.mass_properties(),
480 Self::ShockCord(p) => p.mass_properties(),
481 }
482 }
483}
484
485#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
487#[serde(tag = "from", rename_all = "snake_case", deny_unknown_fields)]
488pub enum Position {
489 Top {
491 #[serde(default)]
493 aft_offset_m: f64,
494 },
495 Middle {
497 #[serde(default)]
499 aft_offset_m: f64,
500 },
501 Bottom {
503 #[serde(default)]
505 aft_offset_m: f64,
506 },
507 After {
510 #[serde(default)]
512 aft_offset_m: f64,
513 },
514 Absolute {
516 station_m: f64,
518 },
519}
520
521#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
523#[serde(rename_all = "snake_case")]
524#[non_exhaustive]
525pub enum AutoDimension {
526 BaseRadius,
528 OuterRadius,
543 ForeRadius,
545 AftRadius,
547 ShoulderRadius,
549 ForeShoulderRadius,
551 AftShoulderRadius,
553 InnerRadius,
556 PackedRadius,
559}
560
561impl AutoDimension {
562 pub fn name(self) -> &'static str {
564 match self {
565 Self::BaseRadius => "base_radius",
566 Self::OuterRadius => "outer_radius",
567 Self::ForeRadius => "fore_radius",
568 Self::AftRadius => "aft_radius",
569 Self::ShoulderRadius => "shoulder_radius",
570 Self::ForeShoulderRadius => "fore_shoulder_radius",
571 Self::AftShoulderRadius => "aft_shoulder_radius",
572 Self::InnerRadius => "inner_radius",
573 Self::PackedRadius => "packed_radius",
574 }
575 }
576
577 fn applies_to(self, part: &Part) -> bool {
578 use AutoDimension as A;
579 matches!(
580 (self, part),
581 (A::BaseRadius | A::ShoulderRadius, Part::NoseCone(_))
582 | (
583 A::OuterRadius,
584 Part::BodyTube(_)
585 | Part::CenteringRing(_)
586 | Part::InnerTube(_)
587 | Part::TubeFinSet(_)
588 )
589 | (
590 A::ForeRadius | A::AftRadius | A::ForeShoulderRadius | A::AftShoulderRadius,
591 Part::Transition(_)
592 )
593 | (A::InnerRadius, Part::CenteringRing(_))
594 | (
595 A::PackedRadius,
596 Part::MassComponent(_)
597 | Part::Parachute(_)
598 | Part::Streamer(_)
599 | Part::ShockCord(_)
600 )
601 )
602 }
603}
604
605#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize, schemars::JsonSchema)]
619#[serde(deny_unknown_fields)]
620pub struct Overrides {
621 #[serde(default, skip_serializing_if = "Option::is_none")]
623 pub mass_kg: Option<f64>,
624 #[serde(default, skip_serializing_if = "Option::is_none")]
626 pub cg_aft_m: Option<f64>,
627 #[serde(default, skip_serializing_if = "Option::is_none")]
631 pub cg_xy_m: Option<[f64; 2]>,
632 #[serde(default, skip_serializing_if = "Option::is_none")]
635 pub inertia: Option<InertiaOverride>,
636}
637
638#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
658#[serde(deny_unknown_fields)]
659pub struct DragOverride {
660 pub coefficient: f64,
663 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
666 pub include_children: bool,
667}
668
669#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
672#[serde(deny_unknown_fields)]
673pub struct InertiaOverride {
674 pub xx_kg_m2: f64,
676 pub yy_kg_m2: f64,
678 pub zz_kg_m2: f64,
680 #[serde(default)]
682 pub xy_kg_m2: f64,
683 #[serde(default)]
685 pub xz_kg_m2: f64,
686 #[serde(default)]
688 pub yz_kg_m2: f64,
689}
690
691impl InertiaOverride {
692 pub fn axisymmetric(axial_kg_m2: f64, transverse_kg_m2: f64) -> Self {
694 Self {
695 xx_kg_m2: transverse_kg_m2,
696 yy_kg_m2: transverse_kg_m2,
697 zz_kg_m2: axial_kg_m2,
698 xy_kg_m2: 0.0,
699 xz_kg_m2: 0.0,
700 yz_kg_m2: 0.0,
701 }
702 }
703
704 pub fn tensor(&self) -> DMat3 {
706 DMat3::from_cols(
707 DVec3::new(self.xx_kg_m2, self.xy_kg_m2, self.xz_kg_m2),
708 DVec3::new(self.xy_kg_m2, self.yy_kg_m2, self.yz_kg_m2),
709 DVec3::new(self.xz_kg_m2, self.yz_kg_m2, self.zz_kg_m2),
710 )
711 }
712}
713
714impl Overrides {
715 pub fn sets_center(&self) -> bool {
717 self.cg_aft_m.is_some() || self.cg_xy_m.is_some()
718 }
719
720 pub fn sets_axial_center(&self) -> bool {
722 self.cg_aft_m.is_some()
723 }
724
725 pub fn is_empty(&self) -> bool {
727 self.mass_kg.is_none()
728 && self.cg_aft_m.is_none()
729 && self.cg_xy_m.is_none()
730 && self.inertia.is_none()
731 }
732
733 pub fn apply(
742 &self,
743 mass: MassProperties,
744 fore_station_m: f64,
745 ) -> Result<MassProperties, DesignError> {
746 if self.is_empty() {
747 return Ok(mass);
748 }
749 let mut out = mass;
750 if let Some(m) = self.mass_kg {
751 check_dimension("mass override (kg)", m, true)?;
752 out = if out.mass_kg > 0.0 {
753 out.scaled(m / out.mass_kg)
754 } else {
755 MassProperties::point(m, out.cg_m)
756 };
757 }
758 if let Some(aft) = self.cg_aft_m {
759 if !aft.is_finite() {
760 return Err(DesignError::Domain {
761 what: "center-of-mass override (m)",
762 value: aft,
763 });
764 }
765 out.cg_m.z = -(fore_station_m + aft);
766 }
767 if let Some([x, y]) = self.cg_xy_m {
768 for value in [x, y] {
769 if !value.is_finite() {
770 return Err(DesignError::Domain {
771 what: "off-axis center-of-mass override (m)",
772 value,
773 });
774 }
775 }
776 out.cg_m.x = x;
777 out.cg_m.y = y;
778 }
779 if let Some(inertia) = self.inertia {
780 out.inertia_kg_m2 = inertia.tensor();
781 }
782 out.validate()?;
783 Ok(out)
784 }
785
786 pub(crate) fn apply_with_parts_in_place(
802 &self,
803 whole: MassProperties,
804 placed: MassProperties,
805 fore_station_m: f64,
806 ) -> Result<MassProperties, DesignError> {
807 let mut out = self.apply(whole, fore_station_m)?;
808 if self.inertia.is_none() {
809 out.inertia_kg_m2 = if out.mass_kg > 0.0 {
810 placed.inertia_about(out.cg_m)
811 } else {
812 DMat3::ZERO
813 };
814 out.validate()?;
815 }
816 Ok(out)
817 }
818}
819
820#[derive(
844 Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, schemars::JsonSchema,
845)]
846#[serde(rename_all = "snake_case")]
847#[non_exhaustive]
848pub enum StageOverrideRule {
849 #[default]
856 Rescaled,
857 PartsInPlace,
869}
870
871impl StageOverrideRule {
872 pub fn is_rescaled(&self) -> bool {
874 *self == Self::Rescaled
875 }
876
877 pub fn weigh(
884 self,
885 parts: MassProperties,
886 added_mass: Option<AddedMass>,
887 overrides: &Overrides,
888 fore_station_m: f64,
889 ) -> Result<MassProperties, DesignError> {
890 let whole = match added_mass {
891 Some(added) => added.add_to(parts, fore_station_m)?,
892 None => parts,
893 };
894 if overrides.is_empty() {
895 return Ok(whole);
896 }
897 match self {
898 Self::Rescaled => overrides.apply(whole, fore_station_m),
899 Self::PartsInPlace => {
900 let placed = match added_mass {
904 Some(added) if added.cg_aft_m.is_some() => whole,
905 _ => parts,
906 };
907 overrides.apply_with_parts_in_place(whole, placed, fore_station_m)
908 }
909 }
910 }
911}
912
913#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
957#[serde(deny_unknown_fields)]
958pub struct AddedMass {
959 pub mass_kg: f64,
961 #[serde(default, skip_serializing_if = "Option::is_none")]
965 pub cg_aft_m: Option<f64>,
966}
967
968impl AddedMass {
969 pub fn add_to(
976 &self,
977 parts: MassProperties,
978 fore_station_m: f64,
979 ) -> Result<MassProperties, DesignError> {
980 check_dimension("added mass (kg)", self.mass_kg, true)?;
981 if let Some(aft) = self.cg_aft_m
982 && !aft.is_finite()
983 {
984 return Err(DesignError::Domain {
985 what: "added mass's station (m)",
986 value: aft,
987 });
988 }
989 if self.mass_kg == 0.0 {
990 return Ok(parts);
991 }
992 let at = match self.cg_aft_m {
993 Some(aft) if parts.mass_kg > 0.0 => {
997 DVec3::new(parts.cg_m.x, parts.cg_m.y, -(fore_station_m + aft))
998 }
999 Some(aft) => DVec3::new(0.0, 0.0, -(fore_station_m + aft)),
1000 None if parts.mass_kg > 0.0 => parts.cg_m,
1003 None => {
1004 return Err(DesignError::Domain {
1005 what: "added mass with no station, on parts that weigh nothing (kg)",
1006 value: self.mass_kg,
1007 });
1008 }
1009 };
1010 let out = MassProperties::combine(&[parts, MassProperties::point(self.mass_kg, at)]);
1011 out.validate()?;
1012 Ok(out)
1013 }
1014}
1015
1016#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
1018#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
1019#[non_exhaustive]
1020pub enum ReferenceDiameter {
1021 Maximum {},
1024 NoseBase {},
1026 Custom {
1028 diameter_m: f64,
1030 },
1031}
1032
1033impl Default for ReferenceDiameter {
1034 fn default() -> Self {
1035 Self::Maximum {}
1036 }
1037}
1038
1039#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1041pub struct PlacedComponent {
1042 pub id: String,
1044 pub stage: usize,
1046 pub parent: Option<usize>,
1049 pub part: Part,
1051 pub fore_station_m: f64,
1053 pub length_m: f64,
1055 #[serde(default)]
1057 pub finish: Finish,
1058 pub body_radius_m: Option<f64>,
1060 pub motor_mount: Option<MotorMount>,
1062 pub own: MassProperties,
1064 pub with_children: MassProperties,
1066 #[serde(default, alias = "centre_overridden")]
1069 pub center_overridden: bool,
1070 #[serde(default = "one_copy")]
1078 pub copies: Vec<Placement>,
1079 #[serde(default, skip_serializing_if = "Option::is_none")]
1081 pub drag_override: Option<DragOverride>,
1082}
1083
1084fn one_copy() -> Vec<Placement> {
1086 vec![Placement::HERE]
1087}
1088
1089impl PlacedComponent {
1090 pub fn aft_station_m(&self) -> f64 {
1092 self.fore_station_m + self.length_m
1093 }
1094
1095 pub fn contents_copies(&self) -> Result<Vec<Placement>, DesignError> {
1105 let repeats = repeats(&self.part)?;
1106 Ok(self
1107 .copies
1108 .iter()
1109 .flat_map(|copy| repeats.iter().map(move |inner| copy.after(inner)))
1110 .collect())
1111 }
1112}
1113
1114fn repeats(part: &Part) -> Result<Vec<Placement>, DesignError> {
1117 match part {
1118 Part::InnerTube(tube) => Ok(tube.tubes_m()?.into_iter().map(Placement::moved).collect()),
1119 Part::PodSet(pods) => pods.pods(),
1120 _ => Ok(one_copy()),
1121 }
1122}
1123
1124#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1126pub struct PlacedStage {
1127 pub id: String,
1129 pub fore_station_m: f64,
1131 pub aft_station_m: f64,
1133 pub mass: MassProperties,
1135 #[serde(default, alias = "centre_overridden")]
1139 pub center_overridden: bool,
1140 #[serde(default, skip_serializing_if = "Option::is_none")]
1142 pub drag_override: Option<DragOverride>,
1143 #[serde(default, skip_serializing_if = "Option::is_none")]
1146 pub hung_on: Option<usize>,
1147}
1148
1149#[derive(Debug, Clone, PartialEq)]
1152pub(crate) struct StageMasses {
1153 masses: Vec<Vec<MassProperties>>,
1155 ends: Vec<Option<(f64, f64)>>,
1157 length_m: f64,
1159}
1160
1161#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1163pub struct Layout {
1164 pub components: Vec<PlacedComponent>,
1166 pub stages: Vec<PlacedStage>,
1168 pub length_m: f64,
1171 pub reference_diameter_m: f64,
1173 pub structure: MassProperties,
1175}
1176
1177impl Layout {
1178 pub fn find(&self, id: &str) -> Option<(usize, &PlacedComponent)> {
1180 self.components.iter().enumerate().find(|(_, c)| c.id == id)
1181 }
1182
1183 pub fn body(&self) -> impl Iterator<Item = &PlacedComponent> {
1185 self.components.iter().filter(|c| c.parent.is_none())
1186 }
1187
1188 pub fn pod_set_of(&self, index: usize) -> Option<usize> {
1192 let mut parent = self.components.get(index)?.parent;
1193 for _ in 0..self.components.len() {
1194 let at = parent?;
1195 let component = self.components.get(at)?;
1196 if matches!(component.part, Part::PodSet(_)) {
1197 return Some(at);
1198 }
1199 parent = component.parent;
1200 }
1201 None
1202 }
1203
1204 pub fn motor_pod_sets(&self) -> Vec<usize> {
1208 let mut sets = Vec::new();
1209 for (index, component) in self.components.iter().enumerate() {
1210 if component.motor_mount.is_none() {
1211 continue;
1212 }
1213 if let Some(set) = self.pod_set_of(index)
1214 && !sets.contains(&set)
1215 {
1216 sets.push(set);
1217 }
1218 }
1219 sets
1220 }
1221
1222 pub fn reference_area_m2(&self) -> f64 {
1224 0.25 * std::f64::consts::PI * self.reference_diameter_m * self.reference_diameter_m
1225 }
1226}
1227
1228#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1231pub struct UnresolvableRadius {
1232 pub stage: usize,
1234 pub component: usize,
1236 pub id: String,
1238 pub dimension: AutoDimension,
1241}
1242
1243impl Rocket {
1244 pub fn layout(&self) -> Result<Layout, DesignError> {
1263 let (components, masses) = self.placed_components()?;
1264 self.staged_layout(components, &masses)
1265 }
1266
1267 pub(crate) fn placed_components(
1270 &self,
1271 ) -> Result<(Vec<PlacedComponent>, StageMasses), DesignError> {
1272 if self.stages.is_empty() {
1273 return Err(DesignError::Tree {
1274 id: self.name.clone(),
1275 message: "a rocket needs at least one stage".to_owned(),
1276 });
1277 }
1278 let mut ids = BTreeSet::new();
1279 for stage in &self.stages {
1280 if stage.components.is_empty() {
1281 return Err(tree(&stage.id, "a stage needs at least one body component"));
1282 }
1283 if stage.parallel.is_some() {
1284 continue;
1286 }
1287 unique(&mut ids, &stage.id)?;
1288 for component in &stage.components {
1289 check_node(&mut ids, component, None, 0, false)?;
1290 }
1291 }
1292 let mut hung = Hung::default();
1293 for ((k, stage), carrier) in self.stages.iter().enumerate().zip(self.carriers()?) {
1294 let (Some(parallel), Some(carrier)) = (&stage.parallel, carrier) else {
1295 continue;
1296 };
1297 let on = &self.stages[carrier.stage].components[carrier.component];
1298 if matches!(parallel.position, Position::After { .. }) {
1299 return Err(tree(
1300 &stage.id,
1301 "a parallel stage is placed along the tube it hangs on, not after a sibling",
1302 ));
1303 }
1304 if let Some(added) = self.stages[carrier.stage]
1311 .added_mass
1312 .filter(|added| added.mass_kg != 0.0)
1313 {
1314 if added.cg_aft_m.is_none() {
1315 return Err(tree(
1316 &stage.id,
1317 format!(
1318 "a parallel stage hangs on `{}`, whose stage carries an added mass \
1319 with no station. Where that mass sits once the parallel stage \
1320 drops isn't modeled",
1321 on.id
1322 ),
1323 ));
1324 }
1325 if parallel.pods.count == 1 && parallel.pods.radial_offset_m != 0.0 {
1329 return Err(tree(
1330 &stage.id,
1331 format!(
1332 "a parallel stage of one pod off the axis hangs on `{}`, whose stage \
1333 carries an added mass. How far off the axis that mass sits once \
1334 the parallel stage drops isn't modeled",
1335 on.id
1336 ),
1337 ));
1338 }
1339 }
1340 if !self.stages[carrier.stage].overrides.is_empty()
1347 || (on.overrides_include_children && !on.overrides.is_empty())
1348 {
1349 return Err(tree(
1350 &stage.id,
1351 format!(
1352 "a parallel stage hangs on `{}`, under a mass override that covers what \
1353 the tube or its stage holds. That override doesn't say whether it covers \
1354 the parallel stage",
1355 on.id
1356 ),
1357 ));
1358 }
1359 let pods = parallel_pods(stage, parallel);
1360 check_node(&mut ids, &pods, Some(&on.part), 1, false)?;
1361 hung.stages
1362 .entry(on.id.clone())
1363 .or_default()
1364 .push((k, pods));
1365 }
1366
1367 let nodes: Vec<(usize, &Component)> = self
1368 .stages
1369 .iter()
1370 .enumerate()
1371 .filter(|(_, stage)| stage.parallel.is_none())
1372 .flat_map(|(k, stage)| stage.components.iter().map(move |c| (k, c)))
1373 .collect();
1374 let mut parts: Vec<Part> = nodes.iter().map(|(_, c)| c.part.clone()).collect();
1375 let autos: Vec<&[AutoDimension]> = nodes.iter().map(|(_, c)| c.auto.as_slice()).collect();
1376 let ids: Vec<&str> = nodes.iter().map(|(_, c)| c.id.as_str()).collect();
1377 resolve_body_radii(&mut parts, &autos, &ids)?;
1378 resolve_shoulders(&mut parts, &autos, &ids)?;
1379
1380 let mut components = Vec::new();
1381 let mut stage_masses: Vec<Vec<MassProperties>> = vec![Vec::new(); self.stages.len()];
1382 let mut stage_ends: Vec<Option<(f64, f64)>> = vec![None; self.stages.len()];
1383 let mut station = 0.0;
1384 for ((stage, node), part) in nodes.iter().zip(parts) {
1385 let length = part.length_m();
1386 check_dimension("body component length", length, false)
1387 .map_err(|e| within(&node.id, e))?;
1388 let placed = place(&part, None, station, &node.id)?;
1389 let index = components.len();
1390 components.push(PlacedComponent {
1391 id: node.id.clone(),
1392 stage: *stage,
1393 parent: None,
1394 part,
1395 fore_station_m: station,
1396 length_m: length,
1397 finish: node.finish.unwrap_or_default(),
1398 body_radius_m: None,
1399 motor_mount: node.motor_mount,
1400 own: placed,
1401 with_children: placed,
1402 center_overridden: node.overrides.sets_axial_center(),
1403 copies: one_copy(),
1404 drag_override: node.drag_override,
1405 });
1406 let with_children = finish(&mut components, index, node, &mut hung)?;
1407 stage_masses[*stage].push(with_children);
1408 let ends = stage_ends[*stage].get_or_insert((station, station));
1409 ends.1 = station + length;
1410 station += length;
1411 }
1412 for (k, mass, ends) in hung.placed {
1413 stage_masses[k].push(mass);
1414 stage_ends[k] = Some(ends);
1415 }
1416 Ok((
1417 components,
1418 StageMasses {
1419 masses: stage_masses,
1420 ends: stage_ends,
1421 length_m: station,
1422 },
1423 ))
1424 }
1425
1426 pub(crate) fn staged_layout(
1430 &self,
1431 components: Vec<PlacedComponent>,
1432 masses: &StageMasses,
1433 ) -> Result<Layout, DesignError> {
1434 let mut stages = Vec::with_capacity(self.stages.len());
1435 let carriers = self.carriers()?;
1436 for ((stage, masses), ends) in self.stages.iter().zip(&masses.masses).zip(&masses.ends) {
1437 let (fore, aft) = ends.unwrap_or((0.0, 0.0));
1438 let parts = MassProperties::combine(masses);
1439 let mass = stage
1440 .override_rule
1441 .weigh(parts, stage.added_mass, &stage.overrides, fore)
1442 .map_err(|e| within(&stage.id, e))?;
1443 let hung_on = carriers[stages.len()].map(|carrier| carrier.stage);
1444 stages.push(PlacedStage {
1445 id: stage.id.clone(),
1446 fore_station_m: fore,
1447 aft_station_m: aft,
1448 mass,
1449 center_overridden: stage.overrides.sets_axial_center()
1450 || stage
1451 .added_mass
1452 .is_some_and(|added| added.cg_aft_m.is_some()),
1453 drag_override: stage.drag_override,
1454 hung_on,
1455 });
1456 }
1457 let structure = MassProperties::combine(stages.iter().map(|s| &s.mass));
1458 let reference_diameter_m = self.reference_diameter_m(&components)?;
1459 Ok(Layout {
1460 components,
1461 stages,
1462 length_m: masses.length_m,
1463 reference_diameter_m,
1464 structure,
1465 })
1466 }
1467
1468 pub fn unresolvable_body_radii(&self) -> Vec<UnresolvableRadius> {
1484 let nodes: Vec<(usize, usize, &Component)> = self
1485 .stages
1486 .iter()
1487 .enumerate()
1488 .filter(|(_, stage)| stage.parallel.is_none())
1489 .flat_map(|(k, stage)| {
1490 stage
1491 .components
1492 .iter()
1493 .enumerate()
1494 .map(move |(i, c)| (k, i, c))
1495 })
1496 .collect();
1497 let parts: Vec<&Part> = nodes.iter().map(|(_, _, c)| &c.part).collect();
1498 let autos: Vec<&[AutoDimension]> =
1499 nodes.iter().map(|(_, _, c)| c.auto.as_slice()).collect();
1500 let (fore, aft) = sweep_body_radii(&parts, &autos);
1501 let mut unresolvable = Vec::new();
1502 for (n, &(stage, component, node)) in nodes.iter().enumerate() {
1503 let mut add = |dimension| {
1504 unresolvable.push(UnresolvableRadius {
1505 stage,
1506 component,
1507 id: node.id.clone(),
1508 dimension,
1509 });
1510 };
1511 match node.part {
1512 Part::NoseCone(_) if aft[n].is_none() => add(AutoDimension::BaseRadius),
1513 Part::BodyTube(_) if aft[n].is_none() => add(AutoDimension::OuterRadius),
1514 Part::Transition(_) => {
1515 if fore[n].is_none() {
1516 add(AutoDimension::ForeRadius);
1517 }
1518 if aft[n].is_none() {
1519 add(AutoDimension::AftRadius);
1520 }
1521 }
1522 _ => {}
1523 }
1524 }
1525 unresolvable
1526 }
1527
1528 pub fn fill_unresolvable_body_radii(&mut self, radius_m: f64) -> Vec<UnresolvableRadius> {
1536 let unresolvable = self.unresolvable_body_radii();
1537 for radius in &unresolvable {
1538 let component = &mut self.stages[radius.stage].components[radius.component];
1539 match (&mut component.part, radius.dimension) {
1540 (Part::NoseCone(p), AutoDimension::BaseRadius) => p.base_radius_m = radius_m,
1541 (Part::BodyTube(p), AutoDimension::OuterRadius) => p.outer_radius_m = radius_m,
1542 (Part::Transition(p), AutoDimension::ForeRadius) => p.fore_radius_m = radius_m,
1543 (Part::Transition(p), AutoDimension::AftRadius) => p.aft_radius_m = radius_m,
1544 _ => continue,
1546 }
1547 component.auto.retain(|auto| *auto != radius.dimension);
1548 }
1549 unresolvable
1550 }
1551
1552 fn reference_diameter_m(&self, components: &[PlacedComponent]) -> Result<f64, DesignError> {
1553 let diameter = match self.reference_diameter {
1554 ReferenceDiameter::Maximum {} => {
1555 let mut widest = 0.0f64;
1556 for c in components.iter().filter(|c| c.parent.is_none()) {
1557 if let Some(r) = c.part.max_radius_m()? {
1558 widest = widest.max(r);
1559 }
1560 }
1561 2.0 * widest
1562 }
1563 ReferenceDiameter::NoseBase {} => components
1565 .iter()
1566 .filter(|c| c.parent.is_none())
1567 .find_map(|c| match &c.part {
1568 Part::NoseCone(nose) => Some(2.0 * nose.base_radius_m),
1569 _ => None,
1570 })
1571 .ok_or_else(|| {
1572 tree(
1573 &self.name,
1574 "the reference diameter is the nose base, but there is no nose cone",
1575 )
1576 })?,
1577 ReferenceDiameter::Custom { diameter_m } => diameter_m,
1578 };
1579 check_dimension("reference diameter (m)", diameter, false)?;
1580 Ok(diameter)
1581 }
1582}
1583
1584fn within(id: &str, error: DesignError) -> DesignError {
1586 DesignError::InComponent {
1587 id: id.to_owned(),
1588 source: Box::new(error),
1589 }
1590}
1591
1592pub const MAX_DEPTH: usize = 32;
1596
1597fn tree(id: &str, message: impl Into<String>) -> DesignError {
1598 DesignError::Tree {
1599 id: id.to_owned(),
1600 message: message.into(),
1601 }
1602}
1603
1604fn unique(ids: &mut BTreeSet<String>, id: &str) -> Result<(), DesignError> {
1605 if id.is_empty() || !ids.insert(id.to_owned()) {
1606 return Err(DesignError::DuplicateId(id.to_owned()));
1607 }
1608 Ok(())
1609}
1610
1611fn check_node(
1614 ids: &mut BTreeSet<String>,
1615 node: &Component,
1616 parent: Option<&Part>,
1617 depth: usize,
1618 in_pod: bool,
1619) -> Result<(), DesignError> {
1620 unique(ids, &node.id)?;
1621 if let Some(finish) = node.finish {
1622 finish.roughness_m().map_err(|e| within(&node.id, e))?;
1623 }
1624 if depth >= MAX_DEPTH {
1625 return Err(tree(
1626 &node.id,
1627 format!("components nest more than {MAX_DEPTH} deep"),
1628 ));
1629 }
1630 let kind = node.part.kind_name();
1631 match (parent, node.part.role()) {
1632 (None | Some(Part::PodSet(_)), Role::Body) => {
1633 if node.position.is_some() {
1634 return Err(tree(
1635 &node.id,
1636 "a body component stacks and takes no position",
1637 ));
1638 }
1639 }
1640 (Some(Part::PodSet(_)), _) => {
1641 return Err(tree(
1642 &node.id,
1643 format!("a pod holds body components; attach a {kind} to one of them"),
1644 ));
1645 }
1646 (None, _) => {
1647 return Err(tree(
1648 &node.id,
1649 format!("a {kind} can't be a body component; attach it to one"),
1650 ));
1651 }
1652 (Some(_), Role::Body) => {
1653 return Err(tree(
1654 &node.id,
1655 format!("a {kind} is a body component; list it in a stage"),
1656 ));
1657 }
1658 (Some(parent), Role::External)
1661 if !(matches!(parent, Part::BodyTube(_))
1662 || matches!(node.part, Part::FinSet(_))
1663 && matches!(parent, Part::NoseCone(_) | Part::Transition(_))) =>
1664 {
1665 return Err(tree(
1666 &node.id,
1667 format!(
1668 "a {kind} attaches to a body tube{}, not a {}",
1669 if matches!(node.part, Part::FinSet(_)) {
1670 ", a nose cone or a transition"
1671 } else {
1672 ""
1673 },
1674 parent.kind_name()
1675 ),
1676 ));
1677 }
1678 (Some(parent), Role::Internal)
1679 if !(parent.is_body() || matches!(parent, Part::InnerTube(_))) =>
1680 {
1681 return Err(tree(
1682 &node.id,
1683 format!("a {kind} can't go inside a {}", parent.kind_name()),
1684 ));
1685 }
1686 (Some(_), _) => {
1687 if node.position.is_none() {
1688 return Err(tree(&node.id, "an attached part needs a position"));
1689 }
1690 }
1691 }
1692 for auto in &node.auto {
1693 if !auto.applies_to(&node.part) {
1694 return Err(tree(
1695 &node.id,
1696 format!("a {kind} has no automatic {} dimension", auto.name()),
1697 ));
1698 }
1699 }
1700 if matches!(node.part, Part::PodSet(_)) {
1701 if in_pod {
1702 return Err(tree(&node.id, "a pod set can't hang from a pod"));
1703 }
1704 if !node.overrides.is_empty() && !node.overrides_include_children {
1705 return Err(tree(
1706 &node.id,
1707 "a pod set weighs nothing of its own, so an override on it must cover its pods \
1708 (`overrides_include_children`)",
1709 ));
1710 }
1711 }
1712 if node.motor_mount.is_some() && !matches!(node.part, Part::BodyTube(_) | Part::InnerTube(_)) {
1713 return Err(tree(&node.id, format!("a {kind} can't be a motor mount")));
1714 }
1715 if !node.children.is_empty()
1716 && !(node.part.is_body() || matches!(node.part, Part::InnerTube(_) | Part::PodSet(_)))
1717 {
1718 return Err(tree(
1719 &node.id,
1720 format!("a {kind} can't have attached parts"),
1721 ));
1722 }
1723 for child in &node.children {
1724 let in_pod = in_pod || matches!(node.part, Part::PodSet(_));
1725 check_node(ids, child, Some(&node.part), depth + 1, in_pod)?;
1726 }
1727 Ok(())
1728}
1729
1730fn resolve_body_radii(
1733 parts: &mut [Part],
1734 autos: &[&[AutoDimension]],
1735 ids: &[&str],
1736) -> Result<(), DesignError> {
1737 let (fore, aft) = sweep_body_radii(parts, autos);
1738 for (i, part) in parts.iter_mut().enumerate() {
1739 let missing = || {
1740 tree(
1741 ids[i],
1742 "an automatic radius has no fixed radius among its neighbors to take",
1743 )
1744 };
1745 match part {
1746 Part::NoseCone(p) => p.base_radius_m = aft[i].ok_or_else(missing)?,
1747 Part::BodyTube(p) => p.outer_radius_m = aft[i].ok_or_else(missing)?,
1748 Part::Transition(p) => {
1749 p.fore_radius_m = fore[i].ok_or_else(missing)?;
1750 p.aft_radius_m = aft[i].ok_or_else(missing)?;
1751 }
1752 _ => {}
1753 }
1754 }
1755 Ok(())
1756}
1757
1758fn sweep_body_radii<P: std::borrow::Borrow<Part>>(
1768 parts: &[P],
1769 autos: &[&[AutoDimension]],
1770) -> (Vec<Option<f64>>, Vec<Option<f64>>) {
1771 let n = parts.len();
1772 let is_auto = |i: usize, a: AutoDimension| autos[i].contains(&a);
1773 let mut fore: Vec<Option<f64>> = Vec::with_capacity(n);
1774 let mut aft: Vec<Option<f64>> = Vec::with_capacity(n);
1775 for (i, part) in parts.iter().enumerate() {
1776 let (f, a) = match part.borrow() {
1777 Part::NoseCone(p) => (
1778 Some(0.0),
1779 (!is_auto(i, AutoDimension::BaseRadius)).then_some(p.base_radius_m),
1780 ),
1781 Part::BodyTube(p) => {
1782 let r = (!is_auto(i, AutoDimension::OuterRadius)).then_some(p.outer_radius_m);
1783 (r, r)
1784 }
1785 Part::Transition(p) => (
1786 (!is_auto(i, AutoDimension::ForeRadius)).then_some(p.fore_radius_m),
1787 (!is_auto(i, AutoDimension::AftRadius)).then_some(p.aft_radius_m),
1788 ),
1789 _ => (None, None),
1790 };
1791 fore.push(f);
1792 aft.push(a);
1793 }
1794 loop {
1795 let mut progress = false;
1796 for i in 0..n {
1797 let previous_aft = if i > 0 { aft[i - 1] } else { None };
1798 let next_fore = fore.get(i + 1).copied().flatten();
1799 match parts[i].borrow() {
1800 Part::NoseCone(_) => {
1801 if aft[i].is_none()
1802 && let Some(r) = next_fore
1803 {
1804 aft[i] = Some(r);
1805 progress = true;
1806 }
1807 }
1808 Part::BodyTube(_) => {
1809 if fore[i].is_none()
1810 && let Some(r) = previous_aft
1811 {
1812 fore[i] = Some(r);
1813 aft[i] = Some(r);
1814 progress = true;
1815 }
1816 }
1817 Part::Transition(_) => {
1818 if fore[i].is_none()
1819 && let Some(r) = previous_aft
1820 {
1821 fore[i] = Some(r);
1822 progress = true;
1823 }
1824 if aft[i].is_none()
1825 && let Some(r) = next_fore
1826 {
1827 aft[i] = Some(r);
1828 progress = true;
1829 }
1830 }
1831 _ => {}
1832 }
1833 }
1834 if progress {
1835 continue;
1836 }
1837 let fallback = (0..n).find(|&i| {
1838 matches!(parts[i].borrow(), Part::BodyTube(_))
1839 && fore[i].is_none()
1840 && fore.get(i + 1).copied().flatten().is_some()
1841 });
1842 match fallback {
1843 Some(i) => {
1844 fore[i] = fore[i + 1];
1845 aft[i] = fore[i + 1];
1846 }
1847 None => break,
1848 }
1849 }
1850 (fore, aft)
1851}
1852
1853fn resolve_shoulders(
1855 parts: &mut [Part],
1856 autos: &[&[AutoDimension]],
1857 ids: &[&str],
1858) -> Result<(), DesignError> {
1859 let inner = |parts: &[Part], i: Option<usize>| -> Option<f64> {
1860 match i.and_then(|i| parts.get(i)) {
1861 Some(Part::BodyTube(t)) => Some(t.outer_radius_m - t.thickness_m),
1862 _ => None,
1863 }
1864 };
1865 for i in 0..parts.len() {
1866 let previous = inner(parts, i.checked_sub(1));
1867 let next = inner(parts, Some(i + 1));
1868 let fit = |shoulder: &mut Option<crate::parts::Shoulder>,
1869 radius: Option<f64>,
1870 which: &str|
1871 -> Result<(), DesignError> {
1872 let Some(shoulder) = shoulder else {
1873 return Err(tree(
1874 ids[i],
1875 format!("an automatic {which} shoulder radius needs a shoulder"),
1876 ));
1877 };
1878 shoulder.outer_radius_m = radius.ok_or_else(|| {
1879 tree(
1880 ids[i],
1881 format!("an automatic {which} shoulder radius needs a body tube there"),
1882 )
1883 })?;
1884 Ok(())
1885 };
1886 match &mut parts[i] {
1887 Part::NoseCone(p) if autos[i].contains(&AutoDimension::ShoulderRadius) => {
1888 fit(&mut p.shoulder, next, "aft")?;
1889 }
1890 Part::Transition(p) => {
1891 if autos[i].contains(&AutoDimension::ForeShoulderRadius) {
1892 fit(&mut p.fore_shoulder, previous, "forward")?;
1893 }
1894 if autos[i].contains(&AutoDimension::AftShoulderRadius) {
1895 fit(&mut p.aft_shoulder, next, "aft")?;
1896 }
1897 }
1898 _ => {}
1899 }
1900 }
1901 Ok(())
1902}
1903
1904fn place(
1906 part: &Part,
1907 body_radius_m: Option<f64>,
1908 fore_station_m: f64,
1909 id: &str,
1910) -> Result<MassProperties, DesignError> {
1911 let mass = part
1912 .mass_properties(body_radius_m)
1913 .map_err(|e| within(id, e))?;
1914 Ok(mass.translated(DVec3::new(0.0, 0.0, -fore_station_m)))
1915}
1916
1917fn packed_for_override(
1927 part: &Part,
1928 overrides: &Overrides,
1929 mass: MassProperties,
1930 fore_station_m: f64,
1931) -> Result<MassProperties, DesignError> {
1932 match (overrides.mass_kg, part.packing()) {
1933 (Some(mass_kg), Some(packing)) => {
1936 check_dimension("mass override (kg)", mass_kg, true)?;
1937 Ok(packing
1938 .place(mass_kg)?
1939 .translated(DVec3::new(0.0, 0.0, -fore_station_m)))
1940 }
1941 _ => Ok(mass),
1942 }
1943}
1944
1945#[derive(Default)]
1948struct Hung {
1949 stages: BTreeMap<String, Vec<(usize, Component)>>,
1952 placed: Vec<(usize, MassProperties, (f64, f64))>,
1954}
1955
1956fn parallel_pods(stage: &Stage, parallel: &ParallelStage) -> Component {
1960 Component {
1961 id: stage.id.clone(),
1962 name: stage.name.clone(),
1963 part: Part::PodSet(parallel.pods.clone()),
1964 position: Some(parallel.position),
1965 auto: Vec::new(),
1966 motor_mount: None,
1967 finish: None,
1968 overrides: Overrides::default(),
1969 overrides_include_children: false,
1970 drag_override: None,
1971 children: stage.components.clone(),
1972 }
1973}
1974
1975#[derive(Debug, Clone, Copy)]
1977struct Carrier {
1978 stage: usize,
1979 component: usize,
1980}
1981
1982impl Rocket {
1983 fn carriers(&self) -> Result<Vec<Option<Carrier>>, DesignError> {
1991 let mut tubes: BTreeMap<&str, Carrier> = BTreeMap::new();
1992 let mut carriers = Vec::with_capacity(self.stages.len());
1993 for (k, stage) in self.stages.iter().enumerate() {
1994 let Some(parallel) = &stage.parallel else {
1995 for (component, c) in stage.components.iter().enumerate() {
1996 if matches!(c.part, Part::BodyTube(_)) {
1997 tubes.entry(&c.id).or_insert(Carrier {
1998 stage: k,
1999 component,
2000 });
2001 }
2002 }
2003 carriers.push(None);
2004 continue;
2005 };
2006 let carrier = tubes.get(parallel.on.as_str()).copied().ok_or_else(|| {
2007 tree(
2008 &stage.id,
2009 format!(
2010 "a parallel stage hangs on a body tube of an axial stage before it, and \
2011 `{}` is none",
2012 parallel.on
2013 ),
2014 )
2015 })?;
2016 carriers.push(Some(carrier));
2017 }
2018 Ok(carriers)
2019 }
2020}
2021
2022fn finish(
2032 components: &mut Vec<PlacedComponent>,
2033 index: usize,
2034 node: &Component,
2035 hung: &mut Hung,
2036) -> Result<MassProperties, DesignError> {
2037 let hanging: Vec<(usize, Component)> = hung.stages.get(&node.id).cloned().unwrap_or_default();
2040 let children: Vec<(&Component, Option<usize>)> = node
2041 .children
2042 .iter()
2043 .map(|child| (child, None))
2044 .chain(hanging.iter().map(|(k, pods)| (pods, Some(*k))))
2045 .collect();
2046 let parent = &components[index];
2047 let (p_fore, p_length, stage) = (parent.fore_station_m, parent.length_m, parent.stage);
2048 let (p_kind, p_inner) = (parent.part.kind_name(), parent.part.inner_radius_m());
2049 let p_axis = parent.part.axis_offset_m();
2050 let pod = matches!(parent.part, Part::PodSet(_));
2052 let p_tubes = repeats(&parent.part).map_err(|e| within(&node.id, e))?;
2055 let p_copies = parent.copies.clone();
2056 let p_contents = parent.contents_copies().map_err(|e| within(&node.id, e))?;
2057 let p_tube_radius = match &parent.part {
2058 Part::BodyTube(tube) => Some(tube.outer_radius_m),
2059 _ => None,
2060 };
2061 let p_surface = match &parent.part {
2063 Part::NoseCone(nose) => Some(nose.profile()),
2064 Part::Transition(part) => Some(part.profile()),
2065 _ => None,
2066 }
2067 .transpose()
2068 .map_err(|e| within(&node.id, e))?;
2069 let shell = |wall: &Wall| match wall {
2072 Wall::Shell { thickness_m } => Some(*thickness_m),
2073 Wall::Filled {} => None,
2074 };
2075 let p_narrowing = match &parent.part {
2076 Part::NoseCone(nose) => shell(&nose.wall).map(|t| nose.profile().map(|p| (p, t))),
2077 Part::Transition(part) => shell(&part.wall).map(|t| part.profile().map(|p| (p, t))),
2078 _ => None,
2079 }
2080 .transpose()
2081 .map_err(|e| within(&node.id, e))?;
2082 let own = if node.overrides_include_children {
2083 parent.own
2084 } else {
2085 packed_for_override(&parent.part, &node.overrides, parent.own, p_fore)
2086 .and_then(|own| node.overrides.apply(own, p_fore))
2087 .map_err(|e| within(&node.id, e))?
2088 };
2089
2090 let mut stations = Vec::with_capacity(children.len());
2093 let mut previous_aft = None;
2094 for &(child, _) in &children {
2095 let length = child.length_m();
2096 check_dimension("attached part length", length, true).map_err(|e| within(&child.id, e))?;
2097 let fore = if pod {
2098 previous_aft.unwrap_or(p_fore)
2099 } else {
2100 match child.position {
2101 Some(Position::Top { aft_offset_m }) => p_fore + aft_offset_m,
2102 Some(Position::Middle { aft_offset_m }) => {
2103 p_fore + 0.5 * (p_length - length) + aft_offset_m
2104 }
2105 Some(Position::Bottom { aft_offset_m }) => {
2106 p_fore + p_length - length + aft_offset_m
2107 }
2108 Some(Position::After { aft_offset_m }) => {
2109 previous_aft.unwrap_or(p_fore) + aft_offset_m
2110 }
2111 Some(Position::Absolute { station_m }) => station_m,
2112 None => return Err(tree(&child.id, "an attached part needs a position")),
2113 }
2114 };
2115 if !fore.is_finite() {
2116 return Err(within(
2117 &child.id,
2118 DesignError::Domain {
2119 what: "attached part position (m)",
2120 value: fore,
2121 },
2122 ));
2123 }
2124 stations.push((fore, length));
2125 previous_aft = Some(fore + length);
2126 }
2127
2128 let bore = |id: &str| {
2129 p_inner.ok_or_else(|| {
2130 tree(
2131 id,
2132 format!("an automatic radius needs a tube's inner radius, and a {p_kind} has none"),
2133 )
2134 })
2135 };
2136 let bore_over = |id: &str, (fore, length): (f64, f64)| match &p_narrowing {
2144 Some((profile, wall_m)) => {
2145 let at = |station: f64| profile.radius_m(station - p_fore);
2146 Ok((at(fore).min(at(fore + length)) - wall_m).max(0.0))
2147 }
2148 None => bore(id),
2149 };
2150 let mut resolved: Vec<Part> = children.iter().map(|(c, _)| c.part.clone()).collect();
2158 if pod {
2159 let autos: Vec<&[AutoDimension]> =
2161 node.children.iter().map(|c| c.auto.as_slice()).collect();
2162 let ids: Vec<&str> = node.children.iter().map(|c| c.id.as_str()).collect();
2163 resolve_body_radii(&mut resolved, &autos, &ids)?;
2164 resolve_shoulders(&mut resolved, &autos, &ids)?;
2165 }
2166 for ((part, &(child, _)), &station) in resolved.iter_mut().zip(&children).zip(&stations) {
2167 if child.auto.contains(&AutoDimension::OuterRadius) {
2168 match part {
2169 Part::CenteringRing(ring) => ring.outer_radius_m = bore_over(&child.id, station)?,
2170 Part::InnerTube(tube) => {
2173 tube.outer_radius_m = bore_over(&child.id, station)?;
2174 tube.thickness_m = tube.thickness_m.min(tube.outer_radius_m);
2175 }
2176 Part::TubeFinSet(tubes) => {
2180 let body_radius_m = p_tube_radius.ok_or_else(|| {
2181 tree(
2182 &child.id,
2183 "an automatic tube fin radius needs a body tube to ring",
2184 )
2185 })?;
2186 tubes.outer_radius_m =
2187 crate::TubeFinSet::closing_radius_m(body_radius_m, tubes.count);
2188 tubes.thickness_m = tubes.thickness_m.min(tubes.outer_radius_m);
2189 }
2190 _ => {}
2191 }
2192 }
2193 }
2194
2195 let mut parts = vec![own];
2196 for (k, &(child, hung_stage)) in children.iter().enumerate() {
2197 let (fore, length) = stations[k];
2198 let mut part = resolved[k].clone();
2199 let parent_inner = || bore(&child.id);
2200 let packed = |packing: &mut crate::parts::Packing| -> Result<(), DesignError> {
2202 let (x, y) = (
2203 packing.radial_offset_m * packing.angle_rad.cos(),
2204 packing.radial_offset_m * packing.angle_rad.sin(),
2205 );
2206 let room = parent_inner()? - (x - p_axis[0]).hypot(y - p_axis[1]);
2207 if !(room.is_finite() && room > 0.0) {
2208 return Err(tree(
2209 &child.id,
2210 "an automatic packed radius needs a radial offset inside the parent's bore",
2211 ));
2212 }
2213 packing.radius_m = room;
2214 Ok(())
2215 };
2216 for auto in &child.auto {
2217 match (auto, &mut part) {
2218 (AutoDimension::OuterRadius, _) => {}
2220 (AutoDimension::InnerRadius, Part::CenteringRing(ring)) => {
2221 let aft = fore + length;
2222 let outer_radius_m = ring.outer_radius_m;
2228 ring.inner_radius_m = resolved
2229 .iter()
2230 .zip(&stations)
2231 .filter_map(|(sibling, &(s_fore, s_length))| match sibling {
2232 Part::InnerTube(tube)
2233 if tube.radial_offset_m == 0.0
2234 && tube.outer_radius_m < outer_radius_m
2235 && s_fore.max(fore) < (s_fore + s_length).min(aft) =>
2236 {
2237 Some(tube.outer_radius_m)
2238 }
2239 _ => None,
2240 })
2241 .fold(0.0, f64::max);
2242 }
2243 (AutoDimension::PackedRadius, Part::MassComponent(p)) => packed(&mut p.packing)?,
2244 (AutoDimension::PackedRadius, Part::Parachute(p)) => packed(&mut p.packing)?,
2245 (AutoDimension::PackedRadius, Part::Streamer(p)) => packed(&mut p.packing)?,
2246 (AutoDimension::PackedRadius, Part::ShockCord(p)) => packed(&mut p.packing)?,
2247 _ => {}
2248 }
2249 }
2250 let body_radius_m = match (&part, &p_surface) {
2253 (Part::FinSet(fins), Some(surface)) => Some(
2254 fins.root_radius_on(surface, fore - p_fore)
2255 .map_err(|e| within(&child.id, e))?,
2256 ),
2257 _ if part.is_external() => {
2258 if let Part::FinSet(fins) = &part {
2259 fins.check_level_root().map_err(|e| within(&child.id, e))?;
2260 }
2261 Some(
2262 p_tube_radius
2263 .ok_or_else(|| tree(&child.id, "external parts attach to a body tube"))?,
2264 )
2265 }
2266 _ => None,
2267 };
2268 let placed = place(&part, body_radius_m, fore, &child.id)?;
2270 let child_index = components.len();
2271 components.push(PlacedComponent {
2272 id: child.id.clone(),
2273 stage: hung_stage.unwrap_or(stage),
2274 parent: Some(index),
2275 part,
2276 fore_station_m: fore,
2277 length_m: length,
2278 finish: child.finish.unwrap_or_default(),
2279 body_radius_m,
2280 motor_mount: child.motor_mount,
2281 own: placed,
2282 with_children: placed,
2283 center_overridden: child.overrides.sets_axial_center(),
2284 copies: p_contents.clone(),
2285 drag_override: child.drag_override,
2286 });
2287 let mass = MassProperties::placed(finish(components, child_index, child, hung)?, &p_tubes);
2288 match hung_stage {
2289 Some(k) => hung.placed.push((k, mass, (fore, fore + length))),
2290 None => parts.push(mass),
2291 }
2292 }
2293
2294 let mut with_children = MassProperties::combine(&parts);
2295 if node.overrides_include_children {
2296 with_children = packed_for_override(
2297 &components[index].part,
2298 &node.overrides,
2299 with_children,
2300 p_fore,
2301 )
2302 .and_then(|mass| node.overrides.apply(mass, p_fore))
2303 .map_err(|e| within(&node.id, e))?;
2304 }
2305 components[index].own = MassProperties::placed(own, &p_copies);
2306 components[index].with_children = MassProperties::placed(with_children, &p_copies);
2307 Ok(with_children)
2308}
2309
2310#[cfg(test)]
2311mod tests {
2312 use proptest::prelude::*;
2313
2314 use super::*;
2315 use crate::parts::Shoulder;
2316 use crate::testing::{
2317 attached, body, bottom, fins, inner_tube, mass_component, nose, ring, rocket, stage,
2318 three_fin_rocket, top, tube,
2319 };
2320
2321 fn close(got: f64, want: f64, tol: f64, what: &str) {
2322 assert!((got - want).abs() <= tol, "{what}: {got} vs {want}");
2323 }
2324
2325 fn station(layout: &Layout, id: &str) -> f64 {
2326 layout.find(id).unwrap().1.fore_station_m
2327 }
2328
2329 #[test]
2332 fn stacks_body_components_and_places_attached_parts() {
2333 let mut airframe = body("airframe", tube(0.8, 0.03, 0.001));
2334 let mut coupler = attached("coupler", inner_tube(0.2, 0.029, 0.001), top(0.1));
2335 coupler.children = vec![attached(
2336 "bay",
2337 mass_component(0.1, 0.05, 0.02),
2338 Position::After { aft_offset_m: 0.02 },
2339 )];
2340 airframe.children = vec![
2341 coupler,
2342 attached(
2343 "middle",
2344 mass_component(0.1, 0.1, 0.02),
2345 Position::Middle { aft_offset_m: 0.02 },
2346 ),
2347 attached("bottom", mass_component(0.1, 0.1, 0.02), bottom(-0.01)),
2348 attached(
2349 "after",
2350 mass_component(0.1, 0.004, 0.02),
2351 Position::After {
2352 aft_offset_m: 0.001,
2353 },
2354 ),
2355 attached(
2356 "absolute",
2357 mass_component(0.1, 0.05, 0.02),
2358 Position::Absolute { station_m: 0.4 },
2359 ),
2360 ];
2361 let design = rocket(vec![
2362 stage("upper", vec![body("nose", nose(0.2, 0.03)), airframe]),
2363 stage(
2364 "booster",
2365 vec![
2366 body(
2367 "interstage",
2368 Part::Transition(Transition {
2369 shape: crate::NoseShape::Conical {},
2370 clipped: false,
2371 length_m: 0.1,
2372 fore_radius_m: 0.03,
2373 aft_radius_m: 0.04,
2374 wall: crate::Wall::Shell { thickness_m: 0.002 },
2375 fore_shoulder: None,
2376 aft_shoulder: None,
2377 material: crate::testing::cardboard(),
2378 }),
2379 ),
2380 body("booster-tube", tube(0.5, 0.04, 0.001)),
2381 ],
2382 ),
2383 ]);
2384 let layout = design.layout().unwrap();
2385 let tol = 1e-15;
2386 close(station(&layout, "nose"), 0.0, tol, "nose");
2387 close(station(&layout, "airframe"), 0.2, tol, "airframe");
2388 close(station(&layout, "coupler"), 0.3, tol, "top");
2389 close(station(&layout, "bay"), 0.32, tol, "after, first child");
2391 close(station(&layout, "middle"), 0.2 + 0.35 + 0.02, tol, "middle");
2392 close(station(&layout, "bottom"), 1.0 - 0.1 - 0.01, tol, "bottom");
2393 close(station(&layout, "after"), 0.99 + 0.001, tol, "after");
2394 close(station(&layout, "absolute"), 0.4, tol, "absolute");
2395 close(station(&layout, "interstage"), 1.0, tol, "second stage");
2396 close(station(&layout, "booster-tube"), 1.1, tol, "booster tube");
2397 close(layout.length_m, 1.6, tol, "length");
2398 let [upper, booster] = &layout.stages[..] else {
2399 panic!("two stages")
2400 };
2401 close(upper.fore_station_m, 0.0, tol, "upper fore");
2402 close(upper.aft_station_m, 1.0, tol, "upper aft");
2403 close(booster.fore_station_m, 1.0, tol, "booster fore");
2404 close(booster.aft_station_m, 1.6, tol, "booster aft");
2405 let (bay, placed) = layout.find("bay").unwrap();
2406 assert_eq!(
2407 layout.components[placed.parent.unwrap()].id,
2408 "coupler",
2409 "parent"
2410 );
2411 assert_eq!(layout.components[bay].stage, 0);
2412 assert_eq!(layout.find("booster-tube").unwrap().1.stage, 1);
2413 let own = mass_component(0.1, 0.05, 0.02)
2415 .mass_properties(None)
2416 .unwrap();
2417 close(placed.own.cg_m.z, own.cg_m.z - 0.32, 1e-15, "placed center");
2418 let sum: f64 = layout.body().map(|c| c.with_children.mass_kg).sum();
2420 close(layout.structure.mass_kg, sum, 1e-15, "structure mass");
2421 }
2422
2423 #[test]
2429 fn a_fin_set_on_a_nose_cone_follows_its_surface() {
2430 let fin = |end_h: f64| {
2431 let mut set = match fins(0.05, 0.04) {
2432 Part::FinSet(set) => set,
2433 _ => unreachable!("`fins` makes a fin set"),
2434 };
2435 set.planform = crate::FinPlanform::Freeform {
2436 points_m: vec![[0.0, 0.0], [0.03, 0.04], [0.05, end_h]],
2437 root_m: Vec::new(),
2438 };
2439 set
2440 };
2441 let design = |child: Component, on_the_nose: bool| {
2442 let mut nose_cone = body("nose", nose(0.2, 0.03));
2443 let mut airframe = body("airframe", tube(0.6, 0.03, 0.001));
2444 if on_the_nose {
2445 nose_cone.children = vec![child];
2446 } else {
2447 airframe.children = vec![child];
2448 }
2449 rocket(vec![stage("only", vec![nose_cone, airframe])])
2450 };
2451 let layout = design(
2452 attached("cockpit", Part::FinSet(fin(0.0075)), bottom(0.0)),
2453 true,
2454 )
2455 .layout()
2456 .unwrap();
2457 let (_, placed) = layout.find("cockpit").unwrap();
2458 close(placed.fore_station_m, 0.15, 1e-15, "root leading edge");
2459 close(placed.body_radius_m.unwrap(), 0.0225, 1e-15, "body radius");
2460 close(
2461 placed.own.mass_kg,
2462 fin(0.0075).mass_properties(0.0225).unwrap().mass_kg,
2463 1e-15,
2464 "mass",
2465 );
2466 let refused = |child: Component, on_the_nose: bool, says: &str| {
2467 let err = design(child, on_the_nose).layout().unwrap_err().to_string();
2468 assert!(err.contains(says), "{says}: {err}");
2469 };
2470 refused(
2471 attached("rising", Part::FinSet(fin(0.0075)), bottom(0.0)),
2472 false,
2473 "needs a level root",
2474 );
2475 refused(
2476 attached("level", fins(0.05, 0.04), bottom(0.0)),
2477 true,
2478 "stands",
2479 );
2480 refused(
2481 attached("short", Part::FinSet(fin(0.0075)), bottom(0.01)),
2482 true,
2483 "must stay on it",
2484 );
2485 let lug = Part::LaunchLug(crate::LaunchLug {
2486 length_m: 0.03,
2487 outer_radius_m: 0.003,
2488 thickness_m: 0.0005,
2489 angle_rad: 0.0,
2490 count: 1,
2491 spacing_m: 0.0,
2492 material: crate::testing::cardboard(),
2493 });
2494 refused(
2495 attached("lug", lug, bottom(0.0)),
2496 true,
2497 "a launch_lug attaches to a body tube, not a nose_cone",
2498 );
2499 }
2500
2501 #[test]
2505 fn automatic_radii_follow_neighbors_across_stages() {
2506 let auto = |mut c: Component, dims: &[AutoDimension]| {
2507 c.auto = dims.to_vec();
2508 c
2509 };
2510 let transition = Part::Transition(Transition {
2511 shape: crate::NoseShape::Conical {},
2512 clipped: false,
2513 length_m: 0.1,
2514 fore_radius_m: 0.0,
2515 aft_radius_m: 0.04,
2516 wall: crate::Wall::Filled {},
2517 fore_shoulder: Some(Shoulder {
2518 length_m: 0.05,
2519 outer_radius_m: 0.0,
2520 thickness_m: 0.002,
2521 capped: false,
2522 }),
2523 aft_shoulder: None,
2524 material: crate::testing::cardboard(),
2525 });
2526 let mut nose_cone = auto(body("nose", nose(0.2, 0.0)), &[AutoDimension::BaseRadius]);
2527 if let Part::NoseCone(n) = &mut nose_cone.part {
2528 n.shoulder = Some(Shoulder {
2529 length_m: 0.05,
2530 outer_radius_m: 0.0,
2531 thickness_m: 0.002,
2532 capped: true,
2533 });
2534 }
2535 nose_cone.auto.push(AutoDimension::ShoulderRadius);
2536 let design = rocket(vec![
2537 stage(
2538 "upper",
2539 vec![nose_cone, body("upper-tube", tube(0.5, 0.03, 0.001))],
2540 ),
2541 stage(
2542 "booster",
2543 vec![
2544 auto(
2545 body("interstage", transition),
2546 &[AutoDimension::ForeRadius, AutoDimension::ForeShoulderRadius],
2547 ),
2548 auto(
2549 body("booster-tube", tube(0.5, 0.0, 0.001)),
2550 &[AutoDimension::OuterRadius],
2551 ),
2552 ],
2553 ),
2554 ]);
2555 let layout = design.layout().unwrap();
2556 let part = |id: &str| layout.find(id).unwrap().1.part.clone();
2557 let Part::NoseCone(n) = part("nose") else {
2558 panic!()
2559 };
2560 assert_eq!(n.base_radius_m, 0.03);
2561 assert_eq!(n.shoulder.unwrap().outer_radius_m, 0.03 - 0.001);
2562 let Part::Transition(t) = part("interstage") else {
2563 panic!()
2564 };
2565 assert_eq!(t.fore_radius_m, 0.03);
2566 assert_eq!(t.fore_shoulder.unwrap().outer_radius_m, 0.03 - 0.001);
2567 let Part::BodyTube(b) = part("booster-tube") else {
2568 panic!()
2569 };
2570 assert_eq!(b.outer_radius_m, 0.04);
2571
2572 let design = rocket(vec![stage(
2574 "only",
2575 vec![
2576 auto(body("nose", nose(0.2, 0.0)), &[AutoDimension::BaseRadius]),
2577 auto(
2578 body("a", tube(0.3, 0.0, 0.001)),
2579 &[AutoDimension::OuterRadius],
2580 ),
2581 body("b", tube(0.3, 0.05, 0.001)),
2582 ],
2583 )]);
2584 let layout = design.layout().unwrap();
2585 assert_eq!(layout.find("a").unwrap().1.part.aft_radius_m(), Some(0.05));
2586 assert_eq!(
2587 layout.find("nose").unwrap().1.part.aft_radius_m(),
2588 Some(0.05)
2589 );
2590 let design = rocket(vec![stage(
2592 "only",
2593 vec![
2594 body("nose", nose(0.2, 0.02)),
2595 auto(
2596 body("a", tube(0.3, 0.0, 0.001)),
2597 &[AutoDimension::OuterRadius],
2598 ),
2599 body("b", tube(0.3, 0.05, 0.001)),
2600 ],
2601 )]);
2602 let layout = design.layout().unwrap();
2603 assert_eq!(layout.find("a").unwrap().1.part.aft_radius_m(), Some(0.02));
2604
2605 let design = rocket(vec![stage(
2607 "only",
2608 vec![
2609 auto(body("nose", nose(0.2, 0.0)), &[AutoDimension::BaseRadius]),
2610 auto(
2611 body("a", tube(0.3, 0.0, 0.001)),
2612 &[AutoDimension::OuterRadius],
2613 ),
2614 ],
2615 )]);
2616 assert!(matches!(
2617 design.layout(),
2618 Err(DesignError::Tree { ref id, .. }) if id == "nose"
2619 ));
2620 }
2621
2622 fn cone_transition(fore_radius_m: f64, aft_radius_m: f64) -> Part {
2624 Part::Transition(Transition {
2625 shape: crate::NoseShape::Conical {},
2626 clipped: false,
2627 length_m: 0.1,
2628 fore_radius_m,
2629 aft_radius_m,
2630 wall: crate::Wall::Shell { thickness_m: 0.001 },
2631 fore_shoulder: None,
2632 aft_shoulder: None,
2633 material: crate::testing::cardboard(),
2634 })
2635 }
2636
2637 #[test]
2643 fn unresolvable_body_radii_are_the_chain_with_nothing_fixed() {
2644 let auto = |mut c: Component, dims: &[AutoDimension]| {
2645 c.auto = dims.to_vec();
2646 c
2647 };
2648 let mut design = rocket(vec![stage(
2649 "only",
2650 vec![
2651 auto(body("nose", nose(0.3, 0.0)), &[AutoDimension::BaseRadius]),
2652 auto(
2653 body("upper", tube(0.5, 0.0, 0.002)),
2654 &[AutoDimension::OuterRadius],
2655 ),
2656 auto(
2657 body("shoulder", cone_transition(0.0, 0.022)),
2658 &[AutoDimension::ForeRadius],
2659 ),
2660 body("lower", tube(0.45, 0.022, 0.0018)),
2661 ],
2662 )]);
2663 let listed = |design: &Rocket| -> Vec<(usize, usize, String, AutoDimension)> {
2664 design
2665 .unresolvable_body_radii()
2666 .into_iter()
2667 .map(|r| (r.stage, r.component, r.id, r.dimension))
2668 .collect()
2669 };
2670 let chain = vec![
2671 (0, 0, "nose".to_owned(), AutoDimension::BaseRadius),
2672 (0, 1, "upper".to_owned(), AutoDimension::OuterRadius),
2673 (0, 2, "shoulder".to_owned(), AutoDimension::ForeRadius),
2674 ];
2675 assert_eq!(listed(&design), chain);
2676 assert!(design.layout().is_err());
2677
2678 let filled = design.fill_unresolvable_body_radii(0.025);
2679 let filled: Vec<_> = filled
2680 .into_iter()
2681 .map(|r| (r.stage, r.component, r.id, r.dimension))
2682 .collect();
2683 assert_eq!(filled, chain);
2684 assert!(listed(&design).is_empty());
2685 assert!(
2686 design.stages[0]
2687 .components
2688 .iter()
2689 .all(|c| c.auto.is_empty())
2690 );
2691 let layout = design.layout().unwrap();
2692 let radius = |id: &str| layout.find(id).unwrap().1.part.aft_radius_m();
2693 assert_eq!(radius("nose"), Some(0.025));
2694 assert_eq!(radius("upper"), Some(0.025));
2695 let Part::Transition(t) = &layout.find("shoulder").unwrap().1.part else {
2696 panic!("a transition")
2697 };
2698 assert_eq!((t.fore_radius_m, t.aft_radius_m), (0.025, 0.022));
2699
2700 let mut design = three_fin_rocket();
2702 let before = design.clone();
2703 assert!(design.unresolvable_body_radii().is_empty());
2704 assert!(design.fill_unresolvable_body_radii(0.025).is_empty());
2705 assert_eq!(design, before);
2706 design.layout().unwrap();
2707 }
2708
2709 #[test]
2712 fn ring_and_packed_radii_come_from_parent_and_siblings() {
2713 let layout = three_fin_rocket().layout().unwrap();
2714 let part = |id: &str| layout.find(id).unwrap().1.part.clone();
2715 for id in ["ring-fore", "ring-aft"] {
2716 let Part::CenteringRing(r) = part(id) else {
2717 panic!()
2718 };
2719 assert_eq!(r.outer_radius_m, 0.027 - 0.0015, "{id}");
2720 assert_eq!(r.inner_radius_m, 0.020, "{id}");
2721 }
2722 let Part::Parachute(p) = part("chute") else {
2723 panic!()
2724 };
2725 assert_eq!(p.packing.radius_m, 0.027 - 0.0015);
2726
2727 let mut design = three_fin_rocket();
2728 let airframe = &mut design.stages[0].components[1];
2729 airframe.children[1].position = Some(top(0.1));
2731 let layout = design.layout().unwrap();
2732 let Part::CenteringRing(r) = layout.find("ring-fore").unwrap().1.part.clone() else {
2733 panic!()
2734 };
2735 assert_eq!(r.inner_radius_m, 0.0);
2736 }
2737
2738 #[test]
2742 fn an_automatic_tube_fin_radius_closes_the_ring_around_its_body() {
2743 let tubes = |count: u32, thickness_m: f64| {
2744 Part::TubeFinSet(crate::TubeFinSet {
2745 count,
2746 length_m: 0.1,
2747 outer_radius_m: 0.0,
2748 thickness_m,
2749 base_angle_rad: 0.0,
2750 material: crate::Material::bulk("cardboard", 680.0),
2751 })
2752 };
2753 let with = |part: Part, auto: bool, on: usize| {
2754 let mut design = three_fin_rocket();
2755 let mut child = attached("tubes", part, bottom(0.0));
2756 if auto {
2757 child.auto = vec![AutoDimension::OuterRadius];
2758 }
2759 design.stages[0].components[on].children.push(child);
2760 design.layout()
2761 };
2762 let resolved = |layout: &Layout| match &layout.find("tubes").unwrap().1.part {
2763 Part::TubeFinSet(set) => (set.outer_radius_m, set.thickness_m),
2764 other => panic!("{other:?}"),
2765 };
2766 let layout = with(tubes(6, 0.001), true, 1).unwrap();
2767 let (r, t) = resolved(&layout);
2768 close(r, 0.027, 1e-15, "six");
2769 assert_eq!(t, 0.001);
2770 let mut stated = tubes(6, 0.001);
2771 if let Part::TubeFinSet(set) = &mut stated {
2772 set.outer_radius_m = r;
2773 }
2774 let same = with(stated, false, 1).unwrap();
2775 assert_eq!(
2776 layout.find("tubes").unwrap().1.own,
2777 same.find("tubes").unwrap().1.own
2778 );
2779 let (r, _) = resolved(&with(tubes(4, 0.001), true, 1).unwrap());
2780 close(r, 0.027 * (1.0 + 2f64.sqrt()), 1e-15, "four");
2781 let (r, _) = resolved(&with(tubes(2, 0.001), true, 1).unwrap());
2782 assert_eq!(r, 0.027);
2783 let (r, t) = resolved(&with(tubes(6, 0.05), true, 1).unwrap());
2784 assert_eq!(t, r);
2785 let error = with(tubes(6, 0.001), true, 0).unwrap_err().to_string();
2787 assert!(error.contains("attaches to a body tube"), "{error}");
2788 }
2789
2790 #[test]
2795 fn an_automatic_radius_inside_a_nose_is_its_bore_at_the_narrow_end() {
2796 let with = |part: Part, position: Position| {
2797 let mut design = three_fin_rocket();
2798 let mut child = attached("inside", part, position);
2799 child.auto = vec![AutoDimension::OuterRadius];
2800 design.stages[0].components[0].children = vec![child];
2801 design.layout()
2802 };
2803 let radius = |layout: &Layout| match &layout.find("inside").unwrap().1.part {
2804 Part::InnerTube(tube) => (tube.outer_radius_m, tube.thickness_m),
2805 Part::CenteringRing(ring) => (ring.outer_radius_m, ring.inner_radius_m),
2806 other => panic!("{other:?}"),
2807 };
2808 let coupler = || inner_tube(0.1, 0.0, 0.001);
2809 let (r, t) = radius(&with(coupler(), bottom(0.0)).unwrap());
2811 close(r, 0.135 * 0.1 - 0.002, 1e-17, "at the bottom");
2812 assert_eq!(t, 0.001);
2813 let (r, _) = radius(&with(coupler(), bottom(0.05)).unwrap());
2815 close(r, 0.135 * 0.15 - 0.002, 1e-17, "past the base");
2816 let (r, bore) = radius(&with(ring(0.006, 0.0, 0.005), bottom(0.0)).unwrap());
2818 close(r, 0.135 * 0.194 - 0.002, 1e-17, "a ring");
2819 assert_eq!(bore, 0.005);
2820 let (r, t) = radius(&with(inner_tube(0.1, 0.0, 0.02), bottom(0.0)).unwrap());
2822 assert_eq!(t, r);
2823 let error = with(coupler(), top(0.0)).unwrap_err();
2825 assert!(
2826 matches!(
2827 &error,
2828 DesignError::InComponent { id, source }
2829 if id == "inside"
2830 && matches!(**source, DesignError::Domain { what: "outer radius", value } if value == 0.0)
2831 ),
2832 "{error:?}"
2833 );
2834 let mut design = three_fin_rocket();
2836 if let Part::NoseCone(nose) = &mut design.stages[0].components[0].part {
2837 nose.wall = Wall::Filled {};
2838 }
2839 let mut child = attached("inside", coupler(), bottom(0.0));
2840 child.auto = vec![AutoDimension::OuterRadius];
2841 design.stages[0].components[0].children = vec![child];
2842 let error = design.layout().unwrap_err().to_string();
2843 assert!(error.contains("a nose_cone has none"), "{error}");
2844
2845 let transition = Part::Transition(Transition {
2848 shape: crate::shapes::NoseShape::Conical {},
2849 clipped: false,
2850 length_m: 0.1,
2851 fore_radius_m: 0.03,
2852 aft_radius_m: 0.02,
2853 wall: Wall::Shell { thickness_m: 0.002 },
2854 fore_shoulder: None,
2855 aft_shoulder: None,
2856 material: crate::testing::cardboard(),
2857 });
2858 let mut part = body("transition", transition);
2859 let mut child = attached("inside", inner_tube(0.05, 0.0, 0.001), top(0.0));
2860 child.auto = vec![AutoDimension::OuterRadius];
2861 part.children = vec![child];
2862 let design = rocket(vec![stage(
2863 "only",
2864 vec![body("tube", tube(0.3, 0.03, 0.001)), part],
2865 )]);
2866 let (r, _) = radius(&design.layout().unwrap());
2867 close(r, 0.025 - 0.002, 1e-17, "a transition");
2868 }
2869
2870 #[test]
2876 fn a_cluster_repeats_what_it_holds_in_every_tube() {
2877 let three: Vec<[f64; 2]> = [90.0_f64, 210.0, 330.0]
2878 .iter()
2879 .map(|a| [0.02 * a.to_radians().cos(), 0.02 * a.to_radians().sin()])
2880 .collect();
2881 let with_block = |cluster_m: Vec<[f64; 2]>| {
2882 let mut design = crate::testing::three_fin_rocket();
2883 let mount = &mut design.stages[0].components[1].children[0];
2884 if let Part::InnerTube(tube) = &mut mount.part {
2885 tube.cluster_m = cluster_m;
2886 }
2887 mount.children = vec![attached("block", inner_tube(0.01, 0.019, 0.005), top(0.0))];
2888 design
2889 };
2890 let single = with_block(Vec::new()).layout().unwrap();
2891 let clustered_design = with_block(three.clone());
2892 let clustered = clustered_design.layout().unwrap();
2893 let (_, one) = single.find("block").unwrap();
2894 let (_, block) = clustered.find("block").unwrap();
2895 assert_eq!(one.copies, [Placement::HERE]);
2896 let moved: Vec<Placement> = three.iter().copied().map(Placement::moved).collect();
2897 assert_eq!(block.copies, moved);
2898 close(
2899 block.own.mass_kg,
2900 3.0 * one.own.mass_kg,
2901 1e-15,
2902 "three blocks",
2903 );
2904 assert!(block.own.cg_m.truncate().length() < 1e-17);
2905 let (_, tube) = single.find("mmt").unwrap();
2906 let extra = 2.0 * (tube.own.mass_kg + one.own.mass_kg);
2907 close(
2908 clustered.structure.mass_kg,
2909 single.structure.mass_kg + extra,
2910 1e-14,
2911 "structure",
2912 );
2913 let (_, mount) = clustered.find("mmt").unwrap();
2914 assert_eq!(mount.contents_copies().unwrap(), moved);
2915 let (_, ring) = clustered.find("ring-fore").unwrap();
2916 let Part::CenteringRing(ring) = &ring.part else {
2917 panic!("a ring");
2918 };
2919 assert_eq!(ring.inner_radius_m, 0.02);
2920 let findings = crate::checks::check(&clustered_design).unwrap();
2921 for id in ["ring-fore", "ring-aft"] {
2922 assert!(
2923 findings.contains(&crate::Finding::RingOverlapsInnerTube {
2924 ring: id.to_owned(),
2925 tube: "mmt".to_owned(),
2926 }),
2927 "{findings:?}"
2928 );
2929 }
2930 assert!(
2932 findings.iter().any(|f| matches!(
2933 f,
2934 crate::Finding::InternalPartWiderThanParent { component, reach_m, .. }
2935 if component == "mmt" && (reach_m - 0.04).abs() < 1e-15
2936 )),
2937 "{findings:?}"
2938 );
2939 assert!(
2940 !crate::checks::check(&with_block(Vec::new()))
2941 .unwrap()
2942 .iter()
2943 .any(|f| matches!(f, crate::Finding::RingOverlapsInnerTube { .. }))
2944 );
2945 }
2946
2947 fn podded(count: u32, angle_rad: f64) -> Rocket {
2951 let mut design = three_fin_rocket();
2952 let mut pod_tube = body("pod-tube", tube(0.3, 0.012, 0.001));
2953 pod_tube.children = vec![attached(
2954 "pod-mass",
2955 mass_component(0.05, 0.1, 0.008),
2956 top(0.02),
2957 )];
2958 let mut pods = attached(
2959 "pods",
2960 Part::PodSet(PodSet {
2961 count,
2962 radial_offset_m: 0.05,
2963 angle_rad,
2964 }),
2965 top(0.1),
2966 );
2967 pods.children = vec![pod_tube];
2968 design.stages[0].components[1].children.push(pods);
2969 design
2970 }
2971
2972 fn boosted(count: u32, angle_rad: f64) -> Rocket {
2974 let mut design = podded(count, angle_rad);
2975 let pods = design.stages[0].components[1]
2976 .children
2977 .pop()
2978 .expect("podded hangs its pods last");
2979 let Part::PodSet(set) = pods.part else {
2980 unreachable!("podded's last child is its pod set")
2981 };
2982 let mut boosters = stage("pods", pods.children);
2983 boosters.parallel = Some(ParallelStage {
2984 on: "airframe".to_owned(),
2985 position: pods.position.expect("an attached part has a position"),
2986 pods: set,
2987 });
2988 design.stages.push(boosters);
2989 design
2990 }
2991
2992 #[test]
2997 fn a_parallel_stage_lays_out_as_a_pod_set_of_its_own_stage() {
2998 for (count, angle_rad) in [(2, 0.0), (1, 0.3), (3, 1.0)] {
2999 let pods = podded(count, angle_rad).layout().unwrap();
3000 let boosters = boosted(count, angle_rad).layout().unwrap();
3001 assert_eq!(boosters.components.len(), pods.components.len());
3002 let own_stage = ["pods", "pod-tube", "pod-mass"];
3003 for (got, want) in boosters.components.iter().zip(&pods.components) {
3004 assert_eq!(got.id, want.id, "depth-first order kept");
3005 let theirs = own_stage.contains(&got.id.as_str());
3006 assert_eq!(got.stage, usize::from(theirs), "{}'s stage", got.id);
3007 let mut same = got.clone();
3008 same.stage = want.stage;
3009 if got.id == "airframe" {
3010 let (_, set) = pods.find("pods").unwrap();
3013 close(
3014 got.with_children.mass_kg,
3015 want.with_children.mass_kg - set.with_children.mass_kg,
3016 1e-15,
3017 "the tube without its pods",
3018 );
3019 same.with_children = want.with_children;
3020 }
3021 assert_eq!(&same, want, "{}", got.id);
3022 }
3023 let (_, set) = pods.find("pods").unwrap();
3024 assert_eq!(boosters.stages.len(), 2);
3025 let stage = &boosters.stages[1];
3026 assert_eq!(stage.id, "pods");
3027 assert_eq!(stage.hung_on, Some(0));
3028 assert_eq!(boosters.stages[0].hung_on, None);
3029 assert_eq!(stage.mass, set.with_children);
3030 assert_eq!(
3031 (stage.fore_station_m, stage.aft_station_m),
3032 (set.fore_station_m, set.aft_station_m())
3033 );
3034 assert_eq!(boosters.length_m, pods.length_m, "the pods don't stack");
3035 close(
3036 boosters.structure.mass_kg,
3037 pods.structure.mass_kg,
3038 1e-15,
3039 "structure mass",
3040 );
3041 close(
3042 (boosters.structure.cg_m - pods.structure.cg_m).length(),
3043 0.0,
3044 1e-15,
3045 "structure center",
3046 );
3047 let inertia = boosters.structure.inertia_kg_m2 - pods.structure.inertia_kg_m2;
3048 for column in 0..3 {
3049 close(
3050 inertia.col(column).length(),
3051 0.0,
3052 1e-15,
3053 "structure inertia",
3054 );
3055 }
3056 }
3057
3058 let boosters = boosted(2, 0.0);
3060 let tube_kg = 790.0 * std::f64::consts::PI * (0.012_f64.powi(2) - 0.011_f64.powi(2)) * 0.3;
3061 close(
3062 boosters.layout().unwrap().stages[1].mass.mass_kg,
3063 2.0 * (tube_kg + 0.05),
3064 1e-15,
3065 "the stage's mass",
3066 );
3067 let page = include_str!("../../../docs/physics/design.md");
3069 let block = page
3070 .split("\n### Parallel stages\n")
3071 .nth(1)
3072 .and_then(|stages| stages.split("```json\n").nth(1))
3073 .and_then(|json| json.split("```").next())
3074 .expect("the Parallel stages section has a JSON block");
3075 let mut written = boosters.stages[1].clone();
3076 written.components[0].children.clear();
3077 assert_eq!(
3078 serde_json::from_str::<Stage>(block).unwrap(),
3079 written,
3080 "{block}"
3081 );
3082 }
3083
3084 #[test]
3087 fn a_parallel_stage_hangs_on_a_body_tube_of_an_earlier_axial_stage() {
3088 let refused = |design: &Rocket, needle: &str| match design.layout() {
3089 Err(DesignError::Tree { id, message }) => {
3090 assert_eq!(id, "pods");
3091 assert!(message.contains(needle), "{message}");
3092 }
3093 other => panic!("expected a tree error naming `{needle}`, got {other:?}"),
3094 };
3095 let hangs = "hangs on a body tube of an axial stage before it";
3096 let on = |on: &str| {
3097 let mut design = boosted(2, 0.0);
3098 design.stages[1].parallel.as_mut().unwrap().on = on.to_owned();
3099 design
3100 };
3101 refused(&on("nose"), hangs);
3102 refused(&on("fins"), hangs);
3103 refused(&on("nowhere"), hangs);
3104 refused(&on("pod-tube"), hangs);
3106 let mut first = boosted(2, 0.0);
3107 first.stages.swap(0, 1);
3108 refused(&first, hangs);
3109 let mut nested = boosted(2, 0.0);
3111 let mut more = nested.stages[1].clone();
3112 more.id = "more".to_owned();
3113 more.components[0].id = "more-tube".to_owned();
3114 more.components[0].children[0].id = "more-mass".to_owned();
3115 more.parallel.as_mut().unwrap().on = "pod-tube".to_owned();
3116 nested.stages.push(more);
3117 match nested.layout() {
3118 Err(DesignError::Tree { id, message }) => {
3119 assert_eq!(id, "more");
3120 assert!(message.contains(hangs), "{message}");
3121 }
3122 other => panic!("expected a tree error, got {other:?}"),
3123 }
3124 let mut after = boosted(2, 0.0);
3126 after.stages[1].parallel.as_mut().unwrap().position = Position::After { aft_offset_m: 0.0 };
3127 refused(&after, "not after a sibling");
3128 let covered = "under a mass override that covers what the tube or its stage holds";
3131 let heavy = Overrides {
3132 mass_kg: Some(1.0),
3133 ..Overrides::default()
3134 };
3135 let mut staged = boosted(2, 0.0);
3136 staged.stages[0].overrides = heavy;
3137 refused(&staged, covered);
3138 let mut tube = boosted(2, 0.0);
3139 tube.stages[0].components[1].overrides = heavy;
3140 tube.layout().unwrap();
3141 tube.stages[0].components[1].overrides_include_children = true;
3142 refused(&tube, covered);
3143 let mut added = boosted(2, 0.0);
3147 added.stages[0].added_mass = Some(AddedMass {
3148 mass_kg: 0.1,
3149 cg_aft_m: None,
3150 });
3151 refused(&added, "carries an added mass with no station");
3152 let mut nothing = boosted(2, 0.0);
3154 nothing.stages[0].added_mass = Some(AddedMass {
3155 mass_kg: 0.0,
3156 cg_aft_m: None,
3157 });
3158 assert_eq!(
3159 nothing.layout().unwrap().structure,
3160 boosted(2, 0.0).layout().unwrap().structure
3161 );
3162 let stationed = Some(AddedMass {
3166 mass_kg: 0.1,
3167 cg_aft_m: Some(0.1),
3168 });
3169 let mut lone = boosted(1, 0.0);
3170 lone.stages[0].added_mass = stationed;
3171 refused(&lone, "one pod off the axis");
3172 lone.stages[1]
3173 .parallel
3174 .as_mut()
3175 .unwrap()
3176 .pods
3177 .radial_offset_m = 0.0;
3178 lone.layout().unwrap();
3179 let mut loose = boosted(2, 0.0);
3181 loose.stages[1].components[0] = attached("pod-tube", fins(0.1, 0.06), top(0.0));
3182 assert!(loose.layout().is_err());
3183 let mut twice = boosted(2, 0.0);
3185 twice.stages[1].id = "airframe".to_owned();
3186 assert!(matches!(twice.layout(), Err(DesignError::DuplicateId(_))));
3187 }
3188
3189 #[test]
3195 fn a_parallel_stages_added_mass_sits_among_its_pods() {
3196 let pitch = |m: &MassProperties| m.inertia_kg_m2.x_axis.x;
3197 for (count, angle_rad) in [(2, 0.0), (1, 0.3), (3, 1.0)] {
3198 let plain = boosted(count, angle_rad).layout().unwrap();
3199 let (core, pods) = (plain.stages[0].mass, plain.stages[1].mass);
3200 let fore = plain.stages[1].fore_station_m;
3201 let off_axis = pods.cg_m.x.hypot(pods.cg_m.y);
3202 assert_eq!(count == 1, off_axis > 0.04, "{count} pods: {off_axis}");
3203
3204 let mut design = boosted(count, angle_rad);
3206 design.stages[1].added_mass = Some(AddedMass {
3207 mass_kg: 0.25,
3208 cg_aft_m: None,
3209 });
3210 let layout = design.layout().unwrap();
3211 let stage = layout.stages[1].mass;
3212 close(stage.mass_kg, pods.mass_kg + 0.25, 1e-15, "mass");
3213 close((stage.cg_m - pods.cg_m).length(), 0.0, 1e-15, "center");
3214 close(pitch(&stage), pitch(&pods), 1e-15, "inertia");
3215 assert_eq!(layout.stages[0].mass, core, "the stage it hangs on");
3216
3217 design.stages[1].added_mass = Some(AddedMass {
3220 mass_kg: 0.25,
3221 cg_aft_m: Some(0.1),
3222 });
3223 let layout = design.layout().unwrap();
3224 let stage = layout.stages[1].mass;
3225 let (m_p, x_p, x_a) = (pods.mass_kg, -pods.cg_m.z, fore + 0.1);
3226 let center = (m_p * x_p + 0.25 * x_a) / (m_p + 0.25);
3227 close(stage.mass_kg, m_p + 0.25, 1e-15, "mass at a station");
3228 close(-stage.cg_m.z, center, 1e-15, "center at a station");
3229 close(
3230 stage.cg_m.x.hypot(stage.cg_m.y),
3231 off_axis,
3232 1e-15,
3233 "off the axis",
3234 );
3235 let along = m_p * (x_p - center).powi(2) + 0.25 * (x_a - center).powi(2);
3238 let trace = |m: &MassProperties| m.inertia_kg_m2.x_axis.x + m.inertia_kg_m2.y_axis.y;
3239 close(
3240 trace(&stage),
3241 trace(&pods) + 2.0 * along,
3242 1e-12,
3243 "inertia at a station",
3244 );
3245 close(
3246 stage.inertia_kg_m2.z_axis.z,
3247 pods.inertia_kg_m2.z_axis.z,
3248 1e-15,
3249 "roll at a station",
3250 );
3251
3252 if count == 1 {
3256 continue;
3257 }
3258 let mut design = boosted(count, angle_rad);
3259 design.stages[0].added_mass = Some(AddedMass {
3260 mass_kg: 0.25,
3261 cg_aft_m: Some(0.1),
3262 });
3263 let layout = design.layout().unwrap();
3264 let stage = layout.stages[0].mass;
3265 let (m_c, x_c) = (core.mass_kg, -core.cg_m.z);
3266 close(stage.mass_kg, m_c + 0.25, 1e-15, "the core's mass");
3267 close(
3268 -stage.cg_m.z,
3269 (m_c * x_c + 0.25 * 0.1) / (m_c + 0.25),
3270 1e-15,
3271 "the core's center",
3272 );
3273 assert_eq!(layout.stages[1].mass, pods, "the parallel stage");
3274 close(
3275 layout.structure.mass_kg,
3276 plain.structure.mass_kg + 0.25,
3277 1e-15,
3278 "structure",
3279 );
3280 }
3281 }
3282
3283 #[test]
3286 fn a_pod_is_its_stack_repeated_with_its_parallel_axis_term() {
3287 use std::f64::consts::{FRAC_PI_2, PI};
3288 let (rho, length, ro, ri) = (790.0, 0.3, 0.012, 0.011);
3290 let m_t = rho * PI * (ro * ro - ri * ri) * length;
3291 let (ax_t, tr_t) = (
3292 m_t * (ro * ro + ri * ri) / 2.0,
3293 m_t * (3.0 * (ro * ro + ri * ri) + length * length) / 12.0,
3294 );
3295 let z_t = 0.3 + 0.15;
3296 let (m_c, l_c, r_c) = (0.05, 0.1, 0.008);
3297 let (ax_c, tr_c) = (
3298 m_c * r_c * r_c / 2.0,
3299 m_c * (3.0 * r_c * r_c + l_c * l_c) / 12.0,
3300 );
3301 let z_c = 0.3 + 0.02 + 0.05;
3302 let m1 = m_t + m_c;
3303 let z1 = (m_t * z_t + m_c * z_c) / m1;
3304 let axial1 = ax_t + ax_c;
3305 let transverse1 = tr_t + m_t * (z_t - z1).powi(2) + tr_c + m_c * (z_c - z1).powi(2);
3306 let d = 0.05;
3307
3308 let base = three_fin_rocket().layout().unwrap();
3310 let two = podded(2, 0.0).layout().unwrap();
3311 let (_, pods) = two.find("pods").unwrap();
3312 let mass = pods.with_children;
3313 close(mass.mass_kg, 2.0 * m1, 1e-15, "two pods' mass");
3314 close(mass.cg_m.x, 0.0, 1e-16, "center x");
3315 close(mass.cg_m.y, 0.0, 1e-16, "center y");
3316 close(-mass.cg_m.z, z1, 1e-15, "center station");
3317 let i = mass.inertia_kg_m2;
3318 close(i.col(0).x, 2.0 * transverse1, 1e-15, "I_xx");
3320 close(i.col(1).y, 2.0 * (transverse1 + m1 * d * d), 1e-15, "I_yy");
3321 close(i.col(2).z, 2.0 * (axial1 + m1 * d * d), 1e-15, "I_zz");
3322 for (k, product) in [i.col(1).x, i.col(2).x, i.col(2).y].into_iter().enumerate() {
3323 close(product, 0.0, 1e-16, &format!("product {k}"));
3324 }
3325 close(pods.length_m, 0.3, 1e-15, "the pod's extent");
3326 assert_eq!(pods.own.mass_kg, 0.0);
3327 let (_, pod_tube) = two.find("pod-tube").unwrap();
3328 close(pod_tube.fore_station_m, 0.3, 1e-15, "pod tube station");
3329 assert_eq!(pod_tube.copies.len(), 2);
3330 close(pod_tube.copies[1].offset_m[0], -d, 1e-16, "second pod x");
3331 assert_eq!(pod_tube.copies[1].roll_rad, PI);
3332 close(
3333 two.structure.mass_kg,
3334 base.structure.mass_kg + 2.0 * m1,
3335 1e-14,
3336 "structure",
3337 );
3338
3339 let one = podded(1, FRAC_PI_2).layout().unwrap();
3342 let (_, pod) = one.find("pods").unwrap();
3343 let mass = pod.with_children;
3344 close(mass.mass_kg, m1, 1e-15, "one pod's mass");
3345 close(mass.cg_m.x, 0.0, 1e-16, "center x");
3346 close(mass.cg_m.y, d, 1e-16, "center y");
3347 let i = mass.inertia_kg_m2;
3348 close(i.col(0).x, transverse1, 1e-15, "I_xx about its center");
3349 close(i.col(2).z, axial1, 1e-15, "I_zz about its center");
3350 let about_origin = mass.inertia_about(DVec3::ZERO);
3351 close(about_origin.col(2).y, m1 * d * z1, 1e-15, "I_yz");
3352 close(
3353 about_origin.col(2).z,
3354 axial1 + m1 * d * d,
3355 1e-15,
3356 "I_zz about the axis",
3357 );
3358 close(
3359 one.structure.cg_m.y,
3360 (base.structure.mass_kg * base.structure.cg_m.y + m1 * d)
3361 / (base.structure.mass_kg + m1),
3362 1e-15,
3363 "the rocket's center across the axis",
3364 );
3365 }
3366
3367 #[test]
3373 fn what_a_pod_holds_turns_with_it_and_overrides_keep_their_scope() {
3374 use std::f64::consts::{FRAC_PI_2, PI};
3375 let (d, e) = (0.05, 0.003);
3376 let off_axis = |count: u32, angle_rad: f64| {
3377 let mut design = podded(count, angle_rad);
3378 let pod_tube = &mut design.stages[0].components[1].children[6].children[0];
3379 if let Part::MassComponent(mass) = &mut pod_tube.children[0].part {
3380 mass.packing.radial_offset_m = e;
3381 }
3382 design
3383 };
3384 let (rho, length, ro, ri) = (790.0, 0.3, 0.012, 0.011);
3385 let m_t = rho * PI * (ro * ro - ri * ri) * length;
3386 let m_c = 0.05;
3387
3388 let two = off_axis(2, 0.0).layout().unwrap();
3389 let pods = two.find("pods").unwrap().1.with_children;
3390 close(pods.cg_m.x, 0.0, 1e-16, "the pair's center x");
3391 close(pods.cg_m.y, 0.0, 1e-16, "the pair's center y");
3392 let roll = pods
3393 .inertia_about(DVec3::new(0.0, 0.0, pods.cg_m.z))
3394 .col(2)
3395 .z;
3396 let hand = 2.0
3397 * (m_t * (ro * ro + ri * ri) / 2.0
3398 + m_t * d * d
3399 + m_c * 0.008 * 0.008 / 2.0
3400 + m_c * (d + e) * (d + e));
3401 close(roll, hand, 1e-15, "the pair's roll inertia");
3402
3403 let one = off_axis(1, FRAC_PI_2).layout().unwrap();
3404 let (_, mass) = one.find("pod-mass").unwrap();
3405 close(mass.own.cg_m.x, 0.0, 1e-16, "the turned mass's x");
3406 close(mass.own.cg_m.y, d + e, 1e-16, "the turned mass's y");
3407
3408 let mut design = podded(1, FRAC_PI_2);
3410 let pod_tube = &mut design.stages[0].components[1].children[6].children[0];
3411 pod_tube.overrides.cg_xy_m = Some([0.01, 0.0]);
3412 let layout = design.layout().unwrap();
3413 let (_, tube) = layout.find("pod-tube").unwrap();
3414 close(tube.own.cg_m.x, 0.0, 1e-16, "the overridden center's x");
3415 close(
3416 tube.own.cg_m.y,
3417 d + 0.01,
3418 1e-16,
3419 "the overridden center's y",
3420 );
3421
3422 let set_to = |mass_kg: f64, on_set: bool| {
3423 let mut design = podded(2, 0.0);
3424 let pods = &mut design.stages[0].components[1].children[6];
3425 if on_set {
3426 pods.overrides.mass_kg = Some(mass_kg);
3427 pods.overrides_include_children = true;
3428 } else {
3429 pods.children[0].children[0].overrides.mass_kg = Some(mass_kg);
3430 }
3431 let layout = design.layout().unwrap();
3432 layout.find("pods").unwrap().1.with_children.mass_kg
3433 };
3434 close(set_to(0.3, true), 0.3, 1e-15, "an override on the pod set");
3435 close(
3436 set_to(0.1, false),
3437 2.0 * (m_t + 0.1),
3438 1e-15,
3439 "an override in each pod",
3440 );
3441 }
3442
3443 #[test]
3445 fn a_pod_s_nose_is_not_the_reference_nose() {
3446 let mut design = podded(2, 0.0);
3447 let pods = &mut design.stages[0].components[1].children[6];
3448 pods.children.insert(0, body("pod-nose", nose(0.06, 0.012)));
3449 design.stages[0].components.remove(0);
3450 design.reference_diameter = ReferenceDiameter::NoseBase {};
3451 let error = design.layout().unwrap_err().to_string();
3452 assert!(error.contains("there is no nose cone"), "{error}");
3453 }
3454
3455 #[test]
3459 fn pods_stack_hold_motors_and_refuse_the_wrong_trees() {
3460 let mut design = podded(3, 0.0);
3461 let pods = &mut design.stages[0].components[1].children[6];
3462 pods.position = Some(bottom(0.2));
3464 let mut pod_nose = body("pod-nose", nose(0.06, 0.0));
3465 pod_nose.auto = vec![AutoDimension::BaseRadius];
3466 pods.children.insert(0, pod_nose);
3467 pods.children[1].motor_mount = Some(MotorMount { overhang_m: 0.005 });
3468 design.configurations.push(Configuration {
3469 id: "pods".to_owned(),
3470 name: String::new(),
3471 motors: vec![crate::testing::motor("pod-tube", 0.018, 0.1)],
3472 });
3473 let layout = design.layout().unwrap();
3474 let (_, set) = layout.find("pods").unwrap();
3475 close(set.length_m, 0.36, 1e-15, "the pods' extent");
3476 let (_, cone) = layout.find("pod-nose").unwrap();
3477 let Part::NoseCone(cone_part) = &cone.part else {
3478 panic!("a nose cone");
3479 };
3480 assert_eq!(cone_part.base_radius_m, 0.012);
3481 close(cone.fore_station_m, 0.84, 1e-15, "pod nose station");
3482 close(station(&layout, "pod-tube"), 0.9, 1e-15, "pod tube station");
3483 let three = PodSet {
3484 count: 3,
3485 radial_offset_m: 0.05,
3486 angle_rad: 0.0,
3487 }
3488 .pods()
3489 .unwrap();
3490 assert_eq!(cone.copies, three);
3491 assert_eq!(layout.find("pod-mass").unwrap().1.copies, three);
3492
3493 let assembly = design.assemble("pods").unwrap();
3494 assert_eq!(assembly.motors.len(), 3);
3495 for (motor, pod) in assembly.motors.iter().zip(&three) {
3496 assert_eq!([motor.nozzle_m.x, motor.nozzle_m.y], pod.offset_m);
3497 close(motor.nozzle_station_m(), 1.2 + 0.005, 1e-15, "nozzle");
3498 }
3499
3500 let findings = crate::checks::check(&design).unwrap();
3502 assert!(
3503 !findings.iter().any(|f| format!("{f:?}").contains("pod")),
3504 "{findings:?}"
3505 );
3506
3507 let page = include_str!("../../../docs/physics/design.md");
3509 let block = page
3510 .split("\n### Pods\n")
3511 .nth(1)
3512 .and_then(|pods| pods.split("```json\n").nth(1))
3513 .and_then(|json| json.split("```").next())
3514 .expect("the Pods section has a JSON block");
3515 let mut written = podded(2, 0.0).stages[0].components[1].children[6].clone();
3516 written.children[0].children.clear();
3517 assert_eq!(
3518 serde_json::from_str::<Component>(block).unwrap(),
3519 written,
3520 "{block}"
3521 );
3522
3523 let json = serde_json::to_string(&design).unwrap();
3524 assert!(json.contains("\"pod_set\""));
3525 assert_eq!(serde_json::from_str::<Rocket>(&json).unwrap(), design);
3526
3527 let refused = |edit: &dyn Fn(&mut Component), want: &str| {
3528 let mut design = podded(2, 0.0);
3529 edit(&mut design.stages[0].components[1].children[6]);
3530 let error = design.layout().unwrap_err().to_string();
3531 assert!(error.contains(want), "{error}");
3532 };
3533 refused(
3534 &|pods| {
3535 pods.children
3536 .push(attached("fin", fins(0.1, 0.05), top(0.0)))
3537 },
3538 "a pod holds body components",
3539 );
3540 refused(
3541 &|pods| pods.children[0].position = Some(top(0.0)),
3542 "stacks and takes no position",
3543 );
3544 refused(
3545 &|pods| {
3546 if let Part::PodSet(set) = &mut pods.part {
3547 set.count = 0;
3548 }
3549 },
3550 "pod count",
3551 );
3552 refused(
3553 &|pods| {
3554 if let Part::PodSet(set) = &mut pods.part {
3555 set.radial_offset_m = f64::NAN;
3556 }
3557 },
3558 "pod radial offset",
3559 );
3560 refused(
3561 &|pods| {
3562 if let Part::PodSet(set) = &mut pods.part {
3563 set.count = PodSet::MAX_COUNT + 1;
3564 }
3565 },
3566 "pod count (1 to 64)",
3567 );
3568 refused(
3569 &|pods| pods.overrides.mass_kg = Some(0.2),
3570 "an override on it must cover its pods",
3571 );
3572 refused(
3573 &|pods| {
3574 let mut inner = pods.clone();
3575 inner.id = "inner-pods".to_owned();
3576 inner.children[0].id = "inner-tube".to_owned();
3577 inner.children[0].children[0].id = "inner-mass".to_owned();
3578 pods.children[0].children.push(inner);
3579 },
3580 "a pod set can't hang from a pod",
3581 );
3582 let mut on_nose = podded(2, 0.0);
3583 let pods = on_nose.stages[0].components[1].children.pop().unwrap();
3584 on_nose.stages[0].components[0].children.push(pods);
3585 let error = on_nose.layout().unwrap_err().to_string();
3586 assert!(error.contains("attaches to a body tube"), "{error}");
3587 }
3588
3589 #[test]
3595 fn a_pod_of_no_length_holds_its_parts_at_the_pod_s_axis() {
3596 use std::f64::consts::PI;
3597 let (rho, length, ro, ri, d) = (790.0, 0.05, 0.004, 0.0035, 0.05);
3598 let lug = LaunchLug {
3599 length_m: length,
3600 outer_radius_m: ro,
3601 thickness_m: ro - ri,
3602 angle_rad: PI,
3603 count: 1,
3604 spacing_m: 0.0,
3605 material: crate::testing::cardboard(),
3606 };
3607 let mut phantom = body("phantom", tube(0.0, 0.0, 0.0));
3608 phantom.children = vec![attached(
3609 "pod-lug",
3610 Part::LaunchLug(lug),
3611 Position::Middle { aft_offset_m: 0.0 },
3612 )];
3613 let mut pods = attached(
3614 "pods",
3615 Part::PodSet(PodSet {
3616 count: 2,
3617 radial_offset_m: d,
3618 angle_rad: 0.0,
3619 }),
3620 top(0.1),
3621 );
3622 pods.children = vec![phantom];
3623 let mut design = three_fin_rocket();
3624 design.stages[0].components[1].children.push(pods);
3625 let base = three_fin_rocket().layout().unwrap();
3626 let layout = design.layout().unwrap();
3627
3628 let (_, set) = layout.find("pods").unwrap();
3629 assert_eq!(set.length_m, 0.0);
3630 let (_, phantom) = layout.find("phantom").unwrap();
3631 assert_eq!(phantom.own.mass_kg, 0.0);
3632 close(phantom.fore_station_m, 0.3, 1e-15, "the phantom's station");
3633 close(
3635 station(&layout, "pod-lug"),
3636 0.3 - 0.5 * length,
3637 1e-15,
3638 "lug station",
3639 );
3640 let m = rho * PI * (ro * ro - ri * ri) * length;
3641 let axial = m * (ro * ro + ri * ri) / 2.0;
3642 let transverse = m * (3.0 * (ro * ro + ri * ri) + length * length) / 12.0;
3643 let r = d - ro;
3644 let mass = set.with_children;
3645 close(mass.mass_kg, 2.0 * m, 1e-18, "two lugs' mass");
3646 close(mass.cg_m.x, 0.0, 1e-16, "center x");
3647 close(mass.cg_m.y, 0.0, 1e-16, "center y");
3648 close(-mass.cg_m.z, 0.3, 1e-15, "center station");
3649 let i = mass.inertia_kg_m2;
3650 close(i.col(0).x, 2.0 * transverse, 1e-18, "I_xx");
3651 close(i.col(1).y, 2.0 * (transverse + m * r * r), 1e-18, "I_yy");
3652 close(i.col(2).z, 2.0 * (axial + m * r * r), 1e-18, "I_zz");
3653 let (_, lug) = layout.find("pod-lug").unwrap();
3655 close(lug.own.cg_m.x, 0.0, 1e-16, "the pair's center");
3656 let Part::LaunchLug(one) = &lug.part else {
3657 unreachable!("the lug")
3658 };
3659 let one = MassProperties::placed(one.mass_properties(0.0).unwrap(), &lug.copies[..1]);
3660 close(one.cg_m.x, r, 1e-16, "the first lug across the axis");
3661
3662 let mut empty = design.clone();
3663 let pods = empty.stages[0].components[1].children.last_mut();
3664 pods.expect("the pod set").children.clear();
3665 let layout = empty.layout().unwrap();
3666 let (_, set) = layout.find("pods").unwrap();
3667 assert!(set.length_m.is_sign_positive());
3668 assert_eq!(set.with_children.mass_kg, 0.0);
3669 assert_eq!(set.with_children.inertia_kg_m2, DMat3::ZERO);
3670 assert_eq!(layout.structure, base.structure);
3671
3672 let mut flat = three_fin_rocket();
3674 flat.stages[0]
3675 .components
3676 .push(body("flat", tube(0.0, 0.0, 0.0)));
3677 let error = flat.layout().unwrap_err();
3678 assert!(
3679 matches!(
3680 error,
3681 DesignError::InComponent { ref id, ref source }
3682 if id == "flat" && matches!(**source, DesignError::Domain {
3683 what: "body component length",
3684 ..
3685 })
3686 ),
3687 "{error:?}"
3688 );
3689 }
3690
3691 #[test]
3695 fn an_override_inside_a_cluster_is_each_copy_s() {
3696 let three: Vec<[f64; 2]> = [90.0_f64, 210.0, 330.0]
3697 .iter()
3698 .map(|a| [0.02 * a.to_radians().cos(), 0.02 * a.to_radians().sin()])
3699 .collect();
3700 let with = |part: Part, mass_kg: Option<f64>| {
3701 let mut design = crate::testing::three_fin_rocket();
3702 let mount = &mut design.stages[0].components[1].children[0];
3703 if let Part::InnerTube(tube) = &mut mount.part {
3704 tube.cluster_m = three.clone();
3705 }
3706 let mut inside = attached("inside", part, top(0.0));
3707 inside.overrides.mass_kg = mass_kg;
3708 mount.children = vec![inside];
3709 design.layout().unwrap()
3710 };
3711 for part in [
3712 inner_tube(0.01, 0.019, 0.005),
3713 mass_component(0.05, 0.04, 0.015),
3714 ] {
3715 let free = with(part.clone(), None);
3716 let (_, one) = free.find("inside").unwrap();
3717 let each_kg = one.own.mass_kg / 3.0;
3718 let same = with(part.clone(), Some(each_kg));
3719 let (a, b) = (&free.structure, &same.structure);
3720 close(b.mass_kg, a.mass_kg, 1e-15, "structure mass");
3721 assert!(
3722 (b.cg_m - a.cg_m).length() < 1e-15,
3723 "{:?} vs {:?}",
3724 b.cg_m,
3725 a.cg_m
3726 );
3727 for (x, y) in [
3728 (a.inertia_kg_m2.x_axis, b.inertia_kg_m2.x_axis),
3729 (a.inertia_kg_m2.y_axis, b.inertia_kg_m2.y_axis),
3730 (a.inertia_kg_m2.z_axis, b.inertia_kg_m2.z_axis),
3731 ] {
3732 assert!((x - y).length() < 1e-15, "{x:?} vs {y:?}");
3733 }
3734 let doubled = with(part, Some(2.0 * each_kg));
3735 let (_, inside) = doubled.find("inside").unwrap();
3736 close(inside.own.mass_kg, 6.0 * each_kg, 1e-15, "doubled");
3737 assert!(inside.own.cg_m.truncate().length() < 1e-17);
3738 }
3739 }
3740
3741 #[test]
3743 fn tree_structure_matches_parts_placed_by_hand() {
3744 let design = three_fin_rocket();
3745 let layout = design.layout().unwrap();
3746 let bore = 0.027 - 0.0015;
3747 let placed = |part: Part, body_radius: Option<f64>, s: f64| {
3748 part.mass_properties(body_radius)
3749 .unwrap()
3750 .translated(DVec3::new(0.0, 0.0, -s))
3751 };
3752 let mut chute = design.stages[0].components[1].children[4].part.clone();
3753 if let Part::Parachute(p) = &mut chute {
3754 p.packing.radius_m = bore;
3755 }
3756 let parts = [
3757 placed(nose(0.2, 0.027), None, 0.0),
3758 placed(tube(0.8, 0.027, 0.0015), None, 0.2),
3759 placed(inner_tube(0.3, 0.020, 0.001), None, 0.7),
3760 placed(ring(0.006, bore, 0.020), None, 1.0 - 0.006 - 0.25),
3761 placed(ring(0.006, bore, 0.020), None, 1.0 - 0.006 - 0.02),
3762 placed(fins(0.1, 0.06), Some(0.027), 0.9),
3763 placed(chute, None, 0.25),
3764 placed(
3765 design.stages[0].components[1].children[5].part.clone(),
3766 Some(0.027),
3767 0.2 + 0.5 * (0.8 - 0.05),
3768 ),
3769 ];
3770 let want = MassProperties::combine(&parts);
3771 let got = layout.structure;
3772 close(got.mass_kg, want.mass_kg, 1e-15 * want.mass_kg, "mass");
3773 assert!(
3774 (got.cg_m - want.cg_m).length() < 1e-14,
3775 "{:?} vs {:?}",
3776 got.cg_m,
3777 want.cg_m
3778 );
3779 let scale = want
3780 .inertia_kg_m2
3781 .to_cols_array()
3782 .iter()
3783 .fold(0.0f64, |m, v| m.max(v.abs()));
3784 let diff = (got.inertia_kg_m2 - want.inertia_kg_m2)
3785 .to_cols_array()
3786 .iter()
3787 .fold(0.0f64, |m, v| m.max(v.abs()));
3788 assert!(diff < 1e-13 * scale, "{diff:e}");
3789 assert_eq!(layout.stages[0].mass, got);
3790 }
3791
3792 fn tensor_close(a: DMat3, b: DMat3, rel: f64) {
3793 let scale = b.to_cols_array().iter().fold(0.0f64, |m, v| m.max(v.abs()));
3794 let diff = (a - b)
3795 .to_cols_array()
3796 .iter()
3797 .fold(0.0f64, |m, v| m.max(v.abs()));
3798 assert!(diff <= rel * scale, "{a:?}\nvs\n{b:?}");
3799 }
3800
3801 #[test]
3804 fn overrides_rescale_move_and_replace() {
3805 let bay = || attached("bay", mass_component(0.4, 0.1, 0.02), top(0.3));
3806 let mut airframe = body("airframe", tube(0.8, 0.03, 0.001));
3807 airframe.children = vec![bay()];
3808 let plain = rocket(vec![stage(
3809 "s",
3810 vec![body("nose", nose(0.2, 0.03)), airframe.clone()],
3811 )]);
3812 let base = plain.layout().unwrap();
3813 let (_, tube_plain) = base.find("airframe").unwrap();
3814 let (_, bay_plain) = base.find("bay").unwrap();
3815
3816 let mut overridden = airframe.clone();
3818 overridden.overrides.mass_kg = Some(2.0 * tube_plain.own.mass_kg);
3819 let design = rocket(vec![stage(
3820 "s",
3821 vec![body("nose", nose(0.2, 0.03)), overridden.clone()],
3822 )]);
3823 let layout = design.layout().unwrap();
3824 let (_, t) = layout.find("airframe").unwrap();
3825 close(
3826 t.own.mass_kg,
3827 2.0 * tube_plain.own.mass_kg,
3828 1e-15,
3829 "scaled mass",
3830 );
3831 assert!((t.own.cg_m - tube_plain.own.cg_m).length() < 1e-15);
3832 tensor_close(
3833 t.own.inertia_kg_m2,
3834 tube_plain.own.inertia_kg_m2 * 2.0,
3835 1e-14,
3836 );
3837 let with = MassProperties::combine([&t.own, &bay_plain.with_children]);
3838 assert_eq!(t.with_children, with, "the child is still added");
3839
3840 overridden.overrides = Overrides {
3842 mass_kg: Some(1.5),
3843 cg_aft_m: Some(0.35),
3844 cg_xy_m: Some([0.001, -0.002]),
3845 inertia: Some(InertiaOverride::axisymmetric(0.001, 0.08)),
3846 };
3847 overridden.overrides_include_children = true;
3848 let design = rocket(vec![stage(
3849 "s",
3850 vec![body("nose", nose(0.2, 0.03)), overridden.clone()],
3851 )]);
3852 let layout = design.layout().unwrap();
3853 let (_, t) = layout.find("airframe").unwrap();
3854 assert_eq!(t.own, tube_plain.own, "own mass untouched");
3855 close(t.with_children.mass_kg, 1.5, 0.0, "mass");
3856 close(
3857 t.with_children.cg_m.z,
3858 -(0.2 + 0.35),
3859 1e-15,
3860 "center from the tube's forward end",
3861 );
3862 assert_eq!(
3863 (t.with_children.cg_m.x, t.with_children.cg_m.y),
3864 (0.001, -0.002)
3865 );
3866 assert_eq!(
3867 t.with_children.inertia_kg_m2,
3868 DMat3::from_diagonal(DVec3::new(0.08, 0.08, 0.001))
3869 );
3870
3871 let mut design = design;
3873 design.stages[0].overrides = Overrides {
3874 mass_kg: Some(3.0),
3875 cg_aft_m: Some(0.5),
3876 cg_xy_m: None,
3877 inertia: None,
3878 };
3879 let layout = design.layout().unwrap();
3880 let stage_mass = layout.stages[0].mass;
3881 close(stage_mass.mass_kg, 3.0, 0.0, "stage mass");
3882 close(stage_mass.cg_m.z, -0.5, 1e-15, "stage center");
3883 let bodies: Vec<MassProperties> = layout.body().map(|c| c.with_children).collect();
3884 let unscaled = MassProperties::combine(&bodies);
3885 assert!(unscaled.cg_m.x.abs() > 1e-5);
3887 assert_eq!(
3888 (stage_mass.cg_m.x, stage_mass.cg_m.y),
3889 (unscaled.cg_m.x, unscaled.cg_m.y)
3890 );
3891 tensor_close(
3892 stage_mass.inertia_kg_m2,
3893 unscaled.inertia_kg_m2 * (3.0 / unscaled.mass_kg),
3894 1e-14,
3895 );
3896 assert_eq!(layout.structure, stage_mass);
3897
3898 design.stages[0].added_mass = Some(AddedMass {
3900 mass_kg: 1.0,
3901 cg_aft_m: Some(0.1),
3902 });
3903 let under = design.layout().unwrap().stages[0].mass;
3904 close(under.mass_kg, 3.0, 0.0, "stage mass over an added mass");
3905 close(under.cg_m.z, -0.5, 1e-15, "stage center over an added mass");
3906
3907 let center = DVec3::new(0.0, 0.0, -0.4);
3909 let point = Overrides {
3910 mass_kg: Some(0.25),
3911 ..Overrides::default()
3912 }
3913 .apply(MassProperties::point(0.0, center), 0.0)
3914 .unwrap();
3915 assert_eq!(point, MassProperties::point(0.25, center));
3916
3917 for covering in [false, true] {
3920 let mut airframe = airframe.clone();
3921 airframe.children = vec![attached(
3922 "ballast",
3923 mass_component(0.0, 0.1, 0.02),
3924 top(0.3),
3925 )];
3926 airframe.children[0].overrides.mass_kg = Some(0.25);
3927 airframe.children[0].overrides_include_children = covering;
3928 let design = rocket(vec![stage(
3929 "s",
3930 vec![body("nose", nose(0.2, 0.03)), airframe],
3931 )]);
3932 let layout = design.layout().unwrap();
3933 let (_, b) = layout.find("ballast").unwrap();
3934 let b = if covering { b.with_children } else { b.own };
3935 assert_eq!(b.mass_kg, 0.25);
3936 close(b.cg_m.z, -(0.2 + 0.3 + 0.05), 1e-15, "packing's center");
3937 let (r, l) = (0.02_f64, 0.1_f64);
3938 close(
3939 b.inertia_kg_m2.z_axis.z,
3940 0.5 * 0.25 * r * r,
3941 1e-15,
3942 "roll, m r²/2",
3943 );
3944 close(
3945 b.inertia_kg_m2.x_axis.x,
3946 0.25 * (3.0 * r * r + l * l) / 12.0,
3947 1e-15,
3948 "pitch, m (3r² + l²)/12",
3949 );
3950 }
3951
3952 let in_stage = |design: &Rocket| match design.layout() {
3954 Err(DesignError::InComponent { id, source }) if id == "s" => *source,
3955 other => panic!("{other:?}"),
3956 };
3957 let mut bad = plain.clone();
3958 bad.stages[0].overrides.mass_kg = Some(-1.0);
3959 assert!(matches!(in_stage(&bad), DesignError::Domain { .. }));
3960 let mut bad = plain.clone();
3961 bad.stages[0].overrides.inertia = Some(InertiaOverride::axisymmetric(1.0, 0.1));
3962 assert!(matches!(in_stage(&bad), DesignError::UnphysicalInertia(_)));
3963 for broken in [
3964 Overrides {
3965 cg_aft_m: Some(f64::NAN),
3966 ..Overrides::default()
3967 },
3968 Overrides {
3969 cg_xy_m: Some([0.0, f64::INFINITY]),
3970 ..Overrides::default()
3971 },
3972 ] {
3973 let mut bad = plain.clone();
3974 bad.stages[0].overrides = broken;
3975 assert!(matches!(in_stage(&bad), DesignError::Domain { .. }));
3976 }
3977 let mut bad = plain.clone();
3978 bad.stages[0].overrides.inertia = Some(InertiaOverride {
3979 xy_kg_m2: f64::NAN,
3980 ..InertiaOverride::axisymmetric(0.1, 1.0)
3981 });
3982 assert!(matches!(in_stage(&bad), DesignError::UnphysicalInertia(_)));
3983 let mut zero = plain.clone();
3985 zero.stages[0].overrides.mass_kg = Some(0.0);
3986 assert_eq!(zero.layout().unwrap().structure.inertia_kg_m2, DMat3::ZERO);
3987 let mut bad = plain;
3988 bad.stages[0].overrides.mass_kg = Some(0.0);
3989 bad.stages[0].overrides.inertia = Some(InertiaOverride::axisymmetric(1.0, 5.0));
3990 assert!(matches!(in_stage(&bad), DesignError::UnphysicalInertia(_)));
3991 }
3992
3993 #[test]
3995 fn malformed_trees_are_refused() {
3996 let base = || {
3997 rocket(vec![stage(
3998 "s",
3999 vec![
4000 body("nose", nose(0.2, 0.03)),
4001 body("tube", tube(0.5, 0.03, 0.001)),
4002 ],
4003 )])
4004 };
4005 let tree_error = |design: Rocket, want: &str| match design.layout() {
4006 Err(DesignError::Tree { id, .. }) => assert_eq!(id, want),
4007 other => panic!("{want}: {other:?}"),
4008 };
4009
4010 let mut d = base();
4011 d.stages[0].components[1].children =
4012 vec![attached("mmt", inner_tube(0.2, 0.01, 0.001), top(0.0))];
4013 d.stages[0].components[1].children[0].children =
4014 vec![attached("fins", fins(0.1, 0.05), top(0.0))];
4015 tree_error(d, "fins");
4016
4017 let mut d = base();
4020 let lug = Part::LaunchLug(crate::LaunchLug {
4021 length_m: 0.03,
4022 outer_radius_m: 0.003,
4023 thickness_m: 0.0005,
4024 angle_rad: 0.0,
4025 count: 1,
4026 spacing_m: 0.0,
4027 material: crate::testing::cardboard(),
4028 });
4029 d.stages[0].components[0].children = vec![attached("lug", lug, top(0.0))];
4030 tree_error(d, "lug");
4031 let mut d = base();
4032 d.stages[0].components[0].children = vec![attached("fins", fins(0.1, 0.05), top(0.0))];
4033 match d.layout() {
4034 Err(DesignError::InComponent { id, source }) => {
4035 assert_eq!(id, "fins");
4036 assert!(
4037 matches!(&*source, DesignError::Geometry(m) if m.contains("stands")),
4038 "{source}"
4039 );
4040 }
4041 other => panic!("fins on the nose: {other:?}"),
4042 }
4043
4044 let mut d = base();
4045 d.stages[0].components[1].children =
4046 vec![attached("inner-body", tube(0.1, 0.02, 0.001), top(0.0))];
4047 tree_error(d, "inner-body");
4048
4049 let mut d = base();
4050 d.stages[0]
4051 .components
4052 .push(body("ballast", mass_component(0.1, 0.1, 0.01)));
4053 tree_error(d, "ballast");
4054
4055 let mut d = base();
4056 d.stages[0].components[1].children = vec![body("unplaced", mass_component(0.1, 0.1, 0.01))];
4057 tree_error(d, "unplaced");
4058
4059 let mut d = base();
4060 d.stages[0].components[1].position = Some(top(0.0));
4061 tree_error(d, "tube");
4062
4063 let mut d = base();
4064 d.stages[0].components[1].auto = vec![AutoDimension::BaseRadius];
4065 tree_error(d, "tube");
4066
4067 let mut d = base();
4068 d.stages[0].components[1].children =
4069 vec![attached("ring", ring(0.005, 0.02, 0.0), top(0.0))];
4070 d.stages[0].components[1].children[0].motor_mount = Some(MotorMount::default());
4071 tree_error(d, "ring");
4072
4073 let mut d = base();
4074 d.stages[0].components[1].children =
4075 vec![attached("bay", mass_component(0.1, 0.1, 0.01), top(0.0))];
4076 d.stages[0].components[1].children[0].children =
4077 vec![attached("x", mass_component(0.1, 0.1, 0.01), top(0.0))];
4078 tree_error(d, "bay");
4079
4080 let mut d = base();
4081 d.stages[0].components[0].children =
4082 vec![attached("weight", mass_component(0.1, 0.05, 0.0), top(0.0))];
4083 d.stages[0].components[0].children[0].auto = vec![AutoDimension::PackedRadius];
4084 tree_error(d, "weight");
4085
4086 let mut d = base();
4087 d.stages.push(stage("empty", Vec::new()));
4088 tree_error(d, "empty");
4089
4090 let mut d = base();
4091 d.stages[0].components[1].id = "nose".to_owned();
4092 assert_eq!(d.layout(), Err(DesignError::DuplicateId("nose".to_owned())));
4093 let mut d = base();
4094 d.stages[0].components[1].id = String::new();
4095 assert!(matches!(d.layout(), Err(DesignError::DuplicateId(_))));
4096
4097 let mut d = base();
4098 d.stages.clear();
4099 assert!(matches!(d.layout(), Err(DesignError::Tree { .. })));
4100 }
4101
4102 #[test]
4105 fn nested_overrides_apply_deepest_first() {
4106 let mut airframe = body("airframe", tube(0.8, 0.03, 0.001));
4107 let mut bay = attached("bay", mass_component(0.4, 0.1, 0.02), top(0.3));
4108 bay.overrides.mass_kg = Some(1.0);
4109 airframe.children = vec![bay];
4110 let plain = rocket(vec![stage("s", vec![airframe.clone()])]);
4111 let layout = plain.layout().unwrap();
4112 let (_, t) = layout.find("airframe").unwrap();
4113 let (_, b) = layout.find("bay").unwrap();
4114 assert_eq!(b.own.mass_kg, 1.0);
4115 close(
4116 t.with_children.mass_kg,
4117 t.own.mass_kg + 1.0,
4118 1e-15,
4119 "child override inside",
4120 );
4121
4122 airframe.overrides.mass_kg = Some(3.0);
4123 airframe.overrides_include_children = true;
4124 let layout = rocket(vec![stage("s", vec![airframe])]).layout().unwrap();
4125 let (_, t2) = layout.find("airframe").unwrap();
4126 close(
4127 t2.with_children.mass_kg,
4128 3.0,
4129 0.0,
4130 "parent override over the total",
4131 );
4132 close(
4134 t2.with_children.cg_m.z,
4135 t.with_children.cg_m.z,
4136 1e-15,
4137 "center kept",
4138 );
4139 }
4140
4141 #[test]
4145 fn aft_radii_and_resolution_errors() {
4146 let boattail = |aft_shoulder: bool| {
4147 let mut c = body(
4148 "flare",
4149 Part::Transition(Transition {
4150 shape: crate::NoseShape::Conical {},
4151 clipped: false,
4152 length_m: 0.1,
4153 fore_radius_m: 0.03,
4154 aft_radius_m: 0.0,
4155 wall: crate::Wall::Shell { thickness_m: 0.002 },
4156 fore_shoulder: None,
4157 aft_shoulder: aft_shoulder.then_some(Shoulder {
4158 length_m: 0.04,
4159 outer_radius_m: 0.0,
4160 thickness_m: 0.002,
4161 capped: false,
4162 }),
4163 material: crate::testing::cardboard(),
4164 }),
4165 );
4166 c.auto = vec![AutoDimension::AftRadius, AutoDimension::AftShoulderRadius];
4167 c
4168 };
4169 let with = |flare: Component, last: Component| {
4170 rocket(vec![stage(
4171 "s",
4172 vec![
4173 body("nose", nose(0.2, 0.03)),
4174 body("upper", tube(0.5, 0.03, 0.001)),
4175 flare,
4176 last,
4177 ],
4178 )])
4179 };
4180 let layout = with(boattail(true), body("lower", tube(0.4, 0.04, 0.0015)))
4181 .layout()
4182 .unwrap();
4183 let Part::Transition(t) = layout.find("flare").unwrap().1.part.clone() else {
4184 panic!()
4185 };
4186 assert_eq!(t.aft_radius_m, 0.04);
4187 assert_eq!(t.aft_shoulder.unwrap().outer_radius_m, 0.04 - 0.0015);
4188
4189 let tree_id = |result: Result<Layout, DesignError>| match result {
4190 Err(DesignError::Tree { id, .. }) => id,
4191 other => panic!("{other:?}"),
4192 };
4193 let lower = || body("lower", tube(0.4, 0.04, 0.0015));
4195 assert_eq!(tree_id(with(boattail(false), lower()).layout()), "flare");
4196 let mut cone = boattail(true);
4198 cone.id = "cone".to_owned();
4199 cone.auto = vec![AutoDimension::AftShoulderRadius];
4200 if let Part::Transition(t) = &mut cone.part {
4201 t.aft_radius_m = 0.02;
4202 }
4203 assert_eq!(tree_id(with(boattail(true), cone).layout()), "flare");
4204
4205 let mut no_nose = with(boattail(true), lower());
4206 no_nose.stages[0].components.remove(0);
4207 no_nose.reference_diameter = ReferenceDiameter::NoseBase {};
4208 assert!(matches!(no_nose.layout(), Err(DesignError::Tree { .. })));
4209
4210 let nest = |n: usize| {
4212 let mut deepest = attached("t0", inner_tube(0.1, 0.02, 0.001), top(0.0));
4213 for k in 1..n {
4214 let mut outer = attached(&format!("t{k}"), inner_tube(0.1, 0.02, 0.001), top(0.0));
4215 outer.children = vec![deepest];
4216 deepest = outer;
4217 }
4218 let mut airframe = body("airframe", tube(0.5, 0.03, 0.001));
4219 airframe.children = vec![deepest];
4220 rocket(vec![stage("s", vec![airframe])])
4221 };
4222 nest(MAX_DEPTH - 1).layout().unwrap();
4223 assert_eq!(tree_id(nest(MAX_DEPTH).layout()), "t0");
4224
4225 let bad = with(boattail(true), body("lower", tube(0.4, 0.04, -0.001)));
4227 assert!(matches!(
4228 bad.layout(),
4229 Err(DesignError::InComponent { ref id, ref source })
4230 if id == "lower" && matches!(**source, DesignError::Domain { .. })
4231 ));
4232 let mut bad = with(boattail(true), lower());
4233 bad.stages[0].components[1].children = vec![attached(
4234 "lost",
4235 mass_component(0.1, 0.1, 0.01),
4236 top(f64::NAN),
4237 )];
4238 assert!(matches!(
4239 bad.layout(),
4240 Err(DesignError::InComponent { ref id, .. }) if id == "lost"
4241 ));
4242 }
4243
4244 #[test]
4247 fn packed_radius_leaves_room_for_the_offset() {
4248 let mut design = three_fin_rocket();
4249 if let Part::Parachute(chute) = &mut design.stages[0].components[1].children[4].part {
4250 chute.packing.radial_offset_m = 0.005;
4251 }
4252 let layout = design.layout().unwrap();
4253 let Part::Parachute(chute) = layout.find("chute").unwrap().1.part.clone() else {
4254 panic!()
4255 };
4256 close(
4257 chute.packing.radius_m,
4258 0.0255 - 0.005,
4259 1e-15,
4260 "packed radius",
4261 );
4262 assert!(crate::checks::check(&design).unwrap().is_empty());
4263 if let Part::Parachute(chute) = &mut design.stages[0].components[1].children[4].part {
4264 chute.packing.radial_offset_m = 0.03;
4265 }
4266 assert!(matches!(
4267 design.layout(),
4268 Err(DesignError::Tree { ref id, .. }) if id == "chute"
4269 ));
4270 }
4271
4272 #[test]
4273 fn design_round_trips_through_json() {
4274 let design = three_fin_rocket();
4275 let text = serde_json::to_string_pretty(&design).unwrap();
4276 let back: Rocket = serde_json::from_str(&text).unwrap();
4277 assert_eq!(back, design);
4278 assert_eq!(back.layout().unwrap(), design.layout().unwrap());
4279 let bad = text.replacen("\"auto\"", "\"autos\"", 1);
4281 assert!(serde_json::from_str::<Rocket>(&bad).is_err());
4282 }
4283
4284 type SpineSpec = Vec<(usize, bool, bool, u8, u8)>;
4287
4288 fn random_spine(spec: &SpineSpec, split: usize) -> Rocket {
4289 let mut components = Vec::new();
4290 for (k, &(kind, fore_auto, aft_auto, fore_cm, aft_cm)) in spec.iter().enumerate() {
4291 let (fore, aft) = (f64::from(fore_cm) * 0.01, f64::from(aft_cm) * 0.01);
4292 let id = format!("c{k}");
4293 let mut c = match kind {
4294 0 if k == 0 => body(&id, nose(0.2, aft)),
4295 2 => body(&id, cone_transition(fore, aft)),
4296 _ => body(&id, tube(0.3, aft, 0.001)),
4297 };
4298 c.auto = match &c.part {
4299 Part::NoseCone(_) if aft_auto => vec![AutoDimension::BaseRadius],
4300 Part::BodyTube(_) if aft_auto => vec![AutoDimension::OuterRadius],
4301 Part::Transition(_) => [
4302 (fore_auto, AutoDimension::ForeRadius),
4303 (aft_auto, AutoDimension::AftRadius),
4304 ]
4305 .into_iter()
4306 .filter_map(|(on, dimension)| on.then_some(dimension))
4307 .collect(),
4308 _ => Vec::new(),
4309 };
4310 components.push(c);
4311 }
4312 let split = split.clamp(1, components.len());
4314 let aft = components.split_off(split);
4315 let mut stages = vec![stage("upper", components)];
4316 if !aft.is_empty() {
4317 stages.push(stage("lower", aft));
4318 }
4319 rocket(stages)
4320 }
4321
4322 proptest! {
4323 #[test]
4327 fn unresolvable_radii_are_exactly_what_layout_refuses(
4328 spec in proptest::collection::vec((0usize..3, any::<bool>(), any::<bool>(), 1u8..5, 1u8..5), 1..7),
4329 split in 1usize..7,
4330 ) {
4331 let mut design = random_spine(&spec, split);
4332 let unresolvable = design.unresolvable_body_radii();
4333 prop_assert_eq!(unresolvable.is_empty(), design.layout().is_ok(), "{:?}", unresolvable);
4334
4335 let body = |design: &Rocket| -> (Vec<Part>, Vec<Vec<AutoDimension>>) {
4336 design
4337 .stages
4338 .iter()
4339 .flat_map(|s| s.components.iter())
4340 .map(|c| (c.part.clone(), c.auto.clone()))
4341 .unzip()
4342 };
4343 let (parts, autos) = body(&design);
4344 let autos: Vec<&[AutoDimension]> = autos.iter().map(Vec::as_slice).collect();
4345 let (fore, aft) = sweep_body_radii(&parts, &autos);
4346
4347 let filled = design.fill_unresolvable_body_radii(0.025);
4348 prop_assert_eq!(&filled, &unresolvable);
4349 prop_assert!(design.unresolvable_body_radii().is_empty());
4350 let layout = design.layout();
4351 prop_assert!(layout.is_ok(), "{:?}", layout.as_ref().err());
4352 let layout = layout.unwrap();
4353 for (n, placed) in layout.body().enumerate() {
4354 let (f, a) = match &placed.part {
4355 Part::NoseCone(p) => (None, Some(p.base_radius_m)),
4356 Part::BodyTube(p) => (Some(p.outer_radius_m), Some(p.outer_radius_m)),
4357 Part::Transition(p) => (Some(p.fore_radius_m), Some(p.aft_radius_m)),
4358 _ => (None, None),
4359 };
4360 if let (Some(before), Some(after)) = (fore[n], f) {
4362 prop_assert_eq!(before, after, "forward radius of {}", placed.id);
4363 }
4364 if let (Some(before), Some(after)) = (aft[n], a) {
4365 prop_assert_eq!(before, after, "aft radius of {}", placed.id);
4366 }
4367 }
4368 }
4369
4370 #[test]
4374 fn structure_is_the_mass_weighted_sum_and_slides_rigidly(
4375 parts in proptest::collection::vec((0.01f64..2.0, 0.0f64..0.7, 0.0f64..0.02, -3.0f64..3.0), 1..6),
4376 d in -0.1f64..0.1,
4377 ) {
4378 let build = |shift: f64| {
4379 let mut airframe = body("airframe", tube(1.0, 0.03, 0.001));
4380 airframe.children = parts
4381 .iter()
4382 .enumerate()
4383 .map(|(k, &(m, s, r, angle))| {
4384 let mut c = attached(&format!("m{k}"), mass_component(m, 0.05, 0.005), top(s + shift));
4385 if let Part::MassComponent(p) = &mut c.part {
4386 p.packing.radial_offset_m = r;
4387 p.packing.angle_rad = angle;
4388 }
4389 c
4390 })
4391 .collect();
4392 if let Part::BodyTube(t) = &mut airframe.part {
4394 t.material = crate::Material::bulk("none", 0.0);
4395 }
4396 rocket(vec![stage("s", vec![airframe])]).layout().unwrap()
4397 };
4398 let layout = build(0.0);
4399 let total: f64 = parts.iter().map(|p| p.0).sum();
4400 prop_assert!((layout.structure.mass_kg - total).abs() <= 1e-12 * total);
4401 let moment: f64 = parts.iter().map(|&(m, s, _, _)| m * -(s + 0.025)).sum();
4402 prop_assert!((layout.structure.cg_m.z - moment / total).abs() <= 1e-12);
4403 let slid = build(d);
4404 prop_assert!((slid.structure.cg_m.z - (layout.structure.cg_m.z - d)).abs() <= 1e-12);
4405 let scale = layout.structure.inertia_kg_m2.to_cols_array().iter().fold(1e-12f64, |m, v| m.max(v.abs()));
4406 let diff = (slid.structure.inertia_kg_m2 - layout.structure.inertia_kg_m2)
4407 .to_cols_array()
4408 .iter()
4409 .fold(0.0f64, |m, v| m.max(v.abs()));
4410 prop_assert!(diff <= 1e-9 * scale, "{diff:e} of {scale:e}");
4411 }
4412 }
4413
4414 #[test]
4419 fn a_stages_overrides_leave_its_parts_in_place_by_its_rule() {
4420 let mut design = three_fin_rocket();
4421 let mut booster = design.stages[0].clone();
4422 booster.id = "booster".to_owned();
4423 booster
4424 .components
4425 .retain(|c| matches!(c.part, Part::BodyTube(_)));
4426 for (index, component) in booster.components.iter_mut().enumerate() {
4427 component.id = format!("booster-{index}");
4428 component.children.clear();
4429 }
4430 design.stages.push(booster);
4431 let plain = design.layout().unwrap();
4432 let parts = plain.stages[1].mass;
4433 let fore = plain.stages[1].fore_station_m;
4434 let with = |rule: StageOverrideRule, added: Option<AddedMass>, overrides: Overrides| {
4435 let mut design = design.clone();
4436 design.stages[1].override_rule = rule;
4437 design.stages[1].added_mass = added;
4438 design.stages[1].overrides = overrides;
4439 design.layout().map(|layout| layout.stages[1].mass)
4440 };
4441 let in_place =
4442 |added, overrides| with(StageOverrideRule::PartsInPlace, added, overrides).unwrap();
4443 let rescaled =
4444 |added, overrides| with(StageOverrideRule::Rescaled, added, overrides).unwrap();
4445 let pitch = |mass: &MassProperties| mass.inertia_kg_m2.x_axis.x;
4446 let roll = |mass: &MassProperties| mass.inertia_kg_m2.z_axis.z;
4447 let (m_p, x_p) = (parts.mass_kg, -parts.cg_m.z);
4448 let c = fore + 0.3;
4449 assert!((x_p - c).abs() > 0.05, "{x_p} {c}");
4450 let heavy = Overrides {
4451 mass_kg: Some(4.0),
4452 ..Overrides::default()
4453 };
4454 let center = Overrides {
4455 cg_aft_m: Some(0.3),
4456 ..Overrides::default()
4457 };
4458 let both = Overrides {
4459 mass_kg: Some(4.0),
4460 cg_aft_m: Some(0.3),
4461 ..Overrides::default()
4462 };
4463
4464 assert_eq!(in_place(None, Overrides::default()), parts);
4466
4467 let stage = in_place(None, heavy);
4469 close(stage.mass_kg, 4.0, 0.0, "mass under a mass");
4470 close(stage.cg_m.z, parts.cg_m.z, 1e-15, "center under a mass");
4471 close(pitch(&stage), pitch(&parts), 1e-15, "pitch under a mass");
4472 close(roll(&stage), roll(&parts), 1e-15, "roll under a mass");
4473 close(
4474 pitch(&rescaled(None, heavy)),
4475 pitch(&parts) * 4.0 / m_p,
4476 1e-12,
4477 "the default rule scales it",
4478 );
4479
4480 let about_c = pitch(&parts) + m_p * (x_p - c).powi(2);
4482 for (overrides, mass_kg) in [(center, m_p), (both, 4.0)] {
4483 let stage = in_place(None, overrides);
4484 close(stage.mass_kg, mass_kg, 1e-15, "mass");
4485 close(-stage.cg_m.z, c, 1e-15, "center");
4486 close(pitch(&stage), about_c, 1e-12, "pitch about the center");
4487 close(roll(&stage), roll(&parts), 1e-15, "roll");
4488 let default = rescaled(None, overrides);
4489 assert_eq!(
4490 (default.mass_kg, default.cg_m),
4491 (stage.mass_kg, stage.cg_m),
4492 "{overrides:?}"
4493 );
4494 }
4495
4496 let added = AddedMass {
4499 mass_kg: 0.5,
4500 cg_aft_m: None,
4501 };
4502 let stage = in_place(Some(added), center);
4503 close(stage.mass_kg, m_p + 0.5, 1e-15, "mass with an added mass");
4504 close(-stage.cg_m.z, c, 1e-15, "center with an added mass");
4505 close(pitch(&stage), about_c, 1e-12, "the added mass adds nothing");
4506 assert_eq!(
4508 in_place(Some(added), heavy),
4509 MassProperties {
4510 mass_kg: 4.0,
4511 ..parts
4512 }
4513 );
4514
4515 let stationed = AddedMass {
4517 mass_kg: 0.5,
4518 cg_aft_m: Some(0.1),
4519 };
4520 let whole = stationed.add_to(parts, fore).unwrap();
4521 let stage = in_place(Some(stationed), heavy);
4522 close(pitch(&stage), pitch(&whole), 1e-15, "a stationed mass");
4523 let stage = in_place(Some(stationed), center);
4524 close(
4525 pitch(&stage),
4526 pitch(&whole) + whole.mass_kg * (-whole.cg_m.z - c).powi(2),
4527 1e-12,
4528 "a stationed mass under a center",
4529 );
4530
4531 let stated = Overrides {
4533 inertia: Some(InertiaOverride::axisymmetric(0.01, 0.2)),
4534 ..both
4535 };
4536 let stage = in_place(None, stated);
4537 assert_eq!(
4538 stage.inertia_kg_m2,
4539 InertiaOverride::axisymmetric(0.01, 0.2).tensor()
4540 );
4541 let nothing = Overrides {
4542 mass_kg: Some(0.0),
4543 ..center
4544 };
4545 let stage = in_place(None, nothing);
4546 assert_eq!((stage.mass_kg, stage.inertia_kg_m2), (0.0, DMat3::ZERO));
4547 assert!(
4548 with(
4549 StageOverrideRule::PartsInPlace,
4550 None,
4551 Overrides {
4552 mass_kg: Some(-1.0),
4553 ..Overrides::default()
4554 }
4555 )
4556 .is_err()
4557 );
4558 }
4559
4560 #[test]
4563 fn a_stages_override_rule_reads_and_writes_by_name() {
4564 let mut stage = crate::testing::stage("s", Vec::new());
4565 let json = serde_json::to_string(&stage).unwrap();
4566 assert!(!json.contains("override_rule"), "{json}");
4567 stage.override_rule = StageOverrideRule::PartsInPlace;
4568 let json = serde_json::to_string(&stage).unwrap();
4569 assert!(
4570 json.contains(r#""override_rule":"parts_in_place""#),
4571 "{json}"
4572 );
4573 assert_eq!(serde_json::from_str::<Stage>(&json).unwrap(), stage);
4574 let rescaled = json.replace("parts_in_place", "rescaled");
4575 assert_eq!(
4576 serde_json::from_str::<Stage>(&rescaled)
4577 .unwrap()
4578 .override_rule,
4579 StageOverrideRule::Rescaled
4580 );
4581 assert!(
4582 serde_json::from_str::<Stage>(&json.replace("parts_in_place", "in_place")).is_err()
4583 );
4584 }
4585
4586 #[test]
4591 fn a_stages_added_mass_is_a_point_among_its_parts() {
4592 let mut design = three_fin_rocket();
4594 let mut booster = design.stages[0].clone();
4595 booster.id = "booster".to_owned();
4596 booster
4597 .components
4598 .retain(|c| matches!(c.part, Part::BodyTube(_)));
4599 for (index, component) in booster.components.iter_mut().enumerate() {
4600 component.id = format!("booster-{index}");
4601 component.children.clear();
4602 }
4603 design.stages.push(booster);
4604 let plain = design.layout().unwrap();
4605 let parts = plain.stages[1].mass;
4606 let fore = plain.stages[1].fore_station_m;
4607 assert!(fore > 0.5 && parts.mass_kg > 0.0, "{fore} {parts:?}");
4608 let with = |added: Option<AddedMass>, overrides: Overrides| {
4609 let mut design = design.clone();
4610 design.stages[1].added_mass = added;
4611 design.stages[1].overrides = overrides;
4612 design.layout()
4613 };
4614 let none = Overrides::default();
4615 let pitch = |mass: &MassProperties| mass.inertia_kg_m2.x_axis.x;
4616 let roll = |mass: &MassProperties| mass.inertia_kg_m2.z_axis.z;
4617
4618 let added = AddedMass {
4620 mass_kg: 0.5,
4621 cg_aft_m: None,
4622 };
4623 let layout = with(Some(added), none).unwrap();
4624 let stage = layout.stages[1].mass;
4625 close(stage.mass_kg, parts.mass_kg + 0.5, 1e-15, "mass");
4626 close(stage.cg_m.z, parts.cg_m.z, 1e-15, "center");
4627 close(pitch(&stage), pitch(&parts), 1e-12, "pitch inertia");
4628 close(roll(&stage), roll(&parts), 1e-15, "roll inertia");
4629 assert!(!layout.stages[1].center_overridden);
4630 assert_eq!(layout.stages[0], plain.stages[0]);
4632 close(
4633 layout.structure.mass_kg,
4634 plain.structure.mass_kg + 0.5,
4635 1e-15,
4636 "rocket mass",
4637 );
4638
4639 let stationed = AddedMass {
4641 mass_kg: 0.5,
4642 cg_aft_m: Some(0.1),
4643 };
4644 let layout = with(Some(stationed), none).unwrap();
4645 let stage = layout.stages[1].mass;
4646 let (m_p, x_p, x_a) = (parts.mass_kg, -parts.cg_m.z, fore + 0.1);
4647 let x = (m_p * x_p + 0.5 * x_a) / (m_p + 0.5);
4648 close(stage.mass_kg, m_p + 0.5, 1e-15, "mass");
4649 close(-stage.cg_m.z, x, 1e-15, "center");
4650 assert!(
4651 (x - x_p).abs() > 0.01,
4652 "the point moves the center: {x} {x_p}"
4653 );
4654 close(
4655 pitch(&stage),
4656 pitch(&parts) + m_p * (x_p - x).powi(2) + 0.5 * (x_a - x).powi(2),
4657 1e-12,
4658 "pitch inertia",
4659 );
4660 close(roll(&stage), roll(&parts), 1e-15, "roll inertia");
4661 assert_eq!((stage.cg_m.x, stage.cg_m.y), (0.0, 0.0));
4662 assert!(layout.stages[1].center_overridden);
4663
4664 let center = Overrides {
4667 cg_aft_m: Some(0.3),
4668 ..Overrides::default()
4669 };
4670 let stage = with(Some(added), center).unwrap().stages[1].mass;
4671 close(stage.mass_kg, m_p + 0.5, 1e-15, "mass under a center");
4672 close(-stage.cg_m.z, fore + 0.3, 1e-15, "center under a center");
4673 close(
4674 pitch(&stage),
4675 pitch(&parts),
4676 1e-12,
4677 "inertia under a center",
4678 );
4679 let heavy = Overrides {
4680 mass_kg: Some(4.0),
4681 ..Overrides::default()
4682 };
4683 let stage = with(Some(stationed), heavy).unwrap().stages[1].mass;
4684 close(stage.mass_kg, 4.0, 0.0, "mass under a mass");
4685 close(-stage.cg_m.z, x, 1e-15, "center under a mass");
4686
4687 for cg_aft_m in [None, Some(0.1)] {
4689 let nothing = AddedMass {
4690 mass_kg: 0.0,
4691 cg_aft_m,
4692 };
4693 let layout = with(Some(nothing), none).unwrap();
4694 assert_eq!(layout.stages[1].mass, plain.stages[1].mass);
4695 assert_eq!(layout.structure, plain.structure);
4696 }
4697
4698 let what = |added: AddedMass, parts: MassProperties| match added.add_to(parts, 0.0) {
4701 Err(DesignError::Domain { what, .. }) => what,
4702 other => panic!("{other:?}"),
4703 };
4704 for mass_kg in [-0.1, f64::NAN, f64::INFINITY] {
4705 let bad = AddedMass {
4706 mass_kg,
4707 cg_aft_m: None,
4708 };
4709 assert_eq!(what(bad, parts), "added mass (kg)");
4710 assert!(with(Some(bad), none).is_err());
4711 }
4712 for station in [f64::NAN, f64::NEG_INFINITY] {
4713 let bad = AddedMass {
4714 mass_kg: 0.5,
4715 cg_aft_m: Some(station),
4716 };
4717 assert_eq!(what(bad, parts), "added mass's station (m)");
4718 }
4719 let weightless = MassProperties::point(0.0, DVec3::new(0.0, 0.0, -0.4));
4720 assert_eq!(
4721 what(added, weightless),
4722 "added mass with no station, on parts that weigh nothing (kg)"
4723 );
4724 assert_eq!(
4727 stationed.add_to(weightless, 1.0).unwrap(),
4728 MassProperties::point(0.5, DVec3::new(0.0, 0.0, -1.1))
4729 );
4730 let nowhere = MassProperties::point(0.0, DVec3::new(0.02, 0.0, -0.4));
4731 assert_eq!(
4732 stationed.add_to(nowhere, 1.0).unwrap(),
4733 MassProperties::point(0.5, DVec3::new(0.0, 0.0, -1.1))
4734 );
4735
4736 let off_axis = MassProperties::point(0.25, DVec3::new(0.003, -0.004, -0.4));
4739 let level = stationed.add_to(off_axis, 1.0).unwrap();
4740 close(level.cg_m.x, 0.003, 1e-15, "off the axis, one way");
4741 close(level.cg_m.y, -0.004, 1e-15, "off the axis, the other");
4742 close(
4743 -level.cg_m.z,
4744 (0.25 * 0.4 + 0.5 * 1.1) / 0.75,
4745 1e-15,
4746 "center along the axis",
4747 );
4748 close(
4749 pitch(&level),
4750 0.25 * 0.5 / 0.75 * 0.7_f64.powi(2),
4751 1e-15,
4752 "inertia of two points in line with the axis",
4753 );
4754 close(
4755 roll(&level),
4756 0.0,
4757 1e-18,
4758 "roll inertia of two points in line",
4759 );
4760
4761 let json = serde_json::to_string(&design).unwrap();
4763 assert!(!json.contains("added_mass"), "{json}");
4764 let mut carrying = design.clone();
4765 carrying.stages[1].added_mass = Some(stationed);
4766 let json = serde_json::to_string(&carrying).unwrap();
4767 assert!(
4768 json.contains(r#""added_mass":{"mass_kg":0.5,"cg_aft_m":0.1}"#),
4769 "{json}"
4770 );
4771 assert_eq!(serde_json::from_str::<Rocket>(&json).unwrap(), carrying);
4772 }
4773
4774 #[test]
4778 fn a_layout_with_the_old_uk_key_reads_the_same() {
4779 let mut design = three_fin_rocket();
4780 design.stages[0].overrides.cg_aft_m = Some(0.4);
4781 design.stages[0].components[0].overrides.cg_aft_m = Some(0.1);
4782 let layout = design.layout().unwrap();
4783 assert!(layout.stages[0].center_overridden);
4784 let text = serde_json::to_string(&layout).unwrap();
4785 let old = text.replace("\"center_overridden\"", "\"centre_overridden\"");
4786 assert!(!old.contains("\"center_overridden\""));
4787 assert!(
4788 old.matches("\"centre_overridden\":true").count() >= 2,
4789 "a part and a stage: {old}"
4790 );
4791 assert_eq!(serde_json::from_str::<Layout>(&old).unwrap(), layout);
4792 }
4793}