hpr/motor.rs
1//! A solid rocket motor, ready to go in a rocket's motor tube.
2
3use hpr_motor::{Catalog, Delay, MotorError, SolidMotor, eng, rse};
4use serde::Serialize;
5
6use crate::error::{Error, non_negative, positive};
7
8/// A commercial solid motor: its designation, its case's size, its thrust curve and masses, and
9/// the delay of its ejection charge, if it has one.
10///
11/// Three ways to get one:
12///
13/// - [`Motor::from_catalog`]: a motor from the catalog built into HPR Sim, by its designation or
14/// common name, with the catalog's size, masses and thrust curve.
15/// - [`Motor::from_eng`]: a RASP `.eng` file's text, as ThrustCurve.org serves it, or
16/// [`Motor::from_rse`]: a RockSim `.rse` file's.
17/// - [`Motor::new`]: a [`SolidMotor`] you built with [`hpr_motor`], and its case's size.
18///
19/// ```
20/// use hpr::Motor;
21///
22/// let motor = Motor::from_catalog("H54")?.with_delay_s(10.0)?;
23/// assert_eq!(motor.designation(), "168H54-10A");
24/// assert_eq!(motor.diameter_m(), 0.029);
25/// # Ok::<(), hpr::Error>(())
26/// ```
27///
28/// It serializes, for a record of what was flown, but doesn't deserialize: its constructors check
29/// what goes in.
30#[derive(Debug, Clone, PartialEq, Serialize)]
31pub struct Motor {
32 designation: String,
33 diameter_m: f64,
34 length_m: f64,
35 motor: SolidMotor,
36 delay: Option<Delay>,
37 /// What building it warned of ([`Motor::warnings`]); left out of the record when there is
38 /// none.
39 #[serde(skip_serializing_if = "Vec::is_empty")]
40 warnings: Vec<String>,
41}
42
43impl Motor {
44 /// A motor of case diameter `diameter_m` and length `length_m`, called `designation`, with no
45 /// ejection delay.
46 ///
47 /// # Errors
48 ///
49 /// [`Error::EmptyDesignation`] for an empty designation, and [`Error::Domain`] for a diameter
50 /// or length that isn't finite and positive.
51 pub fn new(
52 designation: &str,
53 motor: SolidMotor,
54 diameter_m: f64,
55 length_m: f64,
56 ) -> Result<Self, Error> {
57 if designation.trim().is_empty() {
58 return Err(Error::EmptyDesignation);
59 }
60 Ok(Self {
61 designation: designation.to_owned(),
62 diameter_m: positive("motor diameter, m", diameter_m)?,
63 length_m: positive("motor length, m", length_m)?,
64 motor,
65 delay: None,
66 warnings: Vec::new(),
67 })
68 }
69
70 /// The motor in HPR Sim's built-in catalog whose designation or common name is `name`,
71 /// ignoring case, spaces and hyphens (`"H54"`, `"168H54-10A"`, `"k 400"`), with its default
72 /// thrust curve: a bundled file within 1% of ThrustCurve.org's stated figures where it has
73 /// one ([`hpr_motor::catalog::CatalogMotor::default_curve`]). A failing file flies with its
74 /// warning in [`Motor::warnings`], as `hpr sim --motor` prints it. Only motors
75 /// with a bundled curve can fly: 924 of the catalog's 1,004, which `hpr motors list` lists
76 /// ([motor page][motor-page]). The delay is not set, whatever the designation says: give it
77 /// with [`Motor::with_delay_s`].
78 ///
79 /// [motor-page]: https://hpr.fusionspace.co/physics/motor.html
80 ///
81 /// # Errors
82 ///
83 /// - [`Error::NoSuchMotor`] if no motor matches.
84 /// - [`Error::NoCurve`] if the one motor that matches has no bundled curve.
85 /// - [`Error::AmbiguousMotor`] if several motors match, with a curve or without, as a common
86 /// name can (`"I175"` matches two) and a name several makers use does (`"G80"`); each is
87 /// listed by a name that finds it alone: its designation, or its
88 /// maker's short name and its designation where makers share it (`"Estes C6"`).
89 /// - [`Error::Motor`] if the catalog or the motor's curve can't be read (never, for the
90 /// bundled ones: their tests read them all).
91 pub fn from_catalog(name: &str) -> Result<Self, Error> {
92 Self::from_catalog_in(Catalog::bundled()?, name)
93 }
94
95 /// As [`Motor::from_catalog`], in `catalog` rather than the built-in one: the motor whose
96 /// designation or common name is `name`, with its default curve.
97 ///
98 /// # Errors
99 ///
100 /// As [`Motor::from_catalog`].
101 pub fn from_catalog_in(catalog: &Catalog, name: &str) -> Result<Self, Error> {
102 // Ambiguity is decided before curves: a shared name never flies the one maker's motor
103 // that happens to have a curve.
104 let matches = catalog.find(name).collect::<Vec<_>>();
105 let entry = match matches[..] {
106 [] => return Err(Error::NoSuchMotor(name.to_owned())),
107 [entry] if entry.default_curve().is_none() => {
108 return Err(Error::NoCurve(catalog.selector(entry)));
109 }
110 [entry] => entry,
111 _ => {
112 return Err(Error::AmbiguousMotor {
113 name: name.to_owned(),
114 candidates: matches
115 .iter()
116 .map(|entry| catalog.selector(entry))
117 .collect(),
118 });
119 }
120 };
121 let mut motor = Self::new(
122 &entry.designation,
123 entry.bundled_motor()?,
124 entry.diameter_mm / 1000.0,
125 entry.length_mm / 1000.0,
126 )?;
127 motor.warnings = entry
128 .default_curve()
129 .map(|curve| entry.flight_warnings(curve))
130 .unwrap_or_default();
131 Ok(motor)
132 }
133
134 /// The one motor in the text of a RASP `.eng` file, with the file's size, masses and thrust
135 /// curve ([`SolidMotor::from_envelope`]). The file's warnings and its list of delays are
136 /// dropped (read the file with [`hpr_motor::eng::parse`] to see them): set the delay with
137 /// [`Motor::with_delay_s`]. A `.eng` file doesn't say what kind of motor it holds, so a
138 /// hybrid's file is read as a solid motor; HPR Sim models solid motors only.
139 ///
140 /// # Errors
141 ///
142 /// [`Error::Motor`] if the text isn't a motor file or its numbers don't make a motor, and
143 /// [`Error::MotorCount`] if it holds more than one motor or none.
144 pub fn from_eng(text: &str) -> Result<Self, Error> {
145 let parsed = eng::parse(text)?;
146 let [entry] = &parsed.value.entries[..] else {
147 return Err(Error::MotorCount(parsed.value.entries.len()));
148 };
149 let diameter_m = entry.diameter_mm / 1000.0;
150 let length_m = entry.length_mm / 1000.0;
151 let motor = SolidMotor::from_envelope(
152 entry.thrust_curve()?,
153 diameter_m,
154 length_m,
155 entry.propellant_mass_kg,
156 entry.total_mass_kg,
157 )?;
158 Self::new(&entry.name, motor, diameter_m, length_m)
159 }
160
161 /// The one motor in the text of a RockSim `.rse` file, with the file's size, masses (grams,
162 /// converted) and thrust curve ([`SolidMotor::from_envelope`]). As with [`Motor::from_eng`],
163 /// the file's warnings, its delays and the center-of-gravity column some files carry are
164 /// dropped (read the file with [`hpr_motor::rse::parse`] to see them). A hybrid, which the
165 /// file's `Type` names, is refused: HPR Sim models solid motors only.
166 ///
167 /// # Errors
168 ///
169 /// [`Error::Motor`] if the text isn't a motor file, its numbers don't make a motor, or it is a
170 /// hybrid; [`Error::MotorCount`] if it holds more than one motor.
171 pub fn from_rse(text: &str) -> Result<Self, Error> {
172 let parsed = rse::parse(text)?;
173 let [engine] = &parsed.value.engines[..] else {
174 return Err(Error::MotorCount(parsed.value.engines.len()));
175 };
176 if engine
177 .motor_type
178 .as_deref()
179 .is_some_and(|kind| kind.trim().eq_ignore_ascii_case("hybrid"))
180 {
181 return Err(Error::Motor(MotorError::Inconsistent(format!(
182 "{} is a hybrid; HPR Sim models solid motors only",
183 engine.code
184 ))));
185 }
186 let diameter_m = engine.diameter_mm / 1000.0;
187 let length_m = engine.length_mm / 1000.0;
188 let motor = SolidMotor::from_envelope(
189 engine.thrust_curve()?,
190 diameter_m,
191 length_m,
192 engine.propellant_mass_g / 1000.0,
193 engine.initial_mass_g / 1000.0,
194 )?;
195 Self::new(&engine.code, motor, diameter_m, length_m)
196 }
197
198 /// The same motor with an ejection charge `delay_s` seconds after burnout.
199 ///
200 /// # Errors
201 ///
202 /// [`Error::Domain`] for a delay that is negative or not finite.
203 pub fn with_delay_s(mut self, delay_s: f64) -> Result<Self, Error> {
204 self.delay = Some(Delay::Seconds(non_negative("motor delay, s", delay_s)?));
205 Ok(self)
206 }
207
208 /// The same motor with `delay` as its ejection delay: a time, or a plugged motor
209 /// ([`Delay::Plugged`]), which has no ejection charge.
210 ///
211 /// # Errors
212 ///
213 /// [`Error::Domain`] for a time that is negative or not finite.
214 pub fn with_delay(mut self, delay: Delay) -> Result<Self, Error> {
215 if let Delay::Seconds(delay_s) = delay {
216 non_negative("motor delay, s", delay_s)?;
217 }
218 self.delay = Some(delay);
219 Ok(self)
220 }
221
222 /// The designation, such as `168H54-10A`.
223 #[must_use]
224 pub fn designation(&self) -> &str {
225 &self.designation
226 }
227
228 /// The case's outer diameter, m.
229 #[must_use]
230 pub fn diameter_m(&self) -> f64 {
231 self.diameter_m
232 }
233
234 /// The case's length, m.
235 #[must_use]
236 pub fn length_m(&self) -> f64 {
237 self.length_m
238 }
239
240 /// The ejection delay, if one is set.
241 #[must_use]
242 pub fn delay(&self) -> Option<Delay> {
243 self.delay
244 }
245
246 /// The motor model: thrust curve, propellant and case masses.
247 #[must_use]
248 pub fn solid_motor(&self) -> &SolidMotor {
249 &self.motor
250 }
251
252 /// What building the motor warned of. A catalog motor ([`Motor::from_catalog`]) carries its
253 /// default curve file's warnings ([`hpr_motor::catalog::CatalogMotor::flight_warnings`]): a
254 /// file more than 1% from ThrustCurve.org's figures for it, each failing figure's gap named,
255 /// a propellant mass more than 5% lighter than the record's, a loaded mass more than 5% from
256 /// the record's or a burnout mass more than 5% from the record's burnout mass, and a
257 /// propellant share outside the records' span. A motor from a file or built with
258 /// [`Motor::new`] has none. Setting the delay keeps them.
259 #[must_use]
260 pub fn warnings(&self) -> &[String] {
261 &self.warnings
262 }
263}