1use std::collections::VecDeque;
39use std::f64::consts::PI;
40use std::sync::atomic::{AtomicBool, Ordering};
41use std::sync::{Arc, Mutex, OnceLock};
42
43use hpr_design::{Layout, NoseShape, Part, PlacedComponent};
44use serde::{Deserialize, Serialize};
45
46use crate::afterbody::SEPARATION_ONSET_RAD;
47use crate::body::{BodyGeometry, sinc};
48use crate::crossflow::BodyLift;
49use crate::custom::{DragModel, DragQuery, SharedDragModel};
50use crate::drag::{
51 BUILDUP_MACH_LIMIT, ComponentDrag, ComponentDragTerms, Drag, DragConditions, MOTOR_POD_SETS,
52 axial_drag_alpha_factor, body_friction_form_factor, couple_afterbody,
53};
54use crate::error::{AeroError, check_dimension, check_mach};
55use crate::fins::{
56 FinAero, FinLoading, FinRollTerms, fin_count_factor, interference_factor,
57 roll_damping_interference, roll_forcing_interference, roll_sum, side_sum,
58};
59use crate::shock_expansion::{
60 BodySegment, DEFAULT_ELEMENTS_PER_CURVE, SegmentSlope, ShockExpansionBody,
61 flare_corner_limit_rad,
62};
63use crate::supersonic_boattail::{wp_center_fraction, wp_slope};
64use crate::table::{DragTable, NormalForceLookup, NormalForceTable, TableReference};
65use crate::tube_fins::{TubeFinSetAero, check_tube_fin_mach};
66
67pub const MAX_CANT_RAD: f64 = 15.0 * std::f64::consts::PI / 180.0;
70
71pub const NORMAL_FORCE_MACH_LIMIT: f64 = 5.0;
74
75pub const SUPERSONIC_JOIN_START_MACH: f64 = 1.2;
79
80const SUPERSONIC_STEPS_PER_MACH: f64 = 20.0;
82
83const SUPERSONIC_FIRST_STEP: usize = 24;
85
86const SUPERSONIC_LAST_STEP: usize = 100;
88
89const SUPERSONIC_JOIN_STEPS: usize = 6;
91
92const SUPERSONIC_JOIN_BISECTIONS: usize = 64;
99
100const SUPERSONIC_SHELTER_FLOOR: f64 = 1e-6;
104
105pub const SUPERSONIC_JOIN_WIDTH_MACH: f64 =
108 SUPERSONIC_JOIN_STEPS as f64 / SUPERSONIC_STEPS_PER_MACH;
109
110#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
117#[serde(rename_all = "snake_case", tag = "switch")]
118#[non_exhaustive]
119pub enum SupersonicFallback {
120 RadiusStep {
123 component: String,
125 },
126 LongLip {
129 component: String,
131 },
132 SteepTip,
135 Other,
137}
138
139#[derive(Debug, Clone, PartialEq, Serialize)]
172#[non_exhaustive]
173pub struct SupersonicBody {
174 pub covered: usize,
183 pub join_start_mach: f64,
186 first_step: usize,
188 rows: Vec<Vec<SegmentSlope>>,
191 stationed: Vec<bool>,
194 lead: Option<Vec<SegmentSlope>>,
197 pub shape_weight: f64,
207}
208
209#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
212#[serde(rename_all = "snake_case")]
213#[non_exhaustive]
214pub enum SupersonicBoattail {
215 #[default]
220 WashingtonPettis,
221 Footnote8,
225}
226
227#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
230#[serde(rename_all = "snake_case")]
231#[non_exhaustive]
232pub enum SupersonicFlare {
233 #[default]
241 Marched,
242 SlenderBody,
245}
246
247#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
254#[serde(default, deny_unknown_fields)]
255#[non_exhaustive]
256pub struct BodyModel {
257 pub body_lift: BodyLift,
259 pub supersonic_boattail: SupersonicBoattail,
261 pub supersonic_flare: SupersonicFlare,
263}
264
265impl BodyModel {
266 pub const CURRENT: Self = Self {
269 body_lift: BodyLift::JORGENSEN,
270 supersonic_boattail: SupersonicBoattail::WashingtonPettis,
271 supersonic_flare: SupersonicFlare::Marched,
272 };
273
274 pub const BEFORE_M1_8E6: Self = Self {
278 body_lift: BodyLift::GALEJS,
279 supersonic_boattail: SupersonicBoattail::Footnote8,
280 supersonic_flare: SupersonicFlare::SlenderBody,
281 };
282
283 #[must_use]
285 pub const fn with_body_lift(mut self, body_lift: BodyLift) -> Self {
286 self.body_lift = body_lift;
287 self
288 }
289
290 #[must_use]
292 pub const fn with_supersonic_boattail(
293 mut self,
294 supersonic_boattail: SupersonicBoattail,
295 ) -> Self {
296 self.supersonic_boattail = supersonic_boattail;
297 self
298 }
299
300 #[must_use]
302 pub const fn with_supersonic_flare(mut self, supersonic_flare: SupersonicFlare) -> Self {
303 self.supersonic_flare = supersonic_flare;
304 self
305 }
306}
307
308#[derive(Debug, Clone, PartialEq)]
312struct RunBoattail {
313 in_its_place: Vec<BodySegment>,
314 fore_radius_m: f64,
315 aft_radius_m: f64,
316 length_m: f64,
317}
318
319#[derive(Debug, Clone, PartialEq)]
324struct RunFlare {
325 index: usize,
327 ahead: Vec<BodySegment>,
328 fore_radius_m: f64,
329 aft_radius_m: f64,
330 length_m: f64,
331 clipped: bool,
332}
333
334#[derive(Debug, Clone, PartialEq)]
339struct SupersonicRun {
340 segments: Vec<BodySegment>,
341 vertex_m: f64,
342 bounds_m: Vec<Option<(f64, f64)>>,
343 fore_m: Vec<f64>,
345 boattails: Vec<Option<RunBoattail>>,
347 flare: Option<RunFlare>,
349 sheltered_lips: usize,
353 shape_weight: f64,
358 }
362
363impl SupersonicRun {
364 fn shares(
373 &self,
374 body: &ShockExpansionBody,
375 in_its_place: &[Option<ShockExpansionBody>],
376 ahead: Option<&ShockExpansionBody>,
377 mach: f64,
378 reference_area_m2: f64,
379 ) -> Option<Vec<SegmentSlope>> {
380 let vertex_m = self.vertex_m;
381 let held = match (&self.flare, ahead) {
386 (Some(_), None) => return None,
389 (Some(flare), Some(ahead)) => {
390 let aft = ahead.aft_flow(mach).ok()?;
391 let rise_m = flare.aft_radius_m - flare.fore_radius_m;
392 let angle_rad = (rise_m / flare.length_m).atan();
393 let turn_limit_rad = flare_corner_limit_rad(aft.surface_mach).ok()?;
397 let angle_limit_rad =
398 (turn_limit_rad + aft.angle_rad).min(crate::blunt_tip::CONE_TABLE_CAP_RAD);
399 if angle_rad > angle_limit_rad {
400 if angle_limit_rad <= 0.0 || !angle_limit_rad.is_finite() {
405 return None;
406 }
407 let length_m = rise_m / angle_limit_rad.tan();
408 let mut segments = flare.ahead.clone();
409 segments.push(BodySegment::Profile {
410 profile: hpr_design::Profile::transition(
411 NoseShape::Conical {},
412 length_m,
413 flare.fore_radius_m,
414 flare.aft_radius_m,
415 flare.clipped,
416 )
417 .ok()?,
418 });
419 Some((
420 ShockExpansionBody::new(&segments, DEFAULT_ELEMENTS_PER_CURVE).ok()?,
421 length_m,
422 ))
423 } else {
424 None
425 }
426 }
427 _ => None,
428 };
429 let mut shares = match &held {
430 Some((drawn, _)) => drawn.segment_slopes(mach, reference_area_m2).ok()?,
431 None => body.segment_slopes(mach, reference_area_m2).ok()?,
432 };
433 if let (Some(flare), Some((_, drawn_length_m))) = (&self.flare, &held) {
437 let index = flare.index;
438 let share = *shares.get(index)?;
439 if share.slope_per_rad > 0.0 {
440 let fore_m = self.fore_m[index] - vertex_m;
441 let along = (share.moment_slope_m / share.slope_per_rad - fore_m) / drawn_length_m;
442 shares[index].moment_slope_m =
443 share.slope_per_rad * (fore_m + along * flare.length_m);
444 }
445 }
446 shares.extend(std::iter::repeat_n(
448 SegmentSlope::default(),
449 self.sheltered_lips,
450 ));
451 for (index, (boattail, cylinder_body)) in
452 self.boattails.iter().zip(in_its_place).enumerate()
453 {
454 let (Some(boattail), Some(cylinder_body)) = (boattail, cylinder_body) else {
455 continue;
456 };
457 let cylinder = *cylinder_body
460 .segment_slopes(mach, reference_area_m2)
461 .ok()?
462 .last()?;
463 let fore_radius_m = boattail.fore_radius_m;
464 let drop_m = fore_radius_m - boattail.aft_radius_m;
474 let read = |length_m| wp_slope(mach, fore_radius_m, boattail.aft_radius_m, length_m);
475 let at_true_angle = read(boattail.length_m).ok()?;
476 let held = read(boattail.length_m.max(drop_m / SEPARATION_ONSET_RAD.tan())).ok()?;
477 let ratio = boattail.aft_radius_m / fore_radius_m;
487 let measured = held.max(at_true_angle.min(2.0 * (ratio * ratio - 1.0)));
488 let increment = measured * PI * fore_radius_m * fore_radius_m / reference_area_m2;
489 let center_m =
490 self.fore_m[index] + wp_center_fraction(mach) * boattail.length_m - vertex_m;
491 shares[index] = SegmentSlope {
492 slope_per_rad: cylinder.slope_per_rad + increment,
493 moment_slope_m: cylinder.moment_slope_m + increment * center_m,
494 };
495 }
496 let on_segment = shares.iter().zip(&self.bounds_m).all(|(s, bounds)| {
497 let Some((fore, aft)) = *bounds else {
498 return s.slope_per_rad.is_finite() && s.moment_slope_m.is_finite();
499 };
500 let station = (s.moment_slope_m + s.slope_per_rad * vertex_m) / s.slope_per_rad;
501 let slack = 1e-9 * (aft - vertex_m);
502 s.slope_per_rad > 0.0 && station >= fore - slack && station <= aft + slack
503 });
504 on_segment.then(|| {
505 shares
506 .into_iter()
507 .map(|s| SegmentSlope {
508 slope_per_rad: s.slope_per_rad,
509 moment_slope_m: s.moment_slope_m + s.slope_per_rad * vertex_m,
510 })
511 .collect()
512 })
513 }
514}
515
516#[derive(Debug, Clone, Default)]
519struct SupersonicTable(Arc<OnceLock<Option<SupersonicBody>>>);
520
521const KEPT_TABLES: usize = 64;
525
526static KEEPING_TABLES: AtomicBool = AtomicBool::new(false);
529
530static KEPT: Mutex<KeptTables> = Mutex::new(KeptTables::new(KEPT_TABLES));
532
533pub fn keep_supersonic_tables() {
547 KEEPING_TABLES.store(true, Ordering::Relaxed);
548}
549
550#[derive(Debug)]
553struct KeptTables {
554 tables: VecDeque<(SupersonicRun, f64, Option<SupersonicBody>)>,
555 most: usize,
556}
557
558impl KeptTables {
559 const fn new(most: usize) -> Self {
561 Self {
562 tables: VecDeque::new(),
563 most,
564 }
565 }
566
567 fn find(&self, run: &SupersonicRun, reference_area_m2: f64) -> Option<&Option<SupersonicBody>> {
569 self.tables
570 .iter()
571 .find(|(kept_run, kept_area, _)| {
572 kept_area.to_bits() == reference_area_m2.to_bits() && kept_run == run
573 })
574 .map(|(.., table)| table)
575 }
576
577 fn keep(
580 &mut self,
581 run: &SupersonicRun,
582 reference_area_m2: f64,
583 table: &Option<SupersonicBody>,
584 ) {
585 if self.most == 0 || self.find(run, reference_area_m2).is_some() {
586 return;
587 }
588 if self.tables.len() >= self.most {
589 self.tables.pop_front();
590 }
591 self.tables
592 .push_back((run.clone(), reference_area_m2, table.clone()));
593 }
594}
595
596fn built_table(run: &SupersonicRun, reference_area_m2: f64) -> Option<SupersonicBody> {
601 if !KEEPING_TABLES.load(Ordering::Relaxed) {
602 return SupersonicBody::new(run, reference_area_m2);
603 }
604 if let Ok(kept) = KEPT.lock()
605 && let Some(table) = kept.find(run, reference_area_m2)
606 {
607 return table.clone();
608 }
609 let table = SupersonicBody::new(run, reference_area_m2);
611 if let Ok(mut kept) = KEPT.lock() {
612 kept.keep(run, reference_area_m2, &table);
613 }
614 table
615}
616
617impl PartialEq for SupersonicTable {
618 fn eq(&self, _: &Self) -> bool {
619 true
620 }
621}
622
623impl SupersonicBody {
624 fn new(run: &SupersonicRun, reference_area_m2: f64) -> Option<Self> {
628 let body = ShockExpansionBody::new(&run.segments, DEFAULT_ELEMENTS_PER_CURVE).ok()?;
629 let ahead = match &run.flare {
630 Some(flare) => {
631 Some(ShockExpansionBody::new(&flare.ahead, DEFAULT_ELEMENTS_PER_CURVE).ok()?)
632 }
633 None => None,
634 };
635 let mut in_its_place = Vec::with_capacity(run.boattails.len());
636 for boattail in &run.boattails {
637 in_its_place.push(match boattail {
638 Some(b) => Some(
639 ShockExpansionBody::new(&b.in_its_place, DEFAULT_ELEMENTS_PER_CURVE).ok()?,
640 ),
641 None => None,
642 });
643 }
644 let at = |step: f64| {
645 run.shares(
646 &body,
647 &in_its_place,
648 ahead.as_ref(),
649 step / SUPERSONIC_STEPS_PER_MACH,
650 reference_area_m2,
651 )
652 };
653 let mut rows = Vec::new();
654 let mut first_step = SUPERSONIC_LAST_STEP + 1;
655 for step in (SUPERSONIC_FIRST_STEP..=SUPERSONIC_LAST_STEP).rev() {
657 let Some(row) = at(step as f64) else {
658 break;
659 };
660 rows.push(row);
661 first_step = step;
662 }
663 rows.reverse();
664 if first_step + SUPERSONIC_JOIN_STEPS > SUPERSONIC_LAST_STEP {
666 return None;
667 }
668 let mut lead = None;
673 let mut join_start_mach = first_step as f64 / SUPERSONIC_STEPS_PER_MACH;
674 if first_step > SUPERSONIC_FIRST_STEP {
675 let (mut low, mut high) = (first_step as f64 - 1.0, first_step as f64);
676 let mut held = None;
677 for _ in 0..SUPERSONIC_JOIN_BISECTIONS {
678 let mid = 0.5 * (low + high);
679 if mid <= low || mid >= high {
680 break;
681 }
682 match at(mid) {
683 Some(row) => {
684 high = mid;
685 held = Some(row);
686 }
687 None => low = mid,
688 }
689 }
690 if let Some(row) = held {
691 join_start_mach = high / SUPERSONIC_STEPS_PER_MACH;
692 lead = Some(row);
693 }
694 }
695 Some(Self {
696 covered: run.segments.len() + run.sheltered_lips,
697 join_start_mach,
698 first_step,
699 rows,
700 lead,
701 shape_weight: run.shape_weight,
702 stationed: run
703 .bounds_m
704 .iter()
705 .map(Option::is_some)
706 .chain(std::iter::repeat_n(false, run.sheltered_lips))
708 .collect(),
709 })
710 }
711
712 #[must_use]
717 pub fn weight(&self, mach: f64) -> f64 {
718 self.shape_weight
719 * ((mach - self.join_start_mach) / SUPERSONIC_JOIN_WIDTH_MACH).clamp(0.0, 1.0)
720 }
721
722 #[must_use]
729 pub fn has_station(&self, index: usize) -> bool {
730 self.stationed.get(index).copied().unwrap_or(false)
731 }
732
733 pub fn share(&self, index: usize, mach: f64) -> Option<(f64, f64)> {
738 let x = mach * SUPERSONIC_STEPS_PER_MACH - self.first_step as f64;
739 let (a, b, t) = match &self.lead {
740 Some(lead) if x < 0.0 => {
742 let lead_x =
743 self.join_start_mach * SUPERSONIC_STEPS_PER_MACH - self.first_step as f64;
744 let t = ((x - lead_x) / -lead_x).clamp(0.0, 1.0);
745 (lead.get(index)?, self.rows[0].get(index)?, t)
746 }
747 _ => {
748 let i = (x.floor().max(0.0) as usize).min(self.rows.len() - 2);
750 let t = (x - i as f64).clamp(0.0, 1.0);
751 (self.rows[i].get(index)?, self.rows[i + 1].get(index)?, t)
752 }
753 };
754 Some((
755 a.slope_per_rad + t * (b.slope_per_rad - a.slope_per_rad),
756 a.moment_slope_m + t * (b.moment_slope_m - a.moment_slope_m),
757 ))
758 }
759}
760
761#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
763#[non_exhaustive]
764pub struct Roll {
765 pub forcing: f64,
767 pub damping: f64,
769}
770
771#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
773#[serde(deny_unknown_fields)]
774#[non_exhaustive]
775pub struct Flow {
776 pub mach: f64,
778 pub alpha_rad: f64,
781 pub roll_rad: f64,
784}
785
786impl Flow {
787 pub fn new(mach: f64, alpha_rad: f64, roll_rad: f64) -> Self {
790 Self {
791 mach,
792 alpha_rad,
793 roll_rad,
794 }
795 }
796
797 pub fn axial(mach: f64) -> Self {
799 Self::new(mach, 0.0, 0.0)
800 }
801
802 pub fn validate(&self) -> Result<(), AeroError> {
809 check_mach(self.mach, NORMAL_FORCE_MACH_LIMIT, "the normal force")?;
810 self.validate_angles()
811 }
812
813 fn validate_for_buildup(&self) -> Result<(), AeroError> {
816 check_mach(self.mach, BUILDUP_MACH_LIMIT, "the drag buildup")?;
817 self.validate_angles()
818 }
819
820 fn validate_angles(&self) -> Result<(), AeroError> {
822 if !(0.0..=PI).contains(&self.alpha_rad) {
823 return Err(AeroError::Domain {
824 what: "angle of attack",
825 value: self.alpha_rad,
826 });
827 }
828 if !self.roll_rad.is_finite() {
829 return Err(AeroError::Domain {
830 what: "flow roll angle",
831 value: self.roll_rad,
832 });
833 }
834 Ok(())
835 }
836}
837
838#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
840#[non_exhaustive]
841pub struct NormalForce {
842 pub coefficient: f64,
844 pub slope_per_rad: f64,
846 pub moment_m: f64,
849 pub moment_slope_m: f64,
853 pub cp_station_m: Option<f64>,
856 pub side_coefficient: f64,
859 pub side_moment_m: f64,
862 #[serde(default, skip_serializing_if = "Option::is_none")]
866 pub table: Option<NormalForceLookup>,
867}
868
869#[derive(Clone, Copy, Default)]
872struct Term {
873 slope: f64,
874 moment: f64,
875 side: f64,
876 side_moment: f64,
877 scale: f64,
878}
879
880impl Term {
881 fn times(self, k: f64) -> Term {
883 Term {
884 slope: k * self.slope,
885 moment: k * self.moment,
886 side: k * self.side,
887 side_moment: k * self.side_moment,
888 scale: k * self.scale,
889 }
890 }
891
892 fn add(self, other: Term) -> Term {
893 Term {
894 slope: self.slope + other.slope,
895 moment: self.moment + other.moment,
896 side: self.side + other.side,
897 side_moment: self.side_moment + other.side_moment,
898 scale: self.scale + other.scale,
899 }
900 }
901}
902
903impl NormalForce {
904 fn new(term: Term, alpha_rad: f64) -> Self {
905 let cancelled = term.slope.abs() <= 1e-12 * term.scale;
906 Self {
907 coefficient: term.slope * alpha_rad,
908 slope_per_rad: term.slope,
909 moment_m: term.moment * alpha_rad,
910 moment_slope_m: term.moment,
911 cp_station_m: (term.slope != 0.0 && !cancelled).then(|| term.moment / term.slope),
912 side_coefficient: term.side * alpha_rad,
913 side_moment_m: term.side_moment * alpha_rad,
914 table: None,
915 }
916 }
917}
918
919#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
921#[non_exhaustive]
922pub struct ComponentNormalForce {
923 pub id: String,
925 pub normal_force: NormalForce,
927}
928
929#[derive(Debug, Clone, PartialEq, Serialize)]
933#[non_exhaustive]
934pub struct BodyAero {
935 pub id: String,
937 pub fore_station_m: f64,
939 pub geometry: BodyGeometry,
941 pub step_area_m2: f64,
944 pub slope_per_rad: f64,
948 pub moment_slope_m: f64,
951 pub planform_ratio: f64,
954 pub lift_station_m: f64,
956}
957
958#[derive(Debug, Clone, PartialEq, Serialize)]
962#[non_exhaustive]
963pub struct FinSetAero {
964 pub id: String,
966 pub count: u32,
968 pub base_angle_rad: f64,
970 pub fin: FinAero,
972 pub count_factor: f64,
974 pub interference: f64,
976 pub fore_station_m: f64,
978 pub cant_rad: f64,
980 pub body_radius_m: f64,
982 pub roll_forcing_interference: f64,
984 pub roll_damping_interference: f64,
986 pub roll: FinRollTerms,
988 pub pods: Option<PodFins>,
990}
991
992#[derive(Debug, Clone, PartialEq, Serialize)]
996#[non_exhaustive]
997pub struct PodFins {
998 pub roll_rad: Vec<f64>,
1002 pub axis_roll: [FinRollTerms; 2],
1013 pub fins: u32,
1015}
1016
1017#[derive(Debug, Clone, PartialEq, Serialize)]
1027#[non_exhaustive]
1028pub struct PodSetAero {
1029 pub id: String,
1031 pub copies: u32,
1033 pub offset_squares_m2: f64,
1035 pub fineness: f64,
1038 crossflow_eta_low: f64,
1040 pub bodies: Vec<BodyAero>,
1044}
1045
1046impl FinSetAero {
1047 pub fn cp_station_m(&self, mach: f64) -> Result<f64, AeroError> {
1053 Ok(self.fore_station_m + self.fin.loading(mach)?.cp_m)
1054 }
1055}
1056
1057#[derive(Debug, Clone, PartialEq, Serialize)]
1062pub struct AeroModel {
1063 reference_area_m2: f64,
1064 reference_diameter_m: f64,
1065 length_m: f64,
1066 max_body_radius_m: f64,
1068 fineness: f64,
1070 crossflow_eta_low: f64,
1072 body_model: BodyModel,
1074 bodies: Vec<BodyAero>,
1075 pods: Vec<PodSetAero>,
1077 #[serde(skip)]
1079 supersonic_run: Option<SupersonicRun>,
1080 #[serde(skip)]
1082 supersonic_stop: Option<SupersonicFallback>,
1083 #[serde(skip)]
1087 supersonic: SupersonicTable,
1088 fin_sets: Vec<FinSetAero>,
1089 tube_fin_sets: Vec<TubeFinSetAero>,
1090 drag_terms: Vec<ComponentDragTerms>,
1091 drag_table: Option<DragTable>,
1092 #[serde(skip_serializing_if = "Option::is_none")]
1095 drag_model: Option<SharedDragModel>,
1096 normal_force_table: Option<NormalForceTable>,
1097 full_base_drag_under_power: bool,
1100 #[serde(skip_serializing_if = "is_one")]
1103 drag_scale: f64,
1104}
1105
1106fn is_one(scale: &f64) -> bool {
1109 *scale == 1.0
1110}
1111
1112fn scaled(mut drag: Drag, scale: f64) -> Drag {
1115 if scale != 1.0 {
1116 for part in [
1117 &mut drag.zero_lift_coefficient,
1118 &mut drag.friction,
1119 &mut drag.pressure,
1120 &mut drag.base,
1121 &mut drag.parasitic,
1122 &mut drag.stated,
1123 ] {
1124 *part *= scale;
1125 }
1126 }
1127 drag
1128}
1129
1130fn apply_drag_overrides(
1143 layout: &Layout,
1144 drag_terms: &mut Vec<ComponentDragTerms>,
1145 body_terms: &[(usize, BodyGeometry)],
1146) -> Result<(), AeroError> {
1147 let check = |id: &str, coefficient: f64| {
1148 if coefficient.is_finite() && coefficient >= 0.0 {
1149 Ok(coefficient)
1150 } else {
1151 Err(AeroError::InComponent {
1152 id: id.to_owned(),
1153 source: Box::new(AeroError::Domain {
1154 what: "stated drag coefficient",
1155 value: coefficient,
1156 }),
1157 })
1158 }
1159 };
1160 let unsupported = |id: &str, what: &str| AeroError::InComponent {
1161 id: id.to_owned(),
1162 source: Box::new(AeroError::Unsupported(what.to_owned())),
1163 };
1164 for (k, stage) in layout.stages.iter().enumerate() {
1165 if let Some(stated) = stage.drag_override {
1166 check(&stage.id, stated.coefficient)?;
1167 if stage.hung_on.is_some() {
1170 return Err(unsupported(
1171 &stage.id,
1172 "a drag override on a parallel stage",
1173 ));
1174 }
1175 if stated.include_children && layout.stages.iter().any(|s| s.hung_on == Some(k)) {
1176 return Err(unsupported(
1177 &stage.id,
1178 "a drag override covering a stage a parallel stage hangs on",
1179 ));
1180 }
1181 }
1182 }
1183 let mut covered = Vec::with_capacity(layout.components.len());
1187 for (index, component) in layout.components.iter().enumerate() {
1188 if let Some(stated) = component.drag_override {
1189 check(&component.id, stated.coefficient)?;
1190 }
1191 let mut covers = layout
1192 .stages
1193 .get(component.stage)
1194 .and_then(|s| s.drag_override)
1195 .is_some_and(|o| o.include_children);
1196 let mut parent = component.parent;
1197 for _ in 0..layout.components.len() {
1198 let Some(up) = parent.and_then(|at| layout.components.get(at)) else {
1199 break;
1200 };
1201 covers |= up.drag_override.is_some_and(|o| o.include_children);
1202 parent = up.parent;
1203 }
1204 let in_pod =
1205 layout.pod_set_of(index).is_some() || matches!(component.part, Part::PodSet(_));
1206 if in_pod && component.drag_override.is_some() {
1207 return Err(unsupported(
1208 &component.id,
1209 "a drag override on a pod set or in a pod",
1210 ));
1211 }
1212 if in_pod && covers {
1213 return Err(unsupported(
1214 &component.id,
1215 "a drag override covering a pod set",
1216 ));
1217 }
1218 if component.drag_override.is_some() && matches!(component.part, Part::TubeFinSet(_)) {
1219 return Err(unsupported(
1220 &component.id,
1221 "a drag override on a tube fin set",
1222 ));
1223 }
1224 covered.push(covers);
1225 }
1226 for terms in drag_terms.iter_mut() {
1227 let Some((index, component)) = layout.find(&terms.id) else {
1228 continue;
1229 };
1230 terms.stated = if covered[index] {
1231 Some(0.0)
1232 } else if let Some(stated) = component.drag_override {
1233 let instances = match &component.part {
1234 Part::FinSet(set) => set.count,
1235 Part::LaunchLug(lug) => lug.count,
1236 Part::RailButton(button) => button.count,
1237 _ => 1,
1238 };
1239 Some(stated.coefficient * f64::from(instances))
1240 } else {
1241 None
1242 };
1243 }
1244 for pair in body_terms.windows(2) {
1246 let (ahead, behind) = (pair[0].0, pair[1].0);
1247 if drag_terms[ahead].stated.is_some() {
1248 let terms = &mut drag_terms[behind];
1249 terms.boattail_area_ratio -= terms.fore_step_down_area_ratio;
1250 terms.fore_step_down_area_ratio = 0.0;
1251 }
1252 }
1253 for stage in &layout.stages {
1254 if let Some(stated) = stage.drag_override {
1255 drag_terms.push(ComponentDragTerms::stage(&stage.id, stated.coefficient));
1256 }
1257 }
1258 Ok(())
1259}
1260
1261fn with_axial(mut drag: Drag, factor: f64) -> Result<Drag, AeroError> {
1268 drag.axial_coefficient = drag.zero_lift_coefficient * factor;
1269 if !(drag.zero_lift_coefficient.is_finite() && drag.axial_coefficient.is_finite()) {
1270 return Err(AeroError::Domain {
1271 what: "drag coefficient",
1272 value: drag.zero_lift_coefficient,
1273 });
1274 }
1275 Ok(drag)
1276}
1277
1278impl AeroModel {
1279 pub fn new(layout: &Layout) -> Result<Self, AeroError> {
1286 Self::with_body_model(layout, BodyModel::default())
1287 }
1288
1289 pub fn with_body_model(layout: &Layout, body_model: BodyModel) -> Result<Self, AeroError> {
1312 body_model.body_lift.validate()?;
1313 check_dimension("reference diameter", layout.reference_diameter_m, false)?;
1314 let reference_area_m2 = layout.reference_area_m2();
1315 let length_m = layout.length_m;
1316 check_dimension("rocket length", length_m, false)?;
1317 let mut max_radius: f64 = 0.0;
1318 for component in layout.body() {
1319 if let Some(radius) = component.part.max_radius_m()? {
1320 max_radius = max_radius.max(radius);
1321 }
1322 }
1323 check_dimension("maximum body radius", max_radius, false)?;
1324 let fineness = length_m / (2.0 * max_radius);
1325 let form_factor = body_friction_form_factor(fineness)?;
1326 let mut bodies = Vec::new();
1327 let mut fin_sets = Vec::new();
1328 let mut tube_fin_sets = Vec::new();
1329 let mut drag_terms = Vec::new();
1330 let mut previous_aft_area: Option<f64> = None;
1331 let mut body_terms_at = Vec::new();
1332 let mut last_body_terms: Option<usize> = None;
1333 let mut supersonic_segments = Vec::new();
1336 let mut supersonic_bounds = Vec::new();
1337 let mut supersonic_fore = Vec::new();
1338 let mut supersonic_boattails = Vec::new();
1339 let mut flare: Option<RunFlare> = None;
1340 let mut proposed_flare: Option<&hpr_design::Transition> = None;
1341 let mut supersonic_open = true;
1342 let mut behind_boattail = false;
1343 let (mut vertex_m, mut supersonic_end_m) = (0.0, 0.0);
1344 let mut pods: Vec<PodBuild> = Vec::new();
1346 let mut pod_at: Vec<Option<usize>> = vec![None; layout.components.len()];
1347 let motor_pod_sets = motor_pod_sets(layout)?;
1350 for (index, component) in layout.components.iter().enumerate() {
1351 let in_component = |e: AeroError| AeroError::InComponent {
1352 id: component.id.clone(),
1353 source: Box::new(e),
1354 };
1355 if !component.fore_station_m.is_finite() {
1356 return Err(in_component(AeroError::Domain {
1357 what: "component station",
1358 value: component.fore_station_m,
1359 }));
1360 }
1361 let pod = layout.pod_set_of(index).map(|set| pod_at[set]);
1363 let first_new_drag_term = drag_terms.len();
1364 if let Some(at) = pod
1365 && matches!(
1366 component.part,
1367 Part::NoseCone(_) | Part::Transition(_) | Part::BodyTube(_)
1368 )
1369 {
1370 let build = at.and_then(|at| pods.get_mut(at)).ok_or_else(|| {
1372 in_component(AeroError::Layout(
1373 "a pod's body component before its pod set".to_owned(),
1374 ))
1375 })?;
1376 build
1377 .add_body(component, &mut drag_terms, length_m, reference_area_m2)
1378 .map_err(in_component)?;
1379 continue;
1380 }
1381 let body = match &component.part {
1382 Part::NoseCone(nose) => Some(
1383 nose.profile()
1384 .map_err(AeroError::from)
1385 .and_then(|p| BodyGeometry::from_profile(&p)),
1386 ),
1387 Part::Transition(transition) => Some(
1388 transition
1389 .profile()
1390 .map_err(AeroError::from)
1391 .and_then(|p| BodyGeometry::from_profile(&p)),
1392 ),
1393 Part::BodyTube(tube) => {
1394 Some(BodyGeometry::cylinder(tube.length_m, tube.outer_radius_m))
1395 }
1396 Part::FinSet(set) => {
1397 let mut terms = (|| {
1398 let fin = FinAero::new(&set.planform, reference_area_m2)?;
1399 let body_radius = component.body_radius_m.ok_or_else(|| {
1400 AeroError::Layout(
1401 "a fin set needs the radius of the body tube it is on".to_owned(),
1402 )
1403 })?;
1404 if !set.cant_rad.is_finite() || set.cant_rad.abs() > MAX_CANT_RAD {
1407 return Err(AeroError::Domain {
1408 what: "fin cant",
1409 value: set.cant_rad,
1410 });
1411 }
1412 if set.count < 2 && set.cant_rad != 0.0 {
1413 return Err(AeroError::Unsupported(
1414 "cant on a single fin, whose side force isn't modeled".to_owned(),
1415 ));
1416 }
1417 let span = fin.geometry().span_m;
1418 let taper = fin.outline().tip_chord_m() / set.planform.root_chord_m();
1419 let roll = fin.roll_terms(body_radius, layout.reference_diameter_m)?;
1420 Ok(FinSetAero {
1421 id: component.id.clone(),
1422 count: set.count,
1423 base_angle_rad: set.base_angle_rad,
1424 count_factor: fin_count_factor(set.count)?,
1425 interference: interference_factor(span, body_radius)?,
1426 fore_station_m: component.fore_station_m,
1427 cant_rad: set.cant_rad,
1428 body_radius_m: body_radius,
1429 roll_forcing_interference: roll_forcing_interference(
1430 span,
1431 body_radius,
1432 )?,
1433 roll_damping_interference: roll_damping_interference(
1434 span,
1435 body_radius,
1436 taper,
1437 )?,
1438 roll,
1439 fin,
1440 pods: None,
1441 })
1442 })()
1443 .map_err(in_component)?;
1444 if pod.is_some() {
1445 terms.pods = Some(
1446 pod_fins(set, component, &terms, layout.reference_diameter_m)
1447 .map_err(in_component)?,
1448 );
1449 }
1450 drag_terms.push(
1451 ComponentDragTerms::fins(
1452 component,
1453 set,
1454 terms.fin.geometry(),
1455 length_m,
1456 reference_area_m2,
1457 )
1458 .map_err(in_component)?,
1459 );
1460 fin_sets.push(terms);
1461 None
1462 }
1463 Part::TubeFinSet(set) => {
1464 if pod.is_some() {
1465 return Err(in_component(AeroError::Unsupported(
1466 "tube fins on a pod".to_owned(),
1467 )));
1468 }
1469 let terms = TubeFinSetAero::new(component, set, reference_area_m2)
1470 .map_err(in_component)?;
1471 drag_terms.push(
1472 ComponentDragTerms::tube_fins(component, set, length_m, reference_area_m2)
1473 .map_err(in_component)?,
1474 );
1475 tube_fin_sets.push(terms);
1476 None
1477 }
1478 Part::PodSet(_) if !layout.components.iter().any(|c| c.parent == Some(index)) => {
1480 None
1481 }
1482 Part::PodSet(_) => {
1483 pod_at[index] = Some(pods.len());
1484 let mut build =
1485 PodBuild::new(layout, index, component).map_err(in_component)?;
1486 build.motor_pod_set = motor_pod_sets.iter().position(|&set| set == index);
1487 pods.push(build);
1488 None
1489 }
1490 Part::LaunchLug(lug) => {
1492 drag_terms.push(
1493 ComponentDragTerms::launch_lugs(
1494 component,
1495 lug,
1496 length_m,
1497 reference_area_m2,
1498 )
1499 .map_err(in_component)?,
1500 );
1501 None
1502 }
1503 Part::RailButton(button) => {
1504 drag_terms.push(
1505 ComponentDragTerms::rail_buttons(
1506 component,
1507 button,
1508 length_m,
1509 reference_area_m2,
1510 )
1511 .map_err(in_component)?,
1512 );
1513 None
1514 }
1515 Part::InnerTube(_)
1517 | Part::CenteringRing(_)
1518 | Part::MassComponent(_)
1519 | Part::Parachute(_)
1520 | Part::Streamer(_)
1521 | Part::ShockCord(_) => None,
1522 other => {
1523 return Err(in_component(AeroError::Unsupported(format!(
1524 "a {} part",
1525 other.kind_name()
1526 ))));
1527 }
1528 };
1529 if pod.is_some() {
1531 let copies = copy_count(component).map_err(in_component)?;
1532 for terms in &mut drag_terms[first_new_drag_term..] {
1533 terms.copies = copies;
1534 terms.in_pod = true;
1535 }
1536 }
1537 if let Some(geometry) = body {
1538 let geometry = geometry.map_err(in_component)?;
1539 let step = previous_aft_area.map_or(0.0, |aft| geometry.fore_area_m2 - aft);
1540 last_body_terms = Some(drag_terms.len());
1541 drag_terms.push(
1542 ComponentDragTerms::body(
1543 component,
1544 &geometry,
1545 match &component.part {
1546 Part::NoseCone(nose) => Some(nose.shape),
1547 Part::Transition(transition) => Some(transition.shape),
1548 _ => None,
1549 },
1550 previous_aft_area,
1551 form_factor,
1552 length_m,
1553 reference_area_m2,
1554 )
1555 .map_err(in_component)?,
1556 );
1557 body_terms_at.push((drag_terms.len() - 1, geometry));
1558 let segment = match &component.part {
1559 Part::NoseCone(nose) if bodies.is_empty() => nose
1560 .profile()
1561 .ok()
1562 .map(|profile| BodySegment::Profile { profile }),
1563 Part::BodyTube(tube)
1564 if !bodies.is_empty()
1565 && step.abs() <= 1e-6 * geometry.fore_area_m2
1566 && (component.fore_station_m - supersonic_end_m).abs()
1567 <= 1e-9 * length_m =>
1568 {
1569 Some(BodySegment::Cylinder {
1570 length_m: tube.length_m,
1571 radius_m: tube.outer_radius_m,
1572 })
1573 }
1574 Part::Transition(transition)
1576 if !bodies.is_empty()
1577 && transition.aft_radius_m < transition.fore_radius_m
1578 && step.abs() <= 1e-6 * geometry.fore_area_m2
1579 && (component.fore_station_m - supersonic_end_m).abs()
1580 <= 1e-9 * length_m =>
1581 {
1582 transition
1583 .profile()
1584 .ok()
1585 .map(|profile| BodySegment::Profile { profile })
1586 }
1587 Part::Transition(transition)
1595 if !bodies.is_empty()
1596 && !behind_boattail
1597 && transition.aft_radius_m > transition.fore_radius_m
1598 && matches!(transition.shape, NoseShape::Conical {})
1599 && body_model.supersonic_flare == SupersonicFlare::Marched
1600 && step.abs() <= 1e-6 * geometry.fore_area_m2
1601 && (component.fore_station_m - supersonic_end_m).abs()
1602 <= 1e-9 * length_m =>
1603 {
1604 proposed_flare = Some(transition);
1605 transition
1606 .profile()
1607 .ok()
1608 .map(|profile| BodySegment::Profile { profile })
1609 }
1610 _ => None,
1611 };
1612 match segment {
1613 Some(segment) if supersonic_open => {
1614 if supersonic_segments.is_empty() {
1615 vertex_m = component.fore_station_m;
1616 }
1617 if let Some(transition) = proposed_flare.take() {
1620 flare = Some(RunFlare {
1621 index: supersonic_segments.len(),
1622 ahead: supersonic_segments.clone(),
1623 fore_radius_m: transition.fore_radius_m,
1624 aft_radius_m: transition.aft_radius_m,
1625 length_m: transition.length_m,
1626 clipped: transition.clipped,
1627 });
1628 }
1629 supersonic_boattails.push(match (&component.part, body_model) {
1632 (
1633 Part::Transition(transition),
1634 BodyModel {
1635 supersonic_boattail: SupersonicBoattail::WashingtonPettis,
1636 ..
1637 },
1638 ) if transition.aft_radius_m < transition.fore_radius_m => {
1639 let mut in_its_place = supersonic_segments.clone();
1640 in_its_place.push(BodySegment::Cylinder {
1641 length_m: transition.length_m,
1642 radius_m: transition.fore_radius_m,
1643 });
1644 Some(RunBoattail {
1645 in_its_place,
1646 fore_radius_m: transition.fore_radius_m,
1647 aft_radius_m: transition.aft_radius_m,
1648 length_m: transition.length_m,
1649 })
1650 }
1651 _ => None,
1652 });
1653 supersonic_segments.push(segment);
1654 let fore_m = component.fore_station_m;
1655 supersonic_fore.push(fore_m);
1656 supersonic_end_m = fore_m + geometry.length_m;
1657 behind_boattail |= matches!(&component.part, Part::Transition(t)
1662 if t.aft_radius_m < t.fore_radius_m);
1663 supersonic_bounds
1664 .push((!behind_boattail).then_some((fore_m, supersonic_end_m)));
1665 supersonic_open &= flare.is_none();
1667 }
1668 _ => supersonic_open = false,
1669 }
1670 previous_aft_area = Some(geometry.aft_area_m2);
1671 bodies.push(body_terms(component, geometry, step, reference_area_m2));
1672 }
1673 }
1674 if let (Some(index), Some(last)) = (last_body_terms, bodies.last()) {
1676 drag_terms[index].base_area_m2 = last.geometry.aft_area_m2;
1677 }
1678 couple_afterbody(&mut drag_terms, &body_terms_at, reference_area_m2)?;
1680 let mut pod_sets = Vec::new();
1682 for build in pods {
1683 if let Some((index, geometry)) = build.terms_at.last() {
1684 drag_terms[*index].base_area_m2 = geometry.aft_area_m2;
1685 }
1686 couple_afterbody(&mut drag_terms, &build.terms_at, reference_area_m2)?;
1687 if !build.aero.bodies.is_empty() {
1688 pod_sets.push(build.aero);
1689 }
1690 }
1691 apply_drag_overrides(layout, &mut drag_terms, &body_terms_at)?;
1693 let marched = supersonic_segments.len();
1697 let mut shelter_weight = 1.0_f64;
1701 let mut lip_too_long = false;
1704 let sheltered_lips = (marched..bodies.len())
1705 .take_while(|&index| {
1706 let (term, geometry) = body_terms_at[index];
1707 if bodies[index].slope_per_rad <= 0.0 {
1711 return false;
1712 }
1713 let Some(wake) = drag_terms[term].in_wake_of else {
1716 return false;
1717 };
1718 let boattail = &wake.boattail;
1719 if geometry.length_m > boattail.fore_diameter_m - boattail.aft_diameter_m {
1720 lip_too_long = true;
1721 return false;
1722 }
1723 let steps = body_terms_at[index.saturating_sub(1)]
1727 .1
1728 .aft_area_m2
1729 .lt(&geometry.fore_area_m2);
1730 let shoulders = geometry.aft_area_m2 > geometry.fore_area_m2;
1731 let mut covered = 1.0_f64;
1739 if steps {
1740 covered = covered.min(wake.step_fraction);
1741 }
1742 if shoulders {
1743 covered = covered.min(wake.shoulder_fraction);
1744 }
1745 if !covered.is_finite() || covered <= SUPERSONIC_SHELTER_FLOOR {
1748 return false;
1749 }
1750 shelter_weight = shelter_weight.min(covered);
1751 true
1752 })
1753 .count();
1754 let covered = marched + sheltered_lips;
1755 let rest_carries_nothing = bodies[covered..]
1756 .iter()
1757 .all(|body| body.slope_per_rad.abs() <= 1e-9);
1758 let carrying = (covered..bodies.len()).find(|&index| {
1762 let nothing = bodies[index].slope_per_rad.abs() <= 1e-9;
1763 !nothing
1764 });
1765 let supersonic_stop = if marched > 0 && rest_carries_nothing {
1766 None
1767 } else {
1768 Some(match carrying.map(|index| (index, &bodies[index])) {
1769 Some((index, body)) if lip_too_long && index == covered => {
1770 SupersonicFallback::LongLip {
1771 component: body.id.clone(),
1772 }
1773 }
1774 Some((_, body))
1776 if marched > 0
1777 && (body.step_area_m2.abs() > 1e-6 * body.geometry.fore_area_m2
1778 || body.step_area_m2.is_nan()) =>
1779 {
1780 SupersonicFallback::RadiusStep {
1781 component: body.id.clone(),
1782 }
1783 }
1784 _ => SupersonicFallback::Other,
1785 })
1786 };
1787 let supersonic_run = (marched > 0 && rest_carries_nothing).then_some(SupersonicRun {
1788 segments: supersonic_segments,
1789 vertex_m,
1790 bounds_m: supersonic_bounds,
1791 fore_m: supersonic_fore,
1792 boattails: supersonic_boattails,
1793 flare,
1794 sheltered_lips,
1795 shape_weight: shelter_weight,
1796 });
1797 Ok(Self {
1798 reference_area_m2,
1799 reference_diameter_m: layout.reference_diameter_m,
1800 length_m,
1801 max_body_radius_m: max_radius,
1802 fineness,
1803 crossflow_eta_low: crate::crossflow::crossflow_eta_low(fineness),
1804 body_model,
1805 bodies,
1806 pods: pod_sets,
1807 supersonic_run,
1808 supersonic_stop,
1809 supersonic: SupersonicTable::default(),
1810 fin_sets,
1811 tube_fin_sets,
1812 drag_terms,
1813 drag_table: None,
1814 drag_model: None,
1815 normal_force_table: None,
1816 full_base_drag_under_power: false,
1817 drag_scale: 1.0,
1818 })
1819 }
1820
1821 #[must_use]
1824 pub fn with_drag_table(mut self, table: DragTable) -> Self {
1825 self.drag_table = Some(table);
1826 self.drag_model = None;
1827 self
1828 }
1829
1830 pub fn drag_table(&self) -> Option<&DragTable> {
1832 self.drag_table.as_ref()
1833 }
1834
1835 #[must_use]
1838 pub fn with_drag_model(self, model: impl DragModel + 'static) -> Self {
1839 self.with_shared_drag_model(Arc::new(model))
1840 }
1841
1842 #[must_use]
1845 pub fn with_shared_drag_model(mut self, model: Arc<dyn DragModel>) -> Self {
1846 self.drag_model = Some(SharedDragModel(model));
1847 self.drag_table = None;
1848 self
1849 }
1850
1851 pub fn drag_model(&self) -> Option<&Arc<dyn DragModel>> {
1853 self.drag_model.as_ref().map(|shared| &shared.0)
1854 }
1855
1856 #[must_use]
1873 pub fn with_full_base_drag_under_power(mut self) -> Self {
1874 self.full_base_drag_under_power = true;
1875 self
1876 }
1877
1878 pub fn full_base_drag_under_power(&self) -> bool {
1881 self.full_base_drag_under_power
1882 }
1883
1884 pub fn with_drag_scale(mut self, scale: f64) -> Result<Self, AeroError> {
1896 if !(scale.is_finite() && scale >= 0.0) {
1897 return Err(AeroError::Domain {
1898 what: "drag scale",
1899 value: scale,
1900 });
1901 }
1902 self.drag_scale = scale;
1903 Ok(self)
1904 }
1905
1906 pub fn drag_scale(&self) -> f64 {
1909 self.drag_scale
1910 }
1911
1912 pub fn supersonic_table_built(&self) -> bool {
1916 self.supersonic.0.get().is_some()
1917 }
1918
1919 pub fn share_supersonic_table(&mut self, other: &AeroModel) -> bool {
1933 let shared = self.supersonic_run.is_some()
1934 && self.supersonic_run == other.supersonic_run
1935 && self.reference_area_m2 == other.reference_area_m2;
1936 if shared {
1937 self.supersonic = other.supersonic.clone();
1938 }
1939 shared
1940 }
1941
1942 fn read(&self, conditions: &DragConditions) -> DragConditions {
1945 if self.full_base_drag_under_power {
1946 DragConditions {
1947 thrusting_motor_area_m2: 0.0,
1948 thrusting_pod_motor_areas_m2: [0.0; MOTOR_POD_SETS],
1949 ..*conditions
1950 }
1951 } else {
1952 *conditions
1953 }
1954 }
1955
1956 pub fn with_normal_force_table(mut self, table: NormalForceTable) -> Result<Self, AeroError> {
1968 for column in table.columns() {
1969 let knots = column.cp_station_m.xs();
1970 let used = knots.partition_point(|&mach| mach <= NORMAL_FORCE_MACH_LIMIT) + 1;
1971 for &cp in column.cp_station_m.ys().iter().take(used) {
1972 if !(0.0..=self.length_m).contains(&cp) {
1973 return Err(AeroError::Domain {
1974 what: "normal-force table center of pressure, m aft of the nose tip",
1975 value: cp,
1976 });
1977 }
1978 }
1979 }
1980 self.normal_force_table = Some(table);
1981 Ok(self)
1982 }
1983
1984 pub fn normal_force_table(&self) -> Option<&NormalForceTable> {
1986 self.normal_force_table.as_ref()
1987 }
1988
1989 pub fn drag_terms(&self) -> &[ComponentDragTerms] {
1991 &self.drag_terms
1992 }
1993
1994 pub fn length_m(&self) -> f64 {
1997 self.length_m
1998 }
1999
2000 pub fn drag(&self, flow: &Flow, conditions: &DragConditions) -> Result<Drag, AeroError> {
2020 conditions.validate()?;
2021 let conditions = &self.read(conditions);
2022 let factor = axial_drag_alpha_factor(flow.alpha_rad)?;
2023 let drag = if let Some(custom) = &self.drag_model {
2024 flow.validate_angles()?;
2025 if !(flow.mach.is_finite() && flow.mach >= 0.0) {
2026 return Err(AeroError::Domain {
2027 what: "Mach number for a drag model",
2028 value: flow.mach,
2029 });
2030 }
2031 let coefficient = custom
2032 .0
2033 .zero_lift_drag(&DragQuery::new(flow, conditions, self))
2034 .map_err(|source| AeroError::DragModel {
2035 source: Box::new(source),
2036 })?;
2037 if !(coefficient.is_finite() && coefficient >= 0.0) {
2038 return Err(AeroError::Domain {
2039 what: "zero-lift drag coefficient from a drag model",
2040 value: coefficient,
2041 });
2042 }
2043 Drag {
2044 zero_lift_coefficient: coefficient,
2045 ..Drag::default()
2046 }
2047 } else if let Some(table) = &self.drag_table {
2048 flow.validate_angles()?;
2049 let lookup = table.lookup(flow.mach, conditions.thrusting)?;
2050 if lookup.value < 0.0 {
2054 return Err(AeroError::Domain {
2055 what: "zero-lift drag coefficient from a drag table",
2056 value: lookup.value,
2057 });
2058 }
2059 let scale = match table.reference_diameter_m {
2060 Some(d) => {
2061 check_dimension("drag table reference diameter", d, false)?;
2062 0.25 * PI * d * d / self.reference_area_m2
2063 }
2064 None => 1.0,
2065 };
2066 Drag {
2067 zero_lift_coefficient: lookup.value * scale,
2068 table: Some(lookup),
2069 ..Drag::default()
2070 }
2071 } else {
2072 self.buildup_sum(flow, conditions)?
2073 };
2074 with_axial(scaled(drag, self.drag_scale), factor)
2075 }
2076
2077 pub fn buildup_drag(
2086 &self,
2087 flow: &Flow,
2088 conditions: &DragConditions,
2089 ) -> Result<Drag, AeroError> {
2090 conditions.validate()?;
2091 let conditions = &self.read(conditions);
2092 let factor = axial_drag_alpha_factor(flow.alpha_rad)?;
2093 with_axial(self.buildup_sum(flow, conditions)?, factor)
2094 }
2095
2096 fn buildup_sum(&self, flow: &Flow, conditions: &DragConditions) -> Result<Drag, AeroError> {
2099 flow.validate_for_buildup()?;
2100 self.check_tube_fins(flow.mach)?;
2102 let reynolds = conditions.reynolds_per_m * self.length_m;
2103 let mut sum = Drag::default();
2104 for terms in &self.drag_terms {
2105 let d = terms.evaluate(reynolds, flow.mach, conditions, self.reference_area_m2)?;
2106 sum.friction += d.friction;
2107 sum.pressure += d.pressure;
2108 sum.base += d.base;
2109 sum.parasitic += d.parasitic;
2110 sum.stated += d.stated;
2111 }
2112 sum.zero_lift_coefficient =
2113 sum.friction + sum.pressure + sum.base + sum.parasitic + sum.stated;
2114 Ok(sum)
2115 }
2116
2117 pub fn buildup_components(
2127 &self,
2128 flow: &Flow,
2129 conditions: &DragConditions,
2130 ) -> Result<Vec<ComponentDrag>, AeroError> {
2131 flow.validate_for_buildup()?;
2132 self.check_tube_fins(flow.mach)?;
2133 conditions.validate()?;
2134 let conditions = &self.read(conditions);
2135 let factor = axial_drag_alpha_factor(flow.alpha_rad)?;
2136 let reynolds = conditions.reynolds_per_m * self.length_m;
2137 self.drag_terms
2138 .iter()
2139 .map(|terms| {
2140 let mut drag =
2141 terms.evaluate(reynolds, flow.mach, conditions, self.reference_area_m2)?;
2142 drag.axial_coefficient *= factor;
2143 Ok(ComponentDrag {
2144 id: terms.id.clone(),
2145 drag,
2146 })
2147 })
2148 .collect()
2149 }
2150
2151 pub fn reference_area_m2(&self) -> f64 {
2153 self.reference_area_m2
2154 }
2155
2156 pub fn reference_diameter_m(&self) -> f64 {
2158 self.reference_diameter_m
2159 }
2160
2161 pub fn roll(&self, mach: f64) -> Result<Roll, AeroError> {
2176 check_mach(mach, NORMAL_FORCE_MACH_LIMIT, "the roll moment")?;
2177 let mut roll = Roll::default();
2178 for set in &self.fin_sets {
2179 if let Some(pods) = &set.pods {
2180 let [a, b] = &pods.axis_roll;
2182 let damping =
2183 0.5 * (set.fin.roll_with(a, mach).damping + set.fin.roll_with(b, mach).damping);
2184 roll.damping += f64::from(pods.fins) * damping * set.roll_damping_interference;
2185 continue;
2186 }
2187 let fin = set.fin.roll_with(&set.roll, mach);
2188 let n = f64::from(set.count);
2189 roll.forcing -= n * fin.forcing_per_rad * set.roll_forcing_interference * set.cant_rad;
2190 roll.damping += n * fin.damping * set.roll_damping_interference;
2191 }
2192 let d = self.reference_diameter_m;
2196 for pod in &self.pods {
2197 for body in &pod.bodies {
2198 roll.damping -= 2.0 * body.slope_per_rad * pod.offset_squares_m2 / (d * d);
2199 }
2200 }
2201 for set in &self.tube_fin_sets {
2203 roll.damping += set.roll_damping(mach, d)?;
2204 }
2205 Ok(roll)
2206 }
2207
2208 pub fn steady_roll_rate_rad_s(&self, mach: f64, speed_m_s: f64) -> Result<f64, AeroError> {
2215 check_dimension("airspeed", speed_m_s, true)?;
2216 let roll = self.roll(mach)?;
2217 Ok(if roll.damping < 0.0 {
2218 -roll.forcing / roll.damping * 2.0 * speed_m_s / self.reference_diameter_m
2219 } else {
2220 0.0
2221 })
2222 }
2223
2224 pub fn bodies(&self) -> &[BodyAero] {
2226 &self.bodies
2227 }
2228
2229 pub fn supersonic_body(&self) -> Option<&SupersonicBody> {
2240 let run = self.supersonic_run.as_ref()?;
2241 self.supersonic
2242 .0
2243 .get_or_init(|| built_table(run, self.reference_area_m2))
2244 .as_ref()
2245 }
2246
2247 pub fn supersonic_fallback(&self) -> Option<SupersonicFallback> {
2251 if self.supersonic_run.is_none() {
2252 return Some(
2253 self.supersonic_stop
2254 .clone()
2255 .unwrap_or(SupersonicFallback::Other),
2256 );
2257 }
2258 if self.supersonic_body().is_some() {
2259 return None;
2260 }
2261 let steep_tip = self.supersonic_run.as_ref().is_some_and(|run| {
2263 ShockExpansionBody::new(&run.segments, DEFAULT_ELEMENTS_PER_CURVE).is_ok_and(|body| {
2264 !body.has_blunt_tip()
2265 && crate::shock_expansion::past_cone_tables(body.vertex_angle_rad())
2266 })
2267 });
2268 if steep_tip {
2269 return Some(SupersonicFallback::SteepTip);
2270 }
2271 let marched = self
2275 .supersonic_run
2276 .as_ref()
2277 .map_or(0, |run| run.segments.len());
2278 let stepped = self
2279 .bodies
2280 .iter()
2281 .take(marched)
2282 .find(|body| body.step_area_m2 != 0.0);
2283 Some(match stepped {
2284 Some(body) => SupersonicFallback::RadiusStep {
2285 component: body.id.clone(),
2286 },
2287 None => SupersonicFallback::Other,
2288 })
2289 }
2290
2291 fn supersonic_at(&self, mach: f64) -> Option<&SupersonicBody> {
2294 (mach > SUPERSONIC_JOIN_START_MACH)
2295 .then(|| self.supersonic_body())
2296 .flatten()
2297 }
2298
2299 fn body_potential(&self, index: usize, body: &BodyAero, mach: f64) -> (f64, f64) {
2303 let (slope, moment) = (body.slope_per_rad, body.moment_slope_m);
2304 match self.supersonic_at(mach) {
2305 Some(s) if index < s.covered && mach > s.join_start_mach => {
2306 let w = s.weight(mach);
2307 let Some((se_slope, se_moment)) = s.share(index, mach) else {
2308 return (slope, moment);
2309 };
2310 (
2311 slope + w * (se_slope - slope),
2312 moment + w * (se_moment - moment),
2313 )
2314 }
2315 _ => (slope, moment),
2316 }
2317 }
2318
2319 pub fn body_lift_factor(&self, flow: &Flow) -> f64 {
2323 self.lift_factor_at(flow.mach, flow.alpha_rad.sin())
2324 }
2325
2326 fn lift_factor_at(&self, mach: f64, sin_alpha: f64) -> f64 {
2328 self.lift_factor_of(self.fineness, self.crossflow_eta_low, mach, sin_alpha)
2329 }
2330
2331 fn lift_factor_of(&self, fineness: f64, eta_low: f64, mach: f64, sin_alpha: f64) -> f64 {
2334 let crossflow_mach = mach * sin_alpha.abs();
2335 match self.body_model.body_lift {
2336 BodyLift::Jorgensen {} => {
2337 crate::crossflow::crossflow_factor_from_eta_low(eta_low, crossflow_mach)
2338 }
2339 other => other.factor(fineness, crossflow_mach),
2340 }
2341 }
2342
2343 fn body_factors(&self, flow: &Flow) -> (f64, f64) {
2346 let (potential, lift, sin_alpha) = alpha_factors(flow.alpha_rad);
2347 if lift == 0.0 {
2348 (potential, 0.0)
2349 } else {
2350 (potential, lift * self.lift_factor_at(flow.mach, sin_alpha))
2351 }
2352 }
2353
2354 fn pod_factors(&self, pod: &PodSetAero, flow: &Flow) -> (f64, f64) {
2356 let (potential, lift, sin_alpha) = alpha_factors(flow.alpha_rad);
2357 if lift == 0.0 {
2358 (potential, 0.0)
2359 } else {
2360 let factor =
2361 self.lift_factor_of(pod.fineness, pod.crossflow_eta_low, flow.mach, sin_alpha);
2362 (potential, lift * factor)
2363 }
2364 }
2365
2366 fn pod_body(&self, index: usize) -> Option<(&PodSetAero, &BodyAero)> {
2369 let mut index = index;
2370 for pod in &self.pods {
2371 match pod.bodies.get(index) {
2372 Some(body) => return Some((pod, body)),
2373 None => index -= pod.bodies.len(),
2374 }
2375 }
2376 None
2377 }
2378
2379 fn pod_bodies(&self) -> impl Iterator<Item = (&PodSetAero, &BodyAero)> {
2381 self.pods
2382 .iter()
2383 .flat_map(|pod| pod.bodies.iter().map(move |body| (pod, body)))
2384 }
2385
2386 pub fn body_model(&self) -> BodyModel {
2388 self.body_model
2389 }
2390
2391 pub fn fineness(&self) -> f64 {
2393 self.fineness
2394 }
2395
2396 pub fn fin_sets(&self) -> &[FinSetAero] {
2398 &self.fin_sets
2399 }
2400
2401 pub fn rolls(&self) -> bool {
2405 self.normal_force_table.is_none() && self.fin_sets.iter().any(|set| set.count < 3)
2406 }
2407
2408 pub fn tube_fin_sets(&self) -> &[TubeFinSetAero] {
2410 &self.tube_fin_sets
2411 }
2412
2413 fn check_tube_fins(&self, mach: f64) -> Result<(), AeroError> {
2415 if self.tube_fin_sets.is_empty() {
2416 Ok(())
2417 } else {
2418 check_tube_fin_mach(mach)
2419 }
2420 }
2421
2422 pub fn pod_sets(&self) -> &[PodSetAero] {
2424 &self.pods
2425 }
2426
2427 fn terms<'a>(&'a self, flow: &Flow) -> impl Iterator<Item = (&'a str, Term)> + 'a {
2431 let (potential, lift) = self.body_factors(flow);
2432 let (mach, roll) = (flow.mach, flow.roll_rad);
2433 let bodies = self.bodies.iter().enumerate().map(move |(index, body)| {
2434 let (slope, moment) = self.body_potential(index, body, mach);
2435 (
2436 body.id.as_str(),
2437 body_term(body, slope, moment, potential, lift),
2438 )
2439 });
2440 let flow = *flow;
2441 let pods = self
2442 .pod_bodies()
2443 .map(move |(pod, body)| (body.id.as_str(), self.pod_body_term(pod, body, &flow)));
2444 let fins = self
2445 .fin_sets
2446 .iter()
2447 .map(move |set| (set.id.as_str(), fin_term(set, mach, roll)));
2448 let tubes = self
2449 .tube_fin_sets
2450 .iter()
2451 .map(move |set| (set.id.as_str(), tube_fin_term(set, mach)));
2452 bodies.chain(pods).chain(fins).chain(tubes)
2453 }
2454
2455 fn pod_body_term(&self, pod: &PodSetAero, body: &BodyAero, flow: &Flow) -> Term {
2458 let (potential, lift) = self.pod_factors(pod, flow);
2459 body_term(
2460 body,
2461 body.slope_per_rad,
2462 body.moment_slope_m,
2463 potential,
2464 lift,
2465 )
2466 .times(f64::from(pod.copies))
2467 }
2468
2469 pub fn component_count(&self) -> usize {
2472 self.tube_fin_set_start() + self.tube_fin_sets.len()
2473 }
2474
2475 pub fn tube_fin_set_start(&self) -> usize {
2478 self.fin_set_start() + self.fin_sets.len()
2479 }
2480
2481 pub fn fin_set_start(&self) -> usize {
2485 self.bodies.len() + self.pods.iter().map(|pod| pod.bodies.len()).sum::<usize>()
2486 }
2487
2488 pub fn component_normal_force(
2497 &self,
2498 index: usize,
2499 flow: &Flow,
2500 ) -> Result<NormalForce, AeroError> {
2501 flow.validate()?;
2502 let term = if let Some(body) = self.bodies.get(index) {
2503 let (potential, lift) = self.body_factors(flow);
2504 let (slope, moment) = self.body_potential(index, body, flow.mach);
2505 body_term(body, slope, moment, potential, lift)
2506 } else if let Some((pod, body)) = self.pod_body(index - self.bodies.len()) {
2507 self.pod_body_term(pod, body, flow)
2508 } else if let Some(set) = self.fin_sets.get(index - self.fin_set_start()) {
2509 fin_term(set, flow.mach, flow.roll_rad)
2510 } else if let Some(set) = self.tube_fin_sets.get(index - self.tube_fin_set_start()) {
2511 check_tube_fin_mach(flow.mach)?;
2512 tube_fin_term(set, flow.mach)
2513 } else {
2514 return Err(AeroError::Domain {
2515 what: "component index",
2516 value: index as f64,
2517 });
2518 };
2519 Ok(NormalForce::new(term, flow.alpha_rad))
2520 }
2521
2522 pub fn component_station_m(&self, index: usize, mach: f64) -> Result<f64, AeroError> {
2544 check_mach(mach, NORMAL_FORCE_MACH_LIMIT, "the normal force")?;
2545 if let Some(body) = self.bodies.get(index) {
2546 let station = slender_station_m(body, self.reference_area_m2);
2547 Ok(match self.supersonic_at(mach) {
2551 Some(s) if index < s.covered && s.stationed[index] && mach > s.join_start_mach => {
2552 match s.share(index, mach) {
2553 Some((slope, moment)) => {
2556 station + s.weight(mach) * (moment / slope - station)
2557 }
2558 None => station,
2559 }
2560 }
2561 _ => station,
2562 })
2563 } else if let Some((_, body)) = self.pod_body(index - self.bodies.len()) {
2564 Ok(slender_station_m(body, self.reference_area_m2))
2565 } else if let Some(set) = self.fin_sets.get(index - self.fin_set_start()) {
2566 Ok(set.fore_station_m + set.fin.loading_at(mach).cp_m)
2567 } else {
2568 let set = self
2569 .tube_fin_sets
2570 .get(index - self.tube_fin_set_start())
2571 .ok_or(AeroError::Domain {
2572 what: "component index",
2573 value: index as f64,
2574 })?;
2575 check_tube_fin_mach(mach)?;
2576 Ok(set.loading_at(mach).1)
2577 }
2578 }
2579
2580 pub fn pitch_damping(&self, mach: f64, reference_station_m: f64) -> Result<f64, AeroError> {
2607 self.pitch_damping_of(mach, reference_station_m, 0..self.component_count())
2608 }
2609
2610 pub fn pitch_damping_of(
2623 &self,
2624 mach: f64,
2625 reference_station_m: f64,
2626 components: std::ops::Range<usize>,
2627 ) -> Result<f64, AeroError> {
2628 if !reference_station_m.is_finite() {
2629 return Err(AeroError::Domain {
2630 what: "pitch damping reference station",
2631 value: reference_station_m,
2632 });
2633 }
2634 let flow = Flow::axial(mach);
2635 let x_r = reference_station_m;
2636 let mut sum = 0.0;
2637 for index in components {
2638 let force = self.component_normal_force(index, &flow)?;
2639 let station = self.component_station_m(index, mach)?;
2640 sum += (station - x_r) * (force.moment_slope_m - force.slope_per_rad * x_r);
2641 }
2642 let d = self.reference_diameter_m();
2643 Ok(-2.0 * sum / (d * d))
2644 }
2645
2646 pub fn normal_force(&self, flow: &Flow) -> Result<NormalForce, AeroError> {
2660 if let Some(table) = &self.normal_force_table {
2661 flow.validate_angles()?;
2662 let lookup = table.lookup_within(flow.mach, flow.alpha_rad, (0.0, self.length_m))?;
2663 let area_m2 = match table.reference() {
2664 TableReference::Diameter { diameter_m } => 0.25 * PI * diameter_m * diameter_m,
2665 TableReference::LargestBody => PI * self.max_body_radius_m * self.max_body_radius_m,
2666 TableReference::Rocket => self.reference_area_m2,
2668 };
2669 let scale = area_m2 / self.reference_area_m2;
2670 let coefficient = lookup.coefficient * scale;
2671 let slope = lookup.slope_per_rad * scale;
2672 return Ok(NormalForce {
2673 coefficient,
2674 slope_per_rad: slope,
2675 moment_m: coefficient * lookup.cp_station_m,
2676 moment_slope_m: slope * lookup.cp_station_m,
2677 cp_station_m: (slope != 0.0).then_some(lookup.cp_station_m),
2678 side_coefficient: 0.0,
2679 side_moment_m: 0.0,
2680 table: Some(lookup),
2681 });
2682 }
2683 flow.validate()?;
2684 self.check_tube_fins(flow.mach)?;
2685 let total = self
2686 .terms(flow)
2687 .fold(Term::default(), |sum, (_, term)| sum.add(term));
2688 Ok(NormalForce::new(total, flow.alpha_rad))
2689 }
2690
2691 pub fn components(&self, flow: &Flow) -> Result<Vec<ComponentNormalForce>, AeroError> {
2703 flow.validate()?;
2704 self.check_tube_fins(flow.mach)?;
2705 Ok(self
2706 .terms(flow)
2707 .map(|(id, term)| ComponentNormalForce {
2708 id: id.to_owned(),
2709 normal_force: NormalForce::new(term, flow.alpha_rad),
2710 })
2711 .collect())
2712 }
2713}
2714
2715fn slender_station_m(body: &BodyAero, reference_area_m2: f64) -> f64 {
2720 let step_slope = 2.0 * body.step_area_m2 / reference_area_m2;
2721 let scale = (body.slope_per_rad - step_slope).abs() + step_slope.abs();
2722 if body.slope_per_rad.abs() <= 1e-12 * scale {
2723 body.lift_station_m
2724 } else {
2725 body.moment_slope_m / body.slope_per_rad
2726 }
2727}
2728
2729fn fin_term(set: &FinSetAero, mach: f64, roll: f64) -> Term {
2732 let FinLoading {
2733 slope_per_rad,
2734 cp_m,
2735 } = set.fin.loading_at(mach);
2736 let per_set = slope_per_rad * set.count_factor * set.interference;
2737 let station = set.fore_station_m + cp_m;
2738 let (roll_share, side_share) = match &set.pods {
2739 None => (
2740 roll_sum(set.count, set.base_angle_rad, roll),
2741 side_sum(set.count, set.base_angle_rad, roll),
2742 ),
2743 Some(pods) => pods.roll_rad.iter().fold((0.0, 0.0), |(r, s), turn| {
2744 let base = set.base_angle_rad + turn;
2745 (
2746 r + roll_sum(set.count, base, roll),
2747 s + side_sum(set.count, base, roll),
2748 )
2749 }),
2750 };
2751 let slope = per_set * roll_share;
2752 let side = per_set * side_share;
2753 Term {
2754 slope,
2755 moment: slope * station,
2756 side,
2757 side_moment: side * station,
2758 scale: slope.abs(),
2759 }
2760}
2761
2762fn tube_fin_term(set: &TubeFinSetAero, mach: f64) -> Term {
2765 let (slope, station) = set.loading_at(mach);
2766 Term {
2767 slope,
2768 moment: slope * station,
2769 side: 0.0,
2770 side_moment: 0.0,
2771 scale: slope.abs(),
2772 }
2773}
2774
2775fn body_term(body: &BodyAero, slope: f64, moment: f64, potential: f64, lift: f64) -> Term {
2779 let (attached, lift) = (slope * potential, body.planform_ratio * lift);
2780 Term {
2781 slope: attached + lift,
2782 moment: moment * potential + lift * body.lift_station_m,
2783 scale: attached.abs() + lift.abs(),
2784 ..Term::default()
2785 }
2786}
2787
2788fn alpha_factors(alpha_rad: f64) -> (f64, f64, f64) {
2791 let (s, sin) = (sinc(alpha_rad), alpha_rad.sin());
2792 (s, sin * s, sin)
2793}
2794
2795fn motor_pod_sets(layout: &Layout) -> Result<Vec<usize>, AeroError> {
2803 let sets = layout.motor_pod_sets();
2804 if sets.len() > MOTOR_POD_SETS {
2805 return Err(AeroError::Unsupported(format!(
2806 "motor mounts in {} pod sets; the drag tells apart the thrusting motors' areas of at \
2807 most {MOTOR_POD_SETS}",
2808 sets.len()
2809 )));
2810 }
2811 Ok(sets)
2812}
2813
2814fn copy_count(component: &PlacedComponent) -> Result<u32, AeroError> {
2816 u32::try_from(component.copies.len()).map_err(|_| AeroError::Domain {
2817 what: "copies of a component",
2818 value: component.copies.len() as f64,
2819 })
2820}
2821
2822struct PodBuild {
2824 aero: PodSetAero,
2825 form_factor: Option<f64>,
2827 motor_pod_set: Option<usize>,
2830 previous_aft_area: Option<f64>,
2831 terms_at: Vec<(usize, BodyGeometry)>,
2833}
2834
2835impl PodBuild {
2836 fn new(layout: &Layout, index: usize, component: &PlacedComponent) -> Result<Self, AeroError> {
2838 let copies = component.contents_copies()?;
2839 let offset_squares_m2 = copies
2840 .iter()
2841 .map(|c| c.offset_m[0] * c.offset_m[0] + c.offset_m[1] * c.offset_m[1])
2842 .sum();
2843 let mut max_radius: f64 = 0.0;
2844 for child in layout.components.iter().filter(|c| c.parent == Some(index)) {
2845 if let Some(radius) = child.part.max_radius_m()? {
2846 max_radius = max_radius.max(radius);
2847 }
2848 }
2849 let fineness = if max_radius > 0.0 && component.length_m > 0.0 {
2851 component.length_m / (2.0 * max_radius)
2852 } else {
2853 0.0
2854 };
2855 let form_factor = if fineness > 0.0 {
2856 Some(body_friction_form_factor(fineness)?)
2857 } else {
2858 None
2859 };
2860 Ok(Self {
2861 aero: PodSetAero {
2862 id: component.id.clone(),
2863 copies: u32::try_from(copies.len()).map_err(|_| AeroError::Domain {
2864 what: "pods in a pod set",
2865 value: copies.len() as f64,
2866 })?,
2867 offset_squares_m2,
2868 fineness,
2869 crossflow_eta_low: if fineness > 0.0 {
2870 crate::crossflow::crossflow_eta_low(fineness)
2871 } else {
2872 0.0
2873 },
2874 bodies: Vec::new(),
2875 },
2876 form_factor,
2877 motor_pod_set: None,
2878 previous_aft_area: None,
2879 terms_at: Vec::new(),
2880 })
2881 }
2882
2883 fn add_body(
2887 &mut self,
2888 component: &PlacedComponent,
2889 drag_terms: &mut Vec<ComponentDragTerms>,
2890 length_m: f64,
2891 reference_area_m2: f64,
2892 ) -> Result<(), AeroError> {
2893 let (geometry, shape) = match &component.part {
2894 Part::NoseCone(nose) => (
2895 BodyGeometry::from_profile(&nose.profile()?)?,
2896 Some(nose.shape),
2897 ),
2898 Part::Transition(transition) => (
2899 BodyGeometry::from_profile(&transition.profile()?)?,
2900 Some(transition.shape),
2901 ),
2902 Part::BodyTube(tube) if tube.length_m == 0.0 => {
2903 if tube.outer_radius_m == 0.0 {
2904 return Ok(());
2905 }
2906 return Err(AeroError::Unsupported(
2907 "a pod's tube of no length with a radius: a flat disc, which the drag buildup \
2908 has no term for"
2909 .to_owned(),
2910 ));
2911 }
2912 Part::BodyTube(tube) => (
2913 BodyGeometry::cylinder(tube.length_m, tube.outer_radius_m)?,
2914 None,
2915 ),
2916 _ => return Ok(()),
2917 };
2918 let form_factor = self.form_factor.ok_or(AeroError::Domain {
2920 what: "pod fineness",
2921 value: self.aero.fineness,
2922 })?;
2923 let step = self
2924 .previous_aft_area
2925 .map_or(0.0, |aft| geometry.fore_area_m2 - aft);
2926 let mut terms = ComponentDragTerms::body(
2927 component,
2928 &geometry,
2929 shape,
2930 self.previous_aft_area,
2931 form_factor,
2932 length_m,
2933 reference_area_m2,
2934 )?;
2935 terms.copies = self.aero.copies;
2936 terms.in_pod = true;
2937 terms.motor_pod_set = self.motor_pod_set;
2938 drag_terms.push(terms);
2939 self.terms_at.push((drag_terms.len() - 1, geometry));
2940 self.previous_aft_area = Some(geometry.aft_area_m2);
2941 self.aero
2942 .bodies
2943 .push(body_terms(component, geometry, step, reference_area_m2));
2944 Ok(())
2945 }
2946}
2947
2948fn pod_fins(
2956 set: &hpr_design::FinSet,
2957 component: &PlacedComponent,
2958 terms: &FinSetAero,
2959 reference_diameter_m: f64,
2960) -> Result<PodFins, AeroError> {
2961 use std::f64::consts::TAU;
2962 if set.cant_rad != 0.0 {
2963 return Err(AeroError::Unsupported(
2964 "cant on a pod's fins, whose roll forcing about the rocket's axis isn't modeled"
2965 .to_owned(),
2966 ));
2967 }
2968 let mut offsets = Vec::new();
2969 for copy in &component.copies {
2970 for j in 0..set.count {
2971 let angle =
2972 set.base_angle_rad + TAU * f64::from(j) / f64::from(set.count) + copy.roll_rad;
2973 let (sin, cos) = angle.sin_cos();
2974 offsets.push(copy.offset_m[0] * cos + copy.offset_m[1] * sin + terms.body_radius_m);
2975 }
2976 }
2977 let fins = u32::try_from(offsets.len()).map_err(|_| AeroError::Domain {
2978 what: "fins over a pod set's pods",
2979 value: offsets.len() as f64,
2980 })?;
2981 let (mean, deviation) = if offsets.is_empty() {
2982 (0.0, 0.0)
2983 } else {
2984 let n = f64::from(fins);
2985 let mean = offsets.iter().sum::<f64>() / n;
2986 let variance = offsets.iter().map(|o| (o - mean) * (o - mean)).sum::<f64>() / n;
2987 (mean, variance.sqrt())
2988 };
2989 Ok(PodFins {
2990 roll_rad: component.copies.iter().map(|c| c.roll_rad).collect(),
2991 axis_roll: [
2992 terms
2993 .fin
2994 .roll_terms_about(mean + deviation, reference_diameter_m)?,
2995 terms
2996 .fin
2997 .roll_terms_about(mean - deviation, reference_diameter_m)?,
2998 ],
2999 fins,
3000 })
3001}
3002
3003fn body_terms(
3004 component: &PlacedComponent,
3005 geometry: BodyGeometry,
3006 step_area_m2: f64,
3007 a_ref: f64,
3008) -> BodyAero {
3009 let station = component.fore_station_m;
3010 let step_slope = 2.0 * step_area_m2 / a_ref;
3011 let slope = geometry.normal_force_slope(a_ref);
3012 BodyAero {
3013 id: component.id.clone(),
3014 fore_station_m: station,
3015 geometry,
3016 step_area_m2,
3017 slope_per_rad: slope + step_slope,
3018 moment_slope_m: (slope + step_slope) * station + geometry.moment_slope_m(a_ref),
3019 planform_ratio: geometry.planform_area_m2 / a_ref,
3020 lift_station_m: station + geometry.planform_centroid_m,
3021 }
3022}
3023
3024#[cfg(test)]
3025mod tests {
3026 use std::f64::consts::{FRAC_PI_2, FRAC_PI_4};
3027
3028 use hpr_design::{
3029 FinPlanform, LaunchLug, NoseShape, Part, PodSet, Position, RailButton, ReferenceDiameter,
3030 TubeFinSet,
3031 };
3032 use proptest::prelude::*;
3033
3034 use super::*;
3035 use crate::BODY_LIFT_K;
3036 use crate::drag::base_drag_coefficient;
3037 use crate::testing::{body_part, component, fin_set, finned_rocket, material, nose, one_stage};
3038
3039 fn close(got: f64, want: f64, rel: f64, what: &str) {
3040 let err = if want == 0.0 {
3041 got.abs()
3042 } else {
3043 ((got - want) / want).abs()
3044 };
3045 assert!(
3046 err <= rel,
3047 "{what}: got {got}, want {want}, rel err {err:e}"
3048 );
3049 }
3050
3051 fn model(rocket: &hpr_design::Rocket) -> AeroModel {
3052 AeroModel::new(&rocket.layout().unwrap()).unwrap()
3053 }
3054
3055 fn podded_rocket(count: u32) -> hpr_design::Rocket {
3058 let mut rocket = finned_rocket(4);
3059 let mut pods = component(
3060 "pods",
3061 Part::PodSet(PodSet {
3062 count,
3063 radial_offset_m: 0.04,
3064 angle_rad: 0.3,
3065 }),
3066 Some(Position::Top { aft_offset_m: 0.1 }),
3067 );
3068 pods.children = vec![
3069 component("pod-nose", nose(NoseShape::Conical {}, 0.05, 0.01), None),
3070 component("pod-tube", body_part(0.2, 0.01, 0.01), None),
3071 ];
3072 rocket.stages[0].components[1].children.push(pods);
3073 rocket
3074 }
3075
3076 fn pod_fin_planform() -> FinPlanform {
3078 FinPlanform::Trapezoidal {
3079 root_chord_m: 0.06,
3080 tip_chord_m: 0.03,
3081 span_m: 0.04,
3082 sweep_m: 0.02,
3083 }
3084 }
3085
3086 fn winglet_rocket(fins: u32, base_angle_rad: f64) -> hpr_design::Rocket {
3090 let mut rocket = finned_rocket(4);
3091 let mut pods = component(
3092 "pods",
3093 Part::PodSet(PodSet {
3094 count: 2,
3095 radial_offset_m: 0.05,
3096 angle_rad: 0.0,
3097 }),
3098 Some(Position::Top { aft_offset_m: 0.3 }),
3099 );
3100 let mut phantom = component("phantom", body_part(0.0, 0.0, 0.0), None);
3101 let mut set = component(
3102 "winglets",
3103 fin_set(fins, pod_fin_planform()),
3104 Some(Position::Top { aft_offset_m: 0.0 }),
3105 );
3106 if let Part::FinSet(fin_set) = &mut set.part {
3107 fin_set.base_angle_rad = base_angle_rad;
3108 }
3109 phantom.children = vec![set];
3110 pods.children = vec![phantom];
3111 rocket.stages[0].components[1].children.push(pods);
3112 rocket
3113 }
3114
3115 #[test]
3120 fn a_pod_adds_its_bodies_slopes_once_per_pod() {
3121 let bare = model(&finned_rocket(4));
3122 let area_ratio = (0.01_f64 / 0.027).powi(2);
3123 for count in [1, 2, 3] {
3124 let m = model(&podded_rocket(count));
3125 assert_eq!(m.pod_sets().len(), 1);
3126 let pod = &m.pod_sets()[0];
3127 assert_eq!(pod.copies, count);
3128 close(pod.fineness, 0.25 / 0.02, 1e-15, "pod fineness");
3129 close(
3130 pod.offset_squares_m2,
3131 f64::from(count) * 0.04 * 0.04,
3132 1e-14,
3133 "offsets",
3134 );
3135 let n = f64::from(count);
3136 for mach in [0.3, 0.95, 2.0, 3.5] {
3137 let what = format!("{count} pods, Mach {mach}");
3138 let parts = m.components(&Flow::axial(mach)).unwrap();
3139 let find = |id: &str| {
3140 parts
3141 .iter()
3142 .find(|c| c.id == id)
3143 .map(|c| c.normal_force)
3144 .unwrap()
3145 };
3146 let cone = find("pod-nose");
3147 close(cone.slope_per_rad, n * 2.0 * area_ratio, 1e-12, &what);
3148 close(
3150 cone.cp_station_m.unwrap(),
3151 0.35 + 2.0 / 3.0 * 0.05,
3152 1e-12,
3153 &what,
3154 );
3155 close(find("pod-tube").slope_per_rad, 0.0, 1e-15, &what);
3156 let with = m.normal_force(&Flow::axial(mach)).unwrap();
3157 let without = bare.normal_force(&Flow::axial(mach)).unwrap();
3158 close(
3159 with.slope_per_rad - without.slope_per_rad,
3160 n * 2.0 * area_ratio,
3161 1e-11,
3162 &what,
3163 );
3164 close(
3165 with.moment_slope_m - without.moment_slope_m,
3166 n * 2.0 * area_ratio * (0.35 + 2.0 / 3.0 * 0.05),
3167 1e-11,
3168 &what,
3169 );
3170 let index = parts.iter().position(|c| c.id == "pod-nose").unwrap();
3172 assert_eq!(index, bare.bodies().len());
3173 assert_eq!(m.fin_set_start(), bare.bodies().len() + 2);
3174 close(
3175 m.component_station_m(index, mach).unwrap(),
3176 0.35 + 2.0 / 3.0 * 0.05,
3177 1e-12,
3178 &what,
3179 );
3180 let one = m.component_normal_force(index, &Flow::axial(mach)).unwrap();
3181 assert_eq!(one, cone);
3182 }
3183 }
3184 }
3185
3186 #[test]
3189 fn a_pod_s_body_lift_takes_its_own_fineness() {
3190 let m = model(&podded_rocket(3));
3191 let pod = &m.pod_sets()[0];
3192 let (mach, alpha) = (0.5, 0.2_f64);
3193 let parts = m.components(&flow(mach, alpha, 0.0)).unwrap();
3194 let tube = parts.iter().find(|c| c.id == "pod-tube").unwrap();
3195 let factor = m.lift_factor_of(
3196 12.5,
3197 crate::crossflow::crossflow_eta_low(12.5),
3198 mach,
3199 alpha.sin(),
3200 );
3201 assert!(
3202 (factor - m.lift_factor_of(m.fineness(), m.crossflow_eta_low, mach, alpha.sin())).abs()
3203 > 1e-3,
3204 "the pod's fineness must matter"
3205 );
3206 let planform = 2.0 * 0.01 * 0.2 / m.reference_area_m2();
3207 close(
3208 tube.normal_force.coefficient,
3209 3.0 * factor * planform * alpha.sin().powi(2),
3210 1e-12,
3211 "pod tube's body lift",
3212 );
3213 close(pod.fineness, 12.5, 1e-15, "fineness");
3214 }
3215
3216 #[test]
3220 fn a_pod_drags_once_per_pod() {
3221 let (mach, reynolds_per_m) = (0.4, 5e6);
3222 for count in [1_u32, 2, 3] {
3223 let m = model(&podded_rocket(count));
3224 let n = f64::from(count);
3225 let a_ref = m.reference_area_m2();
3226 for conditions in [
3227 DragConditions::coasting(reynolds_per_m),
3228 DragConditions::thrusting(reynolds_per_m, 2e-4),
3229 ] {
3230 let parts = m
3231 .buildup_components(&Flow::axial(mach), &conditions)
3232 .unwrap();
3233 let find = |id: &str| parts.iter().find(|c| c.id == id).unwrap().drag;
3234 let (body, tube) = (find("body"), find("pod-tube"));
3235 let ratio = n * body_friction_form_factor(12.5).unwrap()
3237 / body_friction_form_factor(m.fineness()).unwrap()
3238 * (0.01 * 0.2)
3239 / (0.027 * 0.7);
3240 close(tube.friction, ratio * body.friction, 1e-12, "pod friction");
3241 close(
3242 tube.base,
3243 n * base_drag_coefficient(mach).unwrap() * PI * 0.01 * 0.01 / a_ref,
3244 1e-12,
3245 "pod base",
3246 );
3247 let cone = find("pod-nose");
3249 assert_eq!(cone.base, 0.0);
3250 assert!(cone.pressure > 0.0);
3251 let one = model(&podded_rocket(1));
3252 let single = one
3253 .buildup_components(&Flow::axial(mach), &conditions)
3254 .unwrap();
3255 let single_cone = single.iter().find(|c| c.id == "pod-nose").unwrap().drag;
3256 close(cone.pressure, n * single_cone.pressure, 1e-14, "pod nose");
3257 let total = m.drag(&Flow::axial(mach), &conditions).unwrap();
3258 let sum: f64 = parts.iter().map(|c| c.drag.zero_lift_coefficient).sum();
3259 close(total.zero_lift_coefficient, sum, 1e-14, "total");
3260 }
3261 }
3262 }
3263
3264 #[test]
3269 fn a_pod_s_base_takes_its_own_motors_area() {
3270 let (mach, reynolds_per_m) = (0.4, 5e6);
3271 let mut rocket = podded_rocket(2);
3272 let pods = rocket.stages[0].components[1].children.last_mut().unwrap();
3273 pods.children[1].motor_mount = Some(hpr_design::MotorMount::default());
3274 let m = model(&rocket);
3275 let a_ref = m.reference_area_m2();
3276 let base = |conditions: &DragConditions, id: &str| {
3277 m.buildup_components(&Flow::axial(mach), conditions)
3278 .unwrap()
3279 .into_iter()
3280 .find(|c| c.id == id)
3281 .unwrap()
3282 .drag
3283 .base
3284 };
3285 let pod_area = PI * 0.01 * 0.01;
3286 let c_b = base_drag_coefficient(mach).unwrap();
3287 let coasting = DragConditions::coasting(reynolds_per_m);
3288 close(
3289 base(&coasting, "pod-tube"),
3290 2.0 * c_b * pod_area / a_ref,
3291 1e-14,
3292 "coasting",
3293 );
3294 let motor = PI * 0.008 * 0.008;
3296 let thrusting = DragConditions::thrusting(reynolds_per_m, 0.0).with_pod_motors([
3297 2.0 * motor,
3298 0.0,
3299 0.0,
3300 0.0,
3301 ]);
3302 close(
3303 base(&thrusting, "pod-tube"),
3304 2.0 * c_b * (pod_area - motor) / a_ref,
3305 1e-14,
3306 "pod motors",
3307 );
3308 assert_eq!(base(&thrusting, "tail"), base(&coasting, "tail"));
3309 let core = DragConditions::thrusting(reynolds_per_m, 1e-4);
3311 assert_eq!(base(&core, "pod-tube"), base(&coasting, "pod-tube"));
3312 assert!(base(&core, "tail") < base(&coasting, "tail"));
3313 let mut second = component(
3315 "more-pods",
3316 Part::PodSet(PodSet {
3317 count: 2,
3318 radial_offset_m: 0.04,
3319 angle_rad: 1.8,
3320 }),
3321 Some(Position::Top { aft_offset_m: 0.4 }),
3322 );
3323 let mut tube = component("more-pod-tube", body_part(0.1, 0.01, 0.01), None);
3324 tube.motor_mount = Some(hpr_design::MotorMount::default());
3325 second.children = vec![tube];
3326 rocket.stages[0].components[1].children.push(second);
3327 let two = model(&rocket);
3328 let base = |conditions: &DragConditions, id: &str| {
3329 two.buildup_components(&Flow::axial(mach), conditions)
3330 .unwrap()
3331 .into_iter()
3332 .find(|c| c.id == id)
3333 .unwrap()
3334 .drag
3335 .base
3336 };
3337 let motor = PI * 0.004 * 0.004;
3338 let first = DragConditions::thrusting(reynolds_per_m, 0.0).with_pod_motors([
3339 2.0 * motor,
3340 0.0,
3341 0.0,
3342 0.0,
3343 ]);
3344 let second = DragConditions::thrusting(reynolds_per_m, 0.0).with_pod_motors([
3345 0.0,
3346 2.0 * motor,
3347 0.0,
3348 0.0,
3349 ]);
3350 for (conditions, relieved, whole) in [
3351 (&first, "pod-tube", "more-pod-tube"),
3352 (&second, "more-pod-tube", "pod-tube"),
3353 ] {
3354 close(
3355 base(conditions, relieved),
3356 2.0 * c_b * (pod_area - motor) / a_ref,
3357 1e-14,
3358 relieved,
3359 );
3360 assert_eq!(base(conditions, whole), base(&coasting, whole), "{whole}");
3361 }
3362 }
3363
3364 #[test]
3368 fn a_whole_base_under_power_keeps_the_motors_area() {
3369 let mach = 0.4;
3370 let mut rocket = podded_rocket(2);
3371 let pods = rocket.stages[0].components[1].children.last_mut().unwrap();
3372 pods.children[1].motor_mount = Some(hpr_design::MotorMount::default());
3373 let relieved = model(&rocket);
3374 assert!(!relieved.full_base_drag_under_power());
3375 let whole = relieved.clone().with_full_base_drag_under_power();
3376 assert!(whole.full_base_drag_under_power());
3377 let flow = Flow::axial(mach);
3378 let coasting = DragConditions::coasting(5e6);
3379 let thrusting = DragConditions::thrusting(5e6, 1e-4).with_pod_motors([2e-4, 0.0, 0.0, 0.0]);
3380 let base =
3381 |m: &AeroModel, conditions: &DragConditions| m.drag(&flow, conditions).unwrap().base;
3382 assert_eq!(base(&whole, &thrusting), base(&whole, &coasting));
3383 assert_eq!(base(&whole, &coasting), base(&relieved, &coasting));
3384 assert!(base(&relieved, &thrusting) < base(&relieved, &coasting));
3385 for id in ["tail", "pod-tube"] {
3386 let part = |m: &AeroModel, conditions: &DragConditions| {
3387 m.buildup_components(&flow, conditions)
3388 .unwrap()
3389 .into_iter()
3390 .find(|c| c.id == id)
3391 .unwrap()
3392 .drag
3393 .base
3394 };
3395 assert_eq!(part(&whole, &thrusting), part(&whole, &coasting), "{id}");
3396 assert!(
3397 part(&relieved, &thrusting) < part(&relieved, &coasting),
3398 "{id}"
3399 );
3400 }
3401 let bad = DragConditions::thrusting(5e6, -1e-4);
3403 assert!(whole.drag(&flow, &bad).is_err());
3404 assert!(whole.buildup_components(&flow, &bad).is_err());
3405 }
3406
3407 #[test]
3411 fn a_pod_s_fins_turn_with_their_pod() {
3412 let bare = model(&finned_rocket(4));
3413 let mut rocket = winglet_rocket(1, 0.0);
3414 if let Part::PodSet(pods) = &mut rocket.stages[0].components[1]
3415 .children
3416 .last_mut()
3417 .unwrap()
3418 .part
3419 {
3420 pods.angle_rad = FRAC_PI_4;
3421 }
3422 let m = model(&rocket);
3423 let mach = 0.3;
3424 let slope = FinAero::new(&pod_fin_planform(), m.reference_area_m2())
3425 .unwrap()
3426 .loading(mach)
3427 .unwrap()
3428 .slope_per_rad;
3429 for (roll, share) in [(FRAC_PI_4, 0.0), (-FRAC_PI_4, 2.0)] {
3430 let with = m.normal_force(&flow(mach, 0.0, roll)).unwrap();
3431 let without = bare.normal_force(&flow(mach, 0.0, roll)).unwrap();
3432 close(
3433 with.slope_per_rad - without.slope_per_rad,
3434 share * slope,
3435 1e-12,
3436 &format!("roll {roll}"),
3437 );
3438 }
3439 }
3440
3441 #[test]
3445 fn every_component_index_maps_to_its_own_terms_with_pods() {
3446 let mut rocket = podded_rocket(3);
3447 let winglets = winglet_rocket(2, 0.3);
3448 let mut pods = winglets.stages[0].components[1]
3449 .children
3450 .last()
3451 .unwrap()
3452 .clone();
3453 pods.id = "winglet-pods".to_owned();
3454 rocket.stages[0].components[1].children.push(pods);
3455 let mut second = component(
3456 "aft-pods",
3457 Part::PodSet(PodSet {
3458 count: 2,
3459 radial_offset_m: 0.05,
3460 angle_rad: 1.0,
3461 }),
3462 Some(Position::Top { aft_offset_m: 0.45 }),
3463 );
3464 second.children = vec![
3465 component(
3466 "aft-pod-nose",
3467 nose(NoseShape::Conical {}, 0.04, 0.012),
3468 None,
3469 ),
3470 component("aft-pod-tube", body_part(0.1, 0.012, 0.012), None),
3471 component("aft-pod-tail", body_part(0.03, 0.012, 0.008), None),
3472 ];
3473 rocket.stages[0].components[1].children.push(second);
3474 let m = model(&rocket);
3475 assert_eq!(m.pod_sets().len(), 2);
3476 assert_eq!(m.fin_set_start(), m.bodies().len() + 5);
3477 assert_eq!(m.component_count(), m.fin_set_start() + 2);
3478 for mach in [0.3, 2.0] {
3479 let f = flow(mach, 0.1, 0.4);
3480 let parts = m.components(&f).unwrap();
3481 assert_eq!(parts.len(), m.component_count());
3482 for (index, part) in parts.iter().enumerate() {
3483 let one = m.component_normal_force(index, &f).unwrap();
3484 assert_eq!(one, part.normal_force, "{} at {index}", part.id);
3485 let station = m.component_station_m(index, mach).unwrap();
3486 if let Some(cp) = m.components(&flow(mach, 0.0, 0.4)).unwrap()[index]
3487 .normal_force
3488 .cp_station_m
3489 && index >= m.bodies().len()
3490 {
3491 close(station, cp, 1e-12, &part.id);
3492 }
3493 }
3494 let ids: Vec<&str> = parts.iter().map(|p| p.id.as_str()).collect();
3495 let at = |id: &str| ids.iter().position(|i| *i == id).unwrap();
3496 assert!(at("pod-tube") < at("aft-pod-nose") && at("aft-pod-tail") < at("winglets"));
3497 assert!(m.component_normal_force(m.component_count(), &f).is_err());
3498 }
3499 }
3500
3501 #[test]
3504 fn the_aero_page_s_pod_example() {
3505 let (bare, pods) = (model(&finned_rocket(4)), model(&podded_rocket(3)));
3506 let at = |m: &AeroModel| {
3507 let n = m.normal_force(&Flow::axial(0.3)).unwrap();
3508 let c = DragConditions::coasting(5e6);
3509 let d = m.drag(&Flow::axial(0.3), &c).unwrap();
3510 (
3511 n.slope_per_rad,
3512 n.cp_station_m.unwrap(),
3513 d.zero_lift_coefficient,
3514 m.roll(0.3).unwrap().damping,
3515 )
3516 };
3517 let round = |x: f64, digits: i32| (x * 10_f64.powi(digits)).round() / 10_f64.powi(digits);
3518 let (slope, cp, drag, damping) = at(&bare);
3519 assert_eq!(
3520 [
3521 round(slope, 3),
3522 round(cp, 4),
3523 round(drag, 4),
3524 round(damping, 3)
3525 ],
3526 [12.374, 1.0662, 0.5051, -35.215]
3527 );
3528 let (slope, cp, drag, damping) = at(&pods);
3529 assert_eq!(
3530 [
3531 round(slope, 3),
3532 round(cp, 4),
3533 round(drag, 4),
3534 round(damping, 3)
3535 ],
3536 [13.197, 1.0237, 0.6386, -36.118]
3537 );
3538 let parts = pods
3539 .buildup_components(&Flow::axial(0.3), &DragConditions::coasting(5e6))
3540 .unwrap();
3541 let find = |id: &str| parts.iter().find(|c| c.id == id).unwrap().drag;
3542 let (cone, tube) = (find("pod-nose"), find("pod-tube"));
3543 assert_eq!(
3544 [
3545 round(cone.friction, 4),
3546 round(cone.pressure, 4),
3547 round(tube.friction, 4),
3548 round(tube.base, 4)
3549 ],
3550 [0.0074, 0.0127, 0.0592, 0.0542]
3551 );
3552 let single = model(&podded_rocket(1))
3553 .buildup_components(&Flow::axial(0.3), &DragConditions::coasting(5e6))
3554 .unwrap();
3555 let one_pod: f64 = single
3556 .iter()
3557 .filter(|c| c.id.starts_with("pod"))
3558 .map(|c| c.drag.zero_lift_coefficient)
3559 .sum();
3560 assert_eq!(round(one_pod, 4), 0.0445);
3561 let one_slope = model(&podded_rocket(1))
3562 .normal_force(&Flow::axial(0.3))
3563 .unwrap()
3564 .slope_per_rad;
3565 assert_eq!(round(one_slope, 2), 12.65);
3566 }
3567
3568 #[test]
3573 fn a_pod_s_bodies_damp_the_roll() {
3574 let bare = model(&finned_rocket(4));
3575 let m = model(&podded_rocket(3));
3576 let slope = 2.0 * (0.01_f64 / 0.027).powi(2);
3577 let want = -2.0 * slope * 3.0 * 0.04 * 0.04 / (0.054 * 0.054);
3578 close(want, -0.9032_f64, 1e-4, "worked number");
3579 for mach in [0.3, 1.5] {
3580 let got = m.roll(mach).unwrap().damping - bare.roll(mach).unwrap().damping;
3581 close(got, want, 1e-12, "pod roll damping");
3582 assert_eq!(
3583 m.roll(mach).unwrap().forcing,
3584 bare.roll(mach).unwrap().forcing
3585 );
3586 }
3587 }
3588
3589 #[test]
3593 fn a_pod_s_fins_are_the_pod_s_turned_with_it() {
3594 let bare = model(&finned_rocket(4));
3595 let a_ref = bare.reference_area_m2();
3596 let d = 0.054;
3597 let fin = FinAero::new(&pod_fin_planform(), a_ref).unwrap();
3598 let m = model(&winglet_rocket(1, 0.0));
3601 assert!(m.pod_sets().is_empty(), "a phantom body has no body terms");
3602 for mach in [0.3, 1.8] {
3603 let slope = fin.loading(mach).unwrap().slope_per_rad;
3604 let across = m.normal_force(&flow(mach, 0.0, FRAC_PI_2)).unwrap();
3605 let bare_across = bare.normal_force(&flow(mach, 0.0, FRAC_PI_2)).unwrap();
3606 close(
3607 across.slope_per_rad - bare_across.slope_per_rad,
3608 2.0 * slope,
3609 1e-12,
3610 "across",
3611 );
3612 let along = m.normal_force(&flow(mach, 0.0, 0.0)).unwrap();
3613 let bare_along = bare.normal_force(&flow(mach, 0.0, 0.0)).unwrap();
3614 close(
3615 along.slope_per_rad - bare_along.slope_per_rad,
3616 0.0,
3617 1e-12,
3618 "along",
3619 );
3620 let damping = m.roll(mach).unwrap().damping - bare.roll(mach).unwrap().damping;
3623 close(
3624 damping,
3625 2.0 * fin.roll(mach, 0.05, d).unwrap().damping,
3626 1e-12,
3627 "damping",
3628 );
3629 }
3630 let m = model(&winglet_rocket(2, 0.0));
3633 let mach = 0.5;
3634 let (c_r, c_t, s) = (0.06, 0.03, 0.04);
3635 let area = 0.5 * s * (c_r + c_t);
3636 let per_area = fin.loading(mach).unwrap().slope_per_rad * a_ref / area;
3637 let strips = 20_000;
3638 let mut second = 0.0;
3639 for i in 0..strips {
3640 let y = s * (f64::from(i) + 0.5) / f64::from(strips);
3641 let chord = c_r + (c_t - c_r) * y / s;
3642 for root in [0.05, -0.05] {
3643 second += 2.0 * (root + y) * (root + y) * chord * s / f64::from(strips);
3644 }
3645 }
3646 let want = -2.0 * per_area * second / (a_ref * d * d);
3647 let got = m.roll(mach).unwrap().damping - bare.roll(mach).unwrap().damping;
3648 close(got, want, 1e-7, "strips");
3649 let set = m.fin_sets().iter().find(|s| s.id == "winglets").unwrap();
3650 let pods = set.pods.as_ref().unwrap();
3651 assert_eq!(pods.fins, 4);
3652 assert_eq!(pods.roll_rad.len(), 2);
3653 }
3654
3655 fn flow(mach: f64, alpha_rad: f64, roll_rad: f64) -> Flow {
3656 Flow::new(mach, alpha_rad, roll_rad)
3657 }
3658
3659 #[test]
3664 fn angle_of_attack_terms() {
3665 let (l_n, l_t, r) = (0.2, 0.8, 0.03);
3666 let rocket = one_stage(
3667 vec![
3668 component("nose", nose(NoseShape::Conical {}, l_n, r), None),
3669 component("tube", body_part(l_t, r, r), None),
3670 ],
3671 ReferenceDiameter::Maximum {},
3672 );
3673 let m = model(&rocket);
3674 let a_ref = PI * r * r;
3675 let k = |alpha: f64| crate::crossflow::crossflow_factor(1.0 / 0.06, 0.3 * alpha.sin());
3677 close(m.fineness(), 1.0 / 0.06, 1e-15, "fineness");
3678 let lift_nose = k(FRAC_PI_2) * r * l_n / a_ref;
3679 let lift_tube = k(FRAC_PI_2) * 2.0 * r * l_t / a_ref;
3680
3681 let broadside = m.normal_force(&flow(0.3, FRAC_PI_2, 0.0)).unwrap();
3682 let want = 2.0 + lift_nose + lift_tube;
3683 close(broadside.coefficient, want, 1e-10, "C_N at 90°");
3684 let moment =
3685 2.0 * (2.0 * l_n / 3.0) + lift_nose * (2.0 * l_n / 3.0) + lift_tube * (l_n + 0.5 * l_t);
3686 close(
3687 broadside.cp_station_m.unwrap(),
3688 moment / want,
3689 1e-10,
3690 "CP at 90°",
3691 );
3692
3693 let zero = m.normal_force(&Flow::axial(0.3)).unwrap();
3694 assert_eq!(zero.coefficient, 0.0);
3695 close(zero.slope_per_rad, 2.0, 1e-15, "slope at 0");
3696 for alpha in [1e-6, 1e-3, 0.05] {
3698 let f = m.normal_force(&flow(0.3, alpha, 0.0)).unwrap();
3699 let lift = (lift_nose + lift_tube) * k(alpha) / k(FRAC_PI_2);
3700 let want = 2.0 * alpha.sin() + lift * alpha.sin().powi(2);
3701 close(f.coefficient, want, 1e-12, "C_N");
3702 close(f.slope_per_rad, want / alpha, 1e-12, "C_N/α");
3703 }
3704 let cp = |alpha| {
3706 m.normal_force(&flow(0.3, alpha, 0.0))
3707 .unwrap()
3708 .cp_station_m
3709 .unwrap()
3710 };
3711 assert!(cp(0.02) > cp(0.0) && cp(0.2) > cp(0.02));
3712 let parts = m.components(&flow(0.3, 0.2, 0.0)).unwrap();
3714 let total = m.normal_force(&flow(0.3, 0.2, 0.0)).unwrap();
3715 let sum: f64 = parts.iter().map(|c| c.normal_force.coefficient).sum();
3716 close(sum, total.coefficient, 1e-14, "component sum");
3717 }
3718
3719 #[test]
3722 fn body_lift_models() {
3723 let rocket = one_stage(
3724 vec![
3725 component("nose", nose(NoseShape::Conical {}, 0.2, 0.03), None),
3726 component("tube", body_part(0.8, 0.03, 0.03), None),
3727 ],
3728 ReferenceDiameter::Maximum {},
3729 );
3730 let layout = rocket.layout().unwrap();
3731 let old = AeroModel::with_body_model(&layout, BodyModel::BEFORE_M1_8E6).unwrap();
3732 let new = AeroModel::new(&layout).unwrap();
3733 assert_eq!(new.body_model(), BodyModel::default());
3734 for (mach, alpha) in [(0.3, 0.1), (2.0, 0.5), (4.0, 1.2)] {
3735 assert_eq!(old.body_lift_factor(&flow(mach, alpha, 0.0)), BODY_LIFT_K);
3736 }
3737 let slow = new.body_lift_factor(&flow(0.3, 0.1, 0.0));
3738 assert!(slow > 0.85 && slow < 0.9, "{slow}");
3739 let near_one = new.body_lift_factor(&flow(2.0, 0.5, 0.0));
3740 assert!(near_one > 1.4, "{near_one}");
3741 let k = BodyModel::BEFORE_M1_8E6.with_body_lift(BodyLift::Galejs { k: -0.5 });
3742 assert!(AeroModel::with_body_model(&layout, k).is_err());
3743 for (mach, alpha) in [(0.3, 0.1), (2.0, 0.5), (4.0, 1.2)] {
3745 let f = flow(mach, alpha, 0.0);
3746 assert_eq!(
3747 new.body_lift_factor(&f),
3748 crate::crossflow::crossflow_factor(new.fineness(), mach * alpha.sin())
3749 );
3750 }
3751 }
3752
3753 #[test]
3756 fn body_model_in_json() {
3757 assert_eq!(BodyModel::default(), BodyModel::CURRENT);
3758 let old = serde_json::to_string(&BodyModel::BEFORE_M1_8E6).unwrap();
3759 assert_eq!(
3760 old,
3761 r#"{"body_lift":{"kind":"galejs","k":1.1},"supersonic_boattail":"footnote8","supersonic_flare":"slender_body"}"#
3762 );
3763 let before_m1_8e17 =
3767 r#"{"body_lift":{"kind":"galejs","k":1.1},"supersonic_boattail":"footnote8"}"#;
3768 assert_eq!(
3769 serde_json::from_str::<BodyModel>(before_m1_8e17)
3770 .unwrap()
3771 .supersonic_flare,
3772 SupersonicFlare::Marched
3773 );
3774 assert_eq!(
3775 serde_json::from_str::<BodyModel>(&old).unwrap(),
3776 BodyModel::BEFORE_M1_8E6
3777 );
3778 assert_eq!(
3779 serde_json::from_str::<BodyModel>(r#"{"supersonic_boattail":"washington_pettis"}"#)
3780 .unwrap(),
3781 BodyModel::CURRENT
3782 );
3783 assert_eq!(
3784 serde_json::from_str::<BodyModel>("{}").unwrap(),
3785 BodyModel::CURRENT
3786 );
3787 for bad in [
3788 r#"{"boattail":"footnote8"}"#,
3789 r#"{"supersonic_boattail":"slender_body"}"#,
3790 ] {
3791 assert!(serde_json::from_str::<BodyModel>(bad).is_err(), "{bad}");
3792 }
3793 }
3794
3795 #[test]
3798 fn mach_changes_only_the_fins() {
3799 let m = model(&finned_rocket(4));
3800 let at = |mach| m.components(&Flow::axial(mach)).unwrap();
3801 let (slow, fast) = (at(0.0), at(0.8));
3802 for (a, b) in slow.iter().zip(&fast) {
3803 assert_eq!(
3804 a.normal_force.cp_station_m, b.normal_force.cp_station_m,
3805 "{}",
3806 a.id
3807 );
3808 if a.id == "fins" {
3809 let set = &m.fin_sets()[0];
3810 let ratio = set
3811 .fin
3812 .geometry()
3813 .single_fin_slope(m.reference_area_m2(), 0.8)
3814 .unwrap()
3815 / set
3816 .fin
3817 .geometry()
3818 .single_fin_slope(m.reference_area_m2(), 0.0)
3819 .unwrap();
3820 assert!(ratio > 1.05, "{ratio}");
3821 close(
3822 b.normal_force.slope_per_rad / a.normal_force.slope_per_rad,
3823 ratio,
3824 1e-14,
3825 "fin ratio",
3826 );
3827 } else {
3828 assert_eq!(
3829 a.normal_force.slope_per_rad, b.normal_force.slope_per_rad,
3830 "{}",
3831 a.id
3832 );
3833 }
3834 }
3835 }
3836
3837 #[test]
3839 fn two_fin_sets_depend_on_roll() {
3840 let four = model(&finned_rocket(4));
3841 let slope =
3842 |m: &AeroModel, roll| m.normal_force(&flow(0.2, 0.0, roll)).unwrap().slope_per_rad;
3843 close(slope(&four, 0.0), slope(&four, 0.4), 1e-15, "four fins");
3844
3845 let two = model(&finned_rocket(2));
3846 let bodies: f64 = two.bodies().iter().map(|b| b.slope_per_rad).sum();
3847 let set = &two.fin_sets()[0];
3848 let one_fin = set
3849 .fin
3850 .geometry()
3851 .single_fin_slope(two.reference_area_m2(), 0.2)
3852 .unwrap()
3853 * set.interference;
3854 close(slope(&two, 0.0), bodies, 1e-13, "along the fins");
3856 close(
3857 slope(&two, FRAC_PI_2),
3858 bodies + 2.0 * one_fin,
3859 1e-13,
3860 "across the fins",
3861 );
3862 close(
3864 slope(&two, FRAC_PI_2),
3865 slope(&four, 0.0),
3866 1e-13,
3867 "two across = four",
3868 );
3869 }
3870
3871 fn tube_finned_rocket(
3874 count: u32,
3875 length_m: f64,
3876 outer_radius_m: f64,
3877 thickness_m: f64,
3878 ) -> hpr_design::Rocket {
3879 let mut rocket = crate::testing::finned_rocket(4);
3880 rocket.stages[0].components[3].children.push(component(
3881 "tube-fins",
3882 Part::TubeFinSet(TubeFinSet {
3883 count,
3884 length_m,
3885 outer_radius_m,
3886 thickness_m,
3887 base_angle_rad: 0.3,
3888 material: material(),
3889 }),
3890 Some(Position::Bottom { aft_offset_m: 0.0 }),
3891 ));
3892 rocket
3893 }
3894
3895 #[test]
3896 fn tube_fins_add_their_rings_slopes_at_fletcher_s_center() {
3897 let plain = model(&crate::testing::finned_rocket(4));
3898 let (count, length, outer, wall) = (6_u32, 0.1, 0.022, 0.0005);
3899 let m = model(&tube_finned_rocket(count, length, outer, wall));
3900 let a_ref = m.reference_area_m2();
3901 let d = 2.0 * outer - wall;
3902 let fore = 1.3 - length;
3904 assert_eq!(m.component_count(), plain.component_count() + 1);
3905 assert_eq!(m.tube_fin_set_start(), plain.component_count());
3906 for (mach, roll) in [(0.0_f64, 0.0), (0.3, 0.4), (0.7, 1.1)] {
3907 let beta = (1.0 - mach * mach).sqrt();
3908 let lambda = length / d;
3909 let slope = f64::from(count)
3911 * (PI * PI
3912 / (1.0
3913 + 0.5 * PI * lambda / beta
3914 + lambda / beta * (1.2 * lambda / beta).atan()))
3915 / beta
3916 * d
3917 * length
3918 / a_ref;
3919 let a = beta * d / length;
3921 assert!(a < 2.0 / 3.0);
3922 let center = 0.143 * a / (2.0 / 3.0);
3923 let station = fore + center * length;
3924 let flow = Flow::new(mach, 0.05, roll);
3925 let (with, without) = (
3926 m.normal_force(&flow).unwrap(),
3927 plain.normal_force(&flow).unwrap(),
3928 );
3929 close(
3930 with.slope_per_rad - without.slope_per_rad,
3931 slope,
3932 1e-12,
3933 "slope",
3934 );
3935 close(
3936 with.moment_slope_m - without.moment_slope_m,
3937 slope * station,
3938 1e-12,
3939 "moment",
3940 );
3941 close(
3943 with.side_coefficient,
3944 without.side_coefficient,
3945 1e-12,
3946 "side",
3947 );
3948 let index = m.tube_fin_set_start();
3949 let own = m.component_normal_force(index, &flow).unwrap();
3950 close(own.slope_per_rad, slope, 1e-12, "component slope");
3951 close(
3952 m.component_station_m(index, mach).unwrap(),
3953 station,
3954 1e-12,
3955 "station",
3956 );
3957 let listed = m.components(&flow).unwrap();
3958 assert_eq!(listed[index].id, "tube-fins");
3959 close(
3960 listed[index].normal_force.slope_per_rad,
3961 slope,
3962 1e-12,
3963 "listed",
3964 );
3965 let rho = 0.022 + outer;
3967 let damping = -2.0 * slope * rho * rho / (0.054 * 0.054);
3968 close(
3969 m.roll(mach).unwrap().damping - plain.roll(mach).unwrap().damping,
3970 damping,
3971 1e-12,
3972 "roll damping",
3973 );
3974 assert_eq!(m.roll(mach).unwrap().forcing, 0.0);
3975 }
3976 }
3977
3978 #[test]
3979 fn short_tube_fins_take_fletcher_s_measured_center() {
3980 let (length, outer, wall) = (0.02, 0.022, 0.0005);
3985 let m = model(&tube_finned_rocket(6, length, outer, wall));
3986 let d = 2.0 * outer - wall;
3987 let index = m.tube_fin_set_start();
3988 for (mach, a, by_hand) in [(0.0, d / length, 5.0510), (0.6, 0.8 * d / length, 5.4837)] {
3989 let fraction = 0.253 + (0.355 - 0.253) * (a - 1.5) / 1.5;
3990 let station = 1.3 - length + fraction * length;
3991 close(
3992 m.component_station_m(index, mach).unwrap(),
3993 station,
3994 1e-12,
3995 "station",
3996 );
3997 let slope = m
3998 .component_normal_force(index, &Flow::new(mach, 0.05, 0.0))
3999 .unwrap()
4000 .slope_per_rad;
4001 let per_ring = slope / 6.0 * m.reference_area_m2() / (d * length);
4002 close(per_ring, by_hand, 1e-4, "slope on d L");
4003 }
4004 }
4005
4006 #[test]
4010 fn the_guide_s_tube_fin_example() {
4011 let r = 0.012_395_2;
4012 let mut tail = component("tail", body_part(0.4572, r, r), None);
4013 tail.children = vec![component(
4014 "tube-fins",
4015 Part::TubeFinSet(TubeFinSet {
4016 count: 6,
4017 length_m: 0.0762,
4018 outer_radius_m: r,
4019 thickness_m: 0.000_330_2,
4020 base_angle_rad: 0.0,
4021 material: material(),
4022 }),
4023 Some(Position::Bottom { aft_offset_m: 0.0 }),
4024 )];
4025 let rocket = one_stage(
4026 vec![
4027 component(
4028 "nose",
4029 nose(NoseShape::Ogive { radius_ratio: 1.0 }, 0.119_888, r),
4030 None,
4031 ),
4032 tail,
4033 ],
4034 hpr_design::ReferenceDiameter::Maximum {},
4035 );
4036 let m = model(&rocket);
4037 close(m.reference_area_m2(), 4.827e-4, 1e-4, "reference area");
4038 let set = &m.tube_fin_sets()[0];
4039 close(set.mean_diameter_m, 0.024_460_2, 1e-12, "d");
4040 close(set.length_m / set.mean_diameter_m, 3.115, 1e-3, "λ");
4041 let (slope, station) = set.loading(0.0).unwrap();
4042 close(slope, 22.93, 1e-3, "slope at Mach 0");
4043 close(
4044 set.loading(0.35).unwrap().0,
4045 22.96,
4046 1e-3,
4047 "slope at Mach 0.35",
4048 );
4049 close(
4050 (station - set.fore_station_m) / set.length_m,
4051 0.0689,
4052 1e-3,
4053 "center",
4054 );
4055 let terms = m.drag_terms.iter().find(|t| t.id == "tube-fins").unwrap();
4056 close(terms.friction_area_ratio, 145.6, 1e-3, "friction area");
4057 close(
4058 terms.fins.as_ref().unwrap().frontal_area_ratio,
4059 0.3154,
4060 1e-3,
4061 "wall area",
4062 );
4063 }
4064
4065 #[test]
4066 fn tube_fins_drag_inside_and_out_and_on_their_walls() {
4067 let (count, length, outer, wall) = (6_u32, 0.1, 0.022, 0.0005);
4068 let m = model(&tube_finned_rocket(count, length, outer, wall));
4069 let a_ref = m.reference_area_m2();
4070 let n = f64::from(count);
4071 let inner = outer - wall;
4072 let (mach, reynolds_per_m) = (0.5, 4e6);
4073 let conditions = DragConditions::coasting(reynolds_per_m);
4074 let parts = m
4075 .buildup_components(&Flow::axial(mach), &conditions)
4076 .unwrap();
4077 let tubes = parts.iter().find(|c| c.id == "tube-fins").unwrap().drag;
4078 let terms = m.drag_terms.iter().find(|t| t.id == "tube-fins").unwrap();
4080 let cf = crate::drag::skin_friction_coefficient(
4081 reynolds_per_m * m.length_m,
4082 terms.relative_roughness,
4083 mach,
4084 )
4085 .unwrap();
4086 let wetted = n * 2.0 * PI * length * (outer + inner);
4087 close(tubes.friction, cf * wetted / a_ref, 1e-12, "friction");
4088 let annulus = n * PI * (outer * outer - inner * inner);
4090 let square = crate::drag::stagnation_drag_coefficient(mach).unwrap()
4091 + base_drag_coefficient(mach).unwrap();
4092 close(tubes.pressure, square * annulus / a_ref, 1e-12, "pressure");
4093 assert_eq!((tubes.base, tubes.parasitic), (0.0, 0.0));
4094 }
4095
4096 #[test]
4097 fn tube_fins_refuse_mach_0_8() {
4098 let m = model(&tube_finned_rocket(6, 0.1, 0.022, 0.0005));
4099 let refused = |e: AeroError| {
4102 matches!(e, AeroError::Mach { mach, limit, model }
4103 if mach == 0.8 && limit == 0.8 && model == "the tube-fin model")
4104 };
4105 let flow = Flow::new(0.8, 0.05, 0.0);
4106 let index = m.tube_fin_set_start();
4107 assert!(refused(m.normal_force(&flow).unwrap_err()));
4108 assert!(refused(m.components(&flow).unwrap_err()));
4109 assert!(refused(m.component_normal_force(index, &flow).unwrap_err()));
4110 assert!(refused(m.component_station_m(index, 0.8).unwrap_err()));
4111 assert!(refused(m.roll(0.8).unwrap_err()));
4112 let coasting = DragConditions::coasting(4e6);
4113 assert!(refused(m.drag(&Flow::axial(0.8), &coasting).unwrap_err()));
4114 assert!(refused(
4115 m.buildup_components(&Flow::axial(0.8), &coasting)
4116 .unwrap_err()
4117 ));
4118 let terms = m.drag_terms().iter().find(|t| t.id == "tube-fins").unwrap();
4120 let own = terms.evaluate(4e6, 0.8, &coasting, m.reference_area_m2());
4121 assert!(matches!(own, Err(AeroError::InComponent { id, source })
4122 if id == "tube-fins" && matches!(*source, AeroError::Mach { limit, .. } if limit == 0.8)));
4123 assert!(m.component_normal_force(0, &flow).is_ok());
4125 let below = Flow::new(0.8 - 1e-9, 0.05, 0.0);
4127 assert!(m.normal_force(&below).is_ok());
4128 assert!(m.drag(&below, &coasting).is_ok());
4129 }
4130
4131 #[test]
4134 fn unsupported_inputs_are_refused() {
4135 for (count, length_m, outer_radius_m, thickness_m, why) in [
4139 (2, 0.1, 0.01, 0.001, "2 tube fins"),
4140 (6, 0.1, 0.01, 0.01, "solid tube fins"),
4141 (6, 0.1, 0.023, 0.001, "tube fins that overlap"),
4142 (6, 0.005, 0.022, 0.001, "tube fins shorter than a third"),
4143 ] {
4144 let rocket = tube_finned_rocket(count, length_m, outer_radius_m, thickness_m);
4145 let err = AeroModel::new(&rocket.layout().unwrap()).unwrap_err();
4146 assert!(
4147 matches!(&err, AeroError::InComponent { id, source } if id == "tube-fins"
4148 && matches!(&**source, AeroError::Unsupported(what) if what.starts_with(why))),
4149 "{err}"
4150 );
4151 }
4152
4153 let mut rocket = podded_rocket(2);
4156 let pods = rocket.stages[0].components[1].children.last_mut().unwrap();
4157 pods.children[1].children.push(component(
4158 "pod-fins",
4159 fin_set(3, pod_fin_planform()),
4160 Some(Position::Bottom { aft_offset_m: 0.0 }),
4161 ));
4162 if let Part::FinSet(set) = &mut pods.children[1].children[0].part {
4163 set.cant_rad = 0.01;
4164 }
4165 let err = AeroModel::new(&rocket.layout().unwrap()).unwrap_err();
4166 assert!(
4167 matches!(&err, AeroError::InComponent { id, source } if id == "pod-fins"
4168 && matches!(&**source, AeroError::Unsupported(what) if what.starts_with("cant on a pod"))),
4169 "{err}"
4170 );
4171 let mut rocket = podded_rocket(2);
4172 let pods = rocket.stages[0].components[1].children.last_mut().unwrap();
4173 pods.children
4174 .push(component("pod-disc", body_part(0.0, 0.01, 0.01), None));
4175 let err = AeroModel::new(&rocket.layout().unwrap()).unwrap_err();
4176 assert!(
4177 matches!(&err, AeroError::InComponent { id, source } if id == "pod-disc"
4178 && matches!(&**source, AeroError::Unsupported(what) if what.contains("flat disc"))),
4179 "{err}"
4180 );
4181 let bare = AeroModel::new(&crate::testing::finned_rocket(4).layout().unwrap()).unwrap();
4183 let mut rocket = podded_rocket(2);
4184 let pods = rocket.stages[0].components[1].children.last_mut().unwrap();
4185 pods.children.clear();
4186 let empty = AeroModel::new(&rocket.layout().unwrap()).unwrap();
4187 assert_eq!(format!("{empty:?}"), format!("{bare:?}"));
4188
4189 let err = AeroModel::new(&finned_rocket(9).layout().unwrap()).unwrap_err();
4190 assert!(
4191 matches!(&err, AeroError::InComponent { id, .. } if id == "fins"),
4192 "{err}"
4193 );
4194
4195 let m = model(&finned_rocket(4));
4196 for bad in [
4197 flow(NORMAL_FORCE_MACH_LIMIT, 0.0, 0.0),
4198 flow(-0.01, 0.0, 0.0),
4199 flow(f64::NAN, 0.0, 0.0),
4200 ] {
4201 assert!(matches!(
4202 m.normal_force(&bad),
4203 Err(AeroError::Mach { limit, .. }) if limit == NORMAL_FORCE_MACH_LIMIT
4204 ));
4205 }
4206 assert!(m.normal_force(&flow(1.0, 0.1, 0.0)).is_ok());
4208 let coasting = DragConditions::coasting(1e7);
4209 assert!(m.drag(&flow(1.0, 0.0, 0.0), &coasting).is_ok());
4210 assert!(matches!(
4211 m.drag(&flow(5.0, 0.0, 0.0), &coasting),
4212 Err(AeroError::Mach { limit, model, .. })
4213 if limit == BUILDUP_MACH_LIMIT && model == "the drag buildup"
4214 ));
4215 assert!(
4216 m.buildup_components(&flow(5.0, 0.0, 0.0), &coasting)
4217 .is_err()
4218 );
4219 for bad in [
4220 flow(0.3, -1e-9, 0.0),
4221 flow(0.3, PI + 1e-9, 0.0),
4222 flow(0.3, f64::NAN, 0.0),
4223 flow(0.3, 0.1, f64::INFINITY),
4224 ] {
4225 assert!(matches!(
4226 m.normal_force(&bad),
4227 Err(AeroError::Domain { .. })
4228 ));
4229 assert!(m.components(&bad).is_err());
4230 }
4231
4232 let mut lugged = finned_rocket(4);
4233 lugged.stages[0].components[1].children.push(component(
4234 "lug",
4235 Part::LaunchLug(LaunchLug {
4236 length_m: 0.05,
4237 outer_radius_m: 0.004,
4238 thickness_m: 0.0005,
4239 angle_rad: 0.0,
4240 count: 1,
4241 spacing_m: 0.0,
4242 material: material(),
4243 }),
4244 Some(Position::Middle { aft_offset_m: 0.0 }),
4245 ));
4246 let with = model(&lugged).normal_force(&flow(0.3, 0.1, 0.0)).unwrap();
4247 assert_eq!(with, m.normal_force(&flow(0.3, 0.1, 0.0)).unwrap());
4248 }
4249
4250 #[test]
4253 fn a_bare_tube_has_no_cp_at_zero_incidence() {
4254 let tube = one_stage(
4255 vec![component("tube", body_part(1.0, 0.05, 0.05), None)],
4256 ReferenceDiameter::Maximum {},
4257 );
4258 let m = model(&tube);
4259 assert_eq!(
4260 m.normal_force(&Flow::axial(0.5)).unwrap().cp_station_m,
4261 None
4262 );
4263 let f = m.normal_force(&flow(0.5, 0.1, 0.0)).unwrap();
4264 close(f.cp_station_m.unwrap(), 0.5, 1e-15, "tube lift CP");
4265 }
4266
4267 proptest! {
4268 #[test]
4272 fn components_sum_to_the_total(
4273 count in 1u32..=8,
4274 mach in 0.0f64..0.99,
4275 alpha in 0.0f64..PI,
4276 roll in -4.0f64..4.0,
4277 ) {
4278 let m = model(&finned_rocket(count));
4279 let f = flow(mach, alpha, roll);
4280 let total = m.normal_force(&f).unwrap();
4281 let parts = m.components(&f).unwrap();
4282 let (c, moment) = parts.iter().fold((0.0, 0.0), |(c, x), p| {
4283 (c + p.normal_force.coefficient, x + p.normal_force.moment_m)
4284 });
4285 let tol = 1e-12 * (1.0 + total.coefficient.abs());
4286 prop_assert!((c - total.coefficient).abs() <= tol);
4287 prop_assert!((moment - total.moment_m).abs() <= 1e-12 * (1.0 + total.moment_m.abs()));
4288 let side: f64 = parts.iter().map(|p| p.normal_force.side_coefficient).sum();
4289 prop_assert!((side - total.side_coefficient).abs() <= 1e-12 * (1.0 + total.side_coefficient.abs()));
4290 let slope: f64 = parts.iter().map(|p| p.normal_force.slope_per_rad).sum();
4291 prop_assert!((slope - total.slope_per_rad).abs() <= 1e-12 * total.slope_per_rad.abs());
4292 prop_assert_eq!(m.component_count(), parts.len());
4295 let small = flow(mach, 1e-6, roll);
4296 for (index, part) in parts.iter().enumerate() {
4297 prop_assert_eq!(&m.component_normal_force(index, &f).unwrap(), &part.normal_force);
4298 let station = m.component_station_m(index, mach).unwrap();
4299 if let Some(cp) = m.component_normal_force(index, &small).unwrap().cp_station_m {
4300 prop_assert!((station - cp).abs() <= 1e-6 * (1.0 + cp.abs()));
4301 }
4302 }
4303 prop_assert!(m.component_normal_force(parts.len(), &f).is_err());
4304 prop_assert!(m.component_station_m(parts.len(), mach).is_err());
4305 }
4306
4307 #[test]
4308 fn scaling_leaves_slopes_and_scales_the_cp(
4309 k in 0.1f64..10.0,
4310 nose_fineness in 1.5f64..8.0,
4311 radius in 0.01f64..0.1,
4312 root in 0.02f64..0.3,
4313 tip_ratio in 0.0f64..1.0,
4314 span in 0.01f64..0.3,
4315 sweep in -0.1f64..0.3,
4316 count in 1u32..=8,
4317 alpha in 0.0f64..0.5,
4318 reference in 0.5f64..2.0,
4319 ) {
4320 let build = |s: f64, custom: Option<f64>| {
4321 let (r, l) = (s * radius, s * (root + 0.5));
4322 let mut tube = component("tube", body_part(l, r, r), None);
4323 let planform = FinPlanform::Trapezoidal {
4324 root_chord_m: s * root,
4325 tip_chord_m: s * root * tip_ratio,
4326 span_m: s * span,
4327 sweep_m: s * sweep,
4328 };
4329 tube.children = vec![component(
4330 "fins",
4331 fin_set(count, planform),
4332 Some(Position::Bottom { aft_offset_m: 0.0 }),
4333 )];
4334 let ogive = NoseShape::Ogive { radius_ratio: 1.0 };
4335 let nose = component("nose", nose(ogive, 2.0 * nose_fineness * r, r), None);
4336 let mut rocket = one_stage(vec![nose, tube], ReferenceDiameter::Maximum {});
4337 if let Some(d) = custom {
4338 rocket.reference_diameter = ReferenceDiameter::Custom { diameter_m: d };
4339 }
4340 model(&rocket).normal_force(&flow(0.4, alpha, 0.3)).unwrap()
4341 };
4342 let rel = |a: f64, b: f64| (a / b - 1.0).abs();
4343 let base = build(1.0, None);
4344 let base_cp = base.cp_station_m.unwrap();
4345 let scaled = build(k, None);
4346 prop_assert!(rel(scaled.slope_per_rad, base.slope_per_rad) < 1e-9);
4347 prop_assert!(rel(scaled.cp_station_m.unwrap(), k * base_cp) < 1e-9);
4348 let d = 2.0 * radius * reference;
4349 let custom = build(1.0, Some(d));
4350 let factor = (2.0 * radius / d).powi(2);
4351 prop_assert!(rel(custom.slope_per_rad, factor * base.slope_per_rad) < 1e-12);
4352 prop_assert!(rel(custom.cp_station_m.unwrap(), base_cp) < 1e-12);
4353 }
4354 }
4355
4356 #[test]
4360 fn radius_steps_count_at_the_joint() {
4361 let rocket = one_stage(
4362 vec![
4363 component("nose", nose(NoseShape::Conical {}, 0.2, 0.027), None),
4364 component("tube", body_part(0.5, 0.029, 0.029), None),
4365 component("tail", body_part(0.3, 0.025, 0.025), None),
4366 ],
4367 ReferenceDiameter::Maximum {},
4368 );
4369 let m = model(&rocket);
4370 let a_ref = PI * 0.029 * 0.029;
4371 let total = m.normal_force(&Flow::axial(0.3)).unwrap();
4372 close(
4373 total.slope_per_rad,
4374 2.0 * PI * 0.025 * 0.025 / a_ref,
4375 1e-14,
4376 "eq. 10",
4377 );
4378 let parts = m.components(&Flow::axial(0.3)).unwrap();
4379 let tube = parts[1].normal_force;
4380 close(
4381 tube.slope_per_rad,
4382 2.0 * PI * (0.029f64.powi(2) - 0.027f64.powi(2)) / a_ref,
4383 1e-14,
4384 "step up",
4385 );
4386 close(
4387 tube.cp_station_m.unwrap(),
4388 0.2,
4389 1e-14,
4390 "step up at the joint",
4391 );
4392 let tail = parts[2].normal_force;
4393 assert!(tail.slope_per_rad < 0.0);
4394 close(
4395 tail.cp_station_m.unwrap(),
4396 0.7,
4397 1e-14,
4398 "step down at the joint",
4399 );
4400 assert_eq!(m.bodies()[0].step_area_m2, 0.0);
4401 }
4402
4403 #[test]
4405 fn freeform_fins_through_the_model() {
4406 let trapezoid = finned_rocket(3);
4407 let mut freeform = trapezoid.clone();
4408 if let Part::FinSet(set) = &mut freeform.stages[0].components[3].children[0].part {
4409 set.planform = FinPlanform::Freeform {
4410 points_m: vec![[0.0, 0.0], [0.07, 0.06], [0.12, 0.06], [0.12, 0.0]],
4411 root_m: Vec::new(),
4412 };
4413 }
4414 let (a, b) = (model(&trapezoid), model(&freeform));
4415 let f = flow(0.7, 0.1, 0.0);
4416 let (fa, fb) = (a.normal_force(&f).unwrap(), b.normal_force(&f).unwrap());
4417 close(fb.coefficient, fa.coefficient, 1e-13, "C_N");
4418 close(
4419 fb.cp_station_m.unwrap(),
4420 fa.cp_station_m.unwrap(),
4421 1e-13,
4422 "CP",
4423 );
4424 }
4425
4426 #[test]
4428 fn flow_and_results_round_trip() {
4429 let f = flow(0.3, 0.1, -0.2);
4430 let back: Flow = serde_json::from_str(&serde_json::to_string(&f).unwrap()).unwrap();
4431 assert_eq!(back, f);
4432 assert!(
4433 serde_json::from_str::<Flow>(
4434 r#"{"mach":0.3,"alpha_rad":0.1,"roll_rad":0,"aoa_deg":5}"#
4435 )
4436 .is_err()
4437 );
4438 let n = model(&finned_rocket(4)).normal_force(&f).unwrap();
4439 let back: NormalForce = serde_json::from_str(&serde_json::to_string(&n).unwrap()).unwrap();
4440 assert_eq!(back, n);
4441 }
4442
4443 #[test]
4445 fn inconsistent_layouts_are_refused() {
4446 let layout = finned_rocket(4).layout().unwrap();
4447 let (fins, _) = layout.find("fins").unwrap();
4448 let mut no_radius = layout.clone();
4449 no_radius.components[fins].body_radius_m = None;
4450 let err = AeroModel::new(&no_radius).unwrap_err();
4451 assert!(
4452 matches!(&err, AeroError::InComponent { id, source } if id == "fins"
4453 && matches!(**source, AeroError::Layout(_))),
4454 "{err}"
4455 );
4456 assert_eq!(err, err.clone());
4457 let mut nan = layout;
4458 nan.components[0].fore_station_m = f64::NAN;
4459 assert!(matches!(
4460 AeroModel::new(&nan),
4461 Err(AeroError::InComponent { .. })
4462 ));
4463 }
4464
4465 #[test]
4468 fn two_fin_sets_push_across_the_flow() {
4469 let two = model(&finned_rocket(2));
4470 let set = &two.fin_sets()[0];
4471 let alpha = 0.05;
4472 let f = two.normal_force(&flow(0.4, alpha, FRAC_PI_4)).unwrap();
4473 let one_fin = set
4474 .fin
4475 .geometry()
4476 .single_fin_slope(two.reference_area_m2(), 0.4)
4477 .unwrap()
4478 * set.interference;
4479 close(f.side_coefficient, one_fin * alpha, 1e-13, "side");
4480 close(
4481 f.side_moment_m,
4482 one_fin * alpha * set.cp_station_m(0.4).unwrap(),
4483 1e-13,
4484 "side moment",
4485 );
4486 let fins = &two.components(&flow(0.4, alpha, FRAC_PI_4)).unwrap()[4];
4487 close(
4488 fins.normal_force.coefficient,
4489 one_fin * alpha,
4490 1e-13,
4491 "in plane",
4492 );
4493 let four = model(&finned_rocket(4))
4494 .normal_force(&flow(0.4, alpha, 0.3))
4495 .unwrap();
4496 assert_eq!((four.side_coefficient, four.side_moment_m), (0.0, 0.0));
4497 }
4498
4499 #[test]
4502 fn a_cancelled_slope_has_no_cp() {
4503 let rocket = one_stage(
4504 vec![
4505 component("nose", nose(NoseShape::Conical {}, 0.2, 0.0254), None),
4506 component("tube", body_part(0.5, 0.0254, 0.0254), None),
4507 component("tail", body_part(0.3, 0.0254, 1e-9), None),
4508 ],
4509 ReferenceDiameter::Maximum {},
4510 );
4511 let m = model(&rocket);
4512 let f = m.normal_force(&Flow::axial(0.3)).unwrap();
4513 assert!(f.slope_per_rad.abs() < 1e-12, "{}", f.slope_per_rad);
4514 assert_eq!(f.cp_station_m, None);
4515 let moving = m.normal_force(&flow(0.3, 0.01, 0.0)).unwrap();
4516 assert!(moving.moment_m.is_finite() && moving.cp_station_m.is_some());
4517 }
4518
4519 #[test]
4522 fn a_normal_force_table_replaces_the_sum() {
4523 use crate::table::{NormalForceColumn, NormalForceTable};
4524 use hpr_core::interp::{Extrapolation, Interpolation, Table1D};
4525
4526 let m = model(&finned_rocket(4));
4527 let flat = |value| {
4528 Table1D::new(
4529 vec![0.0, 2.0],
4530 vec![value, value],
4531 Interpolation::Linear,
4532 Extrapolation::Clamp,
4533 )
4534 .unwrap()
4535 };
4536 let table = NormalForceTable::new(vec![NormalForceColumn::new(0.0, flat(10.0), flat(0.9))])
4537 .unwrap();
4538 let with = m.clone().with_normal_force_table(table.clone()).unwrap();
4539 let at = flow(0.5, 0.02, 0.3);
4540 let replaced = with.normal_force(&at).unwrap();
4541 close(replaced.coefficient, 10.0 * 0.02_f64.sin(), 1e-15, "C_N");
4542 close(
4543 replaced.moment_m,
4544 replaced.coefficient * 0.9,
4545 1e-15,
4546 "moment",
4547 );
4548 assert_eq!(replaced.cp_station_m, Some(0.9));
4549 assert_eq!(
4550 (replaced.side_coefficient, replaced.side_moment_m),
4551 (0.0, 0.0)
4552 );
4553 assert!(replaced.table.is_some_and(|lookup| lookup.beyond_alpha));
4555 assert_eq!(m.normal_force(&at).unwrap().table, None);
4556 assert_eq!(with.components(&at).unwrap(), m.components(&at).unwrap());
4557 assert_eq!(
4558 with.component_normal_force(3, &at).unwrap(),
4559 m.component_normal_force(3, &at).unwrap()
4560 );
4561 assert_ne!(m.normal_force(&at).unwrap(), replaced);
4562 let wider = m
4564 .clone()
4565 .with_normal_force_table(table.clone().with_reference_diameter_m(0.108).unwrap())
4566 .unwrap();
4567 let scaled = wider.normal_force(&at).unwrap();
4568 close(
4569 scaled.coefficient,
4570 4.0 * replaced.coefficient,
4571 1e-14,
4572 "rescaled",
4573 );
4574 assert_eq!(scaled.cp_station_m, Some(0.9));
4575 let largest = m
4577 .clone()
4578 .with_normal_force_table(
4579 table
4580 .clone()
4581 .with_reference(TableReference::LargestBody)
4582 .unwrap(),
4583 )
4584 .unwrap();
4585 close(
4586 largest.normal_force(&at).unwrap().coefficient,
4587 replaced.coefficient,
4588 1e-14,
4589 "largest body",
4590 );
4591 let mut half = finned_rocket(4);
4594 half.reference_diameter = ReferenceDiameter::Custom { diameter_m: 0.027 };
4595 let half = model(&half)
4596 .with_normal_force_table(
4597 table
4598 .clone()
4599 .with_reference(TableReference::LargestBody)
4600 .unwrap(),
4601 )
4602 .unwrap();
4603 close(
4604 half.normal_force(&at).unwrap().coefficient,
4605 4.0 * replaced.coefficient,
4606 1e-14,
4607 "largest body on a half-size reference",
4608 );
4609 let hypersonic = |cp_at_6: f64| {
4611 let cps = Table1D::new(
4612 vec![0.0, 5.0, 6.0, 25.0],
4613 vec![0.9, 0.9, cp_at_6, -3.0],
4614 Interpolation::Linear,
4615 Extrapolation::Clamp,
4616 )
4617 .unwrap();
4618 NormalForceTable::new(vec![NormalForceColumn::new(0.0, flat(10.0), cps)]).unwrap()
4619 };
4620 assert!(m.clone().with_normal_force_table(hypersonic(0.8)).is_ok());
4621 assert!(m.clone().with_normal_force_table(hypersonic(-0.1)).is_err());
4622 for cp in [-0.01, 1.4] {
4624 let outside =
4625 NormalForceTable::new(vec![NormalForceColumn::new(0.0, flat(10.0), flat(cp))])
4626 .unwrap();
4627 assert!(matches!(
4628 m.clone().with_normal_force_table(outside),
4629 Err(AeroError::Domain { .. })
4630 ));
4631 }
4632 assert!(with.normal_force(&flow(6.0, 0.02, 0.0)).is_ok());
4634 assert!(matches!(
4635 m.normal_force(&flow(6.0, 0.02, 0.0)),
4636 Err(AeroError::Mach { .. })
4637 ));
4638 }
4639
4640 fn straight_rocket() -> hpr_design::Rocket {
4643 let mut rocket = crate::testing::finned_rocket(4);
4644 rocket.stages[0].components[2].part = body_part(0.05, 0.027, 0.027);
4645 rocket.stages[0].components[3].part = body_part(0.3, 0.027, 0.027);
4646 rocket
4647 }
4648
4649 fn straight_rocket_body() -> ShockExpansionBody {
4651 let nose =
4652 hpr_design::Profile::nose(NoseShape::Ogive { radius_ratio: 1.0 }, 0.25, 0.027).unwrap();
4653 let cylinder = |length_m| BodySegment::Cylinder {
4654 length_m,
4655 radius_m: 0.027,
4656 };
4657 ShockExpansionBody::new(
4658 &[
4659 BodySegment::Profile { profile: nose },
4660 cylinder(0.7),
4661 cylinder(0.05),
4662 cylinder(0.3),
4663 ],
4664 DEFAULT_ELEMENTS_PER_CURVE,
4665 )
4666 .unwrap()
4667 }
4668
4669 fn body_values(model: &AeroModel, mach: f64) -> Vec<[f64; 3]> {
4671 (0..model.bodies().len())
4672 .map(|index| {
4673 let force = model
4674 .component_normal_force(index, &flow(mach, 0.0, 0.0))
4675 .unwrap();
4676 let moment = force
4678 .cp_station_m
4679 .map_or(0.0, |cp| cp * force.slope_per_rad);
4680 [
4681 force.slope_per_rad,
4682 moment,
4683 model.component_station_m(index, mach).unwrap(),
4684 ]
4685 })
4686 .collect()
4687 }
4688
4689 fn no_jump(model: &AeroModel, mach: f64) {
4691 let below = body_values(model, mach - 1e-9);
4692 let above = body_values(model, mach + 1e-9);
4693 for (b, a) in below.iter().zip(&above) {
4694 for k in 0..3 {
4695 let scale = b[k].abs().max(a[k].abs()).max(1.0);
4696 assert!(
4697 (a[k] - b[k]).abs() <= 1e-7 * scale,
4698 "a jump at Mach {mach}: {b:?} to {a:?}"
4699 );
4700 }
4701 }
4702 }
4703
4704 #[test]
4705 fn the_supersonic_join_has_no_jump() {
4706 let model = model(&straight_rocket());
4707 let join = model.supersonic_body().unwrap();
4708 assert_eq!(join.covered, 4);
4709 assert_eq!(join.join_start_mach, SUPERSONIC_JOIN_START_MACH);
4710 let start = join.join_start_mach;
4712 for mach in [
4713 start,
4714 start + SUPERSONIC_JOIN_WIDTH_MACH,
4715 1.35,
4716 2.0,
4717 2.05,
4718 3.0,
4719 4.63,
4720 4.95,
4721 4.999,
4722 ] {
4723 no_jump(&model, mach);
4724 }
4725 let (low, high) = (body_values(&model, 1.0), body_values(&model, 2.0));
4727 assert_eq!(low[1][0], 0.0);
4728 assert!(high[1][0] > 0.1, "{:?}", high[1]);
4729 }
4730
4731 #[test]
4736 fn crossflow_and_the_boattail_fly_without_a_jump() {
4737 use crate::crossflow::{CROSSFLOW_DRAG_MACHS, ETA_MACHS};
4738 let layout = finned_rocket(4).layout().unwrap();
4739 for boattail in [
4740 SupersonicBoattail::WashingtonPettis,
4741 SupersonicBoattail::Footnote8,
4742 ] {
4743 let model = AeroModel::with_body_model(
4744 &layout,
4745 BodyModel::CURRENT.with_supersonic_boattail(boattail),
4746 )
4747 .unwrap();
4748 let start = model.supersonic_body().unwrap().join_start_mach;
4749 for alpha_deg in [10.0_f64, 30.0] {
4750 let s = alpha_deg.to_radians().sin();
4751 let mut machs = vec![start, start + SUPERSONIC_JOIN_WIDTH_MACH, 2.0, 2.05, 4.999];
4752 machs.extend(
4753 CROSSFLOW_DRAG_MACHS
4754 .iter()
4755 .chain(&ETA_MACHS)
4756 .map(|m| m / s)
4757 .filter(|&m| m > 1e-3 && m < 4.999),
4758 );
4759 for mach in machs {
4760 let at = |m: f64| {
4761 let f = model
4762 .normal_force(&flow(m, alpha_deg.to_radians(), 0.0))
4763 .unwrap();
4764 [f.coefficient, f.cp_station_m.unwrap()]
4765 };
4766 let (below, above) = (at(mach - 1e-9), at(mach + 1e-9));
4767 for k in 0..2 {
4768 let scale = below[k].abs().max(1.0);
4769 assert!(
4770 (above[k] - below[k]).abs() <= 1e-7 * scale,
4771 "{boattail:?} at {alpha_deg}° and Mach {mach}: {below:?} to {above:?}"
4772 );
4773 }
4774 }
4775 }
4776 }
4777 }
4778
4779 #[test]
4785 fn vertical_tips_fly_the_method_without_a_jump() {
4786 for shape in [
4787 NoseShape::PowerSeries { exponent: 0.6369 },
4788 NoseShape::PowerSeries { exponent: 0.5 },
4789 NoseShape::VON_KARMAN,
4790 NoseShape::LV_HAACK,
4791 NoseShape::Elliptical {},
4792 ] {
4793 for boattail in [true, false] {
4794 let mut rocket = if boattail {
4795 finned_rocket(4)
4796 } else {
4797 straight_rocket()
4798 };
4799 rocket.stages[0].components[0].part = nose(shape, 0.25, 0.027);
4800 let model = model(&rocket);
4801 let table = model
4802 .supersonic_body()
4803 .unwrap_or_else(|| panic!("{shape:?}: no table"));
4804 assert_eq!(table.covered, 4, "{shape:?}");
4805 if !boattail {
4807 let Part::NoseCone(cone) = &rocket.stages[0].components[0].part else {
4808 unreachable!("`nose` builds a nose cone")
4809 };
4810 let cylinder = |length_m| BodySegment::Cylinder {
4811 length_m,
4812 radius_m: 0.027,
4813 };
4814 let body = ShockExpansionBody::new(
4815 &[
4816 BodySegment::Profile {
4817 profile: cone.profile().unwrap(),
4818 },
4819 cylinder(0.7),
4820 cylinder(0.05),
4821 cylinder(0.3),
4822 ],
4823 DEFAULT_ELEMENTS_PER_CURVE,
4824 )
4825 .unwrap();
4826 let method = body.segment_slopes(3.0, model.reference_area_m2()).unwrap();
4827 let (nose_slope, _) = table.share(0, 3.0).unwrap();
4828 assert!(
4829 (nose_slope - method[0].slope_per_rad).abs() <= 1e-12,
4830 "{shape:?}: {nose_slope} against {:?}",
4831 method[0]
4832 );
4833 }
4834 let start = table.join_start_mach;
4835 let mut machs = vec![start, start + SUPERSONIC_JOIN_WIDTH_MACH, 2.1, 4.999];
4836 machs.extend(
4840 (SUPERSONIC_FIRST_STEP..SUPERSONIC_LAST_STEP).flat_map(|step| {
4841 let row = step as f64 / SUPERSONIC_STEPS_PER_MACH;
4842 [row, row + 0.013, row + 0.027, row + 0.041]
4843 }),
4844 );
4845 for alpha_deg in [1.0_f64, 10.0] {
4846 for &mach in &machs {
4847 let at = |m: f64| {
4848 let f = model
4849 .normal_force(&flow(m, alpha_deg.to_radians(), 0.0))
4850 .unwrap();
4851 [f.coefficient, f.cp_station_m.unwrap()]
4852 };
4853 let (below, above) = (at(mach - 1e-9), at(mach + 1e-9));
4854 for k in 0..2 {
4855 let scale = below[k].abs().max(1.0);
4856 assert!(
4857 (above[k] - below[k]).abs() <= 1e-7 * scale,
4858 "{shape:?} at {alpha_deg}° and Mach {mach}: {below:?} to {above:?}"
4859 );
4860 }
4861 }
4862 }
4863 }
4864 }
4865 }
4866
4867 #[test]
4873 fn a_blunt_tips_join_starts_where_its_cap_first_ends_on_the_nose() {
4874 let mut rocket = crate::testing::committed_design("wind-tunnel-arcas-robin-short.json");
4875 rocket.stages[0].components.truncate(3);
4877 let model = model(&rocket);
4878 let table = model.supersonic_body().unwrap();
4879 let Part::NoseCone(cone) = &rocket.stages[0].components[0].part else {
4880 unreachable!("the committed design starts with its nose")
4881 };
4882 let profile = cone.profile().unwrap();
4883 let base_angle = profile.radius_and_slope(profile.length_m()).1.atan();
4884 let (mut low, mut high) = (1.0 + 1e-9, 2.0);
4885 for _ in 0..200 {
4886 let mid = 0.5 * (low + high);
4887 if crate::blunt_tip::handover_angle_rad(mid).unwrap() < base_angle {
4888 low = mid;
4889 } else {
4890 high = mid;
4891 }
4892 }
4893 assert!(
4894 (table.join_start_mach - high).abs() <= 1e-12,
4895 "{} against {high}",
4896 table.join_start_mach
4897 );
4898 let run = model.supersonic_run.as_ref().unwrap();
4899 let body = ShockExpansionBody::new(&run.segments, DEFAULT_ELEMENTS_PER_CURVE).unwrap();
4900 let in_its_place: Vec<Option<ShockExpansionBody>> = run
4901 .boattails
4902 .iter()
4903 .map(|b| {
4904 b.as_ref().map(|b| {
4905 ShockExpansionBody::new(&b.in_its_place, DEFAULT_ELEMENTS_PER_CURVE).unwrap()
4906 })
4907 })
4908 .collect();
4909 let holds = |m: f64| {
4910 run.shares(&body, &in_its_place, None, m, model.reference_area_m2())
4911 .is_some()
4912 };
4913 for i in 1..=2000 {
4914 let d = f64::from(i) * 1e-10;
4915 assert!(
4916 !holds(table.join_start_mach - d),
4917 "holds {d} below the start"
4918 );
4919 assert!(
4920 holds(table.join_start_mach + d),
4921 "fails {d} above the start"
4922 );
4923 }
4924 }
4925
4926 #[test]
4927 fn a_long_lip_is_reported_as_the_runs_fallback() {
4928 let rocket = crate::testing::committed_design("wind-tunnel-arcas-robin-short.json");
4931 let components = &rocket.stages[0].components;
4932 let drop_m = components
4933 .iter()
4934 .find_map(|c| match &c.part {
4935 Part::Transition(t) if t.aft_radius_m < t.fore_radius_m => {
4936 Some(2.0 * (t.fore_radius_m - t.aft_radius_m))
4937 }
4938 _ => None,
4939 })
4940 .unwrap();
4941 let lip_index = components.iter().position(|c| c.id == "lip").unwrap();
4942 let with_lip = |length_m: f64| {
4943 let mut rocket = rocket.clone();
4944 let lip = &mut rocket.stages[0].components[lip_index];
4945 match &mut lip.part {
4946 Part::Transition(t) => t.length_m = length_m,
4947 Part::BodyTube(t) => t.length_m = length_m,
4948 other => panic!("the lip is a {}", other.kind_name()),
4949 }
4950 model(&rocket).supersonic_fallback()
4951 };
4952 assert_eq!(with_lip(drop_m * (1.0 - 1e-9)), None);
4953 assert_eq!(
4954 with_lip(drop_m * (1.0 + 1e-9)),
4955 Some(SupersonicFallback::LongLip {
4956 component: "lip".to_owned()
4957 })
4958 );
4959 }
4960
4961 #[test]
4966 fn a_lip_in_a_boattails_wake_carries_nothing() {
4967 for name in [
4968 "wind-tunnel-arcas-robin-short.json",
4969 "wind-tunnel-arcas-robin-long.json",
4970 ] {
4971 let rocket = crate::testing::committed_design(name);
4972 let model = model(&rocket);
4973 let table = model
4974 .supersonic_body()
4975 .unwrap_or_else(|| panic!("{name}: no table"));
4976 assert_eq!(table.covered, 4, "{name}");
4978 let lip = model.bodies().last().unwrap();
4979 assert!(lip.slope_per_rad > 0.1, "{name}: the lip is a flare");
4980 for mach in [1.3, 2.0, 3.0, 5.0] {
4981 let (slope, moment) = table.share(3, mach).unwrap();
4982 assert_eq!((slope, moment), (0.0, 0.0), "{name} at Mach {mach}");
4983 }
4984 let start = table.join_start_mach;
4986 let lip_slope = |mach: f64| {
4988 model
4989 .components(&Flow::axial(mach))
4990 .unwrap()
4991 .into_iter()
4992 .find(|c| c.id == "lip")
4993 .unwrap()
4994 .normal_force
4995 .slope_per_rad
4996 };
4997 let below = lip_slope(1.0);
4998 assert!(
4999 (below - lip.slope_per_rad).abs() <= 0.01 * lip.slope_per_rad,
5000 "{name}: {below} against slender-body theory's {}",
5001 lip.slope_per_rad
5002 );
5003 let above = lip_slope(start + SUPERSONIC_JOIN_WIDTH_MACH);
5004 assert!(above.abs() <= 1e-12, "{name}: {above} above the join");
5005 for alpha_deg in [1.0_f64, 10.0] {
5006 let mut machs = vec![start, start + SUPERSONIC_JOIN_WIDTH_MACH, 4.999];
5007 machs.extend(
5008 (SUPERSONIC_FIRST_STEP..SUPERSONIC_LAST_STEP).flat_map(|step| {
5009 let row = step as f64 / SUPERSONIC_STEPS_PER_MACH;
5010 [row, row + 0.017, row + 0.033]
5011 }),
5012 );
5013 for mach in machs {
5014 let at = |m: f64| {
5015 let f = model
5016 .normal_force(&flow(m, alpha_deg.to_radians(), 0.0))
5017 .unwrap();
5018 [f.coefficient, f.cp_station_m.unwrap()]
5019 };
5020 let (below, above) = (at(mach - 1e-9), at(mach + 1e-9));
5021 for k in 0..2 {
5022 let scale = below[k].abs().max(1.0);
5023 assert!(
5024 (above[k] - below[k]).abs() <= 1e-7 * scale,
5025 "{name} at {alpha_deg}° and Mach {mach}: {below:?} to {above:?}"
5026 );
5027 }
5028 }
5029 }
5030 }
5031 let lipped = |rise: f64| {
5036 let mut rocket = crate::testing::finned_rocket(4);
5037 rocket.stages[0].components.truncate(3);
5041 rocket.stages[0].components.push(component(
5042 "lip",
5043 body_part(0.01, 0.022, 0.022 + 0.5 * rise * 0.010),
5044 None,
5045 ));
5046 model(&rocket)
5047 };
5048 assert_eq!(lipped(0.2).supersonic_body().map(|t| t.covered), Some(4));
5049 assert!(lipped(0.6).supersonic_body().is_none());
5050 let at = |rise: f64| {
5051 let model = lipped(rise);
5052 let f = model
5053 .normal_force(&flow(3.0, 4f64.to_radians(), 0.0))
5054 .unwrap();
5055 (f.coefficient, f.cp_station_m.unwrap())
5056 };
5057 let (below, above) = (at(0.2499), at(0.2501));
5062 assert!(
5063 (above.0 - below.0).abs() <= 2e-4 * below.0.abs()
5064 && (above.1 - below.1).abs() <= 2e-4 * below.1.abs(),
5065 "{below:?} to {above:?} across the wake's full-shelter rise"
5066 );
5067 let out_of_wake = {
5071 let mut rocket = crate::testing::finned_rocket(4);
5072 rocket.stages[0].components.truncate(3);
5073 rocket.stages[0].components.push(component(
5074 "lip",
5075 body_part(0.0101, 0.022, 0.022 + 0.5 * 0.25 * 0.010),
5076 None,
5077 ));
5078 let m = model(&rocket);
5079 assert!(
5080 m.supersonic_body().is_none(),
5081 "out of the wake by its length"
5082 );
5083 let f = m.normal_force(&flow(3.0, 4f64.to_radians(), 0.0)).unwrap();
5084 (
5085 f.coefficient,
5086 f.cp_station_m.unwrap() / m.reference_diameter_m(),
5087 )
5088 };
5089 let in_wake = at(0.25);
5090 let diameter_m = model(&crate::testing::finned_rocket(4)).reference_diameter_m();
5091 let gap_force = out_of_wake.0 / in_wake.0 - 1.0;
5092 let gap_calibers = out_of_wake.1 - in_wake.1 / diameter_m;
5093 assert!(
5094 (gap_force + 0.3295).abs() < 5e-4 && (gap_calibers + 1.774).abs() < 5e-3,
5095 "at one shape the two models differ by {gap_force} in force and {gap_calibers} \
5096 calibers in center of pressure"
5097 );
5098 let (full, nearly_none) = (at(0.25), at(0.4999));
5101 let calibers = (nearly_none.1 - full.1) / diameter_m;
5102 assert!(
5103 (nearly_none.0 / full.0 - 1.0 + 0.291).abs() < 5e-4 && (calibers + 0.932).abs() < 5e-3,
5104 "across the band: {full:?} to {nearly_none:?}, {calibers} calibers"
5105 );
5106 assert!((lipped(0.25).supersonic_body().unwrap().shape_weight - 1.0).abs() < 1e-12);
5109 for (rise, want) in [(0.3_f64, 0.8_f64), (0.375, 0.5), (0.45, 0.2)] {
5112 let weight = lipped(rise).supersonic_body().unwrap().shape_weight;
5113 assert!(
5114 (weight - want).abs() < 1e-9,
5115 "at a rise of {rise} the wake covers {weight}, not {want}"
5116 );
5117 }
5118 assert!(
5121 lipped(0.49999).supersonic_body().unwrap().shape_weight < 1e-4,
5122 "a hair inside the wake's far edge the method has almost no weight left"
5123 );
5124 assert!(
5125 lipped(0.5).supersonic_body().is_none(),
5126 "at the wake's far edge there is no run"
5127 );
5128 let gapped = |gap_m: f64| {
5131 let mut rocket = crate::testing::finned_rocket(4);
5132 rocket.stages[0].components.truncate(3);
5133 rocket.stages[0].components.push(component(
5134 "gap",
5135 body_part(gap_m, 0.022, 0.022),
5136 None,
5137 ));
5138 rocket.stages[0].components.push(component(
5139 "lip",
5140 body_part(0.01, 0.022, 0.022 + 0.5 * 0.17 * 0.010),
5141 None,
5142 ));
5143 let m = model(&rocket);
5144 let weight = m.supersonic_body().map_or(0.0, |t| t.shape_weight);
5145 let f = m.normal_force(&flow(3.0, 4f64.to_radians(), 0.0)).unwrap();
5146 (
5147 weight,
5148 f.coefficient,
5149 f.cp_station_m.unwrap() / m.reference_diameter_m(),
5150 )
5151 };
5152 let (near, far) = (gapped(1e-6), gapped(0.010));
5153 assert!(
5154 near.0 > 0.999 && far.0 == 0.0,
5155 "a tube of the boattail's own drop in diameter carries the lip out of the wake: \
5156 {near:?} to {far:?}"
5157 );
5158 assert!(
5159 (far.2 - near.2 + 1.973).abs() < 0.01 && (far.1 / near.1 - 1.0 + 0.3381).abs() < 5e-4,
5160 "over that tube the force moves {} and the center of pressure {} calibers",
5161 far.1 / near.1 - 1.0,
5162 far.2 - near.2
5163 );
5164 let half = lipped(0.375);
5169 let tube = half
5170 .component_normal_force(1, &flow(3.0, 0.0, 0.0))
5171 .unwrap();
5172 let station = half.component_station_m(1, 3.0).unwrap();
5173 assert!(
5174 (station - tube.cp_station_m.unwrap() - 0.1142).abs() < 5e-4,
5175 "the tube's station {station} against its center of pressure {:?}",
5176 tube.cp_station_m
5177 );
5178 assert!(
5179 lipped(0.55).supersonic_body().is_none(),
5180 "past the wake there is no run at all"
5181 );
5182 for rise in [0.2499_f64, 0.25, 0.3, 0.375, 0.45, 0.4999] {
5184 let (low, high) = (at(rise - 1e-9), at(rise + 1e-9));
5185 assert!(
5186 (high.0 - low.0).abs() <= 1e-7 * low.0.abs().max(1.0)
5187 && (high.1 - low.1).abs() <= 1e-7 * low.1.abs().max(1.0),
5188 "at a rise of {rise}: {low:?} to {high:?}"
5189 );
5190 }
5191 for shape in [NoseShape::Conical {}, NoseShape::Haack { parameter: 0.5 }] {
5195 let mut rocket = crate::testing::committed_design("wind-tunnel-arcas-robin-short.json");
5196 let components = &mut rocket.stages[0].components;
5197 let last = components.len() - 1;
5198 let Part::Transition(lip) = &mut components[last].part else {
5199 unreachable!("the committed design ends in its lip")
5200 };
5201 lip.aft_radius_m = lip.fore_radius_m + 0.60 * (0.028575 - 0.0166116);
5203 lip.shape = shape;
5204 assert!(
5205 model(&rocket).supersonic_body().is_none(),
5206 "{shape:?} out of the wake"
5207 );
5208 }
5209 let mut rocket = finned_rocket(4);
5212 rocket.stages[0].components.truncate(3);
5213 rocket.stages[0].components.push(component(
5214 "long flare",
5215 body_part(1.0, 0.022, 0.0229),
5216 None,
5217 ));
5218 assert!(model(&rocket).supersonic_body().is_none());
5219 let mut rocket = finned_rocket(4);
5222 rocket.stages[0].components.truncate(3);
5223 rocket.stages[0].components.push(component(
5224 "second boattail",
5225 body_part(0.03, 0.0231, 0.021),
5226 None,
5227 ));
5228 let narrowing = model(&rocket);
5229 assert!(narrowing.bodies().last().unwrap().slope_per_rad < 0.0);
5230 assert!(narrowing.supersonic_body().is_none());
5231 }
5232
5233 #[test]
5239 fn a_separating_boattail_reads_the_correlation_at_its_steepest_measured_angle() {
5240 let mach = 1.5;
5245 let ogive = nose(NoseShape::Ogive { radius_ratio: 1.0 }, 0.25, 0.027);
5246 let Part::NoseCone(ogive) = ogive else {
5247 unreachable!("`nose` builds a nose cone")
5248 };
5249 let kept_pair = |at: f64, half_angle_deg: f64| {
5252 let length_m = (0.027 - 0.022) / half_angle_deg.to_radians().tan();
5253 let mut rocket = finned_rocket(4);
5254 rocket.stages[0].components[2].part = body_part(length_m, 0.027, 0.022);
5255 let model = model(&rocket);
5256 let a_ref = model.reference_area_m2();
5257 let table = model
5258 .supersonic_body()
5259 .unwrap_or_else(|| panic!("a table at {half_angle_deg}°"));
5260 let share = table.share(2, at).expect("the boattail's share").0;
5261 let in_its_place = ShockExpansionBody::new(
5262 &[
5263 BodySegment::Profile {
5264 profile: ogive.profile().unwrap(),
5265 },
5266 BodySegment::Cylinder {
5267 length_m: 0.7,
5268 radius_m: 0.027,
5269 },
5270 BodySegment::Cylinder {
5271 length_m,
5272 radius_m: 0.027,
5273 },
5274 ],
5275 DEFAULT_ELEMENTS_PER_CURVE,
5276 )
5277 .unwrap();
5278 let cylinder = in_its_place.segment_slopes(at, a_ref).unwrap()[2].slope_per_rad;
5279 let raw = |l: f64| {
5280 crate::supersonic_boattail::wp_slope(at, 0.027, 0.022, l).unwrap()
5281 * PI
5282 * 0.027
5283 * 0.027
5284 / a_ref
5285 };
5286 (share - cylinder, raw(length_m))
5288 };
5289 let kept = |half_angle_deg: f64| kept_pair(mach, half_angle_deg);
5290 let kept_at = |at: f64, half_angle_deg: f64| kept_pair(at, half_angle_deg).0;
5291 let at_16 = (0.027 - 0.022) / 16.0_f64.to_radians().tan();
5292 let close = |got: f64, want: f64, what: &str| {
5293 assert!(
5294 (got - want).abs() < 0.02 * want.abs(),
5295 "{what}: {got} against {want}"
5296 );
5297 };
5298 for angle in [8.0, 15.0, 16.0] {
5300 let (flown, raw) = kept(angle);
5301 close(flown, raw, "read at the true angle");
5302 }
5303 let a_ref = model(&finned_rocket(4)).reference_area_m2();
5309 let at_16_read = crate::supersonic_boattail::wp_slope(mach, 0.027, 0.022, at_16).unwrap()
5310 * PI
5311 * 0.027
5312 * 0.027
5313 / a_ref;
5314 for angle in [17.0, 23.0, 30.0, 40.0] {
5315 let (flown, raw) = kept(angle);
5316 let (held, _) = kept(16.0);
5317 close(flown, held, "held at 16°");
5318 close(flown, at_16_read, "the correlation at the 16° geometry");
5320 assert!(flown < 0.0, "{angle}°: the boattail still takes lift off");
5321 assert!(flown < raw, "{angle}°: {flown} against {raw} read raw");
5324 }
5325 let length_m = (0.027 - 0.022) / 30.0_f64.to_radians().tan();
5330 let mut steep = finned_rocket(4);
5331 steep.stages[0].components[2].part = body_part(length_m, 0.027, 0.022);
5332 steep.stages[0].components.truncate(3);
5333 let steep = model(&steep);
5334 let body_cp_calibers = |at: f64, increment_kept: bool| {
5335 let parts = steep.components(&Flow::axial(at)).unwrap();
5336 let (mut slope, mut moment) = (0.0, 0.0);
5337 for (index, part) in parts.iter().take(steep.bodies().len()).enumerate() {
5338 let mut share = part.normal_force.slope_per_rad;
5339 let station = part.normal_force.cp_station_m.unwrap_or(0.0);
5340 if index == 2 && !increment_kept {
5341 share -= kept_at(at, 30.0);
5342 }
5343 slope += share;
5344 moment += share * station;
5345 }
5346 moment / slope / steep.reference_diameter_m()
5347 };
5348 let gaps: Vec<(f64, f64)> = [1.5_f64, 2.0, 3.0, 4.63]
5350 .iter()
5351 .map(|at| {
5352 (
5353 *at,
5354 body_cp_calibers(*at, false) - body_cp_calibers(*at, true),
5355 )
5356 })
5357 .collect();
5358 for (at, gap) in &gaps {
5359 assert!(
5360 *gap > 0.6,
5361 "Mach {at}: the fading rule sits {gap} calibers aft"
5362 );
5363 }
5364 for (at, want) in [(1.5, 1.35), (2.0, 0.91), (3.0, 0.75), (4.63, 0.67)] {
5366 let got = gaps
5367 .iter()
5368 .find(|(m, _)| (m - at).abs() < 1e-9)
5369 .expect("a measured gap")
5370 .1;
5371 assert!(
5372 (got - want).abs() < 0.02,
5373 "Mach {at}: the gap is {got} calibers, the guide says {want}"
5374 );
5375 }
5376 for angle in [15.9_f64, 16.0, 16.1] {
5381 let (below, above) = (kept(angle - 1e-6).0, kept(angle + 1e-6).0);
5382 assert!((above - below).abs() < 1e-6, "{angle}°: {below} to {above}");
5383 }
5384 assert!((at_16 - (0.027 - 0.022) / 16.0_f64.to_radians().tan()).abs() < 1e-15);
5385 }
5386
5387 #[test]
5392 fn holding_the_correlation_stops_at_potential_flow() {
5393 let (fore_radius_m, aft_radius_m, mach) = (0.027_f64, 0.05 * 0.027_f64, 1.42_f64);
5398 let slender = 2.0 * ((aft_radius_m / fore_radius_m).powi(2) - 1.0);
5399 let length_m = (fore_radius_m - aft_radius_m) / 30.0_f64.to_radians().tan();
5400 let mut rocket = finned_rocket(4);
5401 rocket.stages[0].components[2].part = body_part(length_m, fore_radius_m, aft_radius_m);
5402 rocket.stages[0].components[3].part = body_part(0.3, aft_radius_m, aft_radius_m);
5403 let steep = model(&rocket);
5404 let a_ref = steep.reference_area_m2();
5405 let per_boattail_area = PI * fore_radius_m * fore_radius_m / a_ref;
5406 let table = steep.supersonic_body().expect("the method covers it");
5407 assert!(
5410 mach > table.join_start_mach,
5411 "Mach {mach} is below the table's start, {}",
5412 table.join_start_mach
5413 );
5414 let cylinder = ShockExpansionBody::new(
5415 &[
5416 BodySegment::Profile {
5417 profile: match nose(NoseShape::Ogive { radius_ratio: 1.0 }, 0.25, 0.027) {
5418 Part::NoseCone(ogive) => ogive.profile().unwrap(),
5419 _ => unreachable!("`nose` builds a nose cone"),
5420 },
5421 },
5422 BodySegment::Cylinder {
5423 length_m: 0.7,
5424 radius_m: fore_radius_m,
5425 },
5426 BodySegment::Cylinder {
5427 length_m,
5428 radius_m: fore_radius_m,
5429 },
5430 ],
5431 DEFAULT_ELEMENTS_PER_CURVE,
5432 )
5433 .unwrap()
5434 .segment_slopes(mach, a_ref)
5435 .unwrap()[2]
5436 .slope_per_rad;
5437 let flown = table.share(2, mach).expect("the boattail's share").0 - cylinder;
5438 assert!(
5440 (flown / per_boattail_area - slender).abs() < 2e-3,
5441 "{} against potential flow's {slender}",
5442 flown / per_boattail_area
5443 );
5444 let held = crate::supersonic_boattail::wp_slope(
5445 mach,
5446 fore_radius_m,
5447 aft_radius_m,
5448 (fore_radius_m - aft_radius_m) / SEPARATION_ONSET_RAD.tan(),
5449 )
5450 .unwrap();
5451 assert!(
5452 held < slender - 0.05,
5453 "the held read {held} must pass the bound's {slender} to pin it"
5454 );
5455 let gentle_m = (fore_radius_m - 0.6 * fore_radius_m) / 4.0_f64.to_radians().tan();
5458 let gentle =
5459 crate::supersonic_boattail::wp_slope(1.5, fore_radius_m, 0.6 * fore_radius_m, gentle_m)
5460 .unwrap();
5461 let gentle_slender = 2.0 * (0.6_f64.powi(2) - 1.0);
5462 assert!(
5463 gentle < gentle_slender,
5464 "the 4° read {gentle} should pass {gentle_slender}"
5465 );
5466 let mut gentle_rocket = finned_rocket(4);
5467 gentle_rocket.stages[0].components[2].part =
5468 body_part(gentle_m, fore_radius_m, 0.6 * fore_radius_m);
5469 gentle_rocket.stages[0].components[3].part =
5470 body_part(0.3, 0.6 * fore_radius_m, 0.6 * fore_radius_m);
5471 let gentle_model = model(&gentle_rocket);
5472 let gentle_table = gentle_model.supersonic_body().expect("a table");
5473 let gentle_cylinder = ShockExpansionBody::new(
5474 &[
5475 BodySegment::Profile {
5476 profile: match nose(NoseShape::Ogive { radius_ratio: 1.0 }, 0.25, 0.027) {
5477 Part::NoseCone(ogive) => ogive.profile().unwrap(),
5478 _ => unreachable!("`nose` builds a nose cone"),
5479 },
5480 },
5481 BodySegment::Cylinder {
5482 length_m: 0.7,
5483 radius_m: fore_radius_m,
5484 },
5485 BodySegment::Cylinder {
5486 length_m: gentle_m,
5487 radius_m: fore_radius_m,
5488 },
5489 ],
5490 DEFAULT_ELEMENTS_PER_CURVE,
5491 )
5492 .unwrap()
5493 .segment_slopes(1.5, gentle_model.reference_area_m2())
5494 .unwrap()[2]
5495 .slope_per_rad;
5496 let gentle_flown = gentle_table.share(2, 1.5).expect("the share").0 - gentle_cylinder;
5497 let gentle_area = PI * fore_radius_m * fore_radius_m / gentle_model.reference_area_m2();
5498 assert!(
5499 (gentle_flown / gentle_area - gentle).abs() < 2e-3,
5500 "the 4° boattail flies {} and its correlation reads {gentle}",
5501 gentle_flown / gentle_area
5502 );
5503 }
5504
5505 #[test]
5513 fn what_the_potential_flow_bound_reaches() {
5514 let fore_radius_m = 0.027_f64;
5515 let ogive = nose(NoseShape::Ogive { radius_ratio: 1.0 }, 0.25, 0.027);
5516 let Part::NoseCone(ogive) = ogive else {
5517 unreachable!("`nose` builds a nose cone")
5518 };
5519 let mut worst = (0.0_f64, 0.0_f64, 0.0_f64, 0.0_f64);
5520 let mut steepest_tabled = 0.0_f64;
5521 let mut floor_angles: Vec<f64> = Vec::new();
5522 for angle_deg in [16.0_f64, 16.5, 17.0, 17.25, 17.5, 30.0, 53.0, 53.5, 53.6] {
5523 for ratio in [0.001_f64, 0.02, 0.25, 0.3] {
5524 let aft_radius_m = ratio * fore_radius_m;
5525 let drop_m = fore_radius_m - aft_radius_m;
5526 let length_m = drop_m / angle_deg.to_radians().tan();
5527 let held_length_m = drop_m / SEPARATION_ONSET_RAD.tan();
5528 let ceiling = 2.0 * (ratio * ratio - 1.0);
5529 let read = |mach: f64, length: f64| {
5530 crate::supersonic_boattail::wp_slope(mach, fore_radius_m, aft_radius_m, length)
5531 .unwrap()
5532 };
5533 if read(1.2, held_length_m) >= ceiling {
5536 continue;
5537 }
5538 let mut rocket = finned_rocket(4);
5539 rocket.stages[0].components[2].part =
5540 body_part(length_m, fore_radius_m, aft_radius_m);
5541 rocket.stages[0].components[3].part = body_part(0.3, aft_radius_m, aft_radius_m);
5542 let flown = model(&rocket);
5543 let Some(table) = flown.supersonic_body() else {
5544 continue;
5545 };
5546 steepest_tabled = steepest_tabled.max(angle_deg);
5547 let a_ref = flown.reference_area_m2();
5548 let per_area = PI * fore_radius_m * fore_radius_m / a_ref;
5549 let cylinder_body = ShockExpansionBody::new(
5552 &[
5553 BodySegment::Profile {
5554 profile: ogive.profile().unwrap(),
5555 },
5556 BodySegment::Cylinder {
5557 length_m: 0.7,
5558 radius_m: fore_radius_m,
5559 },
5560 BodySegment::Cylinder {
5561 length_m,
5562 radius_m: fore_radius_m,
5563 },
5564 ],
5565 DEFAULT_ELEMENTS_PER_CURVE,
5566 )
5567 .unwrap();
5568 let mut rows = vec![table.join_start_mach];
5573 let mut step = (table.join_start_mach * SUPERSONIC_STEPS_PER_MACH).ceil();
5574 while step / SUPERSONIC_STEPS_PER_MACH <= 1.55 {
5575 rows.push(step / SUPERSONIC_STEPS_PER_MACH);
5576 step += 1.0;
5577 }
5578 for mach in rows {
5579 let Some((share, _)) = table.share(2, mach) else {
5580 break;
5581 };
5582 let cylinder =
5583 cylinder_body.segment_slopes(mach, a_ref).unwrap()[2].slope_per_rad;
5584 let increment = (share - cylinder) / per_area;
5585 if read(mach, length_m) >= ceiling {
5586 assert!(
5590 increment >= ceiling - 1e-12,
5591 "{angle_deg}° to {ratio} of the radius at Mach {mach}: the boattail \
5592 takes {increment} off, past potential flow's {ceiling}"
5593 );
5594 } else {
5595 assert!(
5598 increment <= ceiling,
5599 "{angle_deg}° to {ratio} at Mach {mach}: {increment} against {ceiling}"
5600 );
5601 let published = read(mach, length_m);
5604 assert!(
5605 (increment - published).abs() < 1e-9,
5606 "{angle_deg}° to {ratio} at Mach {mach}: {increment} against the \
5607 correlation's own {published}"
5608 );
5609 if !floor_angles.contains(&angle_deg) {
5610 floor_angles.push(angle_deg);
5611 }
5612 }
5613 let moved = (increment - read(mach, held_length_m)).abs()
5615 * per_area
5616 * table.weight(mach);
5617 if moved > worst.0 {
5618 worst = (moved, angle_deg, ratio, mach);
5619 }
5620 }
5621 }
5622 }
5623 assert_eq!(
5627 floor_angles,
5628 [16.0, 16.5, 17.0, 17.25],
5629 "the swept angles where a boattail's own read already passes potential flow"
5630 );
5631 assert!(
5634 (steepest_tabled - 53.5).abs() < 1e-12,
5635 "the steepest boattail swept that the method tables is {steepest_tabled}°"
5636 );
5637 assert!(
5638 (worst.0 - 0.060).abs() < 5e-4,
5639 "the bound moves a printed coefficient by at most {:.4} per rad, at {}° to {} of the \
5640 radius at Mach {:.3}",
5641 worst.0,
5642 worst.1,
5643 worst.2,
5644 worst.3
5645 );
5646 }
5647
5648 #[test]
5660 fn footnote_eights_boattail_share_by_hand() {
5661 let a_ref = PI * 0.027 * 0.027;
5662 let ogive = nose(NoseShape::Ogive { radius_ratio: 1.0 }, 0.25, 0.027);
5663 let Part::NoseCone(ogive) = ogive else {
5664 unreachable!("`nose` builds a nose cone")
5665 };
5666 let (length_m, fore_radius_m, aft_radius_m) = (0.05, 0.027, 0.022);
5667 const TUBE_LENGTH_M: f64 = 0.2;
5668 let body = ShockExpansionBody::new(
5669 &[
5670 BodySegment::Profile {
5671 profile: ogive.profile().unwrap(),
5672 },
5673 BodySegment::Cylinder {
5674 length_m: 0.7,
5675 radius_m: 0.027,
5676 },
5677 BodySegment::Profile {
5678 profile: hpr_design::Profile::transition(
5679 NoseShape::Conical {},
5680 length_m,
5681 fore_radius_m,
5682 aft_radius_m,
5683 false,
5684 )
5685 .unwrap(),
5686 },
5687 BodySegment::Cylinder {
5688 length_m: TUBE_LENGTH_M,
5689 radius_m: aft_radius_m,
5690 },
5691 ],
5692 DEFAULT_ELEMENTS_PER_CURVE,
5693 )
5694 .unwrap();
5695 let mach = 2.0;
5696 let shares = body.segment_slopes(mach, a_ref).unwrap();
5697 let flows = body.element_flows(mach).unwrap();
5700 let boattail = flows
5701 .iter()
5702 .rev()
5703 .nth(1)
5704 .copied()
5705 .expect("the boattail's element");
5706 let (load, decay) = (boattail.loading_per_rad, boattail.decay_per_m);
5707 assert!((boattail.corner_radius_m - fore_radius_m).abs() < 1e-12);
5709 let delta = ((aft_radius_m - fore_radius_m) / length_m).atan();
5712 let cone_load = delta.tan() * 2.0;
5713 assert!((boattail.tangent_cone_loading_per_rad - cone_load).abs() < 1e-12);
5714 assert!((boattail.tangent_cone_pressure_ratio - 1.0).abs() < 1e-12);
5715 let integrate = |span_m: f64, fore_r: f64, aft_r: f64, load: f64, cone: f64, decay: f64| {
5717 let steps = 4000;
5718 let mut sum = 0.0;
5719 for i in 0..=steps {
5720 let t = f64::from(i) / f64::from(steps);
5721 let x = t * span_m;
5722 let r = fore_r + (aft_r - fore_r) * t;
5723 let e = (-decay * x).exp();
5724 let lambda = (1.0 - e) * cone + e * load;
5725 let weight = if i == 0 || i == steps {
5726 1.0
5727 } else if i % 2 == 1 {
5728 4.0
5729 } else {
5730 2.0
5731 };
5732 sum += weight * lambda * r;
5733 }
5734 2.0 * PI * (sum * span_m / (3.0 * f64::from(steps))) / a_ref
5735 };
5736 let by_hand = integrate(
5737 length_m,
5738 fore_radius_m,
5739 aft_radius_m,
5740 load,
5741 cone_load,
5742 decay,
5743 );
5744 assert!(
5745 (shares[2].slope_per_rad - by_hand).abs() < 1e-6,
5746 "{} against {by_hand}",
5747 shares[2].slope_per_rad
5748 );
5749 let tube = flows.last().expect("the tube's element");
5752 assert!(tube.angle_rad.abs() < 1e-12 && tube.tangent_cone_loading_per_rad.abs() < 1e-12);
5753 let tube_by_hand = integrate(
5754 TUBE_LENGTH_M,
5755 aft_radius_m,
5756 aft_radius_m,
5757 tube.loading_per_rad,
5758 0.0,
5759 tube.decay_per_m,
5760 );
5761 assert!(
5762 (shares[3].slope_per_rad - tube_by_hand).abs() < 1e-6,
5763 "the tube: {} against {tube_by_hand}",
5764 shares[3].slope_per_rad
5765 );
5766 assert!(
5768 tube_by_hand < by_hand && tube_by_hand < 0.0,
5769 "the tube's {tube_by_hand} against the boattail's {by_hand}"
5770 );
5771 let slender = 2.0 * (aft_radius_m.powi(2) - fore_radius_m.powi(2)) / (0.027 * 0.027);
5774 assert!(
5775 by_hand < 0.0 && by_hand / slender < 0.2,
5776 "{by_hand} against slender-body theory's {slender}"
5777 );
5778 }
5779
5780 #[test]
5784 fn the_boattail_takes_washington_and_pettis_increment() {
5785 let layout = finned_rocket(4).layout().unwrap();
5786 let current = AeroModel::new(&layout).unwrap();
5787 let before = AeroModel::with_body_model(&layout, BodyModel::BEFORE_M1_8E6).unwrap();
5788 let a_ref = current.reference_area_m2();
5789 let ogive = nose(NoseShape::Ogive { radius_ratio: 1.0 }, 0.25, 0.027);
5790 let Part::NoseCone(ogive) = ogive else {
5791 unreachable!("`nose` builds a nose cone")
5792 };
5793 let segments = |last: BodySegment| {
5794 [
5795 BodySegment::Profile {
5796 profile: ogive.profile().unwrap(),
5797 },
5798 BodySegment::Cylinder {
5799 length_m: 0.7,
5800 radius_m: 0.027,
5801 },
5802 last,
5803 ]
5804 };
5805 let in_its_place = ShockExpansionBody::new(
5806 &segments(BodySegment::Cylinder {
5807 length_m: 0.05,
5808 radius_m: 0.027,
5809 }),
5810 DEFAULT_ELEMENTS_PER_CURVE,
5811 )
5812 .unwrap();
5813 let rocket = finned_rocket(4);
5814 let Part::Transition(tail) = &rocket.stages[0].components[2].part else {
5815 unreachable!("the test rocket's third part is its boattail")
5816 };
5817 let with_boattail = ShockExpansionBody::new(
5818 &segments(BodySegment::Profile {
5819 profile: tail.profile().unwrap(),
5820 }),
5821 DEFAULT_ELEMENTS_PER_CURVE,
5822 )
5823 .unwrap();
5824 for mach in [2.0, 3.0, 4.5] {
5825 let cylinder = in_its_place.segment_slopes(mach, a_ref).unwrap()[2];
5826 let increment = crate::supersonic_boattail::wp_slope(mach, 0.027, 0.022, 0.05).unwrap()
5827 * PI
5828 * 0.027
5829 * 0.027
5830 / a_ref;
5831 let center = 0.25 + 0.7 + wp_center_fraction(mach) * 0.05;
5832 let (slope, moment) = current.supersonic_body().unwrap().share(2, mach).unwrap();
5833 close(
5834 slope,
5835 cylinder.slope_per_rad + increment,
5836 1e-12,
5837 "W&P slope",
5838 );
5839 close(
5840 moment,
5841 cylinder.moment_slope_m + increment * center,
5842 1e-12,
5843 "W&P moment",
5844 );
5845 assert!(increment < 0.0 && cylinder.slope_per_rad.abs() < 0.1 * increment.abs());
5847 let footnote_8 = with_boattail.segment_slopes(mach, a_ref).unwrap()[2];
5848 let (old, _) = before.supersonic_body().unwrap().share(2, mach).unwrap();
5849 close(old, footnote_8.slope_per_rad, 1e-12, "footnote 8");
5850 let slender = -2.0 * (1.0 - (0.022_f64 / 0.027).powi(2));
5853 assert!(slender < slope && slope < old, "Mach {mach}: {slope} {old}");
5854 }
5855 }
5856
5857 #[test]
5862 fn two_boattails_each_take_their_own_increment() {
5863 let (l_n, l_1, l_b1, l_2, l_b2) = (0.25, 0.4, 0.05, 0.3, 0.04);
5864 let (r_0, r_1, r_2) = (0.027, 0.024, 0.02);
5865 let rocket = one_stage(
5866 vec![
5867 component(
5868 "nose",
5869 nose(NoseShape::Ogive { radius_ratio: 1.0 }, l_n, r_0),
5870 None,
5871 ),
5872 component("tube", body_part(l_1, r_0, r_0), None),
5873 component("boattail", body_part(l_b1, r_0, r_1), None),
5874 component("waist", body_part(l_2, r_1, r_1), None),
5875 component("tail", body_part(l_b2, r_1, r_2), None),
5876 ],
5877 ReferenceDiameter::Maximum {},
5878 );
5879 let model = AeroModel::new(&rocket.layout().unwrap()).unwrap();
5880 let before =
5881 AeroModel::with_body_model(&rocket.layout().unwrap(), BodyModel::BEFORE_M1_8E6)
5882 .unwrap();
5883 let table = model.supersonic_body().unwrap();
5884 assert_eq!(table.covered, 5);
5885 let a_ref = model.reference_area_m2();
5886 let profile = |part: &Part| match part {
5887 Part::NoseCone(n) => n.profile().unwrap(),
5888 Part::Transition(t) => t.profile().unwrap(),
5889 _ => unreachable!("the test's profiled parts are a nose and transitions"),
5890 };
5891 let parts: Vec<Part> = rocket.stages[0]
5892 .components
5893 .iter()
5894 .map(|c| c.part.clone())
5895 .collect();
5896 let cylinder = |length_m, radius_m| BodySegment::Cylinder { length_m, radius_m };
5897 let profiled = |i: usize| BodySegment::Profile {
5898 profile: profile(&parts[i]),
5899 };
5900 let body = |segments: &[BodySegment]| {
5901 ShockExpansionBody::new(segments, DEFAULT_ELEMENTS_PER_CURVE).unwrap()
5902 };
5903 let whole = body(&[
5904 profiled(0),
5905 cylinder(l_1, r_0),
5906 profiled(2),
5907 cylinder(l_2, r_1),
5908 profiled(4),
5909 ]);
5910 let first_in_place = body(&[profiled(0), cylinder(l_1, r_0), cylinder(l_b1, r_0)]);
5911 let second_in_place = body(&[
5912 profiled(0),
5913 cylinder(l_1, r_0),
5914 profiled(2),
5915 cylinder(l_2, r_1),
5916 cylinder(l_b2, r_1),
5917 ]);
5918 let increment = |mach: f64, fore: f64, aft: f64, length: f64| {
5919 crate::supersonic_boattail::wp_slope(mach, fore, aft, length).unwrap()
5920 * PI
5921 * fore
5922 * fore
5923 / a_ref
5924 };
5925 for mach in [2.0, 3.5] {
5926 let method = whole.segment_slopes(mach, a_ref).unwrap();
5927 let share = |i| table.share(i, mach).unwrap().0;
5928 for i in [0, 1, 3] {
5929 close(
5930 share(i),
5931 method[i].slope_per_rad,
5932 1e-12,
5933 "the method's share",
5934 );
5935 }
5936 let first = first_in_place.segment_slopes(mach, a_ref).unwrap()[2].slope_per_rad
5937 + increment(mach, r_0, r_1, l_b1);
5938 let second = second_in_place.segment_slopes(mach, a_ref).unwrap()[4].slope_per_rad
5939 + increment(mach, r_1, r_2, l_b2);
5940 close(share(2), first, 1e-12, "first boattail");
5941 close(share(4), second, 1e-12, "second boattail");
5942 let old = before.supersonic_body().unwrap();
5944 close(
5945 old.share(2, mach).unwrap().0,
5946 method[2].slope_per_rad,
5947 1e-12,
5948 "fn 8",
5949 );
5950 close(
5951 old.share(4, mach).unwrap().0,
5952 method[4].slope_per_rad,
5953 1e-12,
5954 "fn 8",
5955 );
5956 assert!(share(2) < method[2].slope_per_rad && share(4) < method[4].slope_per_rad);
5957 }
5958 }
5959
5960 #[test]
5961 fn a_boattailed_body_flies_the_method_without_a_jump() {
5962 let model = model(&finned_rocket(4));
5965 let join = model.supersonic_body().unwrap();
5966 assert_eq!(join.covered, 4);
5967 let start = join.join_start_mach;
5968 for mach in [
5969 start,
5970 start + SUPERSONIC_JOIN_WIDTH_MACH,
5971 1.35,
5972 2.0,
5973 2.05,
5974 3.0,
5975 4.63,
5976 4.95,
5977 4.999,
5978 ] {
5979 no_jump(&model, mach);
5980 }
5981 let (low, high) = (body_values(&model, 1.0), body_values(&model, 2.0));
5982 let (boattail, share) = (&model.bodies()[2], join.share(2, 2.0).unwrap());
5983 assert!(boattail.slope_per_rad < 0.0 && share.0 < 0.0, "{share:?}");
5984 assert!(
5986 (high[2][0] - share.0).abs() <= 1e-12 * share.0.abs(),
5987 "{share:?}"
5988 );
5989 assert_eq!(low[2][2], high[2][2]);
5992 assert!((0.95..=1.0).contains(&high[2][2]), "{:?}", high[2]);
5993 assert!(high[3][0] < 0.0, "{:?}", high[3]);
5994 for mach in [1.2, 1.3, 1.5, 3.0, 4.999] {
5995 let at = body_values(&model, mach);
5996 assert_eq!((at[2][2], at[3][2]), (low[2][2], low[3][2]), "Mach {mach}");
5997 }
5998 assert!((1.0..=1.3).contains(&low[3][2]), "{:?}", low[3]);
5999 assert_eq!(low[1][0], 0.0);
6001 assert!(high[1][0] > 0.1, "{:?}", high[1]);
6002 }
6003
6004 #[test]
6005 fn a_blunter_cone_joins_where_the_method_starts_to_hold() {
6006 let mut rocket = straight_rocket();
6009 let length = 0.027 / 20.0_f64.to_radians().tan();
6010 rocket.stages[0].components[0].part = nose(NoseShape::Conical {}, length, 0.027);
6011 let model = model(&rocket);
6012 let join = model.supersonic_body().unwrap();
6013 let start = join.join_start_mach;
6014 assert!(start > SUPERSONIC_JOIN_START_MACH, "{start}");
6015 for mach in [start, start + SUPERSONIC_JOIN_WIDTH_MACH, start + 0.5] {
6016 no_jump(&model, mach);
6017 }
6018 assert_eq!(body_values(&model, start), body_values(&model, 0.5));
6020 }
6021
6022 #[test]
6023 fn the_joins_start_moves_with_the_nose_not_in_steps() {
6024 let start_at = |degrees: f64| {
6027 let mut rocket = straight_rocket();
6028 let length = 0.027 / degrees.to_radians().tan();
6029 rocket.stages[0].components[0].part = nose(NoseShape::Conical {}, length, 0.027);
6030 let model = model(&rocket);
6031 let start = model.supersonic_body().unwrap().join_start_mach;
6032 (model, start)
6033 };
6034 let (model, start) = start_at(20.0);
6035 let grid = start * SUPERSONIC_STEPS_PER_MACH;
6036 assert!((grid - grid.round()).abs() > 1e-3, "on the grid: {start}");
6037 let first_row = grid.ceil() / SUPERSONIC_STEPS_PER_MACH;
6039 for mach in [start, first_row, start + SUPERSONIC_JOIN_WIDTH_MACH] {
6040 no_jump(&model, mach);
6041 }
6042 assert_eq!(body_values(&model, start), body_values(&model, 0.5));
6043 assert!((start - 1.341910).abs() < 1e-6, "{start}");
6045 let join = model.supersonic_body().unwrap();
6050 let (lead, row) = (
6051 join.share(1, start).unwrap(),
6052 join.share(1, first_row).unwrap(),
6053 );
6054 assert!(lead.0 < 1e-5 && row.0 > 0.3, "{lead:?} against {row:?}");
6055 let (_, nudged) = start_at(20.0 + 1e-6);
6057 assert!((nudged - start).abs() < 1e-7, "{start} to {nudged}");
6058 let starts: Vec<f64> = [20.0, 20.1, 20.2, 20.3, 20.4, 20.5]
6060 .into_iter()
6061 .map(|degrees| start_at(degrees).1)
6062 .collect();
6063 assert!((starts[5] - 1.355500).abs() < 1e-6, "{starts:?}");
6064 for pair in starts.windows(2) {
6065 assert!(pair[1] > pair[0] && pair[1] - pair[0] < 0.02, "{starts:?}");
6066 }
6067 }
6068
6069 #[test]
6070 fn below_the_join_the_bodies_keep_slender_body_terms() {
6071 let model = model(&straight_rocket());
6072 let slender: Vec<[f64; 3]> = model
6073 .bodies()
6074 .iter()
6075 .enumerate()
6076 .map(|(index, body)| {
6077 [
6078 body.slope_per_rad,
6079 body.moment_slope_m,
6080 model.component_station_m(index, 0.0).unwrap(),
6081 ]
6082 })
6083 .collect();
6084 for mach in [0.0, 0.5, 0.99, 1.1, SUPERSONIC_JOIN_START_MACH] {
6085 let got = body_values(&model, mach);
6086 for (index, (g, want)) in got.iter().zip(&slender).enumerate() {
6087 assert_eq!(g[0], want[0], "body {index} at Mach {mach}");
6088 assert_eq!(g[2], want[2], "body {index} at Mach {mach}");
6089 if want[0] != 0.0 {
6090 close(g[1], want[1], 1e-14, "moment");
6091 }
6092 }
6093 }
6094 }
6095
6096 #[test]
6097 fn past_the_join_the_covered_bodies_take_the_method() {
6098 let model = model(&straight_rocket());
6099 let area = model.reference_area_m2();
6100 let body = straight_rocket_body();
6101 let join_end = SUPERSONIC_JOIN_START_MACH + SUPERSONIC_JOIN_WIDTH_MACH;
6102 for (mach, rel) in [
6104 (1.5, 1e-12),
6105 (2.0, 1e-12),
6106 (3.0, 1e-12),
6107 (4.95, 1e-12),
6108 (2.96, 1e-3),
6109 ] {
6110 assert!(mach >= join_end);
6111 let want = body.slope(mach, area).unwrap();
6112 let values = body_values(&model, mach);
6113 let slope: f64 = values.iter().map(|v| v[0]).sum();
6114 let moment: f64 = values.iter().map(|v| v[1]).sum();
6115 close(slope, want.slope_per_rad, rel, "slope");
6116 close(
6117 moment / slope,
6118 want.center_of_pressure_m,
6119 rel,
6120 "center of pressure",
6121 );
6122 let bounds = [(0.0, 0.25), (0.25, 0.95), (0.95, 1.0), (1.0, 1.3)];
6124 for (v, (fore, aft)) in values.iter().zip(bounds) {
6125 assert!(v[2] > fore && v[2] < aft, "{v:?} not in {fore} to {aft}");
6126 }
6127 }
6128 }
6129
6130 fn flared_rocket(flare_deg: f64) -> hpr_design::Rocket {
6133 let (fore_r, flare_l) = (0.027, 0.3);
6134 let aft_r = fore_r + flare_l * flare_deg.to_radians().tan();
6135 let mut tail = component("tail", body_part(0.2, aft_r, aft_r), None);
6136 tail.children = vec![component(
6137 "fins",
6138 fin_set(
6139 4,
6140 FinPlanform::Trapezoidal {
6141 root_chord_m: 0.12,
6142 tip_chord_m: 0.05,
6143 span_m: 0.06,
6144 sweep_m: 0.07,
6145 },
6146 ),
6147 Some(Position::Bottom { aft_offset_m: 0.0 }),
6148 )];
6149 one_stage(
6150 vec![
6151 component(
6152 "nose",
6153 nose(NoseShape::Ogive { radius_ratio: 1.0 }, 0.25, fore_r),
6154 None,
6155 ),
6156 component("body", body_part(0.7, fore_r, fore_r), None),
6157 component("flare", body_part(flare_l, fore_r, aft_r), None),
6158 tail,
6159 ],
6160 ReferenceDiameter::Maximum {},
6161 )
6162 }
6163
6164 fn flared_at(rocket: &hpr_design::Rocket, mach: f64) -> (f64, f64) {
6167 let model = model(rocket);
6168 let force = model.normal_force(&flow(mach, 1e-4, 0.0)).unwrap();
6169 (force.coefficient / 1e-4, force.cp_station_m.unwrap())
6170 }
6171
6172 fn flared_run(rocket: &hpr_design::Rocket) -> ShockExpansionBody {
6175 let model = model(rocket);
6176 let run = model.supersonic_run.as_ref().expect("a run with a flare");
6177 let flare = run.flare.as_ref().expect("the flare in the run");
6178 ShockExpansionBody::new(&flare.ahead, DEFAULT_ELEMENTS_PER_CURVE).unwrap()
6179 }
6180
6181 fn corner_limit_deg(ahead: &ShockExpansionBody, mach: f64) -> f64 {
6185 let aft = ahead.aft_flow(mach).unwrap();
6186 (crate::shock_expansion::flare_corner_limit_rad(aft.surface_mach).unwrap() + aft.angle_rad)
6187 .min(crate::blunt_tip::CONE_TABLE_CAP_RAD)
6188 .to_degrees()
6189 }
6190
6191 #[test]
6196 fn a_flared_body_flies_the_method() {
6197 let rocket = flared_rocket(10.0);
6198 let model = model(&rocket);
6199 let body = model
6200 .supersonic_body()
6201 .expect("the method covers the flare");
6202 assert_eq!(body.covered, 3);
6205 let old = AeroModel::with_body_model(
6206 &rocket.layout().unwrap(),
6207 BodyModel::CURRENT.with_supersonic_flare(SupersonicFlare::SlenderBody),
6208 )
6209 .unwrap();
6210 assert!(old.supersonic_body().is_none());
6211 for mach in [2.0, 3.0, 4.95] {
6213 let (slope, moment) = body.share(2, mach).unwrap();
6214 assert!(slope > 0.0, "the flare's share at Mach {mach} is {slope}");
6215 let station = moment / slope;
6216 assert!(
6217 (0.95..=1.25).contains(&station),
6218 "the flare's share acts at {station} m at Mach {mach}"
6219 );
6220 }
6221 let diameter_m = model.reference_diameter_m();
6225 assert!((diameter_m - 0.159_796).abs() < 5e-7, "{diameter_m} m");
6226 for (mach, want_slope, want_calibers, want_old_slope, want_forward) in [
6227 (2.0, 3.537_087_3, 7.365_003, 3.715_259_2, 0.089_048),
6228 (3.0, 2.889_886_8, 7.014_772, 3.081_544_6, 0.168_593),
6229 (4.95, 2.488_028_5, 6.680_843, 2.643_091_4, 0.237_654),
6230 ] {
6231 let (slope, station_m) = flared_at(&rocket, mach);
6232 let old = old.normal_force(&flow(mach, 1e-4, 0.0)).unwrap();
6233 let forward = (old.cp_station_m.unwrap() - station_m) / diameter_m;
6234 assert!(
6235 (slope - want_slope).abs() < 5e-7
6236 && (station_m / diameter_m - want_calibers).abs() < 5e-6,
6237 "Mach {mach}: {slope} per rad at {} calibers",
6238 station_m / diameter_m
6239 );
6240 assert!(
6241 (old.coefficient / 1e-4 - want_old_slope).abs() < 5e-7
6242 && (forward - want_forward).abs() < 5e-6,
6243 "Mach {mach} on slender-body theory: {} per rad, the method {forward} calibers \
6244 forward",
6245 old.coefficient / 1e-4
6246 );
6247 }
6248 }
6249
6250 #[test]
6258 fn a_flare_is_read_no_steeper_than_its_corners_shock_holds() {
6259 let ahead = flared_run(&flared_rocket(18.5));
6260 for (mach, want_surface_mach, want_limit_deg) in [
6261 (1.5, 1.499_968_751_529, 12.111_850_220_062),
6262 (2.0, 1.999_780_928_628, 22.969_761_173_077),
6263 (2.5, 2.498_954_764_087, 29.786_310_648_004),
6264 (3.0, 2.996_526_706_276, 30.0),
6266 (4.95, 4.892_298_698_955, 30.0),
6267 ] {
6268 let aft = ahead.aft_flow(mach).unwrap();
6269 assert!(
6270 (aft.surface_mach - want_surface_mach).abs() < 5e-10 && aft.angle_rad == 0.0,
6271 "Mach {mach}: the corner turns Mach {} at {} rad",
6272 aft.surface_mach,
6273 aft.angle_rad
6274 );
6275 let limit = corner_limit_deg(&ahead, mach);
6276 assert!(
6277 (limit - want_limit_deg).abs() < 5e-10,
6278 "Mach {mach}: the corner is read to {limit}°"
6279 );
6280 }
6281 let steep = model(&flared_rocket(30.0));
6283 let run = steep.supersonic_run.as_ref().unwrap();
6284 let flare = run.flare.as_ref().unwrap();
6285 let rise_m = flare.aft_radius_m - flare.fore_radius_m;
6286 let drawn_length_m = rise_m / corner_limit_deg(&ahead, 2.0).to_radians().tan();
6287 assert!(drawn_length_m > flare.length_m);
6288 let mut segments = flare.ahead.clone();
6289 segments.push(BodySegment::Profile {
6290 profile: hpr_design::Profile::transition(
6291 NoseShape::Conical {},
6292 drawn_length_m,
6293 flare.fore_radius_m,
6294 flare.aft_radius_m,
6295 false,
6296 )
6297 .unwrap(),
6298 });
6299 let drawn = ShockExpansionBody::new(&segments, DEFAULT_ELEMENTS_PER_CURVE).unwrap();
6300 let area = steep.reference_area_m2();
6301 let want = *drawn.segment_slopes(2.0, area).unwrap().last().unwrap();
6302 let body = steep.supersonic_body().unwrap();
6303 let (slope, moment) = body.share(2, 2.0).unwrap();
6304 assert!(
6305 (slope - want.slope_per_rad).abs() < 1e-12 * want.slope_per_rad,
6306 "the held share is {slope}, the drawn-out flare's {}",
6307 want.slope_per_rad
6308 );
6309 let (fore_m, aft_m) = (run.fore_m[2], run.fore_m[2] + flare.length_m);
6313 let drawn_station_m = want.moment_slope_m / want.slope_per_rad;
6314 let station_m = moment / slope;
6315 assert!(
6316 station_m > fore_m && station_m < aft_m,
6317 "the held share acts at {station_m}, off the flare's {fore_m} to {aft_m}"
6318 );
6319 assert!(
6322 (drawn_station_m - 1.207_758).abs() < 5e-6 && station_m < drawn_station_m - 0.05,
6323 "the drawn-out share acts at {drawn_station_m}, the mapped one at {station_m}"
6324 );
6325 let at = |deg: f64| {
6330 let rocket = flared_rocket(deg);
6331 let new = model(&rocket).normal_force(&flow(2.0, 1e-4, 0.0)).unwrap();
6332 let old = AeroModel::with_body_model(
6333 &rocket.layout().unwrap(),
6334 BodyModel::CURRENT.with_supersonic_flare(SupersonicFlare::SlenderBody),
6335 )
6336 .unwrap()
6337 .normal_force(&flow(2.0, 1e-4, 0.0))
6338 .unwrap();
6339 (new.coefficient / 1e-4, old.coefficient / 1e-4)
6340 };
6341 for (deg, want_method, want_slender) in
6342 [(30.0, 1.946_513, 2.307_693), (75.0, 1.637_856, 2.010_350)]
6343 {
6344 let (method, slender) = at(deg);
6345 assert!(
6346 (method - want_method).abs() < 5e-6 && (slender - want_slender).abs() < 5e-6,
6347 "{deg}°: the method reads {method}, slender-body theory {slender}"
6348 );
6349 assert!(
6350 method < slender,
6351 "{deg}° should read below slender-body theory"
6352 );
6353 }
6354 let at_limit = model(&flared_rocket(corner_limit_deg(&ahead, 2.0)));
6357 let limit_run = at_limit.supersonic_run.as_ref().unwrap();
6358 let limit_body =
6359 ShockExpansionBody::new(&limit_run.segments, DEFAULT_ELEMENTS_PER_CURVE).unwrap();
6360 let marched = *limit_body
6361 .segment_slopes(2.0, at_limit.reference_area_m2())
6362 .unwrap()
6363 .last()
6364 .unwrap();
6365 let (limit_slope, limit_moment) =
6366 at_limit.supersonic_body().unwrap().share(2, 2.0).unwrap();
6367 assert!(
6368 (limit_slope - marched.slope_per_rad).abs() < 1e-12 * marched.slope_per_rad
6369 && (limit_moment - marched.moment_slope_m).abs() < 1e-12 * marched.moment_slope_m,
6370 "at the limit the reading is {limit_slope} at {}, the march's {} at {}",
6371 limit_moment / limit_slope,
6372 marched.slope_per_rad,
6373 marched.moment_slope_m / marched.slope_per_rad
6374 );
6375 }
6376
6377 #[test]
6386 fn nothing_jumps_where_the_flares_shock_detaches() {
6387 let ahead = flared_run(&flared_rocket(18.5));
6390 let boundary_deg = corner_limit_deg(&ahead, 2.0);
6391 assert!((boundary_deg - 22.969_761_173_077).abs() < 5e-12);
6392 for (epsilon, want) in [(1e-9, 4.527e-11), (1e-7, 4.527e-9), (1e-5, 4.527e-7)] {
6393 let below = flared_at(&flared_rocket(boundary_deg - epsilon), 2.0);
6394 let above = flared_at(&flared_rocket(boundary_deg + epsilon), 2.0);
6395 let gap = (above.0 / below.0 - 1.0).abs();
6396 assert!(
6397 (gap - want).abs() < 0.01 * want,
6398 "±{epsilon}° across the boundary moves the slope by {gap}, not {want}"
6399 );
6400 assert!(
6401 (above.1 - below.1).abs() < 2e-3 * epsilon,
6402 "the station moves"
6403 );
6404 }
6405 let rocket = flared_rocket(18.5);
6414 let model = model(&rocket);
6415 let run = model.supersonic_run.as_ref().expect("a run with a flare");
6416 let body = ShockExpansionBody::new(&run.segments, DEFAULT_ELEMENTS_PER_CURVE).unwrap();
6417 let in_its_place: Vec<Option<ShockExpansionBody>> =
6418 run.segments.iter().map(|_| None).collect();
6419 let area = model.reference_area_m2();
6420 let (mut low, mut high) = (1.2_f64, 5.0_f64);
6421 for _ in 0..80 {
6422 let mid = 0.5 * (low + high);
6423 if corner_limit_deg(&ahead, mid) < 18.5 {
6424 low = mid;
6425 } else {
6426 high = mid;
6427 }
6428 }
6429 assert!(
6430 (high - 1.767_666_917_849).abs() < 5e-12,
6431 "18.5° attaches from Mach {high}"
6432 );
6433 assert!(corner_limit_deg(&ahead, high - 1e-9) < 18.5);
6436 assert!(corner_limit_deg(&ahead, high + 1e-9) > 18.5);
6437 let flare_share = |mach: f64| {
6438 let shares = run
6439 .shares(&body, &in_its_place, Some(&ahead), mach, area)
6440 .expect("the row holds either side of the crossing");
6441 shares[2]
6442 };
6443 for (epsilon, want) in [(1e-9, 3.622e-10), (1e-7, 3.622e-8), (1e-5, 3.622e-6)] {
6444 let (below, above) = (flare_share(high - epsilon), flare_share(high + epsilon));
6445 let gap = (above.slope_per_rad / below.slope_per_rad - 1.0).abs();
6446 assert!(
6447 (gap - want).abs() < 0.01 * want,
6448 "±{epsilon} in Mach across the boundary moves the flare's share by {gap}, not \
6449 {want}"
6450 );
6451 let station = |s: SegmentSlope| s.moment_slope_m / s.slope_per_rad;
6453 assert!(
6454 (station(above) - station(below)).abs() < 0.1 * epsilon
6455 && (0.95..=1.25).contains(&station(below)),
6456 "the flare's share acts at {} then {}",
6457 station(below),
6458 station(above)
6459 );
6460 }
6461 for epsilon in [1e-9, 1e-7, 1e-5] {
6463 let below = flared_at(&rocket, high - epsilon);
6464 let above = flared_at(&rocket, high + epsilon);
6465 assert!(
6466 (above.0 / below.0 - 1.0).abs() < 2.0 * epsilon,
6467 "±{epsilon} in Mach moves the rocket's slope by {}",
6468 above.0 / below.0 - 1.0
6469 );
6470 }
6471 }
6472
6473 #[test]
6494 fn a_near_flat_flare_marches_every_row_and_the_fallback_is_still_measured() {
6495 let ahead = flared_run(&flared_rocket(1.0));
6498 let at_mach_3 =
6499 crate::shock_expansion::flare_reduction_turns_rad(&ahead.aft_flow(3.0).unwrap())
6500 .unwrap();
6501 let reduced_at_mach_3 =
6502 at_mach_3.crossing_rad.to_degrees()..at_mach_3.balance_rad.to_degrees();
6503 assert!(
6504 reduced_at_mach_3.contains(&0.007) && reduced_at_mach_3.contains(&0.008),
6505 "Mach 3 reduces {reduced_at_mach_3:?}, which was meant to hold 0.007° and 0.008°"
6506 );
6507 for deg in [0.001, 0.007, 0.008, 0.01, 0.03, 0.038_17, 0.045, 0.0589] {
6508 let model = model(&flared_rocket(deg));
6509 let run = model.supersonic_run.as_ref().expect("a run with a flare");
6510 let body = ShockExpansionBody::new(&run.segments, DEFAULT_ELEMENTS_PER_CURVE).unwrap();
6511 let area = model.reference_area_m2();
6512 let refused = (SUPERSONIC_FIRST_STEP..=SUPERSONIC_LAST_STEP).find(|step| {
6513 body.slope(*step as f64 / SUPERSONIC_STEPS_PER_MACH, area)
6514 .is_err()
6515 });
6516 assert_eq!(
6517 refused,
6518 None,
6519 "a {deg}° flare loses Mach {:?}",
6520 refused.map(|step| step as f64 / SUPERSONIC_STEPS_PER_MACH)
6521 );
6522 let flows = body.element_flows(3.0).unwrap();
6525 assert_eq!(
6526 flows[flows.len() - 1].decay_per_m == 0.0,
6527 reduced_at_mach_3.contains(°),
6528 "a {deg}° flare at Mach 3, where the region is {reduced_at_mach_3:?}"
6529 );
6530 }
6531 let dropped = |deg: f64, mach: f64| {
6534 let rocket = flared_rocket(deg);
6535 let layout = rocket.layout().unwrap();
6536 let read = |model: AeroModel| {
6537 let force = model
6538 .normal_force(&flow(mach, 4f64.to_radians(), 0.0))
6539 .unwrap();
6540 (
6541 force.coefficient,
6542 force.cp_station_m.unwrap() / model.reference_diameter_m(),
6543 )
6544 };
6545 let method = read(AeroModel::new(&layout).unwrap());
6546 let bare = read(
6547 AeroModel::with_body_model(
6548 &layout,
6549 BodyModel::CURRENT.with_supersonic_flare(SupersonicFlare::SlenderBody),
6550 )
6551 .unwrap(),
6552 );
6553 (bare.0 / method.0 - 1.0, bare.1 - method.1)
6554 };
6555 let (force, calibers) = dropped(0.058_820_517_4, 3.0);
6556 assert!(
6557 (force + 0.083_0).abs() < 5e-5 && (calibers - 1.157_4).abs() < 5e-5,
6558 "at the band's steep edge the fallback moves the force {force:.4} and the center of \
6559 pressure {calibers:.4} calibers"
6560 );
6561 let (force, calibers) = dropped(9.018_246_55e-4, 2.0);
6562 assert!(
6563 (force + 0.046_2).abs() < 5e-4 && (calibers - 0.752_2).abs() < 5e-4,
6564 "at the join's shallowest step the fallback moves the force {force:.4} and the center \
6565 of pressure {calibers:.4} calibers"
6566 );
6567 }
6568
6569 #[test]
6573 fn where_the_corners_turn_runs_out_the_join_carries_the_reading() {
6574 let model = model(&flared_rocket(18.5));
6575 let body = model.supersonic_body().unwrap();
6576 assert!(
6577 (body.join_start_mach - 1.555_220_046_128_9).abs() < 5e-13,
6578 "the table starts at Mach {}",
6579 body.join_start_mach
6580 );
6581 assert_eq!(body.shape_weight, 1.0);
6584 assert_eq!(body.weight(body.join_start_mach), 0.0);
6585 assert_eq!(
6586 body.weight(body.join_start_mach + SUPERSONIC_JOIN_WIDTH_MACH),
6587 1.0
6588 );
6589 let old = AeroModel::with_body_model(
6592 &flared_rocket(18.5).layout().unwrap(),
6593 BodyModel::CURRENT.with_supersonic_flare(SupersonicFlare::SlenderBody),
6594 )
6595 .unwrap();
6596 let at = |model: &AeroModel, mach| {
6597 model
6598 .normal_force(&flow(mach, 1e-4, 0.0))
6599 .unwrap()
6600 .coefficient
6601 / 1e-4
6602 };
6603 assert!((at(&model, body.join_start_mach) - at(&old, body.join_start_mach)).abs() < 1e-12);
6604 for (epsilon, want) in [
6605 (1e-9, 8.547_36e-10),
6606 (1e-7, 8.547_36e-8),
6607 (1e-5, 8.547_38e-6),
6608 ] {
6609 let below = at(&model, body.join_start_mach - epsilon);
6610 let above = at(&model, body.join_start_mach + epsilon);
6611 let gap = (above / below - 1.0).abs();
6612 assert!(
6613 (gap - want).abs() < 1e-5 * want,
6614 "±{epsilon} across the join's start moves the slope by {gap}, not {want}"
6615 );
6616 }
6617 }
6618
6619 #[test]
6630 fn the_cap_makes_a_kink_in_the_slope_even_though_the_reading_holds() {
6631 let ahead = flared_run(&flared_rocket(18.5));
6632 let boundary_deg = corner_limit_deg(&ahead, 2.0);
6633 let whole = |deg: f64| flared_at(&flared_rocket(deg), 2.0).0;
6634 let share = |deg: f64| {
6635 model(&flared_rocket(deg))
6636 .supersonic_body()
6637 .unwrap()
6638 .share(2, 2.0)
6639 .unwrap()
6640 .0
6641 };
6642 let kink = |f: &dyn Fn(f64) -> f64, at: f64| {
6643 let epsilon = 1e-6;
6644 let (down, up) = (
6645 (f(at) - f(at - epsilon)) / epsilon,
6646 (f(at + epsilon) - f(at)) / epsilon,
6647 );
6648 up / down - 1.0
6649 };
6650 for (what, f, at_boundary, at_20, at_26) in [
6651 (
6652 "the whole rocket",
6653 &whole as &dyn Fn(f64) -> f64,
6654 -0.313_9,
6655 0.035_0,
6656 0.0,
6657 ),
6658 ("the flare's share", &share, -1.415_6, 0.410_6, 0.0),
6659 ] {
6660 assert!(
6661 (kink(f, boundary_deg) - at_boundary).abs() < 5e-4,
6662 "{what} kinks {} at the boundary",
6663 kink(f, boundary_deg)
6664 );
6665 assert!(
6666 (kink(f, 20.0) - at_20).abs() < 5e-4,
6667 "{what} kinks {} at 20°",
6668 kink(f, 20.0)
6669 );
6670 assert!(
6672 (kink(f, 26.0) - at_26).abs() < 1e-6,
6673 "{what} kinks {} at 26°",
6674 kink(f, 26.0)
6675 );
6676 }
6677 }
6678
6679 #[test]
6703 fn a_near_flat_flare_reads_through_and_leaves_only_the_corners_crossing() {
6704 let join = |deg: f64| {
6705 model(&flared_rocket(deg))
6706 .supersonic_body()
6707 .map(|body| body.join_start_mach)
6708 };
6709 for deg in [
6712 0.0,
6713 2.4e-4,
6714 2.5e-4,
6715 3e-4,
6716 9.018_246_55e-4,
6717 0.001,
6718 0.01,
6719 0.03,
6720 0.038_161_270_2,
6721 0.045,
6722 0.05,
6723 0.058_820_517_4,
6724 0.06,
6725 0.1,
6726 1.0,
6727 ] {
6728 assert_eq!(
6729 join(deg),
6730 Some(SUPERSONIC_JOIN_START_MACH),
6731 "a {deg}° flare starts its table at {:?}",
6732 join(deg)
6733 );
6734 }
6735 let at = |deg: f64, mach: f64| {
6738 let model = model(&flared_rocket(deg));
6739 let force = model
6740 .normal_force(&flow(mach, 4f64.to_radians(), 0.0))
6741 .unwrap();
6742 (
6743 force.coefficient,
6744 force.cp_station_m.unwrap() / model.reference_diameter_m(),
6745 )
6746 };
6747 let across = |deg: f64, mach: f64, epsilon: f64| {
6748 let (below, above) = (at(deg - epsilon, mach), at(deg + epsilon, mach));
6749 (above.0 / below.0 - 1.0, above.1 - below.1)
6750 };
6751 for (deg, mach) in [(0.058_820_517_4, 3.0), (9.018_246_55e-4, 2.0)] {
6753 let (force, calibers) = across(deg, mach, 1e-9);
6754 assert!(
6755 force.abs() < 1e-7 && calibers.abs() < 1e-7,
6756 "crossing {deg}° at Mach {mach} moves the force {force:.3e} and the center of \
6757 pressure {calibers:.3e} calibers"
6758 );
6759 }
6760 let ahead = flared_run(&flared_rocket(1.0));
6764 let turns = |mach: f64| {
6765 crate::shock_expansion::flare_reduction_turns_rad(&ahead.aft_flow(mach).unwrap())
6766 .unwrap()
6767 };
6768 for (mach, force_want, caliber_want) in [
6769 (2.0_f64, 3.234e-6, -1.589e-6),
6770 (3.0, 1.1369e-4, 1.8258e-4),
6771 (4.0, 5.5377e-4, 1.6709e-3),
6772 (4.95, 1.2874e-3, 5.1095e-3),
6773 ] {
6774 let crossing = turns(mach).crossing_rad.to_degrees();
6775 let probes: &[f64] = if mach > 2.0 { &[1e-9, 1e-7] } else { &[1e-9] };
6778 for epsilon in probes {
6779 let (force, calibers) = across(crossing, mach, *epsilon);
6780 assert!(
6781 (force - force_want).abs() < 0.02 * force_want.abs()
6782 && (calibers - caliber_want).abs() < 0.02 * caliber_want.abs(),
6783 "Mach {mach}: ±{epsilon}° across the crossing at {crossing}° moves the force \
6784 {force:.4e} and the center of pressure {calibers:.4e} calibers"
6785 );
6786 }
6787 let balance = turns(mach).balance_rad.to_degrees();
6790 let (force, calibers) = across(balance, mach, 1e-9);
6791 assert!(
6792 force.abs() < 1e-7 && calibers.abs() < 1e-7,
6793 "Mach {mach}: the balance at {balance}° moves the force {force:.3e} and the \
6794 center of pressure {calibers:.3e} calibers"
6795 );
6796 }
6797 let machs = [3.0, 4.0];
6802 let step = 0.08 / 16.0;
6803 let swept: Vec<[f64; 2]> = (0..=16)
6804 .map(|index| {
6805 let model = model(&flared_rocket(index as f64 * step));
6806 machs.map(|mach| {
6807 model
6808 .normal_force(&flow(mach, 4f64.to_radians(), 0.0))
6809 .unwrap()
6810 .coefficient
6811 })
6812 })
6813 .collect();
6814 for (column, mach) in machs.iter().enumerate() {
6815 let crossing = turns(*mach).crossing_rad.to_degrees();
6816 let mut rises = Vec::new();
6817 for index in 1..swept.len() {
6818 let moved = swept[index][column] / swept[index - 1][column] - 1.0;
6819 let deg = index as f64 * step;
6820 assert!(
6821 moved.abs() < 2e-3,
6822 "Mach {mach}: from {}° to {deg}° the force moves {moved:.4}",
6823 deg - step
6824 );
6825 if moved > 0.0 {
6826 rises.push(deg);
6827 }
6828 }
6829 assert!(
6830 rises.len() <= 1
6831 && rises
6832 .first()
6833 .is_none_or(|deg| (deg - step..*deg).contains(&crossing)),
6834 "Mach {mach}: the force rises over {rises:?}, against a crossing at {crossing}°"
6835 );
6836 }
6837 }
6838
6839 #[test]
6846 fn issue_87s_switches_are_this_big() {
6847 let at = |rocket: &hpr_design::Rocket| {
6848 let model = model(rocket);
6849 let force = model
6850 .normal_force(&flow(3.0, 4f64.to_radians(), 0.0))
6851 .unwrap();
6852 (
6853 force.coefficient,
6854 force.cp_station_m.unwrap() / model.reference_diameter_m(),
6855 model.supersonic_body().is_some(),
6856 )
6857 };
6858 let stepped = |drop_m: f64| {
6860 let mut rocket = straight_rocket();
6861 rocket.stages[0].components[3].part = body_part(0.3, 0.027 - drop_m, 0.027 - drop_m);
6864 rocket
6865 };
6866 let flared = |rise_m: f64| {
6870 let mut rocket = crate::testing::finned_rocket(4);
6871 rocket.stages[0].components.truncate(3);
6872 rocket.stages[0].components.push(component(
6873 "flare",
6874 body_part(1.0, 0.022, 0.022 + rise_m),
6875 None,
6876 ));
6877 rocket
6878 };
6879 let coned = |half_angle_deg: f64| {
6881 let mut rocket = straight_rocket();
6882 rocket.stages[0].components[0].part = nose(
6883 NoseShape::Conical {},
6884 0.027 / half_angle_deg.to_radians().tan(),
6885 0.027,
6886 );
6887 rocket
6888 };
6889 let blunt = |length_m: f64| {
6891 let mut rocket = straight_rocket();
6892 rocket.stages[0].components[0].part =
6893 nose(NoseShape::PowerSeries { exponent: 0.5 }, length_m, 0.027);
6894 rocket
6895 };
6896 let at_16 = 0.027 / 24.0_f64.to_radians().tan();
6897 assert!(model(&stepped(2.6e-11)).supersonic_body().is_some());
6901 assert!(model(&stepped(2.8e-11)).supersonic_body().is_none());
6902 type Side = (f64, f64, bool);
6906 let switches: [(&str, Side, Side, (f64, f64)); 4] = [
6907 (
6908 "a step in radius",
6909 at(&stepped(1e-12)),
6910 at(&stepped(1e-9)),
6911 (-0.0865, 1.0285),
6912 ),
6913 (
6914 "a flare behind a boattail",
6915 at(&flared(1e-12)),
6916 at(&flared(1e-9)),
6917 (-0.2749, 0.2872),
6918 ),
6919 (
6920 "a pointed tip past the cone tables' 30°",
6921 at(&coned(29.999)),
6922 at(&coned(30.002)),
6923 (-0.0770, 0.8107),
6924 ),
6925 (
6926 "a vertical tip steeper than the handover",
6927 at(&blunt(0.5 * at_16 * 1.0002)),
6928 at(&blunt(0.5 * at_16 * 0.9998)),
6929 (-0.0699, 0.6383),
6930 ),
6931 ];
6932 let (below, above) = (at(&coned(23.999)), at(&coned(24.002)));
6935 assert!(
6936 below.2 && above.2,
6937 "a 24° tip flies the method on both sides now"
6938 );
6939 assert!(
6940 (above.0 / below.0 - 1.0).abs() < 1e-4 && (above.1 - below.1).abs() < 1e-4,
6941 "across Fig. 2's old edge: {below:?} to {above:?}"
6942 );
6943 for (what, covered, bare, (want_force, want_calibers)) in switches {
6944 assert!(
6945 covered.2 && !bare.2,
6946 "{what}: the method should cover one side only ({covered:?}, {bare:?})"
6947 );
6948 let force = bare.0 / covered.0 - 1.0;
6949 let calibers = bare.1 - covered.1;
6950 assert!(
6951 (force - want_force).abs() < 5e-4 && (calibers - want_calibers).abs() < 5e-4,
6952 "{what}: the force moves {force:.4} and the center of pressure {calibers:.4} \
6953 calibers, against {want_force} and {want_calibers}"
6954 );
6955 }
6956 }
6957
6958 #[test]
6959 fn a_steep_tip_is_reported_as_the_runs_fallback() {
6960 let with_tip = |half_angle_deg: f64| {
6963 let mut rocket = straight_rocket();
6964 let Part::NoseCone(nose) = &mut rocket.stages[0].components[0].part else {
6965 panic!("the first part is the nose");
6966 };
6967 nose.shape = NoseShape::Conical {};
6968 nose.length_m = nose.base_radius_m / half_angle_deg.to_radians().tan();
6969 model(&rocket).supersonic_fallback()
6970 };
6971 assert_eq!(with_tip(29.99), None);
6972 assert_eq!(with_tip(30.01), Some(SupersonicFallback::SteepTip));
6973 }
6974
6975 #[test]
6976 fn a_step_is_reported_as_the_runs_fallback() {
6977 let stepped = |drop_m: f64| {
6980 let mut rocket = straight_rocket();
6981 for (i, length_m) in [0.0, 0.7, 0.05, 0.3].iter().enumerate().skip(2) {
6982 rocket.stages[0].components[i].part =
6983 body_part(*length_m, 0.027 - drop_m, 0.027 - drop_m);
6984 }
6985 let id = rocket.stages[0].components[2].id.clone();
6986 (model(&rocket).supersonic_fallback(), id)
6987 };
6988 assert_eq!(stepped(0.0).0, None);
6989 let (fallback, id) = stepped(1e-3);
6990 assert_eq!(
6991 fallback,
6992 Some(SupersonicFallback::RadiusStep { component: id })
6993 );
6994 let (fallback, id) = stepped(-1e-3);
6995 assert_eq!(
6996 fallback,
6997 Some(SupersonicFallback::RadiusStep { component: id })
6998 );
6999 assert_eq!(stepped(2.6e-11).0, None);
7003 for drop_m in [2.8e-11, 1e-9, -1e-9, 1e-8] {
7004 let (fallback, id) = stepped(drop_m);
7005 assert_eq!(
7006 fallback,
7007 Some(SupersonicFallback::RadiusStep { component: id }),
7008 "a step of {drop_m} m"
7009 );
7010 }
7011 }
7012
7013 #[test]
7029 fn a_step_takes_the_whole_body_off_the_method() {
7030 use hpr_design::ReferenceDiameter;
7031 let at_joint = |joint: usize, drop_m: f64| {
7038 let mut rocket = straight_rocket();
7039 rocket.reference_diameter = ReferenceDiameter::Custom { diameter_m: 0.054 };
7040 let lengths = [0.0, 0.7, 0.05, 0.3];
7041 for (i, length_m) in lengths.iter().enumerate().skip(joint) {
7042 rocket.stages[0].components[i].part =
7043 body_part(*length_m, 0.027 - drop_m, 0.027 - drop_m);
7044 }
7045 rocket
7046 };
7047 let read = |joint: usize, drop_m: f64| {
7048 let rocket = at_joint(joint, drop_m);
7049 let model = model(&rocket);
7050 let force = model
7051 .normal_force(&flow(3.0, 4f64.to_radians(), 0.0))
7052 .unwrap();
7053 (
7054 force.coefficient,
7055 force.cp_station_m.unwrap() / model.reference_diameter_m(),
7056 model.supersonic_body().is_some(),
7057 )
7058 };
7059 let (flush, flush_cp, marched) = read(3, 0.0);
7060 assert!(marched, "with no step the method covers the body");
7061 assert!(
7062 (flush - 0.899_591_695).abs() < 5e-7 && (flush_cp - 16.949_177_4).abs() < 5e-5,
7063 "the flush rocket reads {flush} at {flush_cp} calibers"
7064 );
7065
7066 for (joint, drop_m, want_force, want_calibers) in [
7072 (1, 2.8e-11, -0.086_518_790, 1.028_480_4),
7073 (2, 2.8e-11, -0.086_518_790, 1.028_480_4),
7074 (3, 2.8e-11, -0.086_518_789, 1.028_480_4),
7075 (1, 1e-3, -0.106_197_868, 1.193_751_6),
7076 (3, 1e-3, -0.102_873_512, 0.994_855_8),
7077 (1, 2e-3, -0.125_539_709, 1.359_310_7),
7078 (3, 2e-3, -0.118_890_998, 0.959_745_0),
7079 (1, -2.8e-11, -0.086_518_788, 1.028_480_4),
7080 (3, -2.8e-11, -0.086_518_789, 1.028_480_4),
7081 (1, -1e-3, -0.067_194_034, 0.867_387_3),
7082 (3, -1e-3, -0.070_503_028, 1.064_443_7),
7083 (1, -2e-3, -0.047_519_789, 0.706_432_7),
7084 (3, -2e-3, -0.054_109_172, 1.098_652_0),
7085 ] {
7086 let (force, cp, marched) = read(joint, drop_m);
7087 assert!(
7088 !marched,
7089 "a {drop_m} m step at joint {joint} kept the method"
7090 );
7091 let (force, calibers) = (force / flush - 1.0, cp - flush_cp);
7092 assert!(
7093 (force - want_force).abs() < 5e-6 && (calibers - want_calibers).abs() < 5e-5,
7094 "a {drop_m} m step at joint {joint} moves the force {force:.9} and the center of \
7095 pressure {calibers:.7} calibers, against {want_force} and {want_calibers}"
7096 );
7097 }
7098
7099 let (mut low, mut high) = (1e-13, 1e-8);
7105 assert!(
7106 read(3, low).2 && !read(3, high).2,
7107 "the bisection has to start with the march covering one end and refusing the other"
7108 );
7109 while high - low > 1e-6 * high {
7110 let mid = 0.5 * (low + high);
7111 if read(3, mid).2 {
7112 low = mid
7113 } else {
7114 high = mid
7115 }
7116 }
7117 assert!(
7118 (high / 2.7e-11 - 1.0).abs() < 2e-6,
7119 "the march refuses a step of {high} m, not a billionth of the 0.027 m radius"
7120 );
7121 for joint in [1, 2, 3] {
7122 for sign in [1.0, -1.0] {
7123 assert!(
7124 read(joint, sign * 2.6e-11).2 && !read(joint, sign * 2.8e-11).2,
7125 "at joint {joint} with sign {sign} the switch is not at 2.7e-11 m"
7126 );
7127 }
7128 }
7129
7130 let run_segments = |drop_m: f64| {
7135 let rocket = at_joint(3, drop_m);
7136 model(&rocket)
7137 .supersonic_run
7138 .as_ref()
7139 .map(|run| run.segments.len())
7140 };
7141 for drop_m in [1e-8, -1e-8] {
7142 assert_eq!(
7143 run_segments(drop_m),
7144 Some(4),
7145 "{drop_m} m is inside the gate"
7146 );
7147 }
7148 for drop_m in [2e-8, -2e-8] {
7149 assert_eq!(run_segments(drop_m), None, "{drop_m} m is outside the gate");
7150 }
7151
7152 let boattail = |drop_m: f64| {
7160 let mut rocket = crate::testing::finned_rocket(4);
7161 rocket.reference_diameter = ReferenceDiameter::Custom { diameter_m: 0.054 };
7162 rocket.stages[0].components[2].part = body_part(0.05, 0.027 - drop_m, 0.022);
7163 let model = model(&rocket);
7164 let force = model
7165 .normal_force(&flow(3.0, 4f64.to_radians(), 0.0))
7166 .unwrap();
7167 (
7168 force.coefficient,
7169 force.cp_station_m.unwrap() / model.reference_diameter_m(),
7170 model.supersonic_body().is_some(),
7171 )
7172 };
7173 let (boattail_flush, boattail_flush_cp, marched) = boattail(0.0);
7174 assert!(marched, "flush, the method covers the boattailed body too");
7175 let (mut low, mut high) = (1e-18, 1e-8);
7176 assert!(boattail(-low).2 && !boattail(-high).2);
7177 while high - low > 1e-6 * high {
7178 let mid = 0.5 * (low + high);
7179 if boattail(-mid).2 {
7180 low = mid
7181 } else {
7182 high = mid
7183 }
7184 }
7185 assert!(
7186 (high / (1e-12 * 1.3 * 0.1) - 1.0).abs() < 2e-4,
7187 "a step up at the boattail's joint is refused at {high} m, not 1e-12 × 1.3 m × 0.1"
7188 );
7189 assert!(
7190 boattail(2.6e-11).2 && !boattail(2.8e-11).2,
7191 "stepping down at that joint, the merge tolerance still binds"
7192 );
7193 for drop_m in [-1.4e-13, -2.8e-11, 2.8e-11] {
7194 let (force, cp, marched) = boattail(drop_m);
7195 assert!(
7196 !marched,
7197 "a {drop_m} m step at the boattail kept the method"
7198 );
7199 let (force, calibers) = (force / boattail_flush - 1.0, cp - boattail_flush_cp);
7200 assert!(
7201 (force + 0.113_409_121).abs() < 5e-6 && (calibers - 1.095_116_4).abs() < 5e-5,
7202 "a {drop_m} m step at the boattail moves the force {force:.9} and the center of \
7203 pressure {calibers:.7} calibers"
7204 );
7205 }
7206 }
7207
7208 #[test]
7209 fn a_body_the_method_cannot_finish_keeps_slender_body_terms() {
7210 let at = |m: &AeroModel, mach| body_values(m, mach);
7211 let mut rocket = straight_rocket();
7216 rocket.stages[0].components[2].part = body_part(0.05, 0.027, 0.032);
7219 if let Part::Transition(transition) = &mut rocket.stages[0].components[2].part {
7220 transition.shape = NoseShape::Ogive { radius_ratio: 1.0 };
7221 }
7222 rocket.stages[0].components[3].part = body_part(0.3, 0.032, 0.032);
7223 let flared = model(&rocket);
7224 let mut rocket = crate::testing::finned_rocket(4);
7227 rocket.stages[0]
7228 .components
7229 .push(component("lip", body_part(0.01, 0.022, 0.025), None));
7230 let lipped = model(&rocket);
7231 let mut rocket = crate::testing::finned_rocket(4);
7232 rocket.stages[0].components[2].part = body_part(0.05, 0.026, 0.022);
7233 let stepped_boattail = model(&rocket);
7234 let mut rocket = straight_rocket();
7235 rocket.stages[0].components[0].part =
7236 nose(NoseShape::PowerSeries { exponent: 0.5 }, 0.027, 0.027);
7237 let blunt = model(&rocket);
7238 let mut rocket = straight_rocket();
7239 rocket.stages[0].components[1].part = body_part(0.7, 0.03, 0.03);
7240 let stepped = model(&rocket);
7241 for model in [&flared, &lipped, &stepped_boattail, &blunt, &stepped] {
7242 assert!(model.supersonic_body().is_none());
7243 assert_eq!(at(model, 3.0), at(model, 0.5));
7244 }
7245 }
7246
7247 #[test]
7248 fn clones_share_the_table_and_compare_equal() {
7249 let model = model(&straight_rocket());
7250 let clone = model.clone();
7251 assert_eq!(model, clone);
7252 let built = model.supersonic_body().unwrap() as *const SupersonicBody;
7253 assert_eq!(model, clone);
7254 assert!(std::ptr::eq(built, clone.supersonic_body().unwrap()));
7255 }
7256
7257 #[test]
7264 fn kept_tables_are_found_by_run_and_area_and_the_first_kept_drops_first() {
7265 let rocket = straight_rocket();
7266 let mut wider = rocket.clone();
7267 wider.reference_diameter = ReferenceDiameter::Custom { diameter_m: 0.07 };
7268 let mut longer = rocket.clone();
7269 longer.stages[0].components[0].part =
7270 nose(NoseShape::Ogive { radius_ratio: 1.0 }, 0.4, 0.027);
7271 let keys: Vec<(&str, SupersonicRun, f64)> = [
7272 ("the rocket", &rocket),
7273 ("wider", &wider),
7274 ("longer", &longer),
7275 ]
7276 .into_iter()
7277 .map(|(what, design)| {
7278 let aero = model(design);
7279 let run = aero
7280 .supersonic_run
7281 .clone()
7282 .expect("a run the method covers");
7283 (what, run, aero.reference_area_m2)
7284 })
7285 .collect();
7286 assert_eq!(
7287 keys[0].1, keys[1].1,
7288 "the wider rocket's run is the rocket's"
7289 );
7290 assert_ne!(keys[0].2.to_bits(), keys[1].2.to_bits());
7291 assert_ne!(keys[0].1, keys[2].1);
7292 let built: Vec<Option<SupersonicBody>> = keys
7293 .iter()
7294 .map(|(_, run, area)| SupersonicBody::new(run, *area))
7295 .collect();
7296 assert!(built.iter().all(Option::is_some));
7297 let mut kept = KeptTables::new(3);
7298 for ((_, run, area), table) in keys.iter().zip(&built) {
7299 assert!(kept.find(run, *area).is_none());
7300 kept.keep(run, *area, table);
7301 }
7302 for ((what, run, area), table) in keys.iter().zip(&built) {
7303 let found = kept.find(run, *area).expect("kept");
7304 assert_eq!(format!("{found:?}"), format!("{table:?}"), "{what}");
7305 assert_eq!(
7306 format!("{found:?}"),
7307 format!("{:?}", SupersonicBody::new(run, *area)),
7308 "{what}: not what building it again gives"
7309 );
7310 }
7311 kept.keep(&keys[0].1, keys[0].2, &built[2]);
7313 assert_eq!(kept.tables.len(), 3);
7314 assert_eq!(
7315 format!("{:?}", kept.find(&keys[0].1, keys[0].2)),
7316 format!("{:?}", Some(&built[0]))
7317 );
7318 let (_, run, area) = &keys[2];
7319 let mut fewer = KeptTables::new(2);
7320 fewer.keep(&keys[0].1, keys[0].2, &built[0]);
7321 fewer.keep(&keys[1].1, keys[1].2, &built[1]);
7322 fewer.keep(run, *area, &built[2]);
7323 assert_eq!(fewer.tables.len(), 2);
7324 assert!(
7325 fewer.find(&keys[0].1, keys[0].2).is_none(),
7326 "the first kept is dropped"
7327 );
7328 assert!(fewer.find(&keys[1].1, keys[1].2).is_some());
7329 assert!(fewer.find(run, *area).is_some());
7330 let mut none = KeptTables::new(0);
7331 none.keep(run, *area, &built[2]);
7332 assert!(none.tables.is_empty());
7333 }
7334
7335 #[test]
7339 fn models_built_apart_share_the_table_only_on_the_same_body() {
7340 let rocket = straight_rocket();
7341 let nominal = model(&rocket);
7342 let alone = model(&rocket).with_drag_scale(1.1).unwrap();
7343 let built = nominal.supersonic_body().unwrap() as *const SupersonicBody;
7344 assert!(!std::ptr::eq(built, alone.supersonic_body().unwrap()));
7345 let mut scaled = model(&rocket).with_drag_scale(1.1).unwrap();
7346 assert!(!scaled.supersonic_table_built());
7347 assert!(scaled.share_supersonic_table(&nominal));
7348 assert!(scaled.supersonic_table_built());
7349 assert!(std::ptr::eq(built, scaled.supersonic_body().unwrap()));
7350 let first = model(&rocket);
7352 let mut second = model(&rocket);
7353 assert!(second.share_supersonic_table(&first));
7354 assert!(!first.supersonic_table_built());
7355 let built = second.supersonic_body().unwrap() as *const SupersonicBody;
7356 assert!(first.supersonic_table_built());
7357 assert!(std::ptr::eq(built, first.supersonic_body().unwrap()));
7358 let mut longer = rocket.clone();
7360 longer.stages[0].components[0].part =
7361 nose(NoseShape::Ogive { radius_ratio: 1.0 }, 0.4, 0.027);
7362 let mut longer = model(&longer);
7363 assert!(!longer.share_supersonic_table(&nominal));
7364 assert!(!std::ptr::eq(
7365 nominal.supersonic_body().unwrap(),
7366 longer.supersonic_body().unwrap()
7367 ));
7368 let mut wider = rocket.clone();
7370 wider.reference_diameter = ReferenceDiameter::Custom { diameter_m: 0.07 };
7371 let mut wider = model(&wider);
7372 assert!(!wider.share_supersonic_table(&nominal));
7373 assert!(!wider.supersonic_table_built());
7374 let mut blunt = rocket;
7375 blunt.stages[0].components[0].part =
7376 nose(NoseShape::PowerSeries { exponent: 0.5 }, 0.027, 0.027);
7377 let mut blunt = model(&blunt);
7378 assert!(!blunt.share_supersonic_table(&nominal));
7379 assert!(blunt.supersonic_body().is_none());
7380 }
7381
7382 fn shares(rocket: &hpr_design::Rocket) -> (Vec<(String, Drag)>, f64) {
7384 let m = model(rocket);
7385 let conditions = DragConditions::coasting(0.3 * 340.294 / 1.4607e-5);
7386 let parts: Vec<(String, Drag)> = m
7387 .buildup_components(&Flow::axial(0.3), &conditions)
7388 .unwrap()
7389 .into_iter()
7390 .map(|part| (part.id, part.drag))
7391 .collect();
7392 let total = m.drag(&Flow::axial(0.3), &conditions).unwrap();
7393 let sum: f64 = parts.iter().map(|(_, d)| d.zero_lift_coefficient).sum();
7394 close(total.zero_lift_coefficient, sum, 1e-12, "the parts add up");
7395 (parts, total.zero_lift_coefficient)
7396 }
7397
7398 fn share(parts: &[(String, Drag)], id: &str) -> Drag {
7399 parts
7400 .iter()
7401 .find(|(i, _)| i == id)
7402 .map(|(_, d)| *d)
7403 .unwrap()
7404 }
7405
7406 fn stated(coefficient: f64, include_children: bool) -> Option<hpr_design::DragOverride> {
7407 Some(hpr_design::DragOverride {
7408 coefficient,
7409 include_children,
7410 })
7411 }
7412
7413 fn stepped_rocket() -> hpr_design::Rocket {
7416 let mut rocket = finned_rocket(3);
7417 let components = &mut rocket.stages[0].components;
7418 components.remove(2);
7419 rocket
7420 }
7421
7422 #[test]
7426 fn a_stated_drag_coefficient_replaces_the_part_s_own() {
7427 let plain = stepped_rocket();
7428 let (before, total) = shares(&plain);
7429 let step = base_drag_coefficient(0.3).unwrap() * (1.0 - (0.022_f64 / 0.027).powi(2));
7430 assert!(
7432 share(&before, "tail").pressure >= step,
7433 "{:?}",
7434 share(&before, "tail")
7435 );
7436
7437 let mut fins = plain.clone();
7439 fins.stages[0].components[2].children[0].drag_override = stated(0.5, false);
7440 let (after, with) = shares(&fins);
7441 close(share(&after, "fins").stated, 1.5, 1e-15, "per fin");
7442 close(
7443 with,
7444 total - share(&before, "fins").zero_lift_coefficient + 1.5,
7445 1e-12,
7446 "fins",
7447 );
7448
7449 let mut body = plain.clone();
7451 body.stages[0].components[1].drag_override = stated(0.2, false);
7452 let (after, with) = shares(&body);
7453 close(
7454 share(&after, "body").zero_lift_coefficient,
7455 0.2,
7456 1e-15,
7457 "body",
7458 );
7459 close(
7460 share(&before, "tail").zero_lift_coefficient
7461 - share(&after, "tail").zero_lift_coefficient,
7462 step,
7463 1e-12,
7464 "the step goes with the body",
7465 );
7466 close(
7467 with,
7468 total - share(&before, "body").zero_lift_coefficient - step + 0.2,
7469 1e-12,
7470 "body",
7471 );
7472
7473 let mut tail = plain.clone();
7475 tail.stages[0].components[2].drag_override = stated(0.2, false);
7476 let (after, with_tail) = shares(&tail);
7477 let own = share(&after, "tail");
7478 close(own.stated, 0.2, 1e-15, "tail");
7479 close(own.pressure, step, 1e-12, "the step stays");
7480 assert_eq!((own.friction, own.base, own.parasitic), (0.0, 0.0, 0.0));
7481 assert_eq!(share(&after, "fins"), share(&before, "fins"));
7482 close(
7483 with_tail,
7484 total - share(&before, "tail").zero_lift_coefficient + step + 0.2,
7485 1e-12,
7486 "tail",
7487 );
7488
7489 tail.stages[0].components[2].drag_override = stated(0.2, true);
7491 let (after, _) = shares(&tail);
7492 assert_eq!(share(&after, "fins").zero_lift_coefficient, 0.0);
7493
7494 let mut rails = plain.clone();
7497 rails.stages[0].components[1].children = vec![
7498 component(
7499 "lug",
7500 Part::LaunchLug(LaunchLug {
7501 length_m: 0.05,
7502 outer_radius_m: 0.004,
7503 thickness_m: 0.0005,
7504 angle_rad: 0.0,
7505 count: 1,
7506 spacing_m: 0.0,
7507 material: material(),
7508 }),
7509 Some(Position::Middle { aft_offset_m: 0.0 }),
7510 ),
7511 component(
7512 "buttons",
7513 Part::RailButton(RailButton {
7514 outer_diameter_m: 0.01,
7515 inner_diameter_m: 0.006,
7516 height_m: 0.008,
7517 base_height_m: 0.002,
7518 flange_height_m: 0.002,
7519 screw_height_m: 0.0,
7520 angle_rad: 0.0,
7521 count: 2,
7522 spacing_m: 0.2,
7523 material: material(),
7524 }),
7525 Some(Position::Middle { aft_offset_m: 0.0 }),
7526 ),
7527 ];
7528 let (before_rails, total_rails) = shares(&rails);
7529 for id in ["lug", "buttons"] {
7530 assert!(share(&before_rails, id).zero_lift_coefficient > 0.0, "{id}");
7531 }
7532 rails.stages[0].components[1].children[1].drag_override = stated(0.5, false);
7533 let (after, _) = shares(&rails);
7534 close(share(&after, "buttons").stated, 1.0, 1e-15, "per button");
7535 rails.stages[0].components[1].children[1].drag_override = None;
7536 rails.stages[0].components[1].drag_override = stated(0.2, true);
7537 let (after, with) = shares(&rails);
7538 for id in ["lug", "buttons"] {
7539 assert_eq!(share(&after, id).zero_lift_coefficient, 0.0, "{id}");
7540 }
7541 close(
7542 with,
7543 total_rails
7544 - share(&before_rails, "body").zero_lift_coefficient
7545 - share(&before_rails, "lug").zero_lift_coefficient
7546 - share(&before_rails, "buttons").zero_lift_coefficient
7547 - step
7548 + 0.2,
7549 1e-12,
7550 "body covering its lug and buttons",
7551 );
7552
7553 let mut stage = plain.clone();
7555 stage.stages[0].drag_override = stated(0.1, false);
7556 let (after, with) = shares(&stage);
7557 close(share(&after, "stage").stated, 0.1, 1e-15, "stage");
7558 close(with, total + 0.1, 1e-12, "stage added");
7559 stage.stages[0].drag_override = stated(0.1, true);
7560 let (_, with) = shares(&stage);
7561 close(with, 0.1, 1e-15, "stage alone");
7562
7563 let m = model(&stage).with_drag_scale(2.0).unwrap();
7565 let conditions = DragConditions::coasting(0.3 * 340.294 / 1.4607e-5);
7566 let scaled = m.drag(&Flow::axial(0.3), &conditions).unwrap();
7567 close(scaled.zero_lift_coefficient, 0.2, 1e-15, "scaled");
7568 }
7569
7570 #[test]
7573 fn a_stated_drag_coefficient_out_of_range_or_in_a_pod_is_refused() {
7574 for bad in [-0.1, f64::NAN, f64::INFINITY] {
7575 let mut rocket = stepped_rocket();
7576 rocket.stages[0].components[1].drag_override = stated(bad, false);
7577 match AeroModel::new(&rocket.layout().unwrap()) {
7578 Err(AeroError::InComponent { id, source }) => {
7579 assert_eq!(id, "body");
7580 assert!(
7581 matches!(
7582 *source,
7583 AeroError::Domain {
7584 what: "stated drag coefficient",
7585 ..
7586 }
7587 ),
7588 "{source:?}"
7589 );
7590 }
7591 other => panic!("{bad}: {other:?}"),
7592 }
7593 }
7594 let mut rocket = stepped_rocket();
7595 rocket.stages[0].drag_override = stated(-1.0, true);
7596 assert!(matches!(
7597 AeroModel::new(&rocket.layout().unwrap()),
7598 Err(AeroError::InComponent { ref id, .. }) if id == "stage"
7599 ));
7600 let mut rocket = stepped_rocket();
7603 rocket.stages[0].components[2].drag_override = stated(0.1, true);
7604 rocket.stages[0].components[2].children[0].drag_override = stated(f64::NAN, false);
7605 assert!(matches!(
7606 AeroModel::new(&rocket.layout().unwrap()),
7607 Err(AeroError::InComponent { ref id, .. }) if id == "fins"
7608 ));
7609 let refused = |rocket: &hpr_design::Rocket, why: &str| match AeroModel::new(
7610 &rocket.layout().unwrap(),
7611 ) {
7612 Err(AeroError::InComponent { source, .. }) => {
7613 assert!(
7614 matches!(*source, AeroError::Unsupported(ref what) if what == why),
7615 "{source:?}"
7616 );
7617 }
7618 other => panic!("{why}: {other:?}"),
7619 };
7620 for (pod_set, part) in [(true, 0), (false, 1)] {
7621 let mut rocket = podded_rocket(2);
7622 let pods = rocket.stages[0].components[1].children.last_mut().unwrap();
7623 if pod_set {
7624 pods.drag_override = stated(0.1, true);
7625 } else {
7626 pods.children[part].drag_override = stated(0.1, false);
7627 }
7628 refused(&rocket, "a drag override on a pod set or in a pod");
7629 }
7630 let mut rocket = podded_rocket(2);
7632 rocket.stages[0].components[1].drag_override = stated(0.1, true);
7633 refused(&rocket, "a drag override covering a pod set");
7634 let mut rocket = podded_rocket(2);
7635 rocket.stages[0].drag_override = stated(0.1, true);
7636 refused(&rocket, "a drag override covering a pod set");
7637 let mut rocket = podded_rocket(2);
7639 rocket.stages[0].components[1].drag_override = stated(0.1, false);
7640 assert!(AeroModel::new(&rocket.layout().unwrap()).is_ok());
7641 let mut rocket = tube_finned_rocket(6, 0.0762, 0.011, 0.0005);
7643 rocket.stages[0].components[3].children[1].drag_override = stated(0.1, false);
7644 refused(&rocket, "a drag override on a tube fin set");
7645 }
7646
7647 #[test]
7650 fn a_looped_layout_does_not_hang_the_override_walk() {
7651 let mut lugged = stepped_rocket();
7652 lugged.stages[0].components[1].children.push(component(
7653 "lug",
7654 Part::LaunchLug(LaunchLug {
7655 length_m: 0.05,
7656 outer_radius_m: 0.004,
7657 thickness_m: 0.0005,
7658 angle_rad: 0.0,
7659 count: 1,
7660 spacing_m: 0.0,
7661 material: material(),
7662 }),
7663 Some(Position::Middle { aft_offset_m: 0.0 }),
7664 ));
7665 let mut layout = lugged.layout().unwrap();
7666 let (lug, _) = layout.find("lug").unwrap();
7667 layout.components[lug].parent = Some(lug);
7668 let _ = AeroModel::new(&layout);
7670 }
7671
7672 #[test]
7674 fn a_stated_drag_coefficient_flies_a_shape_the_buildup_refuses() {
7675 let mut rocket = stepped_rocket();
7676 rocket.stages[0].components[0].part =
7678 nose(NoseShape::Ogive { radius_ratio: 0.8 }, 0.25, 0.027);
7679 let conditions = DragConditions::coasting(0.3 * 340.294 / 1.4607e-5);
7680 assert!(matches!(
7681 model(&rocket).drag(&Flow::axial(0.3), &conditions),
7682 Err(AeroError::InComponent { .. })
7683 ));
7684 rocket.stages[0].components[0].drag_override = stated(0.3, false);
7685 let (parts, _) = shares(&rocket);
7686 close(
7687 share(&parts, "nose").zero_lift_coefficient,
7688 0.3,
7689 1e-15,
7690 "nose",
7691 );
7692 }
7693}