1use serde::{Deserialize, Serialize};
15
16use crate::config::{Configuration, LaidOut};
17use crate::error::DesignError;
18use crate::solids::Wall;
19use crate::tree::{LENGTH_TOLERANCE_M, Layout, Part, PlacedComponent, Rocket};
20
21pub const DRAWING_TOLERANCE_M: f64 = 0.005 * 0.0254;
24
25pub const COARSE_GENERAL_TOLERANCE_M: [(f64, f64); 8] = [
31 (0.003, 0.0002),
32 (0.006, 0.0003),
33 (0.030, 0.0005),
34 (0.120, 0.0008),
35 (0.400, 0.0012),
36 (1.000, 0.002),
37 (2.000, 0.003),
38 (4.000, 0.004),
39];
40
41pub fn fit_tolerance_m(room_m: f64) -> f64 {
48 let diameter_m = 2.0 * room_m;
49 if diameter_m.is_nan() || diameter_m < 0.0005 {
51 return 0.0;
52 }
53 COARSE_GENERAL_TOLERANCE_M
54 .iter()
55 .find(|(upto, _)| diameter_m <= *upto)
56 .map_or(0.004, |(_, t)| *t)
57}
58
59pub const NARROWER_THAN_NOMINAL_M: [(f64, f64); 3] = [
69 (0.018, 0.698 * 0.0254 + DRAWING_TOLERANCE_M),
70 (0.024, 0.938 * 0.0254 + DRAWING_TOLERANCE_M),
71 (0.029, 1.125 * 0.0254 + DRAWING_TOLERANCE_M),
72];
73
74pub fn motor_fit_slack_m(diameter_m: f64) -> f64 {
79 NARROWER_THAN_NOMINAL_M
80 .iter()
81 .find(|(nominal, _)| (diameter_m - nominal).abs() <= LENGTH_TOLERANCE_M)
82 .map_or(0.0, |(nominal, case)| nominal - case)
83}
84
85#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
87#[serde(rename_all = "snake_case")]
88pub enum Severity {
89 Warning,
91 Error,
93}
94
95#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
97#[serde(tag = "kind", rename_all = "snake_case")]
98#[non_exhaustive]
99pub enum Finding {
100 MotorWiderThanMount {
103 configuration: String,
105 mount: String,
107 motor_diameter_m: f64,
109 mount_inner_diameter_m: f64,
111 },
112 MotorTightInMount {
116 configuration: String,
118 mount: String,
120 motor_diameter_m: f64,
122 mount_inner_diameter_m: f64,
124 },
125 MotorOutsideMount {
128 configuration: String,
130 mount: String,
132 },
133 MotorPastMountTop {
135 configuration: String,
137 mount: String,
139 excess_m: f64,
141 },
142 MotorIntoBlock {
148 configuration: String,
150 mount: String,
152 block: String,
154 block_bore_m: f64,
156 motor_diameter_m: f64,
158 excess_m: f64,
160 },
161 AttachmentOffBody {
166 component: String,
168 body: String,
170 },
171 AttachmentPastBodyEnd {
175 component: String,
177 body: String,
179 excess_m: f64,
181 },
182 PartOutsideRocket {
185 component: String,
187 },
188 InternalPartPastParentEnd {
190 component: String,
192 parent: String,
194 excess_m: f64,
196 },
197 InternalPartWiderThanParent {
204 component: String,
206 parent: String,
208 reach_m: f64,
210 room_m: f64,
212 },
213 InternalPartTightInParent {
217 component: String,
219 parent: String,
221 reach_m: f64,
223 room_m: f64,
225 },
226 InternalPartWedgedInParent {
232 component: String,
234 parent: String,
236 reach_m: f64,
238 room_m: f64,
240 widest_room_m: f64,
242 },
243 PackedPartWiderThanParent {
247 component: String,
249 parent: String,
251 reach_m: f64,
253 room_m: f64,
255 #[serde(default)]
261 room_widens_aft: bool,
262 },
263 RingAgainstParentEnd {
268 ring: String,
270 parent: String,
272 reach_m: f64,
274 room_m: f64,
276 },
277 ClusterTubesOverlap {
280 tube: String,
282 apart_m: f64,
284 diameter_m: f64,
286 },
287 RingOverlapsInnerTube {
290 ring: String,
292 tube: String,
294 },
295 #[serde(alias = "centre_outside_rocket")]
300 CenterOutsideRocket {
301 stage: String,
303 station_m: f64,
305 },
306 RadiusStep {
308 fore: String,
310 aft: String,
312 fore_radius_m: f64,
314 aft_radius_m: f64,
316 },
317 NoNoseCone {
319 component: String,
321 },
322}
323
324impl Finding {
325 pub fn severity(&self) -> Severity {
327 match self {
328 Self::MotorWiderThanMount { .. }
329 | Self::MotorOutsideMount { .. }
330 | Self::AttachmentOffBody { .. }
331 | Self::PartOutsideRocket { .. }
332 | Self::InternalPartWiderThanParent { .. }
333 | Self::CenterOutsideRocket { .. } => Severity::Error,
334 Self::MotorTightInMount { .. }
335 | Self::MotorPastMountTop { .. }
336 | Self::MotorIntoBlock { .. }
337 | Self::AttachmentPastBodyEnd { .. }
338 | Self::InternalPartPastParentEnd { .. }
339 | Self::InternalPartTightInParent { .. }
340 | Self::InternalPartWedgedInParent { .. }
341 | Self::PackedPartWiderThanParent { .. }
342 | Self::RingAgainstParentEnd { .. }
343 | Self::ClusterTubesOverlap { .. }
344 | Self::RingOverlapsInnerTube { .. }
345 | Self::RadiusStep { .. }
346 | Self::NoNoseCone { .. } => Severity::Warning,
347 }
348 }
349
350 pub fn describe(&self, name: &dyn Fn(&str) -> String) -> String {
368 match self {
369 Self::MotorWiderThanMount {
370 configuration,
371 mount,
372 motor_diameter_m,
373 mount_inner_diameter_m,
374 } => {
375 let (motor, bore) = mm_pair(*motor_diameter_m, *mount_inner_diameter_m);
376 format!(
377 "the motor in {} is {motor} wide, wider than the mount's {bore} bore by more \
378 than a real case's slack (configuration {})",
379 name(mount),
380 name(configuration)
381 )
382 }
383 Self::MotorTightInMount {
384 configuration,
385 mount,
386 motor_diameter_m,
387 mount_inner_diameter_m,
388 } => {
389 let (motor, bore) = mm_pair(*motor_diameter_m, *mount_inner_diameter_m);
390 format!(
391 "the motor in {} is nominally {motor} wide in a {bore} bore: it fits, as real \
392 cases run under their nominal size (configuration {})",
393 name(mount),
394 name(configuration)
395 )
396 }
397 Self::MotorOutsideMount {
398 configuration,
399 mount,
400 } => format!(
401 "the motor in {} lies wholly outside the mount along its length, such as an \
402 overhang typed in millimeters as meters (configuration {})",
403 name(mount),
404 name(configuration)
405 ),
406 Self::MotorPastMountTop {
407 configuration,
408 mount,
409 excess_m,
410 } => format!(
411 "the motor in {} reaches {} past the mount's forward end (configuration {}). The \
412 mass, CG and margin are for the motor as drawn: where a ring or bulkhead closes \
413 the mount there, the real case sits that much further aft",
414 name(mount),
415 mm(*excess_m),
416 name(configuration)
417 ),
418 Self::MotorIntoBlock {
419 configuration,
420 mount,
421 block,
422 block_bore_m,
423 motor_diameter_m,
424 excess_m,
425 } => format!(
426 "the motor in {} reaches {} forward of the aft face of {}, whose {} bore can't \
427 pass the {} case (configuration {}). The mass, CG and margin are for the motor \
428 as drawn: a real case stops at the part, that much further aft",
429 name(mount),
430 mm(*excess_m),
431 name(block),
432 mm(*block_bore_m),
433 mm(*motor_diameter_m),
434 name(configuration)
435 ),
436 Self::AttachmentOffBody { component, body } => format!(
437 "{} doesn't touch {}, the body tube it is attached to",
438 name(component),
439 name(body)
440 ),
441 Self::AttachmentPastBodyEnd {
442 component,
443 body,
444 excess_m,
445 } => format!(
446 "{} runs {} past an end of {}, the body tube it is attached to",
447 name(component),
448 mm(*excess_m),
449 name(body)
450 ),
451 Self::PartOutsideRocket { component } => format!(
452 "{} lies wholly forward of the nose tip or aft of the rocket's end",
453 name(component)
454 ),
455 Self::InternalPartPastParentEnd {
456 component,
457 parent,
458 excess_m,
459 } => format!(
460 "{} runs {} past an end of {}, which holds it",
461 name(component),
462 mm(*excess_m),
463 name(parent)
464 ),
465 Self::InternalPartWiderThanParent {
466 component,
467 parent,
468 reach_m,
469 room_m,
470 } => {
471 let (reach, room) = mm_pair(*reach_m, *room_m);
472 format!(
473 "{} reaches {reach} from the axis of {}, which has {room} of room: too wide \
474 to fit, past the fit tolerance",
475 name(component),
476 name(parent)
477 )
478 }
479 Self::InternalPartTightInParent {
480 component,
481 parent,
482 reach_m,
483 room_m,
484 } => {
485 let (reach, room) = mm_pair(*reach_m, *room_m);
486 format!(
487 "{} reaches {reach} from the axis of {}, which has {room} of room. That is a \
488 fit to sand, and the mass where it crosses the wall counts twice",
489 name(component),
490 name(parent)
491 )
492 }
493 Self::InternalPartWedgedInParent {
494 component,
495 parent,
496 reach_m,
497 room_m,
498 widest_room_m,
499 } => {
500 let (reach, room) = mm_pair(*reach_m, *room_m);
501 let (_, widest) = mm_pair(*reach_m, *widest_room_m);
502 format!(
503 "{} reaches {reach} from the axis of {}, which narrows to {room} of room \
504 along it ({widest} where widest). It can't slide in that far as drawn, and \
505 flies where it is drawn",
506 name(component),
507 name(parent)
508 )
509 }
510 Self::PackedPartWiderThanParent {
511 component,
512 parent,
513 reach_m,
514 room_m,
515 room_widens_aft,
516 } => {
517 let (reach, room) = mm_pair(*reach_m, *room_m);
518 let mut text = format!(
519 "{} is packed to reach {reach} from the axis of {}, which has {room} of \
520 room. It can't go in as drawn. Its mass, length and station fly as drawn, and \
521 its width sets only its own inertia",
522 name(component),
523 name(parent)
524 );
525 if *room_widens_aft {
526 text.push_str(
527 ". The room widens aft of it, so its mass can sit only farther aft. The \
528 center of gravity flies forward of where it can be, and the stability \
529 margin may read high (issue #367, \
530 https://github.com/nrdptel/fusionspace-eridanus/issues/367)",
531 );
532 }
533 text
534 }
535 Self::RingAgainstParentEnd {
536 ring,
537 parent,
538 reach_m,
539 room_m,
540 } => {
541 let (reach, room) = mm_pair(*reach_m, *room_m);
542 format!(
543 "{} reaches {reach} from the axis, wider than {}, and caps its end, in \
544 {room} of room around it. The mass where it crosses the wall counts twice",
545 name(ring),
546 name(parent)
547 )
548 }
549 Self::ClusterTubesOverlap {
550 tube,
551 apart_m,
552 diameter_m,
553 } => {
554 let (apart, diameter) = mm_pair(*apart_m, *diameter_m);
555 format!(
556 "the cluster of {} has tubes {apart} apart, closer than their {diameter} \
557 diameter, so they cross. The mass where they cross counts twice and their \
558 motors would not fit",
559 name(tube)
560 )
561 }
562 Self::RingOverlapsInnerTube { ring, tube } => format!(
563 "{} overlaps {} beside it, so the mass where they cross counts twice",
564 name(ring),
565 name(tube)
566 ),
567 Self::CenterOutsideRocket { stage, station_m } => format!(
568 "the center of mass set for {} is {} {} the nose tip, outside the rocket, such \
569 as a center typed in millimeters as meters",
570 name(stage),
571 mm(station_m.abs()),
572 if *station_m < 0.0 {
573 "forward of"
574 } else {
575 "aft of"
576 }
577 ),
578 Self::RadiusStep {
579 fore,
580 aft,
581 fore_radius_m,
582 aft_radius_m,
583 } => {
584 let (fore_radius, aft_radius) = mm_pair(*fore_radius_m, *aft_radius_m);
585 format!(
586 "{} ends {fore_radius} in radius where {} begins {aft_radius}: a step in the \
587 body's outline",
588 name(fore),
589 name(aft)
590 )
591 }
592 Self::NoNoseCone { component } => format!(
593 "the rocket's first body part, {}, is not a nose cone",
594 name(component)
595 ),
596 }
597 }
598}
599
600fn mm(length_m: f64) -> String {
603 let mm = length_m * 1000.0;
604 format!("{mm:.prec$} mm", prec = decimals(mm))
605}
606
607fn decimals(mm: f64) -> usize {
609 match mm.abs() {
610 size if size >= 1.0 || size == 0.0 => 1,
611 size if size >= 0.1 => 2,
612 _ => 3,
613 }
614}
615
616fn mm_pair(a_m: f64, b_m: f64) -> (String, String) {
620 let (a, b) = (a_m * 1000.0, b_m * 1000.0);
621 let mut prec = decimals(a).max(decimals(b));
623 while prec < 4 && format!("{a:.prec$}") == format!("{b:.prec$}") {
624 prec += 1;
625 }
626 (format!("{a:.prec$} mm"), format!("{b:.prec$} mm"))
627}
628
629pub fn check(rocket: &Rocket) -> Result<Vec<Finding>, DesignError> {
636 rocket.check_configuration_ids()?;
637 check_on(rocket, &rocket.layout()?)
638}
639
640impl LaidOut {
641 pub fn check(&self) -> Result<Vec<Finding>, DesignError> {
647 check_on(self.rocket(), self.layout())
648 }
649}
650
651fn check_on(rocket: &Rocket, layout: &Layout) -> Result<Vec<Finding>, DesignError> {
653 let mut findings = check_layout(layout);
654 for configuration in &rocket.configurations {
655 findings.extend(check_configuration(layout, configuration)?);
656 }
657 Ok(findings)
658}
659
660pub fn has_errors(findings: &[Finding]) -> bool {
662 findings.iter().any(|f| f.severity() == Severity::Error)
663}
664
665pub const BLOCK_OVERLAP_TOLERANCE_M: f64 = 0.001;
670
671fn overlap(a0: f64, a1: f64, b0: f64, b1: f64) -> f64 {
673 a1.min(b1) - a0.max(b0)
674}
675
676fn excess(fore: f64, aft: f64, parent_fore: f64, parent_aft: f64) -> Option<f64> {
679 if overlap(fore, aft, parent_fore, parent_aft) <= 0.0 {
680 return None;
681 }
682 Some((parent_fore - fore).max(aft - parent_aft).max(0.0))
683}
684
685pub fn check_layout(layout: &Layout) -> Vec<Finding> {
690 let mut findings = Vec::new();
691 let body: Vec<_> = layout.body().collect();
692 if let Some(first) = body.first()
693 && !matches!(first.part, Part::NoseCone(_))
694 {
695 findings.push(Finding::NoNoseCone {
696 component: first.id.clone(),
697 });
698 }
699 for pair in body.windows(2) {
700 let (fore, aft) = (pair[0], pair[1]);
701 if let (Some(a), Some(b)) = (fore.part.aft_radius_m(), aft.part.fore_radius_m())
702 && (a - b).abs() > LENGTH_TOLERANCE_M
703 {
704 findings.push(Finding::RadiusStep {
705 fore: fore.id.clone(),
706 aft: aft.id.clone(),
707 fore_radius_m: a,
708 aft_radius_m: b,
709 });
710 }
711 }
712 let length = layout.length_m;
715 let apart = |c: &PlacedComponent, fore: f64, aft: f64| {
717 overlap(c.fore_station_m, c.aft_station_m(), fore, aft) < -LENGTH_TOLERANCE_M
718 };
719 let off_rocket: Vec<bool> = layout
720 .components
721 .iter()
722 .map(|c| {
723 if c.parent.is_none()
725 || c.part.is_external()
726 || c.part.is_body()
727 || !apart(c, 0.0, length)
728 {
729 return false;
730 }
731 let mut ancestor = c.parent;
732 for _ in 0..layout.components.len() {
733 let Some(a) = ancestor.and_then(|i| layout.components.get(i)) else {
734 break;
735 };
736 if !apart(c, a.fore_station_m, a.aft_station_m()) {
737 return false;
738 }
739 ancestor = a.parent;
740 }
741 true
742 })
743 .collect();
744 let mut holds_off = off_rocket.clone();
745 for (index, component) in layout.components.iter().enumerate().rev() {
746 if holds_off[index]
747 && let Some(flag) = component.parent.and_then(|p| holds_off.get_mut(p))
748 {
749 *flag = true;
750 }
751 }
752 for (k, stage) in layout.stages.iter().enumerate() {
753 let station = -stage.mass.cg_m.z;
754 let in_stage = || {
755 layout
756 .components
757 .iter()
758 .enumerate()
759 .filter(|(_, c)| c.stage == k)
760 };
761 let holds = in_stage().any(|(i, _)| holds_off[i]);
762 let overridden = stage.center_overridden || in_stage().any(|(_, c)| c.center_overridden);
763 if overridden
764 && !holds
765 && stage.mass.mass_kg > 0.0
766 && !(-LENGTH_TOLERANCE_M..=length + LENGTH_TOLERANCE_M).contains(&station)
767 {
768 findings.push(Finding::CenterOutsideRocket {
769 stage: stage.id.clone(),
770 station_m: station,
771 });
772 }
773 }
774 for (index, component) in layout.components.iter().enumerate() {
775 let Some(parent) = component.parent.and_then(|i| layout.components.get(i)) else {
776 continue;
777 };
778 attached_findings(component, parent, off_rocket[index], layout, &mut findings);
779 }
780 findings
781}
782
783const ROOM_SAMPLES: usize = 31;
786
787#[derive(Debug, Clone, Copy)]
789struct Room {
790 least_m: f64,
792 most_m: f64,
794}
795
796fn room_m(part: &PlacedComponent, fore: f64, aft: f64) -> Option<Room> {
816 let both = |room_m: f64| Room {
817 least_m: room_m,
818 most_m: room_m,
819 };
820 if let Some(bore) = part.part.inner_radius_m() {
821 return Some(both(bore));
822 }
823 let (profile, wall) = match &part.part {
824 Part::NoseCone(nose) => (nose.profile().ok()?, nose.wall),
825 Part::Transition(transition) => (transition.profile().ok()?, transition.wall),
826 _ => return None,
827 };
828 let length = part.length_m;
829 let (x0, x1) = (fore - part.fore_station_m, aft - part.fore_station_m);
830 let inside_m = x1.min(length) - x0.max(0.0);
833 if x1 < -LENGTH_TOLERANCE_M
834 || x0 > length + LENGTH_TOLERANCE_M
835 || (x1 - x0 > LENGTH_TOLERANCE_M && inside_m <= LENGTH_TOLERANCE_M)
836 {
837 return Some(both(profile.max_radius_m()));
838 }
839 let wall_m = match wall {
840 Wall::Filled {} => return Some(both(0.0)),
841 Wall::Shell { thickness_m } => thickness_m,
842 };
843 let (x0, x1) = (x0.clamp(0.0, length), x1.clamp(0.0, length));
844 let (least, most) = (0..=ROOM_SAMPLES + 1)
845 .map(|i| {
846 let x = x0 + (x1 - x0) * (i as f64) / ((ROOM_SAMPLES + 1) as f64);
847 profile.radius_m(x)
848 })
849 .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), r| {
850 (lo.min(r), hi.max(r))
851 });
852 Some(Room {
853 least_m: (least - wall_m).max(0.0),
854 most_m: (most - wall_m).max(0.0),
855 })
856}
857
858fn wrapped_ring_container<'a>(
863 fore: f64,
864 aft: f64,
865 tube: &PlacedComponent,
866 layout: &'a Layout,
867) -> Option<&'a PlacedComponent> {
868 let mut next = tube.parent;
869 while let Some(part) = next.and_then(|i| layout.components.get(i)) {
870 if room_m(part, fore, aft).is_some()
871 && let Some(e) = excess(fore, aft, part.fore_station_m, part.aft_station_m())
872 {
873 return (e <= LENGTH_TOLERANCE_M).then_some(part);
874 }
875 next = part.parent;
876 }
877 None
878}
879
880fn attached_findings(
882 component: &PlacedComponent,
883 parent: &PlacedComponent,
884 off_rocket: bool,
885 layout: &Layout,
886 findings: &mut Vec<Finding>,
887) {
888 if component.part.is_body() {
890 return;
891 }
892 let (fore, aft) = (component.fore_station_m, component.aft_station_m());
893 let holds =
895 |a0: f64, a1: f64, x: f64| a0 - LENGTH_TOLERANCE_M <= x && x <= a1 + LENGTH_TOLERANCE_M;
896 if component.part.is_external() && parent.part.is_body() && parent.length_m == 0.0 {
900 if !holds(fore, aft, parent.fore_station_m) {
901 findings.push(Finding::AttachmentOffBody {
902 component: component.id.clone(),
903 body: parent.id.clone(),
904 });
905 }
906 return;
907 }
908 let span = if component.length_m == 0.0 && matches!(component.part, Part::PodSet(_)) {
909 holds(parent.fore_station_m, parent.aft_station_m(), fore).then_some(0.0)
912 } else {
913 excess(fore, aft, parent.fore_station_m, parent.aft_station_m())
914 };
915 if component.part.is_external() {
916 match span {
917 None => findings.push(Finding::AttachmentOffBody {
918 component: component.id.clone(),
919 body: parent.id.clone(),
920 }),
921 Some(_) if matches!(component.part, Part::PodSet(_)) => {}
924 Some(e) if e > LENGTH_TOLERANCE_M => {
925 findings.push(Finding::AttachmentPastBodyEnd {
926 component: component.id.clone(),
927 body: parent.id.clone(),
928 excess_m: e,
929 });
930 }
931 Some(_) => {}
932 }
933 return;
934 }
935 let e =
937 span.unwrap_or_else(|| (parent.fore_station_m - fore).max(aft - parent.aft_station_m()));
938 if off_rocket {
939 findings.push(Finding::PartOutsideRocket {
940 component: component.id.clone(),
941 });
942 } else if e > LENGTH_TOLERANCE_M {
943 findings.push(Finding::InternalPartPastParentEnd {
944 component: component.id.clone(),
945 parent: parent.id.clone(),
946 excess_m: e,
947 });
948 }
949 let holder = parent.parent.and_then(|i| layout.components.get(i));
950 let concentric = parent.part.axis_offset_m() == component.part.axis_offset_m()
953 && !matches!(&parent.part, Part::InnerTube(tube) if !tube.cluster_m.is_empty());
954 let wraps = concentric
958 && matches!((&component.part, &parent.part), (Part::CenteringRing(ring), Part::InnerTube(tube))
959 if ring.inner_radius_m >= tube.outer_radius_m - LENGTH_TOLERANCE_M);
960 let container = if wraps {
961 wrapped_ring_container(fore, aft, parent, layout).unwrap_or(parent)
962 } else {
963 parent
964 };
965 if let (Some(reach_m), Some(room)) = (
966 component.part.reach_from_m(container.part.axis_offset_m()),
967 room_m(container, fore, aft),
968 ) && reach_m > room.least_m + LENGTH_TOLERANCE_M
969 {
970 let Room { least_m, most_m } = room;
971 let fits = |room_m: f64| reach_m <= room_m + fit_tolerance_m(room_m) + LENGTH_TOLERANCE_M;
972 let at_end = matches!(component.part, Part::CenteringRing(_))
976 && concentric
977 && !wraps
978 && holds(fore, aft, parent.fore_station_m) != holds(fore, aft, parent.aft_station_m());
979 let cap = holder.filter(|_| at_end).and_then(|holder| {
980 let reach_m = component.part.reach_from_m(holder.part.axis_offset_m())?;
981 let room_m = room_m(holder, fore, aft)?.most_m;
982 (reach_m <= room_m + fit_tolerance_m(room_m) + LENGTH_TOLERANCE_M)
983 .then_some((reach_m, room_m))
984 });
985 let packed_center_inside = component
990 .part
991 .packing()
992 .map(|packing| reach_m - packing.radius_m <= least_m + LENGTH_TOLERANCE_M);
993 let rigid = packed_center_inside.is_none();
994 findings.push(if packed_center_inside == Some(true) {
995 let end = container.aft_station_m();
999 let room_widens_aft = room_m(container, aft.min(end), end).is_none_or(|aft_room| {
1000 let most_m = aft_room.most_m;
1001 most_m.is_nan() || least_m.is_nan() || most_m > least_m + LENGTH_TOLERANCE_M
1002 });
1003 Finding::PackedPartWiderThanParent {
1004 component: component.id.clone(),
1005 parent: container.id.clone(),
1006 reach_m,
1007 room_m: least_m,
1008 room_widens_aft,
1009 }
1010 } else if rigid && fits(least_m) {
1011 Finding::InternalPartTightInParent {
1012 component: component.id.clone(),
1013 parent: container.id.clone(),
1014 reach_m,
1015 room_m: least_m,
1016 }
1017 } else if rigid && fits(most_m) {
1018 Finding::InternalPartWedgedInParent {
1021 component: component.id.clone(),
1022 parent: container.id.clone(),
1023 reach_m,
1024 room_m: least_m,
1025 widest_room_m: most_m,
1026 }
1027 } else if let Some((reach_m, room_m)) = cap {
1028 Finding::RingAgainstParentEnd {
1029 ring: component.id.clone(),
1030 parent: parent.id.clone(),
1031 reach_m,
1032 room_m,
1033 }
1034 } else {
1035 Finding::InternalPartWiderThanParent {
1036 component: component.id.clone(),
1037 parent: container.id.clone(),
1038 reach_m,
1039 room_m: if rigid { most_m } else { least_m },
1040 }
1041 });
1042 }
1043 if let Part::InnerTube(inner) = &component.part {
1044 let apart_m = inner
1045 .cluster_m
1046 .iter()
1047 .enumerate()
1048 .flat_map(|(i, &[x, y])| {
1049 inner.cluster_m[i + 1..]
1050 .iter()
1051 .map(move |&[u, v]| (x - u).hypot(y - v))
1052 })
1053 .fold(f64::INFINITY, f64::min);
1054 let diameter_m = 2.0 * inner.outer_radius_m;
1055 if apart_m < diameter_m - LENGTH_TOLERANCE_M {
1056 findings.push(Finding::ClusterTubesOverlap {
1057 tube: component.id.clone(),
1058 apart_m,
1059 diameter_m,
1060 });
1061 }
1062 }
1063 if let Part::CenteringRing(ring) = &component.part {
1064 let around = (container.id != parent.id)
1066 .then(|| layout.find(&container.id))
1067 .flatten()
1068 .map(|(i, _)| i);
1069 for tube in layout.components.iter().filter(|c| {
1070 (c.parent == component.parent || around.is_some_and(|i| c.parent == Some(i)))
1071 && c.id != component.id
1072 && c.id != parent.id
1073 }) {
1074 let Part::InnerTube(inner) = &tube.part else {
1075 continue;
1076 };
1077 let [x, y] = tube.part.axis_offset_m();
1080 let tubes = if inner.cluster_m.is_empty() {
1081 &[[0.0, 0.0]][..]
1082 } else {
1083 inner.cluster_m.as_slice()
1084 };
1085 let radial = tubes
1086 .iter()
1087 .map(|&[u, v]| {
1088 let d = (x + u).hypot(y + v);
1089 (d + inner.outer_radius_m).min(ring.outer_radius_m)
1090 - (d - inner.outer_radius_m).max(ring.inner_radius_m)
1091 })
1092 .fold(f64::NEG_INFINITY, f64::max);
1093 if overlap(fore, aft, tube.fore_station_m, tube.aft_station_m()) > LENGTH_TOLERANCE_M
1094 && radial > LENGTH_TOLERANCE_M
1095 {
1096 findings.push(Finding::RingOverlapsInnerTube {
1097 ring: component.id.clone(),
1098 tube: tube.id.clone(),
1099 });
1100 }
1101 }
1102 }
1103}
1104
1105pub fn check_configuration(
1112 layout: &Layout,
1113 configuration: &Configuration,
1114) -> Result<Vec<Finding>, DesignError> {
1115 let mut findings = Vec::new();
1116 let placed = layout.place_motors(configuration)?;
1119 for motor in placed.into_iter().filter(|motor| motor.tube == 0) {
1120 let Some((_, mount)) = layout.find(&motor.mount) else {
1121 continue;
1122 };
1123 if let Some(inner) = mount.part.inner_radius_m() {
1124 let inner_diameter = 2.0 * inner;
1125 let motor_diameter_m = motor.mounted.diameter_m;
1126 let slack_m = motor_fit_slack_m(motor_diameter_m);
1127 if motor_diameter_m > inner_diameter + slack_m + LENGTH_TOLERANCE_M {
1128 findings.push(Finding::MotorWiderThanMount {
1129 configuration: configuration.id.clone(),
1130 mount: mount.id.clone(),
1131 motor_diameter_m,
1132 mount_inner_diameter_m: inner_diameter,
1133 });
1134 } else if motor_diameter_m > inner_diameter + LENGTH_TOLERANCE_M {
1135 findings.push(Finding::MotorTightInMount {
1136 configuration: configuration.id.clone(),
1137 mount: mount.id.clone(),
1138 motor_diameter_m,
1139 mount_inner_diameter_m: inner_diameter,
1140 });
1141 }
1142 }
1143 let (fore, nozzle) = (motor.fore_station_m(), motor.nozzle_station_m());
1144 if overlap(fore, nozzle, mount.fore_station_m, mount.aft_station_m()) <= 0.0 {
1145 findings.push(Finding::MotorOutsideMount {
1146 configuration: configuration.id.clone(),
1147 mount: mount.id.clone(),
1148 });
1149 continue;
1150 }
1151 let past = mount.fore_station_m - fore;
1152 if past > LENGTH_TOLERANCE_M {
1153 findings.push(Finding::MotorPastMountTop {
1154 configuration: configuration.id.clone(),
1155 mount: mount.id.clone(),
1156 excess_m: past,
1157 });
1158 }
1159 let mount_index = layout.find(&motor.mount).map(|(index, _)| index);
1163 let radius_m = motor.mounted.diameter_m / 2.0;
1164 let block = layout
1165 .components
1166 .iter()
1167 .filter(|part| part.parent.is_some() && part.parent == mount_index)
1168 .filter_map(|part| {
1169 let bore_radius_m = match &part.part {
1170 Part::InnerTube(tube) => tube.outer_radius_m - tube.thickness_m,
1171 Part::CenteringRing(ring) => ring.inner_radius_m,
1172 _ => return None,
1173 };
1174 let aft_m = part.fore_station_m + part.length_m;
1175 (bore_radius_m < radius_m - LENGTH_TOLERANCE_M
1176 && aft_m - fore > BLOCK_OVERLAP_TOLERANCE_M
1177 && aft_m < nozzle - LENGTH_TOLERANCE_M)
1178 .then_some((part, bore_radius_m, aft_m))
1179 })
1180 .max_by(|(_, _, a), (_, _, b)| a.total_cmp(b));
1181 if let Some((block, bore_radius_m, aft_m)) = block {
1182 findings.push(Finding::MotorIntoBlock {
1183 configuration: configuration.id.clone(),
1184 mount: mount.id.clone(),
1185 block: block.id.clone(),
1186 block_bore_m: 2.0 * bore_radius_m.max(0.0),
1187 motor_diameter_m: motor.mounted.diameter_m,
1188 excess_m: aft_m - fore,
1189 });
1190 }
1191 }
1192 Ok(findings)
1193}
1194
1195#[cfg(test)]
1196mod tests {
1197 use super::*;
1198 use crate::testing::{
1199 attached, body, bottom, inner_tube, mass_component, ring, rocket, stage, three_fin_rocket,
1200 top, tube,
1201 };
1202 use crate::{AutoDimension, MotorMount};
1203 use crate::{Part, Position};
1204
1205 #[test]
1208 fn describe_names_parts_and_sizes_in_millimeters() {
1209 let id = |s: &str| s.to_owned();
1210 let findings = [
1211 Finding::MotorWiderThanMount {
1212 configuration: id("cfg"),
1213 mount: id("mt"),
1214 motor_diameter_m: 0.038,
1215 mount_inner_diameter_m: 0.029,
1216 },
1217 Finding::MotorTightInMount {
1218 configuration: id("cfg"),
1219 mount: id("mt"),
1220 motor_diameter_m: 0.029,
1221 mount_inner_diameter_m: 0.028_956,
1222 },
1223 Finding::MotorOutsideMount {
1224 configuration: id("cfg"),
1225 mount: id("mt"),
1226 },
1227 Finding::MotorPastMountTop {
1228 configuration: id("cfg"),
1229 mount: id("mt"),
1230 excess_m: 0.012,
1231 },
1232 Finding::AttachmentOffBody {
1233 component: id("fin"),
1234 body: id("bt"),
1235 },
1236 Finding::AttachmentPastBodyEnd {
1237 component: id("fin"),
1238 body: id("bt"),
1239 excess_m: 0.0004,
1240 },
1241 Finding::PartOutsideRocket {
1242 component: id("mass"),
1243 },
1244 Finding::InternalPartPastParentEnd {
1245 component: id("cord"),
1246 parent: id("bt"),
1247 excess_m: 0.050_800_000_000_000_01,
1248 },
1249 Finding::InternalPartWiderThanParent {
1250 component: id("ring"),
1251 parent: id("bt"),
1252 reach_m: 0.04,
1253 room_m: 0.035,
1254 },
1255 Finding::InternalPartTightInParent {
1256 component: id("ring"),
1257 parent: id("bt"),
1258 reach_m: 0.035_05,
1259 room_m: 0.035,
1260 },
1261 Finding::PackedPartWiderThanParent {
1262 component: id("payload"),
1263 parent: id("bt"),
1264 reach_m: 0.0125,
1265 room_m: 0.0105,
1266 room_widens_aft: false,
1267 },
1268 Finding::RingAgainstParentEnd {
1269 ring: id("ring"),
1270 parent: id("cp"),
1271 reach_m: 0.04,
1272 room_m: 0.0399,
1273 },
1274 Finding::ClusterTubesOverlap {
1275 tube: id("it"),
1276 apart_m: 0.02,
1277 diameter_m: 0.025,
1278 },
1279 Finding::RingOverlapsInnerTube {
1280 ring: id("ring"),
1281 tube: id("it"),
1282 },
1283 Finding::CenterOutsideRocket {
1284 stage: id("st"),
1285 station_m: -0.25,
1286 },
1287 Finding::RadiusStep {
1288 fore: id("nose"),
1289 aft: id("bt"),
1290 fore_radius_m: 0.0205,
1291 aft_radius_m: 0.0207,
1292 },
1293 Finding::NoNoseCone {
1294 component: id("bt"),
1295 },
1296 Finding::InternalPartWedgedInParent {
1297 component: id("coupler"),
1298 parent: id("nose"),
1299 reach_m: 0.0245,
1300 room_m: 0.0115,
1301 widest_room_m: 0.025,
1302 },
1303 Finding::MotorIntoBlock {
1304 configuration: id("cfg"),
1305 mount: id("mt"),
1306 block: id("block"),
1307 block_bore_m: 0.025,
1308 motor_diameter_m: 0.038,
1309 excess_m: 0.012,
1310 },
1311 ];
1312 let name = |id: &str| format!("<{id}>");
1313 let sentences: Vec<String> = findings.iter().map(|f| f.describe(&name)).collect();
1314 for (finding, sentence) in findings.iter().zip(&sentences) {
1315 let value = serde_json::to_value(finding).unwrap();
1317 for (key, field) in value.as_object().unwrap() {
1318 if let Some(text) = field.as_str().filter(|_| key != "kind") {
1319 assert!(sentence.contains(&format!("<{text}>")), "{key}: {sentence}");
1320 }
1321 }
1322 assert!(
1323 !sentence.contains('{') && !sentence.contains('_'),
1324 "{sentence}"
1325 );
1326 }
1327 assert_eq!(
1328 sentences[0],
1329 "the motor in <mt> is 38.0 mm wide, wider than the mount's 29.0 mm bore by more \
1330 than a real case's slack (configuration <cfg>)"
1331 );
1332 assert!(sentences[5].contains(" 0.40 mm past "), "{}", sentences[5]);
1333 assert!(sentences[7].contains(" 50.8 mm past "), "{}", sentences[7]);
1334 assert!(
1335 sentences[3].contains(
1336 "reaches 12.0 mm past the mount's forward end (configuration <cfg>). The mass, CG \
1337 and margin are for the motor as drawn"
1338 ),
1339 "{}",
1340 sentences[3]
1341 );
1342 assert_eq!(
1343 sentences.last().map(String::as_str),
1344 Some(
1345 "the motor in <mt> reaches 12.0 mm forward of the aft face of <block>, whose 25.0 mm \
1346 bore can't pass the 38.0 mm case (configuration <cfg>). The mass, CG and margin \
1347 are for the motor as drawn: a real case stops at the part, that much further aft"
1348 )
1349 );
1350 assert!(sentences[14].contains(" 250.0 mm forward of the nose tip"));
1351 assert_eq!(mm(0.000_05), "0.050 mm");
1352 assert!(
1354 sentences[1].contains(" is nominally 29.00 mm wide in a 28.96 mm bore"),
1355 "{}",
1356 sentences[1]
1357 );
1358 assert!(
1359 sentences[9].contains(" reaches 35.05 mm from the axis of <bt>, which has 35.00 mm")
1360 );
1361 assert!(sentences[10].contains(
1362 "<payload> is packed to reach 12.5 mm from the axis of <bt>, which has 10.5 mm of room"
1363 ));
1364 assert!(
1365 sentences[17].contains(
1366 "<coupler> reaches 24.5 mm from the axis of <nose>, which narrows to 11.5 mm of \
1367 room along it (25.0 mm where widest)"
1368 ),
1369 "{}",
1370 sentences[17]
1371 );
1372 assert!(sentences[11].contains(
1373 " reaches 40.0 mm from the axis, wider than <cp>, and caps its end, in 39.9 mm"
1374 ));
1375 assert!(sentences[15].contains(" ends 20.5 mm in radius where <bt> begins 20.7 mm"));
1376 assert_eq!(
1377 mm_pair(0.038, 0.037_97),
1378 ("38.00 mm".to_owned(), "37.97 mm".to_owned())
1379 );
1380 assert_eq!(
1381 mm_pair(0.040, 0.000_049),
1382 ("40.000 mm".to_owned(), "0.049 mm".to_owned())
1383 );
1384 assert_eq!(
1385 mm_pair(0.025, 0.024_98),
1386 ("25.00 mm".to_owned(), "24.98 mm".to_owned())
1387 );
1388 assert_eq!(
1389 mm_pair(0.020_5, 0.020_500_01),
1390 ("20.5000 mm".to_owned(), "20.5000 mm".to_owned())
1391 );
1392 assert_eq!(mm(0.0005), "0.50 mm");
1393 assert_eq!(mm(0.0), "0.0 mm");
1394 }
1395
1396 fn kinds(findings: &[Finding]) -> Vec<(String, Severity)> {
1397 findings
1398 .iter()
1399 .map(|f| {
1400 let tag = serde_json::to_value(f).unwrap()["kind"]
1401 .as_str()
1402 .unwrap()
1403 .to_owned();
1404 (tag, f.severity())
1405 })
1406 .collect()
1407 }
1408
1409 #[test]
1410 fn sample_rocket_passes_every_check() {
1411 let findings = check(&three_fin_rocket()).unwrap();
1412 assert!(findings.is_empty(), "{findings:?}");
1413 }
1414
1415 #[test]
1418 fn motor_wider_than_mount_is_rejected() {
1419 let mut design = three_fin_rocket();
1420 design.configurations[0].motors[0] = crate::testing::motor("mmt", 0.054, 0.2);
1421 let findings = check(&design).unwrap();
1422 assert_eq!(
1423 findings,
1424 vec![Finding::MotorWiderThanMount {
1425 configuration: "main".to_owned(),
1426 mount: "mmt".to_owned(),
1427 motor_diameter_m: 0.054,
1428 mount_inner_diameter_m: 2.0 * (0.020 - 0.001),
1429 }]
1430 );
1431 assert_eq!(findings[0].severity(), Severity::Error);
1432 assert!(has_errors(&findings));
1433 if let Part::InnerTube(tube) = &mut design.stages[0].components[1].children[0].part {
1435 tube.cluster_m = vec![[0.0, 0.0], [0.04, 0.0], [-0.04, 0.0]];
1436 }
1437 let findings = check(&design).unwrap();
1438 let wider = findings
1439 .iter()
1440 .filter(|f| matches!(f, Finding::MotorWiderThanMount { .. }))
1441 .count();
1442 assert_eq!(wider, 1, "{findings:?}");
1443
1444 let exact = three_fin_rocket();
1446 assert!(check(&exact).unwrap().is_empty());
1447 let mut design = three_fin_rocket();
1449 design.configurations[0].motors[0] = crate::testing::motor("mmt", 0.038 + 1e-6, 0.2);
1450 assert!(has_errors(&check(&design).unwrap()));
1451
1452 let mut design = three_fin_rocket();
1454 design.configurations[0].motors[0] = crate::testing::motor("mmt", 0.038, 0.35);
1455 let findings = check(&design).unwrap();
1456 let [Finding::MotorPastMountTop { excess_m, .. }] = findings[..] else {
1457 panic!("{findings:?}")
1458 };
1459 assert!((excess_m - 0.04).abs() < 1e-12);
1460 assert!(!has_errors(&findings));
1461 }
1462
1463 #[test]
1469 fn a_motor_into_an_engine_block_is_found() {
1470 let with_motor = |block: Part, at_m: f64, motor_diameter_m: f64, motor_length_m: f64| {
1472 let mut design = three_fin_rocket();
1473 let mount = &mut design.stages[0].components[1].children[0];
1474 assert_eq!(mount.id, "mmt");
1475 mount.children = vec![attached("block", block, top(at_m))];
1476 design.configurations[0].motors[0] =
1477 crate::testing::motor("mmt", motor_diameter_m, motor_length_m);
1478 check(&design).unwrap()
1479 };
1480 let with_block = |block: Part, at_m: f64, motor_length_m: f64| {
1481 with_motor(block, at_m, 0.038, motor_length_m)
1482 };
1483 let block = || inner_tube(0.02, 0.019, 0.005);
1485 assert!(with_block(block(), 0.0, 0.2).is_empty());
1486 let findings = with_block(block(), 0.0, 0.3);
1489 let [
1490 Finding::MotorIntoBlock {
1491 block: ref blocker,
1492 block_bore_m,
1493 motor_diameter_m,
1494 excess_m,
1495 ..
1496 },
1497 ] = findings[..]
1498 else {
1499 panic!("{findings:?}")
1500 };
1501 assert_eq!(blocker, "block");
1502 assert!((block_bore_m - 0.028).abs() < 1e-12, "{block_bore_m}");
1503 assert_eq!(motor_diameter_m, 0.038);
1504 assert!((excess_m - 0.01).abs() < 1e-12, "{excess_m}");
1505 assert_eq!(findings[0].severity(), Severity::Warning);
1506 assert!(with_block(block(), 0.0, 0.29).is_empty());
1508 assert!(with_block(block(), 0.0, 0.291).is_empty());
1510 let findings = with_block(block(), 0.0, 0.291 + 1e-6);
1511 assert!(
1512 matches!(findings[..], [Finding::MotorIntoBlock { .. }]),
1513 "{findings:?}"
1514 );
1515 let findings = with_block(block(), 0.01, 0.3);
1517 let [Finding::MotorIntoBlock { excess_m, .. }] = findings[..] else {
1518 panic!("{findings:?}")
1519 };
1520 assert!((excess_m - 0.02).abs() < 1e-12, "{excess_m}");
1521 let findings = with_block(ring(0.006, 0.019, 0.0), 0.008, 0.3);
1523 let [
1524 Finding::MotorIntoBlock {
1525 block_bore_m,
1526 excess_m,
1527 ..
1528 },
1529 ] = findings[..]
1530 else {
1531 panic!("{findings:?}")
1532 };
1533 assert_eq!(block_bore_m, 0.0);
1534 assert!((excess_m - 0.004).abs() < 1e-12, "{excess_m}");
1535 assert!(with_motor(block(), 0.0, 0.028, 0.3).is_empty());
1537 let findings = with_block(ring(0.0008, 0.019, 0.0), 0.1, 0.3);
1540 let [Finding::MotorIntoBlock { excess_m, .. }] = findings[..] else {
1541 panic!("{findings:?}")
1542 };
1543 assert!((excess_m - 0.0908).abs() < 1e-12, "{excess_m}");
1544 let mut design = three_fin_rocket();
1548 let mount = &mut design.stages[0].components[1].children[0];
1549 mount.motor_mount = Some(MotorMount { overhang_m: -0.01 });
1550 mount.children = vec![attached("lip", ring(0.006, 0.019, 0.0), top(0.286))];
1551 design.configurations[0].motors[0] = crate::testing::motor("mmt", 0.038, 0.25);
1552 let findings = check(&design).unwrap();
1553 assert!(findings.is_empty(), "{findings:?}");
1554 let mut design = three_fin_rocket();
1556 let mount = &mut design.stages[0].components[1].children[0];
1557 mount.children = vec![
1558 attached("top-block", block(), top(0.0)),
1559 attached("ring", ring(0.006, 0.019, 0.0), top(0.05)),
1560 ];
1561 design.configurations[0].motors[0] = crate::testing::motor("mmt", 0.038, 0.3);
1562 let findings = check(&design).unwrap();
1563 let [
1564 Finding::MotorIntoBlock {
1565 block: ref binding,
1566 excess_m,
1567 ..
1568 },
1569 ] = findings[..]
1570 else {
1571 panic!("{findings:?}")
1572 };
1573 assert_eq!(binding, "ring");
1574 assert!((excess_m - 0.046).abs() < 1e-12, "{excess_m}");
1575 let findings = with_block(block(), 0.0, 0.35);
1577 let excesses: Vec<f64> = findings
1578 .iter()
1579 .map(|finding| match finding {
1580 Finding::MotorPastMountTop { excess_m, .. }
1581 | Finding::MotorIntoBlock { excess_m, .. } => *excess_m,
1582 _ => panic!("{findings:?}"),
1583 })
1584 .collect();
1585 assert_eq!(excesses.len(), 2, "{findings:?}");
1586 assert!((excesses[0] - 0.04).abs() < 1e-12 && (excesses[1] - 0.06).abs() < 1e-12);
1587 }
1588
1589 #[test]
1594 fn a_nominal_motor_in_its_matching_tube_only_warns() {
1595 let fitted = |motor_m: f64, bore_m: f64| {
1596 let mut design = three_fin_rocket();
1597 let Part::InnerTube(tube) = &mut design.stages[0].components[1].children[0].part else {
1598 panic!("the tests' rocket's mount is an inner tube");
1599 };
1600 tube.outer_radius_m = bore_m / 2.0 + tube.thickness_m;
1601 design.configurations[0].motors[0] = crate::testing::motor("mmt", motor_m, 0.2);
1602 check(&design).unwrap()
1603 };
1604 let findings = fitted(0.029, 0.028956);
1605 let [
1606 Finding::MotorTightInMount {
1607 motor_diameter_m,
1608 mount_inner_diameter_m,
1609 ..
1610 },
1611 ] = findings[..]
1612 else {
1613 panic!("{findings:?}")
1614 };
1615 assert_eq!(motor_diameter_m, 0.029);
1616 assert!((mount_inner_diameter_m - 0.028956).abs() < 1e-12);
1617 assert_eq!(findings[0].severity(), Severity::Warning);
1618 assert!(!has_errors(&findings));
1619 assert!((motor_fit_slack_m(0.029) - 0.000_298).abs() < 1e-12);
1621 assert!((motor_fit_slack_m(0.024) - 0.000_047_8).abs() < 1e-12);
1622 assert!((motor_fit_slack_m(0.018) - 0.000_143_8).abs() < 1e-12);
1623 assert_eq!(motor_fit_slack_m(0.038), 0.0);
1624 assert!(!has_errors(&fitted(0.029, 0.028702 + 1e-7)));
1625 for (motor_m, bore_m) in [
1626 (0.029, 0.028702 - 1e-6),
1627 (0.029, 0.028),
1628 (0.024, 0.023952 - 1e-6),
1629 (0.038, 0.038 - 1e-6),
1630 (0.054, 0.054 - 1e-6),
1631 (0.0289, 0.0289 - 1e-6),
1633 ] {
1634 let findings: Vec<_> = fitted(motor_m, bore_m)
1636 .into_iter()
1637 .filter(|f| {
1638 matches!(
1639 f,
1640 Finding::MotorWiderThanMount { .. } | Finding::MotorTightInMount { .. }
1641 )
1642 })
1643 .collect();
1644 assert!(
1645 matches!(&findings[..], [Finding::MotorWiderThanMount { .. }]),
1646 "{motor_m} in {bore_m}: {findings:?}"
1647 );
1648 }
1649 }
1650
1651 #[test]
1656 fn a_pod_set_of_no_length_touches_its_tube_where_it_sits() {
1657 let podded = |children: Vec<crate::Component>, position: Position| {
1658 let mut design = three_fin_rocket();
1659 let mut pods = attached(
1660 "pods",
1661 Part::PodSet(crate::parts::PodSet {
1662 count: 2,
1663 radial_offset_m: 0.06,
1664 angle_rad: 0.0,
1665 }),
1666 position,
1667 );
1668 pods.children = children;
1669 design.stages[0].components[1].children.push(pods);
1670 check(&design).unwrap()
1671 };
1672 let mut phantom = body("phantom", tube(0.0, 0.0, 0.0));
1673 phantom.children = vec![attached(
1674 "wings",
1675 crate::testing::fins(0.05, 0.03),
1676 bottom(0.0),
1677 )];
1678 let base = check(&three_fin_rocket()).unwrap();
1679 assert_eq!(podded(vec![phantom.clone()], top(0.1)), base);
1680 assert_eq!(podded(Vec::new(), top(0.1)), base);
1681 assert_eq!(podded(Vec::new(), bottom(0.0)), base);
1683 let off = podded(vec![phantom], bottom(0.01));
1684 assert!(
1685 off.contains(&Finding::AttachmentOffBody {
1686 component: "pods".to_owned(),
1687 body: "airframe".to_owned(),
1688 }),
1689 "{off:?}"
1690 );
1691 assert_eq!(off.len(), base.len() + 1, "{off:?}");
1692
1693 let mut far = body("phantom", tube(0.0, 0.0, 0.0));
1695 far.children = vec![attached(
1696 "wings",
1697 crate::testing::fins(0.05, 0.03),
1698 top(0.01),
1699 )];
1700 let off = podded(vec![far], top(0.1));
1701 assert_eq!(
1702 off.iter()
1703 .filter(
1704 |f| matches!(f, Finding::AttachmentOffBody { component, body }
1705 if component == "wings" && body == "phantom")
1706 )
1707 .count(),
1708 1,
1709 "{off:?}"
1710 );
1711 assert_eq!(off.len(), base.len() + 1, "{off:?}");
1712 }
1713
1714 #[test]
1717 fn fin_root_must_touch_body() {
1718 let with_fins = |offset: f64| {
1719 let mut design = three_fin_rocket();
1720 design.stages[0].components[1].children[3].position = Some(bottom(offset));
1721 check(&design).unwrap()
1722 };
1723 let off = with_fins(0.15);
1725 assert_eq!(
1726 off,
1727 vec![Finding::AttachmentOffBody {
1728 component: "fins".to_owned(),
1729 body: "airframe".to_owned(),
1730 }]
1731 );
1732 assert!(has_errors(&off));
1733 assert!(has_errors(&with_fins(0.1)));
1735 let past = with_fins(0.04);
1736 let [
1737 Finding::AttachmentPastBodyEnd {
1738 ref component,
1739 excess_m,
1740 ..
1741 },
1742 ] = past[..]
1743 else {
1744 panic!("{past:?}")
1745 };
1746 assert_eq!(component, "fins");
1747 assert!((excess_m - 0.04).abs() < 1e-12);
1748 assert!(!has_errors(&past));
1749 assert!(with_fins(0.0).is_empty());
1750 let mut design = three_fin_rocket();
1752 design.stages[0].components[1].children[3].position = Some(top(-0.2));
1753 assert!(has_errors(&check(&design).unwrap()));
1754 }
1755
1756 #[test]
1757 fn internal_parts_radius_steps_and_a_missing_nose_are_found() {
1758 let mut airframe = body("airframe", tube(0.5, 0.03, 0.001));
1759 airframe.children = vec![
1760 attached("wide-ring", ring(0.005, 0.03, 0.01), top(0.1)),
1762 attached("long-mmt", inner_tube(0.2, 0.01, 0.001), bottom(0.05)),
1764 attached("lost", mass_component(0.1, 0.05, 0.01), top(-0.2)),
1766 attached("tight-ring", ring(0.005, 0.0295, 0.01), top(0.2)),
1768 ];
1769 let mut mount = airframe.children[1].clone();
1770 mount.motor_mount = Some(MotorMount::default());
1771 airframe.children[1] = mount;
1772 let design = rocket(vec![stage(
1773 "s",
1774 vec![airframe, body("tail", tube(0.1, 0.02, 0.001))],
1775 )]);
1776 let findings = check(&design).unwrap();
1777 assert_eq!(
1778 kinds(&findings),
1779 vec![
1780 ("no_nose_cone".to_owned(), Severity::Warning),
1781 ("radius_step".to_owned(), Severity::Warning),
1782 (
1783 "internal_part_wider_than_parent".to_owned(),
1784 Severity::Error
1785 ),
1786 (
1787 "internal_part_past_parent_end".to_owned(),
1788 Severity::Warning
1789 ),
1790 ("part_outside_rocket".to_owned(), Severity::Error),
1792 (
1793 "internal_part_tight_in_parent".to_owned(),
1794 Severity::Warning
1795 ),
1796 ]
1797 );
1798
1799 let mut design = three_fin_rocket();
1801 design.stages[0].components[1].children[1].auto = vec![AutoDimension::OuterRadius];
1802 assert_eq!(
1803 check(&design).unwrap(),
1804 vec![Finding::RingOverlapsInnerTube {
1805 ring: "ring-fore".to_owned(),
1806 tube: "mmt".to_owned(),
1807 }]
1808 );
1809 }
1810
1811 #[test]
1814 fn internal_parts_are_measured_from_their_parents_axis() {
1815 let offset = |part: Part, r: f64| match part {
1816 Part::InnerTube(mut t) => {
1817 t.radial_offset_m = r;
1818 Part::InnerTube(t)
1819 }
1820 Part::MassComponent(mut m) => {
1821 m.packing.radial_offset_m = r;
1822 Part::MassComponent(m)
1823 }
1824 other => other,
1825 };
1826 let mut pod = attached(
1827 "pod",
1828 offset(inner_tube(0.3, 0.02, 0.001), 0.025),
1829 bottom(0.0),
1830 );
1831 pod.children = vec![attached(
1832 "block",
1833 offset(inner_tube(0.01, 0.019, 0.003), 0.025),
1834 top(0.0),
1835 )];
1836 let mut airframe = body("airframe", tube(0.8, 0.05, 0.002));
1837 airframe.children = vec![pod, attached("ring", ring(0.005, 0.048, 0.0), bottom(-0.1))];
1838 let design = rocket(vec![stage(
1839 "s",
1840 vec![body("nose", crate::testing::nose(0.2, 0.05)), airframe],
1841 )]);
1842 assert_eq!(
1843 check(&design).unwrap(),
1844 vec![Finding::RingOverlapsInnerTube {
1845 ring: "ring".to_owned(),
1846 tube: "pod".to_owned(),
1847 }]
1848 );
1849
1850 let mut design = design;
1851 design.stages[0].components[1].children[0].children[0] =
1852 attached("on-axis", mass_component(0.1, 0.05, 0.004), top(0.1));
1853 let findings = check(&design).unwrap();
1854 let wide = findings
1855 .iter()
1856 .find_map(|f| match f {
1857 Finding::InternalPartWiderThanParent {
1858 component,
1859 reach_m,
1860 room_m,
1861 ..
1862 } if component == "on-axis" => Some((*reach_m, *room_m)),
1863 _ => None,
1864 })
1865 .unwrap();
1866 assert!(
1867 (wide.0 - 0.029).abs() < 1e-15 && (wide.1 - 0.019).abs() < 1e-15,
1868 "{wide:?}"
1869 );
1870 }
1871
1872 #[test]
1877 fn a_packed_part_wider_than_its_bore_warns_while_its_center_is_inside() {
1878 let room = 0.0255;
1880 let placed = |part: Part, offset_m: f64| {
1881 let part = match part {
1882 Part::MassComponent(mut m) => {
1883 m.packing.radial_offset_m = offset_m;
1884 Part::MassComponent(m)
1885 }
1886 Part::Parachute(mut p) => {
1887 p.packing.radial_offset_m = offset_m;
1888 Part::Parachute(p)
1889 }
1890 other => other,
1891 };
1892 let mut design = three_fin_rocket();
1893 design.stages[0].components[1]
1894 .children
1895 .push(attached("packed", part, top(0.2)));
1896 check(&design).unwrap()
1897 };
1898 let packed = |reach_m: f64| {
1899 vec![Finding::PackedPartWiderThanParent {
1900 component: "packed".to_owned(),
1901 parent: "airframe".to_owned(),
1902 reach_m,
1903 room_m: room,
1904 room_widens_aft: false,
1907 }]
1908 };
1909 for radius_m in [0.0305, 0.026] {
1911 assert_eq!(
1912 placed(mass_component(0.1, 0.05, radius_m), 0.0),
1913 packed(radius_m)
1914 );
1915 }
1916 let mut chute = three_fin_rocket().stages[0].components[1].children[4]
1917 .part
1918 .clone();
1919 if let Part::Parachute(p) = &mut chute {
1920 p.packing.radius_m = 0.03;
1921 }
1922 assert_eq!(placed(chute, 0.0), packed(0.03));
1923 let reach = room + 0.002;
1925 assert_eq!(
1926 placed(mass_component(0.1, 0.05, 0.002), room),
1927 packed(reach)
1928 );
1929 assert_eq!(
1930 placed(mass_component(0.1, 0.05, 0.002), room + 1e-7),
1931 vec![Finding::InternalPartWiderThanParent {
1932 component: "packed".to_owned(),
1933 parent: "airframe".to_owned(),
1934 reach_m: room + 1e-7 + 0.002,
1935 room_m: room,
1936 }]
1937 );
1938 for (radius_m, offset_m) in [(0.0002, room + 0.0002), (0.0001, room + 0.0005)] {
1941 assert_eq!(
1942 placed(mass_component(0.1, 0.05, radius_m), offset_m),
1943 vec![Finding::InternalPartWiderThanParent {
1944 component: "packed".to_owned(),
1945 parent: "airframe".to_owned(),
1946 reach_m: offset_m + radius_m,
1947 room_m: room,
1948 }]
1949 );
1950 }
1951 let findings = placed(ring(0.005, 0.0305, 0.0), 0.0);
1953 assert!(
1954 matches!(&findings[..], [Finding::InternalPartWiderThanParent { component, .. }]
1955 if component == "packed"),
1956 "{findings:?}"
1957 );
1958 }
1959
1960 #[test]
1966 fn a_part_wider_than_its_parent_warns_only_as_a_fit_or_a_cap() {
1967 let fitted = |radius_m: f64, at: Position| {
1970 let mut design = three_fin_rocket();
1971 let mut coupler = attached("coupler", inner_tube(0.1, 0.0255, 0.001), top(0.1));
1972 coupler.children = vec![attached("bulkhead", ring(0.005, radius_m, 0.0), at)];
1973 design.stages[0].components[1].children.push(coupler);
1974 check(&design).unwrap()
1975 };
1976 let room = 0.0255 - 0.001;
1977 let tight = room + 0.0008;
1978 assert_eq!(
1979 fitted(tight, top(0.02)),
1980 vec![Finding::InternalPartTightInParent {
1981 component: "bulkhead".to_owned(),
1982 parent: "coupler".to_owned(),
1983 reach_m: tight,
1984 room_m: room,
1985 }]
1986 );
1987 assert_eq!(
1988 fitted(tight + 1e-7, top(0.02)),
1989 vec![Finding::InternalPartWiderThanParent {
1990 component: "bulkhead".to_owned(),
1991 parent: "coupler".to_owned(),
1992 reach_m: tight + 1e-7,
1993 room_m: room,
1994 }]
1995 );
1996 let capped = 0.0255 + 0.0008;
1999 for (radius_m, at) in [
2000 (0.0255, top(0.0)),
2001 (0.0255, top(-0.005)),
2002 (0.0255, bottom(0.0)),
2003 (capped, bottom(0.005)),
2004 ] {
2005 let findings = fitted(radius_m, at);
2006 assert!(!has_errors(&findings));
2007 let findings: Vec<_> = findings
2009 .into_iter()
2010 .filter(|f| !matches!(f, Finding::InternalPartPastParentEnd { .. }))
2011 .collect();
2012 assert_eq!(
2013 findings,
2014 vec![Finding::RingAgainstParentEnd {
2015 ring: "bulkhead".to_owned(),
2016 parent: "coupler".to_owned(),
2017 reach_m: radius_m,
2018 room_m: 0.0255,
2019 }],
2020 "{radius_m} at {at:?}"
2021 );
2022 }
2023 for (radius_m, at) in [(0.0255, top(0.02)), (capped + 1e-7, top(0.0))] {
2025 let findings = fitted(radius_m, at);
2026 assert!(
2027 matches!(&findings[..], [Finding::InternalPartWiderThanParent { component, .. }]
2028 if component == "bulkhead"),
2029 "{radius_m} at {at:?}: {findings:?}"
2030 );
2031 }
2032 for (cluster, offset_m, length_m) in [
2035 (vec![[0.018, 0.0], [-0.018, 0.0]], 0.0, 0.005),
2036 (Vec::new(), 0.018, 0.005),
2037 (Vec::new(), 0.0, 0.1),
2038 ] {
2039 let mut design = three_fin_rocket();
2040 let mut tube = inner_tube(0.1, 0.007, 0.001);
2041 if let Part::InnerTube(inner) = &mut tube {
2042 inner.cluster_m = cluster.clone();
2043 inner.radial_offset_m = offset_m;
2044 }
2045 let mut holder = attached("holder", tube, top(0.1));
2046 holder.children = vec![attached("ring", ring(length_m, 0.012, 0.0), top(0.0))];
2047 design.stages[0].components[1].children.push(holder);
2048 let findings = check(&design).unwrap();
2049 assert!(
2050 findings.iter().any(|f| matches!(f,
2051 Finding::InternalPartWiderThanParent { component, .. } if component == "ring")),
2052 "{cluster:?} {offset_m} {length_m}: {findings:?}"
2053 );
2054 }
2055 let mut design = three_fin_rocket();
2057 let mut coupler = attached("coupler", inner_tube(0.1, 0.0255, 0.001), top(0.1));
2058 coupler.children = vec![attached(
2059 "sleeve",
2060 inner_tube(0.01, 0.0255, 0.001),
2061 top(0.0),
2062 )];
2063 design.stages[0].components[1].children.push(coupler);
2064 assert!(matches!(
2065 &check(&design).unwrap()[..],
2066 [Finding::InternalPartWiderThanParent { component, .. }] if component == "sleeve"
2067 ));
2068 }
2069
2070 #[test]
2075 fn a_ring_around_its_motor_tube_needs_room_in_the_airframe() {
2076 let wrapped = |outer_m: f64, inner_m: f64, offset_m: f64, cluster: Vec<[f64; 2]>| {
2079 let mut design = three_fin_rocket();
2080 let mount = &mut design.stages[0].components[1].children[0];
2081 if let Part::InnerTube(tube) = &mut mount.part {
2082 tube.radial_offset_m = offset_m;
2083 tube.cluster_m = cluster;
2084 }
2085 mount.children = vec![attached("wrap", ring(0.003, outer_m, inner_m), top(0.1))];
2086 check(&design).unwrap()
2087 };
2088 let (outer, bore, airframe) = (0.020, 0.019, 0.0255);
2089 assert_eq!(wrapped(airframe, outer, 0.0, Vec::new()), vec![]);
2090 assert_eq!(wrapped(airframe, outer + 0.001, 0.0, Vec::new()), vec![]);
2092 let tight = airframe + 0.0008;
2093 assert_eq!(
2094 wrapped(tight, outer, 0.0, Vec::new()),
2095 vec![Finding::InternalPartTightInParent {
2096 component: "wrap".to_owned(),
2097 parent: "airframe".to_owned(),
2098 reach_m: tight,
2099 room_m: airframe,
2100 }]
2101 );
2102 assert_eq!(
2103 wrapped(tight + 1e-7, outer, 0.0, Vec::new()),
2104 vec![Finding::InternalPartWiderThanParent {
2105 component: "wrap".to_owned(),
2106 parent: "airframe".to_owned(),
2107 reach_m: tight + 1e-7,
2108 room_m: airframe,
2109 }]
2110 );
2111 let in_tube = |findings: Vec<Finding>| {
2113 findings.iter().any(|f| {
2114 matches!(f, Finding::InternalPartWiderThanParent { component, parent, room_m, .. }
2115 if component == "wrap" && parent == "mmt" && *room_m == bore)
2116 })
2117 };
2118 assert!(in_tube(wrapped(airframe, outer - 1e-6, 0.0, Vec::new())));
2119 assert!(in_tube(wrapped(airframe, outer, 0.002, Vec::new())));
2120 assert!(in_tube(wrapped(
2121 airframe,
2122 outer,
2123 0.0,
2124 vec![[0.0, 0.0], [0.05, 0.0]]
2125 )));
2126 assert_eq!(wrapped(airframe, outer - 5e-10, 0.0, Vec::new()), vec![]);
2128
2129 let overhung = |at: Position| {
2133 let mut design = three_fin_rocket();
2134 let mount = &mut design.stages[0].components[1].children[0];
2135 mount.position = Some(bottom(0.05));
2136 mount.children = vec![attached("wrap", ring(0.003, airframe, outer), at)];
2137 check(&design).unwrap()
2138 };
2139 assert!(in_tube(overhung(bottom(0.0))));
2140 assert!(in_tube(overhung(bottom(-0.048))));
2141 assert_eq!(
2142 overhung(top(0.1))
2143 .into_iter()
2144 .filter(
2145 |f| matches!(f, Finding::InternalPartWiderThanParent { component, .. }
2146 | Finding::InternalPartTightInParent { component, .. } if component == "wrap")
2147 )
2148 .count(),
2149 0
2150 );
2151
2152 let mut design = three_fin_rocket();
2154 let airframe_part = &mut design.stages[0].components[1];
2155 airframe_part.children[0].children =
2156 vec![attached("wrap", ring(0.003, airframe, outer), top(0.1))];
2157 let mut side = inner_tube(0.04, 0.004, 0.0005);
2158 if let Part::InnerTube(tube) = &mut side {
2159 tube.radial_offset_m = 0.021;
2160 }
2161 airframe_part
2162 .children
2163 .push(attached("side", side, top(0.58)));
2164 assert_eq!(
2165 check(&design).unwrap(),
2166 vec![Finding::RingOverlapsInnerTube {
2167 ring: "wrap".to_owned(),
2168 tube: "side".to_owned(),
2169 }]
2170 );
2171 }
2172
2173 #[test]
2176 fn the_fit_tolerance_is_the_coarse_general_tolerance_of_the_bore() {
2177 for (diameter_m, tolerance_m) in [
2178 (0.0004, 0.0),
2179 (0.0005, 0.0002),
2180 (0.002, 0.0002),
2181 (0.006, 0.0003),
2182 (0.0061, 0.0005),
2183 (0.030, 0.0005),
2184 (0.0301, 0.0008),
2185 (0.120, 0.0008),
2186 (0.150, 0.0012),
2187 (5.0, 0.004),
2188 ] {
2189 assert_eq!(
2190 fit_tolerance_m(diameter_m / 2.0),
2191 tolerance_m,
2192 "{diameter_m}"
2193 );
2194 }
2195 assert_eq!(fit_tolerance_m(f64::NAN), 0.0);
2196 }
2197
2198 #[test]
2200 fn motor_outside_its_mount_is_rejected() {
2201 for overhang in [5.0, 0.2, -0.3] {
2202 let mut design = three_fin_rocket();
2203 design.stages[0].components[1].children[0].motor_mount = Some(MotorMount {
2204 overhang_m: overhang,
2205 });
2206 let findings = check(&design).unwrap();
2207 assert_eq!(
2208 findings,
2209 vec![Finding::MotorOutsideMount {
2210 configuration: "main".to_owned(),
2211 mount: "mmt".to_owned(),
2212 }],
2213 "{overhang}"
2214 );
2215 assert!(has_errors(&findings));
2216 }
2217 }
2218
2219 #[test]
2221 fn parts_and_centers_off_the_rocket_are_rejected() {
2222 let mut design = three_fin_rocket();
2223 design.stages[0].components[1].children[4].position = Some(top(2.0));
2224 assert_eq!(
2225 check(&design).unwrap(),
2226 vec![Finding::PartOutsideRocket {
2227 component: "chute".to_owned(),
2228 }]
2229 );
2230 let mut design = three_fin_rocket();
2231 design.stages[0].overrides.cg_aft_m = Some(350.0);
2232 let findings = check(&design).unwrap();
2233 assert!(
2234 matches!(&findings[..], [Finding::CenterOutsideRocket { stage, station_m }]
2235 if stage == "sustainer" && *station_m == 350.0),
2236 "{findings:?}"
2237 );
2238 let mut design = three_fin_rocket();
2240 design.stages[0].added_mass = Some(crate::AddedMass {
2241 mass_kg: 1.0,
2242 cg_aft_m: Some(350.0),
2243 });
2244 let findings = check(&design).unwrap();
2245 assert!(
2246 matches!(&findings[..], [Finding::CenterOutsideRocket { stage, station_m }]
2247 if stage == "sustainer" && *station_m > 100.0),
2248 "{findings:?}"
2249 );
2250 design.stages[0].added_mass = Some(crate::AddedMass {
2252 mass_kg: 1.0,
2253 cg_aft_m: None,
2254 });
2255 assert_eq!(check(&design).unwrap(), Vec::new());
2256 let mut design = three_fin_rocket();
2258 let mount = &mut design.stages[0].components[1].children[0];
2259 mount.position = Some(bottom(0.012));
2260 mount.children = vec![attached(
2261 "retainer",
2262 mass_component(0.05, 0.01, 0.015),
2263 bottom(0.0),
2264 )];
2265 let findings = check(&design).unwrap();
2266 assert!(
2267 matches!(&findings[..], [Finding::InternalPartPastParentEnd { component, .. }]
2268 if component == "mmt"),
2269 "{findings:?}"
2270 );
2271 let mut flush = design.clone();
2273 flush.stages[0].components[1].children[0].children[0].position = Some(top(0.3));
2274 let layout = flush.layout().unwrap();
2275 let (_, retainer) = layout.find("retainer").unwrap();
2276 assert!(
2277 retainer.fore_station_m >= layout.length_m,
2278 "the test needs it behind"
2279 );
2280 let findings = check(&flush).unwrap();
2281 assert!(
2282 findings
2283 .iter()
2284 .all(|f| !matches!(f, Finding::PartOutsideRocket { .. })),
2285 "{findings:?}"
2286 );
2287 assert!(!has_errors(&findings), "{findings:?}");
2288 let mut clear = design.clone();
2290 clear.stages[0].components[1].children[0].children[0].position = Some(top(0.35));
2291 assert_eq!(
2292 check(&clear).unwrap(),
2293 vec![
2294 Finding::InternalPartPastParentEnd {
2295 component: "mmt".to_owned(),
2296 parent: "airframe".to_owned(),
2297 excess_m: check(&design)
2298 .unwrap()
2299 .iter()
2300 .find_map(|f| match f {
2301 Finding::InternalPartPastParentEnd { excess_m, .. } => Some(*excess_m),
2302 _ => None,
2303 })
2304 .unwrap(),
2305 },
2306 Finding::PartOutsideRocket {
2307 component: "retainer".to_owned(),
2308 },
2309 ]
2310 );
2311 let mut can = body("can", tube(0.3, 0.03, 0.0005));
2314 let mut fins = attached("trailing-fins", crate::testing::fins(0.2, 0.1), bottom(0.0));
2315 if let Part::FinSet(set) = &mut fins.part {
2316 set.planform = crate::FinPlanform::Trapezoidal {
2317 root_chord_m: 0.2,
2318 tip_chord_m: 0.2,
2319 span_m: 0.1,
2320 sweep_m: 0.4,
2321 };
2322 }
2323 can.children = vec![fins];
2324 let design = rocket(vec![stage("s", vec![can])]);
2325 let layout = design.layout().unwrap();
2326 assert!(
2327 -layout.stages[0].mass.cg_m.z > layout.length_m,
2328 "the test needs it off"
2329 );
2330 assert!(!has_errors(&check(&design).unwrap()));
2331 let mut heavier = design.clone();
2333 heavier.stages[0].components[0].children[0]
2334 .overrides
2335 .mass_kg = Some(1.0);
2336 assert!(!has_errors(&check(&heavier).unwrap()));
2337 let mut sideways = design.clone();
2339 sideways.stages[0].components[0].children[0]
2340 .overrides
2341 .cg_xy_m = Some([0.0, 0.0]);
2342 assert!(!has_errors(&check(&sideways).unwrap()));
2343 let mut moved = design.clone();
2345 moved.stages[0].components[0].children[0].overrides.cg_aft_m = Some(50.0);
2346 let findings = check(&moved).unwrap();
2347 assert!(
2348 matches!(&findings[..], [Finding::NoNoseCone { .. }, Finding::CenterOutsideRocket { stage, .. }] if stage == "s"),
2349 "{findings:?}"
2350 );
2351 let mut design = rocket(vec![stage(
2354 "s",
2355 vec![
2356 body("nose", crate::testing::nose(0.1, 0.03)),
2357 body("airframe", tube(0.7, 0.03, 0.001)),
2358 ],
2359 )]);
2360 design.stages[0].components[1].children = vec![attached(
2361 "tail-weight",
2362 mass_component(0.05, 0.0, 0.01),
2363 Position::Absolute { station_m: 0.8 },
2364 )];
2365 assert!(design.layout().unwrap().length_m < 0.8);
2366 assert!(check(&design).unwrap().is_empty());
2367 for (nose, tube_length) in [(0.1, 0.2), (0.15, 0.15)] {
2370 let mut design = rocket(vec![stage(
2371 "s",
2372 vec![
2373 body("nose", crate::testing::nose(nose, 0.03)),
2374 body("airframe", tube(tube_length, 0.03, 0.001)),
2375 ],
2376 )]);
2377 design.stages[0].components[1].children = vec![attached(
2378 "tail-block",
2379 mass_component(0.05, 0.05, 0.01),
2380 Position::Absolute { station_m: 0.3 },
2381 )];
2382 let findings = check(&design).unwrap();
2383 assert!(
2384 matches!(&findings[..], [Finding::InternalPartPastParentEnd { component, .. }]
2385 if component == "tail-block"),
2386 "{nose} + {tube_length}: {findings:?}"
2387 );
2388 }
2389 let mut design = three_fin_rocket();
2392 design.stages[0].components[0].children = vec![attached(
2393 "ballast",
2394 mass_component(0.1, 0.02, 0.2),
2395 bottom(0.0),
2396 )];
2397 assert!(matches!(
2398 &check(&design).unwrap()[..],
2399 [Finding::PackedPartWiderThanParent { component, .. }] if component == "ballast"
2400 ));
2401 let mut layout = three_fin_rocket().layout().unwrap();
2403 layout.components[2].parent = Some(999);
2404 let _ = check_layout(&layout);
2405 }
2406
2407 #[test]
2413 fn a_packed_part_names_367_only_where_the_room_widens_aft_of_it() {
2414 let widens = |fore_radius_m: f64, aft_radius_m: f64, position: Option<Position>| {
2415 let transition = Part::Transition(crate::Transition {
2416 shape: crate::NoseShape::Conical {},
2417 clipped: false,
2418 length_m: 0.2,
2419 fore_radius_m,
2420 aft_radius_m,
2421 wall: crate::Wall::Shell { thickness_m: 0.002 },
2422 fore_shoulder: None,
2423 aft_shoulder: None,
2424 material: crate::Material::bulk("PLA", 1240.0),
2425 });
2426 let mut middle = body("transition", transition);
2427 let position = position.unwrap_or(if fore_radius_m < aft_radius_m {
2430 top(0.01)
2431 } else {
2432 bottom(-0.01)
2433 });
2434 middle.children = vec![attached("mass", mass_component(0.05, 0.03, 0.02), position)];
2435 let design = rocket(vec![stage(
2436 "sustainer",
2437 vec![
2438 body("nose", crate::testing::nose(0.2, fore_radius_m)),
2439 middle,
2440 body("airframe", tube(0.6, aft_radius_m, 0.0015)),
2441 ],
2442 )]);
2443 let findings = check(&design).unwrap();
2444 let packed: Vec<_> = findings
2445 .iter()
2446 .filter_map(|finding| match finding {
2447 Finding::PackedPartWiderThanParent {
2448 component,
2449 room_widens_aft,
2450 ..
2451 } if component == "mass" => Some((
2452 *room_widens_aft,
2453 finding.describe(&|id: &str| id.to_owned()),
2454 )),
2455 _ => None,
2456 })
2457 .collect();
2458 assert_eq!(packed.len(), 1, "{findings:?}");
2459 let (flag, text) = packed[0].clone();
2460 assert_eq!(flag, text.contains("issue #367"), "{text}");
2461 flag
2462 };
2463 assert!(widens(0.015, 0.025, None), "a shoulder widens aft");
2464 assert!(!widens(0.025, 0.015, None), "a boattail narrows aft");
2465 assert!(
2468 !widens(0.025, 0.015, Some(bottom(0.01))),
2469 "past a boattail's end"
2470 );
2471 }
2472
2473 #[test]
2477 fn a_part_in_a_nose_cone_needs_room_where_it_sits() {
2478 let findings = |part: Part, position: Position| {
2479 let mut nose = body("nose", crate::testing::nose(0.2, 0.027));
2480 nose.children = vec![attached("part", part, position)];
2481 let design = rocket(vec![stage(
2482 "sustainer",
2483 vec![nose, body("airframe", tube(0.6, 0.027, 0.0015))],
2484 )]);
2485 check(&design).unwrap()
2486 };
2487 let room = |x_m: f64| (0.135 * x_m - 0.002_f64).max(0.0);
2488 let bulkhead = || ring(0.01, 0.02, 0.0);
2491 let tip = findings(bulkhead(), top(0.0));
2492 assert!(
2493 matches!(&tip[..], [Finding::InternalPartWiderThanParent { component, parent, reach_m, room_m }]
2494 if component == "part" && parent == "nose" && *reach_m == 0.02 && *room_m == 0.0),
2495 "{tip:?}"
2496 );
2497 assert_eq!(findings(bulkhead(), bottom(0.0)), vec![]);
2499 assert_eq!(
2501 findings(mass_component(0.05, 0.01, 0.02), bottom(0.0)),
2502 vec![]
2503 );
2504 let packed = findings(mass_component(0.05, 0.03, 0.02), top(0.0));
2507 assert!(
2508 matches!(&packed[..], [Finding::PackedPartWiderThanParent { component, room_m, room_widens_aft, .. }]
2509 if component == "part" && *room_m == 0.0 && *room_widens_aft),
2510 "{packed:?}"
2511 );
2512 let text = packed[0].describe(&|id: &str| id.to_owned());
2515 assert!(text.contains("issue #367"), "{text}");
2516 assert!(text.contains("margin may read high"), "{text}");
2517 let mut off_axis = mass_component(0.05, 0.03, 0.02);
2519 if let Part::MassComponent(mass) = &mut off_axis {
2520 mass.packing.radial_offset_m = 0.005;
2521 }
2522 let off = findings(off_axis, top(0.0));
2523 assert!(
2524 matches!(&off[..], [Finding::InternalPartWiderThanParent { component, reach_m, room_m, .. }]
2525 if component == "part" && (*reach_m - 0.025).abs() < 1e-15 && *room_m == 0.0),
2526 "{off:?}"
2527 );
2528 let point = findings(mass_component(0.05, 0.0, 0.02), top(0.0));
2531 assert!(
2532 matches!(&point[..], [Finding::PackedPartWiderThanParent { room_m, room_widens_aft, .. }]
2533 if *room_m == 0.0 && *room_widens_aft),
2534 "{point:?}"
2535 );
2536 let mut point_off_axis = mass_component(0.05, 0.0, 0.02);
2537 if let Part::MassComponent(mass) = &mut point_off_axis {
2538 mass.packing.radial_offset_m = 0.005;
2539 }
2540 let point_off = findings(point_off_axis, top(0.0));
2541 assert!(
2542 matches!(&point_off[..], [Finding::InternalPartWiderThanParent { room_m, .. }] if *room_m == 0.0),
2543 "{point_off:?}"
2544 );
2545 let wedged = findings(inner_tube(0.1, 0.0245, 0.001), bottom(0.0));
2548 match &wedged[..] {
2549 [
2550 Finding::InternalPartWedgedInParent {
2551 component,
2552 parent,
2553 reach_m,
2554 room_m,
2555 widest_room_m,
2556 },
2557 ] => {
2558 assert_eq!((component.as_str(), parent.as_str()), ("part", "nose"));
2559 assert_eq!(*reach_m, 0.0245);
2560 assert!((room_m - room(0.1)).abs() < 1e-15, "{room_m}");
2561 assert!((widest_room_m - room(0.2)).abs() < 1e-15, "{widest_room_m}");
2562 }
2563 other => panic!("{other:?}"),
2564 }
2565 let wide = findings(inner_tube(0.1, 0.0265, 0.001), bottom(0.0));
2567 assert!(
2568 matches!(&wide[..], [Finding::InternalPartWiderThanParent { room_m, .. }]
2569 if (room_m - room(0.2)).abs() < 1e-15),
2570 "{wide:?}"
2571 );
2572 let past = findings(ring(0.006, 0.026, 0.0), bottom(0.006));
2575 assert!(
2576 matches!(&past[..], [Finding::InternalPartPastParentEnd { component, .. }]
2577 if component == "part"),
2578 "{past:?}"
2579 );
2580 }
2581
2582 #[test]
2584 fn a_cluster_whose_tubes_cross_is_flagged() {
2585 let at = |r: f64| {
2586 let mut design = three_fin_rocket();
2587 if let Part::InnerTube(tube) = &mut design.stages[0].components[1].children[0].part {
2588 tube.cluster_m = [90.0_f64, 210.0, 330.0]
2589 .iter()
2590 .map(|a| [r * a.to_radians().cos(), r * a.to_radians().sin()])
2591 .collect();
2592 }
2593 check(&design)
2594 .unwrap()
2595 .into_iter()
2596 .filter(|f| matches!(f, Finding::ClusterTubesOverlap { .. }))
2597 .collect::<Vec<_>>()
2598 };
2599 assert!(at(0.04 / 3.0_f64.sqrt()).is_empty());
2600 let [
2601 Finding::ClusterTubesOverlap {
2602 tube,
2603 apart_m,
2604 diameter_m,
2605 },
2606 ] = &at(0.02)[..]
2607 else {
2608 panic!("one finding");
2609 };
2610 assert_eq!(tube, "mmt");
2611 assert!((apart_m - 0.02 * 3.0_f64.sqrt()).abs() < 1e-15, "{apart_m}");
2612 assert_eq!(*diameter_m, 0.04);
2613 assert_eq!(at(0.02)[0].severity(), Severity::Warning);
2614 }
2615
2616 #[test]
2619 fn a_finding_with_the_old_uk_kind_reads_the_same() {
2620 let finding = Finding::CenterOutsideRocket {
2621 stage: "sustainer".to_owned(),
2622 station_m: 2.5,
2623 };
2624 let text = serde_json::to_string(&finding).unwrap();
2625 assert!(
2626 text.contains("\"kind\":\"center_outside_rocket\""),
2627 "{text}"
2628 );
2629 let old = text.replace("center_outside_rocket", "centre_outside_rocket");
2630 assert_eq!(serde_json::from_str::<Finding>(&old).unwrap(), finding);
2631 }
2632}