1use std::collections::BTreeSet;
21use std::sync::Arc;
22
23use hpr_core::DVec3;
24use hpr_motor::{Delay, MassElement, SolidMotor};
25use serde::{Deserialize, Serialize};
26
27use crate::error::DesignError;
28use crate::mass::MassProperties;
29use crate::shapes::check_dimension;
30use crate::tree::{Layout, Rocket, StageMasses};
31
32#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize, schemars::JsonSchema)]
34#[serde(deny_unknown_fields)]
35pub struct MotorMount {
36 #[serde(default)]
38 pub overhang_m: f64,
39}
40
41#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
44#[serde(deny_unknown_fields)]
45pub struct Configuration {
46 pub id: String,
48 #[serde(default)]
50 pub name: String,
51 pub motors: Vec<MountedMotor>,
53}
54
55#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, schemars::JsonSchema)]
61#[serde(rename_all = "snake_case", deny_unknown_fields)]
62#[non_exhaustive]
63pub enum Ignition {
64 #[default]
66 Launch,
67 Time {
69 time_s: f64,
71 },
72 Burnout {
75 mount: String,
77 delay_s: f64,
79 },
80 Separation {
84 delay_s: f64,
86 },
87 Never,
91}
92
93impl Ignition {
94 #[must_use]
96 pub fn is_launch(&self) -> bool {
97 *self == Self::Launch
98 }
99}
100
101#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
103#[serde(deny_unknown_fields)]
104pub struct MountedMotor {
105 pub mount: String,
107 #[serde(default)]
109 pub designation: String,
110 pub diameter_m: f64,
112 pub length_m: f64,
114 pub motor: SolidMotor,
116 #[serde(default, skip_serializing_if = "Option::is_none")]
118 pub delay: Option<Delay>,
119 #[serde(default, skip_serializing_if = "Ignition::is_launch")]
121 pub ignition: Ignition,
122 #[serde(default, skip_serializing_if = "Vec::is_empty")]
131 pub failed_tubes: Vec<usize>,
132}
133
134#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
137pub struct PlacedMotor {
138 pub mount: String,
140 pub stage: usize,
142 pub nozzle_m: DVec3,
144 pub mounted: MountedMotor,
146 #[serde(default)]
148 pub tube: usize,
149 #[serde(default)]
152 pub fails: bool,
153}
154
155impl PlacedMotor {
156 pub fn nozzle_station_m(&self) -> f64 {
158 -self.nozzle_m.z
159 }
160
161 pub fn fore_station_m(&self) -> f64 {
163 self.nozzle_station_m() - self.mounted.length_m
164 }
165
166 pub fn place(&self, element: &MassElement) -> MassProperties {
168 MassProperties::from_motor_element(element, self.nozzle_m.z).translated(DVec3::new(
169 self.nozzle_m.x,
170 self.nozzle_m.y,
171 0.0,
172 ))
173 }
174
175 pub fn mass_properties(&self, t_s: f64) -> MassProperties {
177 self.place(&self.mounted.motor.state(t_s).total)
178 }
179
180 pub fn mass_properties_lit(&self, t_s: f64, ignition_s: Option<f64>) -> MassProperties {
183 let since_s = ignition_s.map_or(0.0, |ignition_s| (t_s - ignition_s).max(0.0));
184 self.mass_properties(since_s)
185 }
186
187 pub fn dry_mass_properties(&self) -> MassProperties {
189 self.place(&self.mounted.motor.dry())
190 }
191}
192
193#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
195pub struct Assembly {
196 pub configuration: String,
198 pub layout: Layout,
200 pub motors: Vec<PlacedMotor>,
202}
203
204impl Assembly {
205 pub fn mass_properties(&self, t_s: f64) -> MassProperties {
210 self.motors
211 .iter()
212 .fold(self.layout.structure, |sum, motor| {
213 let ignition = (!motor.fails).then_some(0.0);
214 MassProperties::combine([&sum, &motor.mass_properties_lit(t_s, ignition)])
215 })
216 }
217
218 pub fn mass_properties_lit(&self, t_s: f64, ignition_s: &[Option<f64>]) -> MassProperties {
223 self.mass_properties_lit_on(self.layout.structure, t_s, ignition_s)
224 }
225
226 pub fn mass_properties_lit_on(
229 &self,
230 structure: MassProperties,
231 t_s: f64,
232 ignition_s: &[Option<f64>],
233 ) -> MassProperties {
234 self.motors
235 .iter()
236 .enumerate()
237 .fold(structure, |sum, (index, motor)| {
238 let ignition = ignition_s.get(index).copied().unwrap_or(Some(0.0));
239 MassProperties::combine([&sum, &motor.mass_properties_lit(t_s, ignition)])
240 })
241 }
242
243 #[must_use]
252 pub fn ignition_times_s(&self, separated_s: impl Fn(usize) -> Option<f64>) -> Vec<Option<f64>> {
253 ignition_times_s(&self.motors, separated_s, true)
254 }
255
256 pub fn dry_mass_properties(&self) -> MassProperties {
259 self.motors
260 .iter()
261 .fold(self.layout.structure, |sum, motor| {
262 let motor = if motor.fails {
263 motor.mass_properties_lit(0.0, None)
264 } else {
265 motor.dry_mass_properties()
266 };
267 MassProperties::combine([&sum, &motor])
268 })
269 }
270}
271
272fn ignition_times_s(
275 motors: &[PlacedMotor],
276 separated_s: impl Fn(usize) -> Option<f64>,
277 failures: bool,
278) -> Vec<Option<f64>> {
279 let fails = |motor: &PlacedMotor| failures && motor.fails;
280 let mut times: Vec<Option<f64>> = motors
281 .iter()
282 .map(|motor| match &motor.mounted.ignition {
283 _ if fails(motor) => None,
284 Ignition::Launch => Some(0.0),
285 Ignition::Time { time_s } => Some(*time_s),
286 Ignition::Separation { delay_s } => separated_s(motor.stage).map(|t| t + delay_s),
287 Ignition::Burnout { .. } => None,
288 Ignition::Never => (!failures).then_some(0.0),
290 })
291 .collect();
292 for _ in 0..motors.len() {
295 let mut changed = false;
296 for (index, motor) in motors.iter().enumerate() {
297 let Ignition::Burnout { mount, delay_s } = &motor.mounted.ignition else {
298 continue;
299 };
300 if times[index].is_some() || fails(motor) {
301 continue;
302 }
303 let lit = motors
305 .iter()
306 .zip(×)
307 .filter(|(other, _)| other.mount == *mount)
308 .find_map(|(other, time)| time.map(|t| t + other.mounted.motor.burnout_time_s()));
309 if let Some(burnout_s) = lit {
310 times[index] = Some(burnout_s + delay_s);
311 changed = true;
312 }
313 }
314 if !changed {
315 break;
316 }
317 }
318 times
319}
320
321impl Layout {
322 pub fn place_motors(
337 &self,
338 configuration: &Configuration,
339 ) -> Result<Vec<PlacedMotor>, DesignError> {
340 let mut mounts = BTreeSet::new();
341 let mut motors = Vec::with_capacity(configuration.motors.len());
342 for mounted in &configuration.motors {
343 let (_, mount) = self
344 .find(&mounted.mount)
345 .ok_or_else(|| DesignError::UnknownId {
346 what: "motor mount",
347 id: mounted.mount.clone(),
348 })?;
349 let in_mount = |error| DesignError::InComponent {
350 id: mount.id.clone(),
351 source: Box::new(error),
352 };
353 check_dimension("motor diameter (m)", mounted.diameter_m, false).map_err(in_mount)?;
354 check_dimension("motor length (m)", mounted.length_m, false).map_err(in_mount)?;
355 let Some(spec) = mount.motor_mount else {
356 return Err(DesignError::Tree {
357 id: mount.id.clone(),
358 message: format!(
359 "configuration {} puts a motor here, but it is not a motor mount",
360 configuration.id
361 ),
362 });
363 };
364 if !mounts.insert(mount.id.as_str()) {
365 return Err(DesignError::Tree {
366 id: mount.id.clone(),
367 message: format!(
368 "configuration {} puts two motors in this mount",
369 configuration.id
370 ),
371 });
372 }
373 if !spec.overhang_m.is_finite() {
374 return Err(in_mount(DesignError::Domain {
375 what: "motor overhang (m)",
376 value: spec.overhang_m,
377 }));
378 }
379 match &mounted.ignition {
380 Ignition::Launch => {}
381 Ignition::Time { time_s: value } => {
382 check_ignition("ignition time after launch (s)", *value).map_err(in_mount)?;
383 }
384 Ignition::Burnout { delay_s: value, .. } => {
385 check_ignition("ignition delay (s)", *value).map_err(in_mount)?;
386 }
387 Ignition::Separation { delay_s: value } => {
388 check_ignition("ignition delay (s)", *value).map_err(in_mount)?;
389 if mount.stage + 1 >= self.stages.len() {
390 return Err(DesignError::Tree {
391 id: mount.id.clone(),
392 message: format!(
393 "configuration {} lights this motor at its stage's separation, \
394 but no stage is aft of it to separate",
395 configuration.id
396 ),
397 });
398 }
399 }
400 Ignition::Never => {}
401 }
402 let tubes = mount.contents_copies().map_err(in_mount)?;
403 for (k, &tube) in mounted.failed_tubes.iter().enumerate() {
404 if tube >= tubes.len() || mounted.failed_tubes[..k].contains(&tube) {
405 return Err(in_mount(DesignError::Domain {
406 what: "failed tube (index into the mount's tubes, each named once)",
407 value: tube as f64,
408 }));
409 }
410 }
411 let axis = mount.part.axis_offset_m();
412 let z = -(mount.aft_station_m() + spec.overhang_m);
413 for (tube, place) in tubes.into_iter().enumerate() {
414 let [x, y] = place.point(axis);
415 motors.push(PlacedMotor {
416 mount: mount.id.clone(),
417 stage: mount.stage,
418 nozzle_m: DVec3::new(x, y, z),
419 mounted: mounted.clone(),
420 tube,
421 fails: mounted.ignition == Ignition::Never
422 || mounted.failed_tubes.contains(&tube),
423 });
424 }
425 }
426 for motor in &motors {
427 if let Ignition::Burnout { mount, .. } = &motor.mounted.ignition
428 && !motors.iter().any(|other| other.mount == *mount)
429 {
430 return Err(DesignError::Tree {
431 id: motor.mount.clone(),
432 message: format!(
433 "configuration {} lights this motor at the burnout of mount {mount}, \
434 which holds no motor in it",
435 configuration.id
436 ),
437 });
438 }
439 }
440 let lit = ignition_times_s(&motors, |_| Some(0.0), false);
443 if let Some(index) = lit.iter().position(Option::is_none) {
444 return Err(DesignError::Tree {
445 id: motors[index].mount.clone(),
446 message: format!(
447 "configuration {} lights this motor by a chain of burnouts that comes back \
448 to it",
449 configuration.id
450 ),
451 });
452 }
453 Ok(motors)
454 }
455}
456
457fn check_ignition(what: &'static str, value: f64) -> Result<(), DesignError> {
459 if value.is_finite() && value >= 0.0 {
460 Ok(())
461 } else {
462 Err(DesignError::Domain { what, value })
463 }
464}
465
466impl Rocket {
467 pub fn configuration(&self, id: &str) -> Option<&Configuration> {
469 self.configurations.iter().find(|c| c.id == id)
470 }
471
472 pub fn check_configuration_ids(&self) -> Result<(), DesignError> {
478 let mut ids = BTreeSet::new();
479 for configuration in &self.configurations {
480 if configuration.id.is_empty() || !ids.insert(configuration.id.as_str()) {
481 return Err(DesignError::DuplicateId(configuration.id.clone()));
482 }
483 }
484 Ok(())
485 }
486
487 pub fn assemble(&self, configuration_id: &str) -> Result<Assembly, DesignError> {
495 self.check_configuration_ids()?;
496 let configuration = self.configuration_or_error(configuration_id)?;
497 let layout = self.layout()?;
498 let motors = layout.place_motors(configuration)?;
499 Ok(Assembly {
500 configuration: configuration.id.clone(),
501 layout,
502 motors,
503 })
504 }
505
506 pub fn lay_out(&self) -> Result<LaidOut, DesignError> {
514 self.clone().into_laid_out()
515 }
516
517 fn into_laid_out(self) -> Result<LaidOut, DesignError> {
519 self.check_configuration_ids()?;
520 let (components, masses) = self.placed_components()?;
521 Ok(LaidOut {
522 layout: self.staged_layout(components, &masses)?,
523 rocket: self,
524 masses: Arc::new(masses),
525 })
526 }
527
528 fn configuration_or_error(
530 &self,
531 configuration_id: &str,
532 ) -> Result<&Configuration, DesignError> {
533 self.configuration(configuration_id)
534 .ok_or_else(|| DesignError::UnknownId {
535 what: "configuration",
536 id: configuration_id.to_owned(),
537 })
538 }
539}
540
541#[derive(Debug, Clone)]
545pub struct LaidOut {
546 rocket: Rocket,
547 layout: Layout,
548 masses: Arc<StageMasses>,
551}
552
553impl LaidOut {
554 pub fn rocket(&self) -> &Rocket {
556 &self.rocket
557 }
558
559 pub fn layout(&self) -> &Layout {
561 &self.layout
562 }
563
564 pub fn into_assembly(self, configuration_id: &str) -> Result<(Rocket, Assembly), DesignError> {
572 let configuration = self.rocket.configuration_or_error(configuration_id)?;
573 let motors = self.layout.place_motors(configuration)?;
574 let assembly = Assembly {
575 configuration: configuration.id.clone(),
576 layout: self.layout,
577 motors,
578 };
579 Ok((self.rocket, assembly))
580 }
581
582 pub fn relay(&self, rocket: Rocket) -> Result<LaidOut, DesignError> {
594 if !self.same_but_overrides_and_motors(&rocket) {
595 return rocket.into_laid_out();
596 }
597 rocket.check_configuration_ids()?;
598 let layout = rocket.staged_layout(self.layout.components.clone(), &self.masses)?;
599 Ok(LaidOut {
600 rocket,
601 layout,
602 masses: Arc::clone(&self.masses),
603 })
604 }
605
606 fn same_but_overrides_and_motors(&self, rocket: &Rocket) -> bool {
609 let Rocket {
610 name,
611 stages,
612 reference_diameter,
613 configurations: _,
614 } = rocket;
615 *name == self.rocket.name
616 && *reference_diameter == self.rocket.reference_diameter
617 && stages.len() == self.rocket.stages.len()
618 && stages.iter().zip(&self.rocket.stages).all(|(stage, ours)| {
619 let crate::Stage {
620 id,
621 name,
622 components,
623 overrides: _,
624 override_rule: _,
625 added_mass,
626 drag_override: _,
627 parallel,
628 } = stage;
629 *id == ours.id
630 && *name == ours.name
631 && *components == ours.components
632 && *added_mass == ours.added_mass
636 && *parallel == ours.parallel
637 })
638 }
639}
640
641#[cfg(test)]
642mod tests {
643 use hpr_core::DMat3;
644
645 use super::*;
646 use crate::testing::{motor, three_fin_rocket};
647
648 #[test]
651 fn a_design_laid_out_once_checks_and_assembles_as_twice() {
652 let design = three_fin_rocket();
653 let laid_out = design.lay_out().unwrap();
654 assert_eq!(laid_out.layout(), &design.layout().unwrap());
655 assert_eq!(
656 laid_out.check().unwrap(),
657 crate::checks::check(&design).unwrap()
658 );
659 let id = design.configurations[0].id.clone();
660 assert_eq!(
661 laid_out.clone().into_assembly(&id).unwrap(),
662 (design.clone(), design.assemble(&id).unwrap())
663 );
664 assert!(matches!(
665 laid_out.into_assembly("no such configuration"),
666 Err(DesignError::UnknownId { what: "configuration", ref id })
667 if id == "no such configuration"
668 ));
669 }
670
671 #[test]
674 fn a_relaid_design_is_laid_out_as_alone() {
675 let nominal = three_fin_rocket();
676 let laid_out = nominal.lay_out().unwrap();
677 let id = nominal.configurations[0].id.clone();
678 let same = |relaid: &LaidOut, design: &Rocket| {
679 let alone = design.lay_out().unwrap();
680 assert_eq!(relaid.rocket(), design);
681 assert_eq!(relaid.layout(), alone.layout());
682 assert_eq!(relaid.check().unwrap(), alone.check().unwrap());
683 assert_eq!(
684 relaid.clone().into_assembly(&id).unwrap(),
685 alone.into_assembly(&id).unwrap()
686 );
687 };
688 let mut overridden = nominal.clone();
689 let stage = &mut overridden.stages[0].overrides;
690 stage.mass_kg = Some(1.234_567);
691 stage.cg_aft_m = Some(0.456_789);
692 stage.cg_xy_m = Some([0.001, -0.002]);
693 let mounted = &mut overridden.configurations[0].motors[0];
694 mounted.motor = motor(&mounted.mount, mounted.diameter_m, 0.25).motor;
695 assert!(laid_out.same_but_overrides_and_motors(&overridden));
696 let relaid = laid_out.relay(overridden.clone()).unwrap();
697 same(&relaid, &overridden);
698 assert_ne!(relaid.layout(), laid_out.layout());
699 same(&relaid.relay(nominal.clone()).unwrap(), &nominal);
701 let mut longer = nominal.clone();
703 let crate::Part::BodyTube(tube) = &mut longer.stages[0].components[1].part else {
704 panic!("the test rocket's second component is its airframe");
705 };
706 tube.length_m += 0.1;
707 assert!(!laid_out.same_but_overrides_and_motors(&longer));
708 let relaid = laid_out.relay(longer.clone()).unwrap();
709 same(&relaid, &longer);
710 let mut renamed = nominal.clone();
712 renamed.stages[0].id = "renamed".to_owned();
713 assert!(!laid_out.same_but_overrides_and_motors(&renamed));
714 same(&laid_out.relay(renamed.clone()).unwrap(), &renamed);
715 let mut staged = nominal.clone();
716 let mut booster = staged.stages[0].clone();
717 booster.id = "booster".to_owned();
718 for (index, component) in booster.components.iter_mut().enumerate() {
719 component.id = format!("booster-{index}");
720 component.children.clear();
721 }
722 booster
723 .components
724 .retain(|c| matches!(c.part, crate::Part::BodyTube(_)));
725 staged.stages.push(booster);
726 assert!(!laid_out.same_but_overrides_and_motors(&staged));
727 let relaid = laid_out.relay(staged.clone()).unwrap();
728 same(&relaid, &staged);
729 assert_eq!(relaid.layout().stages.len(), 2);
730 let mut heavier = staged.clone();
732 heavier.stages[1].overrides.mass_kg = Some(0.75);
733 heavier.stages[1].overrides.cg_aft_m = Some(0.3);
734 assert!(relaid.same_but_overrides_and_motors(&heavier));
735 let twice = relaid.relay(heavier.clone()).unwrap();
736 same(&twice, &heavier);
737 assert_ne!(twice.layout().stages[1], relaid.layout().stages[1]);
738 assert_eq!(twice.layout().stages[0], relaid.layout().stages[0]);
739 assert_ne!(relaid.layout().length_m, laid_out.layout().length_m);
740 let mut added = staged.clone();
744 added.stages[1].added_mass = Some(crate::AddedMass {
745 mass_kg: 0.2,
746 cg_aft_m: None,
747 });
748 assert!(!relaid.same_but_overrides_and_motors(&added));
749 same(&relaid.relay(added.clone()).unwrap(), &added);
750 let mut bad = nominal;
752 bad.stages[0].overrides.mass_kg = Some(-1.0);
753 assert_eq!(
754 laid_out.relay(bad.clone()).unwrap_err().to_string(),
755 bad.lay_out().unwrap_err().to_string()
756 );
757 }
758
759 #[test]
763 fn motor_sits_at_mount_aft_end_plus_overhang() {
764 let design = three_fin_rocket();
765 let assembly = design.assemble("main").unwrap();
766 let [placed] = &assembly.motors[..] else {
767 panic!("one motor")
768 };
769 assert!((placed.nozzle_station_m() - 1.01).abs() < 1e-15);
770 assert!((placed.fore_station_m() - 0.81).abs() < 1e-15);
771 assert_eq!(placed.stage, 0);
772 assert_eq!((placed.nozzle_m.x, placed.nozzle_m.y), (0.0, 0.0));
773
774 let structure = assembly.layout.structure;
775 let (m_s, z_s) = (structure.mass_kg, structure.cg_m.z);
776 for (t, motor_kg) in [(0.0, 1.0), (0.5, 0.75), (2.0, 0.5)] {
777 let whole = assembly.mass_properties(t);
778 let want_mass = m_s + motor_kg;
779 assert!((whole.mass_kg - want_mass).abs() < 1e-12, "{t}");
780 let want_z = (m_s * z_s + motor_kg * -0.91) / want_mass;
781 assert!((whole.cg_m.z - want_z).abs() < 1e-12, "{t}");
782 let state = placed.mounted.motor.state(t).total;
785 let (dx, dy, dz) = (-whole.cg_m.x, -whole.cg_m.y, -0.91 - whole.cg_m.z);
786 let about = structure.inertia_about(whole.cg_m);
787 let transverse =
788 about.x_axis.x + state.transverse_inertia_kg_m2 + motor_kg * (dy * dy + dz * dz);
789 assert!(
790 (whole.inertia_kg_m2.x_axis.x - transverse).abs() < 1e-12 * transverse,
791 "{t}"
792 );
793 let axial = about.z_axis.z + state.axial_inertia_kg_m2 + motor_kg * (dx * dx + dy * dy);
794 assert!(
795 (whole.inertia_kg_m2.z_axis.z - axial).abs() < 1e-12 * axial,
796 "{t}"
797 );
798 assert!(whole.cg_m.x.abs() > 1e-6, "the lug is off the axis");
799 }
800 let dry = assembly.dry_mass_properties();
801 assert!((dry.mass_kg - (m_s + 0.5)).abs() < 1e-12);
802 assert_eq!(dry, assembly.mass_properties(1.0));
803 }
804
805 #[test]
808 fn motor_in_an_offset_mount_is_off_axis() {
809 let mut design = three_fin_rocket();
810 let mount = &mut design.stages[0].components[1].children[0];
811 if let crate::Part::InnerTube(tube) = &mut mount.part {
812 tube.outer_radius_m = 0.0105;
813 tube.radial_offset_m = 0.01;
814 tube.angle_rad = std::f64::consts::FRAC_PI_2;
815 }
816 design.stages[0].components[1].children.drain(1..3);
818 design.configurations[0].motors = vec![motor("mmt", 0.018, 0.1)];
819 let assembly = design.assemble("main").unwrap();
820 let placed = &assembly.motors[0];
821 assert!(placed.nozzle_m.x.abs() < 1e-18);
822 assert!((placed.nozzle_m.y - 0.01).abs() < 1e-18);
823 let m = placed.mass_properties(0.0);
824 assert!((m.cg_m.y - 0.01).abs() < 1e-18);
825 let about_origin = m.inertia_about(DVec3::ZERO);
826 let own = MassProperties {
827 cg_m: DVec3::ZERO,
828 ..m
829 };
830 let offset = about_origin - own.inertia_kg_m2;
831 let want_yz = -m.mass_kg * m.cg_m.y * m.cg_m.z;
832 assert!((offset.z_axis.y - want_yz).abs() < 1e-15, "{offset:?}");
833 assert!(offset.y_axis.x.abs() < 1e-18);
835 assert!(assembly.mass_properties(0.0).inertia_kg_m2.z_axis.y.abs() > 1e-6);
836 assert_ne!(m.inertia_kg_m2, DMat3::ZERO);
837 }
838
839 fn clustered(tubes: Vec<[f64; 2]>) -> Rocket {
842 let mut design = three_fin_rocket();
843 let mount = &mut design.stages[0].components[1].children[0];
844 if let crate::Part::InnerTube(tube) = &mut mount.part {
845 tube.outer_radius_m = 0.0095;
846 tube.cluster_m = tubes;
847 }
848 design.stages[0].components[1].children.drain(1..3);
849 design.configurations[0].motors = vec![motor("mmt", 0.018, 0.1)];
850 design
851 }
852
853 fn ring_of_three() -> Vec<[f64; 2]> {
855 [90.0_f64, 210.0, 330.0]
856 .iter()
857 .map(|a| [0.02 * a.to_radians().cos(), 0.02 * a.to_radians().sin()])
858 .collect()
859 }
860
861 #[test]
866 fn a_cluster_mount_takes_its_motor_in_every_tube() {
867 let assembly = clustered(ring_of_three()).assemble("main").unwrap();
868 assert_eq!(assembly.motors.len(), 3);
869 for (k, (placed, [x, y])) in assembly.motors.iter().zip(ring_of_three()).enumerate() {
870 assert_eq!((placed.tube, placed.fails), (k, false));
871 assert_eq!(placed.mount, "mmt");
872 assert_eq!((placed.nozzle_m.x, placed.nozzle_m.y), (x, y));
873 assert!((placed.nozzle_station_m() - 1.01).abs() < 1e-15);
874 }
875 let structure = assembly.layout.structure;
876 for (t, motor_kg) in [(0.0, 1.0), (0.5, 0.75), (2.0, 0.5)] {
877 let whole = assembly.mass_properties(t);
878 assert!((whole.mass_kg - (structure.mass_kg + 3.0 * motor_kg)).abs() < 1e-12);
879 let axis = DVec3::new(0.0, 0.0, whole.cg_m.z);
880 let own = assembly.motors[0].mounted.motor.state(t).total;
881 let want = structure.inertia_about(axis).z_axis.z
882 + 3.0 * (own.axial_inertia_kg_m2 + motor_kg * 0.02 * 0.02);
883 let got = whole.inertia_about(axis).z_axis.z;
884 assert!((got - want).abs() < 1e-12 * want, "{t}: {got} vs {want}");
885 }
886 }
887
888 #[test]
891 fn a_failed_tube_never_lights() {
892 let mut design = clustered(ring_of_three());
893 design.configurations[0].motors[0].failed_tubes = vec![0];
894 let assembly = design.assemble("main").unwrap();
895 let fails: Vec<bool> = assembly.motors.iter().map(|m| m.fails).collect();
896 assert_eq!(fails, [true, false, false]);
897 let lit = assembly.ignition_times_s(|_| None);
898 assert_eq!(lit, [None, Some(0.0), Some(0.0)]);
899 let spent = assembly.mass_properties_lit(2.0, &lit);
900 let structure = assembly.layout.structure.mass_kg;
901 assert!((spent.mass_kg - (structure + 1.0 + 0.5 + 0.5)).abs() < 1e-12);
902 let all_burning = assembly.mass_properties_lit(2.0, &[Some(0.0); 3]);
904 assert!(spent.cg_m.y > all_burning.cg_m.y + 1e-4);
905 assert_eq!(assembly.mass_properties(2.0), spent);
906
907 for (failed, value) in [(vec![3], 3.0), (vec![1, 1], 1.0)] {
908 let mut design = clustered(ring_of_three());
909 design.configurations[0].motors[0].failed_tubes = failed;
910 let Err(DesignError::InComponent { id, source }) = design.assemble("main") else {
911 panic!("refused");
912 };
913 assert_eq!(id, "mmt");
914 assert!(
915 matches!(*source, DesignError::Domain { what, value: v }
916 if what.starts_with("failed tube") && v == value),
917 "{source:?}"
918 );
919 }
920 let mut design = three_fin_rocket();
922 design.configurations[0].motors[0].failed_tubes = vec![0];
923 let assembly = design.assemble("main").unwrap();
924 assert_eq!(assembly.ignition_times_s(|_| None), [None]);
925 let loaded = MassProperties::combine([
927 &assembly.layout.structure,
928 &assembly.motors[0].mass_properties(0.0),
929 ]);
930 assert_eq!(assembly.dry_mass_properties(), loaded);
931 assert_eq!(assembly.mass_properties(10.0), loaded);
932 }
933
934 #[test]
935 fn bad_configurations_are_refused() {
936 let design = three_fin_rocket();
937 assert!(matches!(
938 design.assemble("missing"),
939 Err(DesignError::UnknownId {
940 what: "configuration",
941 ..
942 })
943 ));
944
945 let mut d = design.clone();
946 d.configurations[0].motors[0].mount = "nowhere".to_owned();
947 assert!(matches!(
948 d.assemble("main"),
949 Err(DesignError::UnknownId {
950 what: "motor mount",
951 ..
952 })
953 ));
954
955 let mut d = design.clone();
956 d.configurations[0].motors[0].mount = "airframe".to_owned();
957 assert!(
958 matches!(d.assemble("main"), Err(DesignError::Tree { ref id, .. }) if id == "airframe")
959 );
960
961 let mut d = design.clone();
962 let second = d.configurations[0].motors[0].clone();
963 d.configurations[0].motors.push(second);
964 assert!(matches!(d.assemble("main"), Err(DesignError::Tree { ref id, .. }) if id == "mmt"));
965
966 let mut d = design.clone();
967 let copy = d.configurations[0].clone();
968 d.configurations.push(copy);
969 assert_eq!(
970 d.assemble("main"),
971 Err(DesignError::DuplicateId("main".to_owned()))
972 );
973
974 let mut d = design.clone();
975 d.configurations[0].motors[0].diameter_m = 0.0;
976 assert!(matches!(
977 d.assemble("main"),
978 Err(DesignError::InComponent { ref id, ref source })
979 if id == "mmt" && matches!(**source, DesignError::Domain { .. })
980 ));
981
982 let mut d = design.clone();
983 d.stages[0].components[1].children[0].motor_mount = Some(MotorMount {
984 overhang_m: f64::NAN,
985 });
986 assert!(matches!(
987 d.assemble("main"),
988 Err(DesignError::InComponent { .. })
989 ));
990
991 let layout = design.layout().unwrap();
993 let mut candidate = design.configurations[0].clone();
994 candidate.id = "candidate".to_owned();
995 assert_eq!(layout.place_motors(&candidate).unwrap().len(), 1);
996 candidate.motors[0].mount = "chute".to_owned();
997 assert!(matches!(
998 layout.place_motors(&candidate),
999 Err(DesignError::Tree { ref id, .. }) if id == "chute"
1000 ));
1001 }
1002 const ROCKETPY_DESIGNS: [(&str, &str); 13] = [
1004 (
1005 "astra",
1006 include_str!("../../../validation/designs/rocketpy-astra.json"),
1007 ),
1008 (
1009 "andromeda",
1010 include_str!("../../../validation/designs/rocketpy-andromeda.json"),
1011 ),
1012 (
1013 "erebus-11",
1014 include_str!("../../../validation/designs/rocketpy-erebus-11.json"),
1015 ),
1016 (
1017 "calisto-getting-started-motor-at-minus-1.255",
1018 include_str!(
1019 "../../../validation/designs/rocketpy-calisto-getting-started-motor-at-minus-1.255.json"
1020 ),
1021 ),
1022 (
1023 "calisto-tests-motor-at-minus-1.373",
1024 include_str!(
1025 "../../../validation/designs/rocketpy-calisto-tests-motor-at-minus-1.373.json"
1026 ),
1027 ),
1028 (
1029 "bella-lui",
1030 include_str!("../../../validation/designs/rocketpy-bella-lui.json"),
1031 ),
1032 (
1033 "ndrt-2020-nose-to-tail",
1034 include_str!("../../../validation/designs/rocketpy-ndrt-2020-nose-to-tail.json"),
1035 ),
1036 (
1037 "valetudo",
1038 include_str!("../../../validation/designs/rocketpy-valetudo.json"),
1039 ),
1040 (
1041 "juno-iii",
1042 include_str!("../../../validation/designs/rocketpy-juno-iii.json"),
1043 ),
1044 (
1045 "cavour",
1046 include_str!("../../../validation/designs/rocketpy-cavour.json"),
1047 ),
1048 (
1049 "genesis",
1050 include_str!("../../../validation/designs/rocketpy-genesis.json"),
1051 ),
1052 (
1053 "lince",
1054 include_str!("../../../validation/designs/rocketpy-lince.json"),
1055 ),
1056 (
1057 "prometheus-2022-generic-motor",
1058 include_str!("../../../validation/designs/rocketpy-prometheus-2022-generic-motor.json"),
1059 ),
1060 ];
1061
1062 #[derive(Debug, serde::Deserialize)]
1063 struct Oracle {
1064 oracle: String,
1065 cases: Vec<OracleCase>,
1066 }
1067
1068 #[derive(Debug, serde::Deserialize)]
1069 struct OracleCase {
1070 name: String,
1071 rocket: OracleRocket,
1072 motor: serde_json::Value,
1073 geometry: serde_json::Value,
1074 scalars: OracleScalars,
1075 series: OracleSeries,
1076 knot_series: Option<OracleSeries>,
1077 }
1078
1079 #[derive(Debug, serde::Deserialize)]
1080 struct OracleRocket {
1081 mass: f64,
1082 inertia: Vec<f64>,
1083 center_of_mass_without_motor: f64,
1084 coordinate_system_orientation: String,
1085 motor_position: f64,
1086 }
1087
1088 #[derive(Debug, serde::Deserialize)]
1089 #[allow(non_snake_case, reason = "RocketPy's attribute names")]
1090 struct OracleScalars {
1091 dry_mass_kg: f64,
1092 center_of_dry_mass_position_m: f64,
1093 dry_I_11_kg_m2: f64,
1094 dry_I_33_kg_m2: f64,
1095 nozzle_position_m: f64,
1096 propellant_initial_mass_kg: f64,
1097 }
1098
1099 #[derive(Debug, serde::Deserialize)]
1100 #[allow(non_snake_case, reason = "RocketPy's attribute names")]
1101 struct OracleSeries {
1102 time_s: Vec<f64>,
1103 propellant_mass: Vec<f64>,
1104 total_mass: Vec<f64>,
1105 center_of_mass: Vec<f64>,
1106 I_11: Vec<f64>,
1107 I_33: Vec<f64>,
1108 I_11_about_cg: Vec<f64>,
1109 }
1110
1111 #[derive(Default)]
1113 struct Worst(Vec<(&'static str, f64, String)>);
1114
1115 impl Worst {
1116 fn see(&mut self, what: &'static str, error: f64, at: impl Fn() -> String) {
1117 assert!(error.is_finite(), "{what}: {}", at());
1118 match self.0.iter_mut().find(|w| w.0 == what) {
1119 Some(w) if error > w.1 => (w.1, w.2) = (error, at()),
1120 Some(_) => {}
1121 None => self.0.push((what, error, at())),
1122 }
1123 }
1124 }
1125
1126 fn relative(got: f64, want: f64) -> f64 {
1127 ((got - want) / want).abs()
1128 }
1129
1130 fn number(v: &serde_json::Value, key: &str) -> f64 {
1131 v[key]
1132 .as_f64()
1133 .unwrap_or_else(|| panic!("fixture motor `{key}`"))
1134 }
1135
1136 #[test]
1152 fn matches_rocketpy_example_rockets() {
1153 let oracle: Oracle = serde_json::from_str(include_str!(
1154 "../../../validation/fixtures/design/rocketpy-rocket-mass.json"
1155 ))
1156 .unwrap();
1157 assert_eq!(oracle.oracle, "rocketpy 1.13.0");
1158 assert_eq!(oracle.cases.len(), ROCKETPY_DESIGNS.len());
1159 let catalog = hpr_motor::Catalog::bundled().unwrap();
1160 let mut worst = Worst::default();
1161 for case in &oracle.cases {
1162 let (_, text) = ROCKETPY_DESIGNS
1163 .iter()
1164 .find(|(name, _)| *name == case.name)
1165 .unwrap_or_else(|| panic!("no design for {}", case.name));
1166 let design: Rocket = serde_json::from_str(text).unwrap();
1167 let assembly = design.assemble("example").unwrap();
1168 let name = case.name.as_str();
1169
1170 let tip = case.geometry["nose"]["position"].as_f64().unwrap();
1172 let rocket_sign = match case.rocket.coordinate_system_orientation.as_str() {
1173 "tail_to_nose" => 1.0,
1174 "nose_to_tail" => -1.0,
1175 other => panic!("{other}"),
1176 };
1177 let station = |z: f64| rocket_sign * (tip - z);
1178
1179 let overrides = design.stages[0].overrides;
1181 assert_eq!(overrides.mass_kg, Some(case.rocket.mass), "{name}");
1182 assert_eq!(overrides.cg_xy_m, Some([0.0, 0.0]), "{name}: on the axis");
1183 let cg_aft = overrides.cg_aft_m.unwrap();
1184 assert!(
1185 (cg_aft - station(case.rocket.center_of_mass_without_motor)).abs() < 1e-12,
1186 "{name}"
1187 );
1188 let [i11, i22, i33] = case.rocket.inertia[..] else {
1189 panic!("{name}: inertia")
1190 };
1191 assert_eq!(i11, i22);
1192 assert_eq!(
1193 overrides.inertia,
1194 Some(crate::InertiaOverride::axisymmetric(i33, i11)),
1195 "{name}"
1196 );
1197
1198 let m = &case.motor;
1200 let motor_sign = match m["coordinate_system_orientation"].as_str().unwrap() {
1201 "nozzle_to_combustion_chamber" => 1.0,
1202 "combustion_chamber_to_nozzle" => -1.0,
1203 other => panic!("{other}"),
1204 };
1205 let nozzle = number(m, "nozzle_position");
1206 let to_motor_axis = |z: f64| motor_sign * (z - nozzle);
1207 let [placed] = &assembly.motors[..] else {
1208 panic!("{name}: one motor")
1209 };
1210 let rocketpy_nozzle = case.rocket.motor_position + rocket_sign * motor_sign * nozzle;
1211 assert!(
1212 (rocketpy_nozzle - case.scalars.nozzle_position_m).abs() < 1e-12,
1213 "{name}"
1214 );
1215 assert!(
1216 (placed.nozzle_station_m() - station(rocketpy_nozzle)).abs() < 1e-12,
1217 "{name}: nozzle at {} vs {}",
1218 placed.nozzle_station_m(),
1219 station(rocketpy_nozzle)
1220 );
1221 let motor = &placed.mounted.motor;
1222 let file = m["thrust_file"].as_str().unwrap();
1223 let (entry, curve) = catalog
1224 .motors
1225 .iter()
1226 .find_map(|e| e.curves.iter().find(|c| c.file == file).map(|c| (e, c)))
1227 .unwrap();
1228 assert_eq!(curve.sha256, m["thrust_file_sha256"].as_str().unwrap());
1229 let bundled = entry
1230 .thrust_curve(
1231 curve,
1232 hpr_motor::catalog::bundled_curve_text(&curve.file).unwrap(),
1233 )
1234 .unwrap();
1235 assert_eq!(motor.curve(), &bundled, "{name}: the bundled curve");
1236 let dry = motor.dry();
1237 let example_dry = number(m, "dry_mass");
1240 let expected_dry = if example_dry == 0.0 {
1241 1e-15
1242 } else {
1243 example_dry
1244 };
1245 assert_eq!(dry.mass_kg, expected_dry, "{name}");
1246 let dry_inertia: Vec<f64> = m["dry_inertia"]
1247 .as_array()
1248 .unwrap()
1249 .iter()
1250 .map(|v| v.as_f64().unwrap())
1251 .collect();
1252 assert_eq!(dry.transverse_inertia_kg_m2, dry_inertia[0], "{name}");
1253 assert_eq!(dry.axial_inertia_kg_m2, dry_inertia[2], "{name}");
1254 match (m["motor_kind"].as_str().unwrap(), motor.propellant()) {
1255 ("solid", hpr_motor::Propellant::Grains(g)) => {
1256 assert_eq!(
1257 *g,
1258 hpr_motor::BatesGrains {
1259 count: u32::try_from(m["grain_number"].as_u64().unwrap()).unwrap(),
1260 density_kg_m3: number(m, "grain_density"),
1261 outer_radius_m: number(m, "grain_outer_radius"),
1262 initial_inner_radius_m: number(m, "grain_initial_inner_radius"),
1263 initial_height_m: number(m, "grain_initial_height"),
1264 separation_m: number(m, "grain_separation"),
1265 center_m: to_motor_axis(number(m, "grains_center_of_mass_position")),
1266 inhibited_ends: m["only_radial_burn"].as_bool().unwrap(),
1267 },
1268 "{name}"
1269 );
1270 assert!(
1271 (dry.cg_m - to_motor_axis(number(m, "center_of_dry_mass_position"))).abs()
1272 < 1e-15,
1273 "{name}"
1274 );
1275 }
1276 ("generic", hpr_motor::Propellant::Column(c)) => {
1277 assert!(m["center_of_dry_mass_position"].is_null());
1279 let chamber = to_motor_axis(number(m, "chamber_position"));
1280 assert_eq!(
1281 *c,
1282 hpr_motor::PropellantColumn {
1283 mass_kg: number(m, "propellant_initial_mass"),
1284 center_m: chamber,
1285 outer_radius_m: number(m, "chamber_radius"),
1286 inner_radius_m: 0.0,
1287 length_m: number(m, "chamber_height"),
1288 },
1289 "{name}"
1290 );
1291 assert_eq!(dry.cg_m, chamber, "{name}");
1292 }
1293 (kind, other) => panic!("{name}: {kind} vs {other:?}"),
1294 }
1295 let m_p0 = motor.propellant_initial_mass_kg();
1296 worst.see(
1297 "initial propellant mass",
1298 relative(m_p0, case.scalars.propellant_initial_mass_kg),
1299 || name.to_owned(),
1300 );
1301
1302 let length = assembly.layout.length_m;
1304 let dry_rocket = assembly.dry_mass_properties();
1305 worst.see(
1306 "dry mass",
1307 relative(dry_rocket.mass_kg, case.scalars.dry_mass_kg),
1308 || name.to_owned(),
1309 );
1310 worst.see(
1311 "dry center (of length)",
1312 (-dry_rocket.cg_m.z - station(case.scalars.center_of_dry_mass_position_m)).abs()
1313 / length,
1314 || name.to_owned(),
1315 );
1316 worst.see(
1317 "dry I_11",
1318 relative(
1319 dry_rocket.inertia_kg_m2.x_axis.x,
1320 case.scalars.dry_I_11_kg_m2,
1321 ),
1322 || name.to_owned(),
1323 );
1324 worst.see(
1325 "dry I_33",
1326 relative(
1327 dry_rocket.inertia_kg_m2.z_axis.z,
1328 case.scalars.dry_I_33_kg_m2,
1329 ),
1330 || name.to_owned(),
1331 );
1332
1333 let grids = [
1335 ("", Some(&case.series)),
1336 (" at knots", case.knot_series.as_ref()),
1337 ];
1338 for (grid, s) in grids.into_iter().filter_map(|(g, s)| Some((g, s?))) {
1339 let label = |what: &'static str| -> &'static str {
1340 match (what, grid.is_empty()) {
1341 (_, true) => what,
1342 ("total mass", false) => "total mass at knots",
1343 ("center of mass (of length)", false) => "center of mass at knots",
1344 ("I_11 about the dry center", false) => {
1345 "I_11 about the dry center at knots"
1346 }
1347 ("I_22 about the dry center", false) => {
1348 "I_22 about the dry center at knots"
1349 }
1350 ("I_11 about the center of mass", false) => {
1351 "I_11 about the center of mass at knots"
1352 }
1353 ("I_33", false) => "I_33 at knots",
1354 ("products of inertia (of I_11)", false) => "products of inertia at knots",
1355 ("propellant mass, grains (of initial)", false) => {
1356 "propellant mass, grains, at knots"
1357 }
1358 (other, false) => panic!("no knot label for {other}"),
1359 }
1360 };
1361 for (i, &t) in s.time_s.iter().enumerate() {
1362 let at = || format!("{name} at t = {t} s");
1363 let whole = assembly.mass_properties(t);
1364 worst.see(
1365 label("total mass"),
1366 relative(whole.mass_kg, s.total_mass[i]),
1367 at,
1368 );
1369 worst.see(
1370 label("center of mass (of length)"),
1371 (-whole.cg_m.z - station(s.center_of_mass[i])).abs() / length,
1372 at,
1373 );
1374 let about_dry = whole.inertia_about(dry_rocket.cg_m);
1375 worst.see(
1376 label("I_11 about the dry center"),
1377 relative(about_dry.x_axis.x, s.I_11[i]),
1378 at,
1379 );
1380 worst.see(
1381 label("I_22 about the dry center"),
1382 relative(about_dry.y_axis.y, s.I_11[i]),
1383 at,
1384 );
1385 worst.see(
1386 label("I_11 about the center of mass"),
1387 relative(whole.inertia_kg_m2.x_axis.x, s.I_11_about_cg[i]),
1388 at,
1389 );
1390 worst.see(
1391 label("I_33"),
1392 relative(whole.inertia_kg_m2.z_axis.z, s.I_33[i]),
1393 at,
1394 );
1395 let products = [
1396 whole.inertia_kg_m2.y_axis.x,
1397 whole.inertia_kg_m2.z_axis.x,
1398 whole.inertia_kg_m2.z_axis.y,
1399 ];
1400 worst.see(
1401 label("products of inertia (of I_11)"),
1402 products.iter().fold(0.0f64, |a, v| a.max(v.abs())) / s.I_11[i],
1403 at,
1404 );
1405 let what = match motor.propellant() {
1406 hpr_motor::Propellant::Column(_) => "propellant mass, column (of initial)",
1407 _ => "propellant mass, grains (of initial)",
1408 };
1409 worst.see(
1410 label(what),
1411 (motor.propellant_mass_kg(t) - s.propellant_mass[i]).abs() / m_p0,
1412 at,
1413 );
1414 }
1415 }
1416 }
1417 let tolerance = |what: &str| match what {
1435 "initial propellant mass"
1436 | "dry mass"
1437 | "dry center (of length)"
1438 | "dry I_11"
1439 | "dry I_33"
1440 | "propellant mass, column (of initial)" => 1e-12,
1441 "products of inertia (of I_11)" | "products of inertia at knots" => 1e-15,
1442 "total mass at knots"
1443 | "center of mass at knots"
1444 | "I_11 about the dry center at knots"
1445 | "I_22 about the dry center at knots"
1446 | "I_11 about the center of mass at knots"
1447 | "I_33 at knots"
1448 | "propellant mass, grains, at knots" => 1e-8,
1449 "total mass" => 5e-5,
1450 "center of mass (of length)" => 2e-5,
1451 "I_11 about the dry center"
1452 | "I_22 about the dry center"
1453 | "I_11 about the center of mass"
1454 | "I_33" => 1e-4,
1455 "propellant mass, grains (of initial)" => 2.5e-4,
1456 other => panic!("no tolerance for {other}"),
1457 };
1458 for (what, error, at) in &worst.0 {
1459 println!("{what}: {error:.3e} ({at})");
1460 }
1461 assert_eq!(worst.0.len(), 22, "every quantity was compared");
1462 for (what, error, at) in &worst.0 {
1463 assert!(*error <= tolerance(what), "{what}: {error:e} at {at}");
1464 }
1465 }
1466
1467 fn two_stage(ignition: Ignition) -> Rocket {
1470 let mut rocket: Rocket = serde_json::from_str(include_str!(
1471 "../../../validation/designs/synthetic-two-stage-75mm-54mm.json"
1472 ))
1473 .unwrap();
1474 rocket.configurations[0].motors[1].ignition = ignition;
1475 rocket
1476 }
1477
1478 #[test]
1482 fn a_burnout_of_a_cluster_is_its_first_motor_that_lights() {
1483 let mut rocket = two_stage(Ignition::Burnout {
1484 mount: "booster-motor-mount".to_owned(),
1485 delay_s: 1.0,
1486 });
1487 let booster = rocket.stages[1].components[1]
1488 .children
1489 .iter_mut()
1490 .find(|c| c.id == "booster-motor-mount")
1491 .expect("the booster's mount");
1492 if let crate::Part::InnerTube(tube) = &mut booster.part {
1493 tube.cluster_m = vec![[-0.01, 0.0], [0.01, 0.0]];
1494 }
1495 let booster_burnout_s =
1496 |assembly: &Assembly| assembly.motors[0].mounted.motor.burnout_time_s();
1497 rocket.configurations[0].motors[0].failed_tubes = vec![0];
1498 let assembly = rocket.assemble("j760-i175").unwrap();
1499 let burnout_s = booster_burnout_s(&assembly);
1500 assert_eq!(
1501 assembly.ignition_times_s(|_| None),
1502 [None, Some(0.0), Some(burnout_s + 1.0)]
1503 );
1504 rocket.configurations[0].motors[0].failed_tubes = vec![1, 0];
1505 let assembly = rocket.assemble("j760-i175").unwrap();
1506 assert_eq!(assembly.ignition_times_s(|_| None), [None, None, None]);
1507 }
1508
1509 #[test]
1512 fn a_motor_set_never_to_light_stays_loaded() {
1513 let assembly = two_stage(Ignition::Never).assemble("j760-i175").unwrap();
1514 assert_eq!(
1515 assembly.motors.iter().map(|m| m.fails).collect::<Vec<_>>(),
1516 [false, true]
1517 );
1518 assert_eq!(assembly.ignition_times_s(|_| Some(0.0)), [Some(0.0), None]);
1519 let loaded = assembly.motors[1].mass_properties(0.0);
1520 let structure = assembly.layout.structure;
1521 let booster = |t: f64| assembly.motors[0].mass_properties(t);
1522 let lit = assembly.ignition_times_s(|_| None);
1523 for t in [0.0, 3.0, 100.0] {
1524 let expected = MassProperties::combine([
1526 &MassProperties::combine([&structure, &booster(t)]),
1527 &loaded,
1528 ]);
1529 assert_eq!(assembly.mass_properties_lit(t, &lit), expected);
1530 assert_eq!(assembly.mass_properties(t), expected);
1531 }
1532 let dry = MassProperties::combine([&structure, &assembly.motors[0].dry_mass_properties()]);
1533 assert_eq!(
1534 assembly.dry_mass_properties(),
1535 MassProperties::combine([&dry, &loaded])
1536 );
1537 let mut rocket = two_stage(Ignition::Burnout {
1538 mount: "booster-motor-mount".to_owned(),
1539 delay_s: 0.0,
1540 });
1541 rocket.configurations[0].motors[0].ignition = Ignition::Never;
1542 let assembly = rocket.assemble("j760-i175").unwrap();
1543 assert_eq!(assembly.ignition_times_s(|_| Some(0.0)), [None, None]);
1544 let json = serde_json::to_string(&two_stage(Ignition::Never)).unwrap();
1545 assert!(json.contains(r#""ignition":"never""#), "{json}");
1546 assert_eq!(
1547 serde_json::from_str::<Rocket>(&json).unwrap(),
1548 two_stage(Ignition::Never)
1549 );
1550 }
1551
1552 #[test]
1553 fn ignition_times_follow_their_events() {
1554 let j760 = |assembly: &Assembly| assembly.motors[0].mounted.motor.burnout_time_s();
1555 let assembly = two_stage(Ignition::Launch).assemble("j760-i175").unwrap();
1557 assert_eq!(assembly.ignition_times_s(|_| None), [Some(0.0), Some(0.0)]);
1558 let assembly = two_stage(Ignition::Time { time_s: 3.5 })
1559 .assemble("j760-i175")
1560 .unwrap();
1561 assert_eq!(assembly.ignition_times_s(|_| None), [Some(0.0), Some(3.5)]);
1562 let assembly = two_stage(Ignition::Burnout {
1564 mount: "booster-motor-mount".to_owned(),
1565 delay_s: 1.25,
1566 })
1567 .assemble("j760-i175")
1568 .unwrap();
1569 let burnout_s = j760(&assembly);
1570 assert!(burnout_s > 1.0, "{burnout_s}");
1571 assert_eq!(
1572 assembly.ignition_times_s(|_| None),
1573 [Some(0.0), Some(burnout_s + 1.25)]
1574 );
1575 let assembly = two_stage(Ignition::Separation { delay_s: 0.5 })
1577 .assemble("j760-i175")
1578 .unwrap();
1579 assert_eq!(assembly.ignition_times_s(|_| None), [Some(0.0), None]);
1580 assert_eq!(
1581 assembly.ignition_times_s(|stage| (stage == 0).then_some(4.0)),
1582 [Some(0.0), Some(4.5)]
1583 );
1584 assert_eq!(
1585 assembly.ignition_times_s(|stage| (stage == 1).then_some(4.0)),
1586 [Some(0.0), None]
1587 );
1588 let lit = [Some(0.0), Some(4.5)];
1590 let loaded = assembly.motors[1].mass_properties(0.0).mass_kg;
1591 let spent = assembly.motors[1].dry_mass_properties().mass_kg;
1592 let at = |t: f64| assembly.mass_properties_lit(t, &lit).mass_kg;
1593 let structure = assembly.layout.structure.mass_kg;
1594 let booster = |t: f64| assembly.motors[0].mass_properties(t).mass_kg;
1595 assert_eq!(at(4.0), structure + booster(4.0) + loaded);
1596 let sustainer = assembly.motors[1].mass_properties(1.0).mass_kg;
1597 assert!(sustainer < loaded && sustainer > spent);
1598 assert!((at(5.5) - (structure + booster(5.5) + sustainer)).abs() < 1e-12);
1599 assert!((at(100.0) - assembly.dry_mass_properties().mass_kg).abs() < 1e-12);
1600 }
1601
1602 #[test]
1603 fn bad_ignitions_are_refused() {
1604 let refused = |ignition: Ignition| two_stage(ignition).assemble("j760-i175").is_err();
1605 assert!(refused(Ignition::Time { time_s: -1.0 }));
1606 assert!(refused(Ignition::Time { time_s: f64::NAN }));
1607 assert!(refused(Ignition::Separation {
1608 delay_s: f64::INFINITY
1609 }));
1610 let mut rocket = two_stage(Ignition::Launch);
1612 rocket.configurations[0].motors[0].ignition = Ignition::Separation { delay_s: 0.0 };
1613 let error = rocket.assemble("j760-i175").unwrap_err();
1614 assert!(matches!(error, DesignError::Tree { .. }), "{error:?}");
1615 assert!(refused(Ignition::Burnout {
1616 mount: "booster-motor-mount".to_owned(),
1617 delay_s: -0.1,
1618 }));
1619 assert!(refused(Ignition::Burnout {
1621 mount: "nose".to_owned(),
1622 delay_s: 0.0,
1623 }));
1624 assert!(refused(Ignition::Burnout {
1626 mount: "sustainer-motor-mount".to_owned(),
1627 delay_s: 0.0,
1628 }));
1629 let mut rocket = two_stage(Ignition::Burnout {
1630 mount: "booster-motor-mount".to_owned(),
1631 delay_s: 0.0,
1632 });
1633 rocket.configurations[0].motors[0].ignition = Ignition::Burnout {
1634 mount: "sustainer-motor-mount".to_owned(),
1635 delay_s: 0.0,
1636 };
1637 let error = rocket.assemble("j760-i175").unwrap_err();
1638 assert!(matches!(error, DesignError::Tree { .. }), "{error:?}");
1639 let json = serde_json::to_string(&two_stage(Ignition::Launch)).unwrap();
1641 assert!(!json.contains("ignition"));
1642 let timed = serde_json::to_string(&two_stage(Ignition::Time { time_s: 2.0 })).unwrap();
1643 assert!(
1644 timed.contains(r#""ignition":{"time":{"time_s":2.0}}"#),
1645 "{timed}"
1646 );
1647 }
1648}