1mod bundled;
52#[cfg(test)]
53mod tests;
54
55pub use bundled::{BUNDLED_FILES, bundled};
56
57use serde::{Deserialize, Serialize};
58
59use crate::ork::{NOTHING_DEPENDS, nothing_depends};
60
61const QUOTE_LIMIT: usize = 64;
63
64#[derive(Debug, Clone, PartialEq, thiserror::Error)]
66#[non_exhaustive]
67pub enum OrcError {
68 #[error("the elements nest {depth} deep, past the {limit} this reads")]
71 TooDeep {
72 limit: usize,
74 depth: usize,
76 },
77 #[error("not well-formed XML: {reason}")]
79 Xml {
80 reason: String,
82 },
83 #[error("the root element is <{root}>, not <OpenRocketComponent>: not a parts catalog")]
85 NotACatalog {
86 root: String,
88 },
89}
90
91pub const MAX_DEPTH: usize = 16;
95
96pub const MAX_WARNINGS: usize = 1000;
98
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
101#[serde(rename_all = "snake_case")]
102#[non_exhaustive]
103pub enum WarningKind {
104 PartLeftOut,
108 MaterialLeftOut,
111 MaterialUndefined,
113 MaterialRepeated,
116 Ignored,
119 Repeated,
121 Implausible,
124 TooMany,
126}
127
128#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
130#[non_exhaustive]
131pub struct Warning {
132 pub at: String,
134 pub kind: WarningKind,
136 pub message: String,
138}
139
140#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
142#[non_exhaustive]
143pub struct CatalogFile {
144 pub catalog: Catalog,
146 pub version: Option<String>,
148 pub materials: Vec<CatalogMaterial>,
150 pub warnings: Vec<Warning>,
153}
154
155#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
157pub struct Catalog {
158 pub parts: Vec<Part>,
160}
161
162#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
164#[non_exhaustive]
165pub struct Part {
166 pub file: String,
168 pub manufacturer: String,
170 pub part_number: String,
172 pub description: String,
175 pub mass_kg: Option<f64>,
178 pub kind: PartKind,
180}
181
182#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
187#[serde(tag = "kind", rename_all = "snake_case")]
188#[non_exhaustive]
189pub enum PartKind {
190 BodyTube(Tube),
192 TubeCoupler(Tube),
195 EngineBlock(Tube),
197 CenteringRing(Tube),
199 LaunchLug(Tube),
201 Bulkhead(Bulkhead),
203 NoseCone(NoseCone),
205 Transition(Transition),
207 Parachute(Parachute),
209 Streamer(Streamer),
211}
212
213#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
215#[non_exhaustive]
216pub struct Tube {
217 pub inner_diameter_m: f64,
219 pub outer_diameter_m: f64,
221 pub length_m: f64,
223 pub material: MaterialRef,
225}
226
227impl Tube {
228 #[must_use]
230 pub fn thickness_m(&self) -> f64 {
231 (self.outer_diameter_m - self.inner_diameter_m) / 2.0
232 }
233}
234
235#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
237#[non_exhaustive]
238pub struct Bulkhead {
239 pub outer_diameter_m: f64,
241 pub length_m: f64,
243 pub filled: Option<bool>,
245 pub material: MaterialRef,
247}
248
249#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
251#[non_exhaustive]
252pub struct NoseCone {
253 pub shape: Shape,
255 pub length_m: f64,
257 pub outer_diameter_m: f64,
259 pub shoulder_diameter_m: f64,
261 pub shoulder_length_m: f64,
263 pub filled: Option<bool>,
265 pub thickness_m: Option<f64>,
267 pub material: MaterialRef,
269}
270
271#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
273#[non_exhaustive]
274pub struct Transition {
275 pub shape: Shape,
277 pub length_m: f64,
279 pub fore_outer_diameter_m: f64,
281 pub fore_shoulder_diameter_m: f64,
283 pub fore_shoulder_length_m: f64,
285 pub aft_outer_diameter_m: f64,
287 pub aft_shoulder_diameter_m: f64,
289 pub aft_shoulder_length_m: f64,
291 pub filled: Option<bool>,
293 pub thickness_m: Option<f64>,
295 pub material: MaterialRef,
297}
298
299#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
301#[non_exhaustive]
302pub struct Parachute {
303 pub diameter_m: f64,
305 pub sides: u32,
307 pub line_count: u32,
309 pub line_length_m: f64,
311 pub material: MaterialRef,
313 pub line_material: Option<MaterialRef>,
315}
316
317#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
319#[non_exhaustive]
320pub struct Streamer {
321 pub length_m: f64,
323 pub width_m: f64,
325 pub thickness_m: f64,
327 pub material: MaterialRef,
329}
330
331#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
333#[serde(rename_all = "snake_case")]
334#[non_exhaustive]
335pub enum Shape {
336 Conical,
338 Ogive,
340 Ellipsoid,
342 Parabolic,
344 Haack,
346 Power,
348}
349
350impl Shape {
351 fn parse(word: &str) -> Option<Self> {
353 Some(match word {
354 "CONICAL" => Self::Conical,
355 "OGIVE" => Self::Ogive,
356 "ELLIPSOID" => Self::Ellipsoid,
357 "PARABOLIC" => Self::Parabolic,
358 "HAACK" => Self::Haack,
359 "POWER" => Self::Power,
360 _ => return None,
361 })
362 }
363}
364
365#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
367#[serde(rename_all = "snake_case")]
368#[non_exhaustive]
369pub enum MaterialKind {
370 Bulk,
372 Surface,
374 Line,
376}
377
378impl MaterialKind {
379 fn parse(word: &str) -> Option<Self> {
381 Some(match word {
382 "BULK" => Self::Bulk,
383 "SURFACE" => Self::Surface,
384 "LINE" => Self::Line,
385 _ => return None,
386 })
387 }
388}
389
390#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
392#[non_exhaustive]
393pub struct CatalogMaterial {
394 pub name: String,
396 pub kind: MaterialKind,
398 pub density: f64,
400}
401
402#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
404#[non_exhaustive]
405pub struct MaterialRef {
406 pub name: String,
408 pub kind: MaterialKind,
410 pub density: Option<f64>,
413}
414
415impl MaterialRef {
416 #[must_use]
418 pub fn material(&self) -> Option<hpr_design::Material> {
419 let density = self.density?;
420 Some(match self.kind {
421 MaterialKind::Bulk => hpr_design::Material::bulk(self.name.clone(), density),
422 MaterialKind::Surface => hpr_design::Material::surface(self.name.clone(), density),
423 MaterialKind::Line => hpr_design::Material::line(self.name.clone(), density),
424 })
425 }
426}
427
428impl Catalog {
429 #[must_use]
435 pub fn find(&self, manufacturer: &str, part_number: &str) -> Vec<&Part> {
436 let manufacturer = manufacturer.trim().to_lowercase();
437 let part_number = part_number.trim();
438 self.parts
439 .iter()
440 .filter(|part| {
441 part.manufacturer.trim().to_lowercase() == manufacturer
442 && part.part_number.trim() == part_number
443 })
444 .collect()
445 }
446
447 #[must_use]
452 pub fn search(&self, manufacturer: Option<&str>, text: &str) -> Vec<&Part> {
453 let text = text.trim().to_lowercase();
454 let manufacturer = manufacturer.map(|maker| maker.trim().to_lowercase());
455 self.parts
456 .iter()
457 .filter(|part| {
458 manufacturer
459 .as_ref()
460 .is_none_or(|maker| part.manufacturer.trim().to_lowercase() == *maker)
461 && (part.part_number.to_lowercase().contains(&text)
462 || part.description.to_lowercase().contains(&text))
463 })
464 .collect()
465 }
466
467 #[must_use]
469 pub fn manufacturers(&self) -> Vec<&str> {
470 let mut seen = std::collections::BTreeSet::new();
471 self.parts
472 .iter()
473 .map(|part| part.manufacturer.as_str())
474 .filter(|name| seen.insert(*name))
475 .collect()
476 }
477
478 pub fn extend(&mut self, other: Catalog) {
480 self.parts.extend(other.parts);
481 }
482}
483
484pub fn read(text: &str, file: &str) -> Result<CatalogFile, OrcError> {
497 let depth = crate::ork::document::deepest_nesting(text);
498 if depth > MAX_DEPTH {
499 return Err(OrcError::TooDeep {
500 limit: MAX_DEPTH,
501 depth,
502 });
503 }
504 let document = roxmltree::Document::parse(text).map_err(|error| OrcError::Xml {
505 reason: error.to_string(),
506 })?;
507 let root = document.root_element();
508 if root.tag_name().name() != "OpenRocketComponent" {
509 return Err(OrcError::NotACatalog {
510 root: quote(root.tag_name().name()),
511 });
512 }
513 let mut warnings = Warnings::default();
514 let mut ignored: Vec<String> = Vec::new();
515 let mut lists: [(&str, Option<roxmltree::Node<'_, '_>>, usize); 3] = [
519 ("Version", None, 0),
520 ("Materials", None, 0),
521 ("Components", None, 0),
522 ];
523 for element in root.children().filter(roxmltree::Node::is_element) {
524 let name = element.tag_name().name();
525 match lists.iter_mut().find(|(list, _, _)| *list == name) {
526 Some((_, last, count)) => {
527 *last = Some(element);
528 *count += 1;
529 }
530 None => ignored.push(format!("<{}>", quote(name))),
531 }
532 }
533 for (name, _, count) in &lists {
534 if *count > 1 {
535 let reads = if *name == "Version" {
537 ""
538 } else {
539 ", as OpenRocket reads it"
540 };
541 warnings.push(
542 file,
543 WarningKind::Repeated,
544 format!("<{name}> is stated {count} times; the last was read{reads}"),
545 );
546 }
547 }
548 let [(_, version, _), (_, materials, _), (_, components, _)] = lists;
549 if !ignored.is_empty() {
550 warnings.push(
551 file,
552 WarningKind::Ignored,
553 format!(
554 "{} beside the catalog's lists {} left out, and {}",
555 listed(&ignored),
556 if ignored.len() == 1 { "was" } else { "were" },
557 nothing_depends(ignored.len())
558 ),
559 );
560 }
561 let version = version.and_then(|node| match value_text(node, "Version") {
562 Ok(text) => Some(text),
563 Err(why) => {
564 warnings.push(
565 file,
566 WarningKind::Ignored,
567 format!("{why}; it was left out, and {NOTHING_DEPENDS}"),
568 );
569 None
570 }
571 });
572 let (materials, index) = materials
573 .map(|list| read_materials(list, &mut warnings))
574 .unwrap_or_default();
575 let mut parts = Vec::new();
576 if let Some(list) = components {
577 for element in list.children().filter(roxmltree::Node::is_element) {
578 if let Some(part) = read_part(element, file, &materials, &index, &mut warnings) {
579 parts.push(part);
580 }
581 }
582 }
583 Ok(CatalogFile {
584 catalog: Catalog { parts },
585 version,
586 materials,
587 warnings: warnings.finish(file),
588 })
589}
590
591#[derive(Default)]
593struct Warnings {
594 list: Vec<Warning>,
595 more: usize,
596}
597
598impl Warnings {
599 fn push(&mut self, at: &str, kind: WarningKind, message: String) {
600 if self.list.len() < MAX_WARNINGS {
601 self.list.push(Warning {
602 at: at.to_owned(),
603 kind,
604 message,
605 });
606 } else {
607 self.more += 1;
608 }
609 }
610
611 fn finish(mut self, file: &str) -> Vec<Warning> {
612 if self.more > 0 {
613 self.list.push(Warning {
614 at: file.to_owned(),
615 kind: WarningKind::TooMany,
616 message: format!("{} more warnings were not listed", self.more),
617 });
618 }
619 self.list
620 }
621}
622
623fn listed(items: &[String]) -> String {
625 let shown = items.iter().take(5).cloned().collect::<Vec<_>>().join(", ");
626 match items.len() {
627 0..=5 => shown,
628 n => format!("{shown} and {} more", n - 5),
629 }
630}
631
632fn child<'a, 'input>(
634 node: roxmltree::Node<'a, 'input>,
635 name: &str,
636) -> Option<roxmltree::Node<'a, 'input>> {
637 node.children()
638 .find(|child| child.is_element() && child.tag_name().name() == name)
639}
640
641fn text_of(node: roxmltree::Node<'_, '_>) -> String {
643 node.children()
644 .filter(roxmltree::Node::is_text)
645 .filter_map(|text| text.text())
646 .collect()
647}
648
649fn value_text(node: roxmltree::Node<'_, '_>, name: &str) -> Result<String, String> {
651 if node.children().any(|child| child.is_element()) {
652 Err(format!("<{name}> holds an element, not a value"))
653 } else {
654 Ok(text_of(node))
655 }
656}
657
658fn quote(text: &str) -> String {
660 match text.char_indices().nth(QUOTE_LIMIT) {
661 Some((end, _)) => format!("{}…", &text[..end]),
662 None => text.to_owned(),
663 }
664}
665
666fn number(text: &str) -> Option<f64> {
668 text.trim()
669 .parse::<f64>()
670 .ok()
671 .filter(|value| value.is_finite())
672 .map(|value| value + 0.0)
674}
675
676fn length_factor(unit: &str) -> Option<f64> {
681 Some(match unit {
682 "m" => 1.0,
683 "cm" => 0.01,
684 "mm" => 0.001,
685 "in" => INCH_M,
686 "ft" => FOOT_M,
687 _ => return None,
688 })
689}
690
691const POUND_KG: f64 = 0.453_592_37;
693const OUNCE_KG: f64 = POUND_KG / 16.0;
695const INCH_M: f64 = 0.0254;
697const FOOT_M: f64 = 0.3048;
699
700fn mass_factor(unit: &str) -> Option<f64> {
702 Some(match unit {
703 "kg" => 1.0,
704 "g" => 0.001,
705 "oz" => OUNCE_KG,
706 "lb" => POUND_KG,
707 _ => return None,
708 })
709}
710
711fn density_factor(kind: MaterialKind, unit: &str) -> Option<f64> {
714 Some(match (kind, unit) {
715 (MaterialKind::Bulk, "kg/m3") => 1.0,
716 (MaterialKind::Bulk, "g/cm3" | "kg/dm3") => 1000.0,
717 (MaterialKind::Bulk, "lb/ft3") => POUND_KG / (FOOT_M * FOOT_M * FOOT_M),
718 (MaterialKind::Surface, "kg/m2") => 1.0,
719 (MaterialKind::Surface, "g/m2") => 0.001,
720 (MaterialKind::Surface, "g/cm2") => 10.0,
721 (MaterialKind::Surface, "oz/in2") => OUNCE_KG / (INCH_M * INCH_M),
722 (MaterialKind::Surface, "oz/ft2") => OUNCE_KG / (FOOT_M * FOOT_M),
723 (MaterialKind::Surface, "lb/ft2") => POUND_KG / (FOOT_M * FOOT_M),
724 (MaterialKind::Line, "kg/m") => 1.0,
725 (MaterialKind::Line, "g/m") => 0.001,
726 (MaterialKind::Line, "g/cm") => 0.1,
727 (MaterialKind::Line, "oz/ft") => OUNCE_KG / FOOT_M,
728 _ => return None,
729 })
730}
731
732const LIGHTEST_FABRIC_KG_M2: f64 = 0.001;
737
738const LIGHTEST_SOLID_KG_M3: f64 = 1.0;
742
743impl MaterialKind {
744 fn name(self) -> &'static str {
746 match self {
747 Self::Bulk => "bulk",
748 Self::Surface => "surface",
749 Self::Line => "line",
750 }
751 }
752}
753
754fn read_materials(
757 list: roxmltree::Node<'_, '_>,
758 warnings: &mut Warnings,
759) -> (Vec<CatalogMaterial>, MaterialIndex) {
760 let mut materials: Vec<CatalogMaterial> = Vec::new();
761 let mut index = MaterialIndex::new();
762 for element in list.children().filter(roxmltree::Node::is_element) {
763 let name = child(element, "Name").map(text_of).unwrap_or_default();
764 let at = format!("Materials: {}", quote(&name));
765 let left_out = |warnings: &mut Warnings, why: String| {
766 warnings.push(
767 &at,
768 WarningKind::MaterialLeftOut,
769 format!("{why}; it was left out, so a part naming it has no density"),
770 );
771 };
772 if element.tag_name().name() != "Material" {
773 let why = format!("<{}> is not a material", quote(element.tag_name().name()));
774 left_out(warnings, why);
775 continue;
776 }
777 if let Some(why) = ["Name", "Type"]
778 .into_iter()
779 .filter_map(|field| child(element, field).map(|node| (field, node)))
780 .find_map(|(field, node)| value_text(node, field).err())
781 {
782 left_out(warnings, why);
783 continue;
784 }
785 let Some(kind) = child(element, "Type")
786 .map(text_of)
787 .and_then(|word| MaterialKind::parse(word.trim()))
788 else {
789 left_out(
790 warnings,
791 "its <Type> is not BULK, SURFACE or LINE".to_owned(),
792 );
793 continue;
794 };
795 let Some((written, value)) = child(element, "Density")
796 .and_then(|node| value_text(node, "Density").ok())
797 .and_then(|text| number(&text).map(|value| (text, value)))
798 else {
799 left_out(
800 warnings,
801 "its <Density> is missing or not a number".to_owned(),
802 );
803 continue;
804 };
805 let unit = element.attribute("UnitsOfMeasure").unwrap_or(match kind {
808 MaterialKind::Bulk => "kg/m3",
809 MaterialKind::Surface => "kg/m2",
810 MaterialKind::Line => "kg/m",
811 });
812 let Some(factor) = density_factor(kind, unit) else {
813 let why = format!(
814 "`{}` is not a unit of {} density this reads",
815 quote(unit),
816 kind.name()
817 );
818 left_out(warnings, why);
819 continue;
820 };
821 let density = value * factor;
822 if !density.is_finite() || density < 0.0 {
823 let why = format!(
824 "its density, {} {}, is not one a material has",
825 quote(written.trim()),
826 quote(unit)
827 );
828 left_out(warnings, why);
829 continue;
830 }
831 if let Some(first) = index
832 .get(&(kind, name.clone()))
833 .and_then(|&first| materials.get(first))
834 && first.density != density
835 {
836 warnings.push(
837 &at,
838 WarningKind::MaterialRepeated,
839 format!(
840 "it is defined again with another density, {density} against {}; parts \
841 take the first",
842 first.density
843 ),
844 );
845 }
846 if kind == MaterialKind::Surface && density < LIGHTEST_FABRIC_KG_M2 {
847 warnings.push(
848 &at,
849 WarningKind::Implausible,
850 format!(
851 "{value} {} is {density} kg/m², lighter than any fabric: the unit is likely \
852 wrong; it was read as written, as OpenRocket reads it",
853 quote(unit)
854 ),
855 );
856 }
857 if kind == MaterialKind::Bulk && density < LIGHTEST_SOLID_KG_M3 {
858 warnings.push(
859 &at,
860 WarningKind::Implausible,
861 format!(
862 "{value} {} is {density} kg/m³, lighter than air: the value or its unit is \
863 likely wrong; it was read as written, as OpenRocket reads it",
864 quote(unit)
865 ),
866 );
867 }
868 index.entry((kind, name.clone())).or_insert(materials.len());
869 materials.push(CatalogMaterial {
870 name,
871 kind,
872 density,
873 });
874 }
875 (materials, index)
876}
877
878type MaterialIndex = std::collections::BTreeMap<(MaterialKind, String), usize>;
880
881struct Skip(String);
883
884const COMMON_FIELDS: &[&str] = &[
886 "Manufacturer",
887 "PartNumber",
888 "Description",
889 "Material",
890 "Mass",
891];
892
893fn read_part(
895 element: roxmltree::Node<'_, '_>,
896 file: &str,
897 materials: &[CatalogMaterial],
898 index: &MaterialIndex,
899 warnings: &mut Warnings,
900) -> Option<Part> {
901 let tag = element.tag_name().name();
902 let mut fields: std::collections::BTreeMap<&str, (roxmltree::Node<'_, '_>, usize)> =
904 std::collections::BTreeMap::new();
905 for node in element.children().filter(roxmltree::Node::is_element) {
906 let entry = fields.entry(node.tag_name().name()).or_insert((node, 0));
907 *entry = (node, entry.1 + 1);
908 }
909 let text = |name: &str| fields.get(name).map(|(node, _)| text_of(*node));
910 let manufacturer = text("Manufacturer").unwrap_or_default();
911 let part_number = text("PartNumber").unwrap_or_default();
912 let at = format!("{} {}", quote(&manufacturer), quote(&part_number));
913 let Some(known) = known_fields(tag) else {
914 warnings.push(
915 &at,
916 WarningKind::PartLeftOut,
917 format!(
918 "<{}> is not a kind of part this reads; it was left out of the catalog",
919 quote(tag)
920 ),
921 );
922 return None;
923 };
924 let unknown: Vec<String> = fields
925 .keys()
926 .filter(|name| !known.contains(name) && !COMMON_FIELDS.contains(name))
927 .map(|name| format!("<{}>", quote(name)))
928 .collect();
929 if !unknown.is_empty() {
930 warnings.push(
931 &at,
932 WarningKind::Ignored,
933 format!(
934 "{} {} not a field of a <{tag}> OpenRocket reads; {} left out, and {}",
935 listed(&unknown),
936 if unknown.len() == 1 { "is" } else { "are" },
937 if unknown.len() == 1 {
938 "it was"
939 } else {
940 "they were"
941 },
942 nothing_depends(unknown.len())
943 ),
944 );
945 }
946 for (name, (_, count)) in &fields {
947 if *count > 1 && (known.contains(name) || COMMON_FIELDS.contains(name)) {
948 warnings.push(
949 &at,
950 WarningKind::Repeated,
951 format!(
952 "<{name}> is stated {count} times; the last was read, as OpenRocket reads it"
953 ),
954 );
955 }
956 }
957 let get = |name: &str| fields.get(name).map(|(node, _)| *node);
958 match part(tag, &get, materials, index) {
959 Ok((kind, mass_kg)) => {
960 for material in kind.materials() {
961 if material.density.is_none() {
962 warnings.push(
963 &at,
964 WarningKind::MaterialUndefined,
965 format!(
966 "its material `{}` is not defined in this file, so it has no density",
967 quote(&material.name)
968 ),
969 );
970 }
971 }
972 if let Some(tube) = kind.tube()
973 && tube.inner_diameter_m >= tube.outer_diameter_m
974 {
975 warnings.push(
976 &at,
977 WarningKind::Implausible,
978 format!(
979 "its inside diameter, {} m, is not less than its outside diameter, {} \
980 m, so its wall is {} m. It is read as written, as OpenRocket reads it",
981 tube.inner_diameter_m,
982 tube.outer_diameter_m,
983 tube.thickness_m()
984 ),
985 );
986 }
987 Some(Part {
988 file: file.to_owned(),
989 manufacturer,
990 part_number,
991 description: text("Description").unwrap_or_default(),
992 mass_kg,
993 kind,
994 })
995 }
996 Err(Skip(reason)) => {
997 warnings.push(
998 &at,
999 WarningKind::PartLeftOut,
1000 format!("{reason}; the part was left out of the catalog"),
1001 );
1002 None
1003 }
1004 }
1005}
1006
1007fn known_fields(tag: &str) -> Option<&'static [&'static str]> {
1010 Some(match tag {
1011 "BodyTube" | "TubeCoupler" | "EngineBlock" | "CenteringRing" | "LaunchLug" => {
1012 &["InsideDiameter", "OutsideDiameter", "Length"]
1013 }
1014 "BulkHead" => &["OutsideDiameter", "Length", "Filled"],
1015 "NoseCone" => &[
1016 "Shape",
1017 "OutsideDiameter",
1018 "ShoulderDiameter",
1019 "ShoulderLength",
1020 "Length",
1021 "Filled",
1022 "Thickness",
1023 ],
1024 "Transition" => &[
1025 "Shape",
1026 "ForeOutsideDiameter",
1027 "ForeShoulderDiameter",
1028 "ForeShoulderLength",
1029 "AftOutsideDiameter",
1030 "AftShoulderDiameter",
1031 "AftShoulderLength",
1032 "Length",
1033 "Filled",
1034 "Thickness",
1035 ],
1036 "Parachute" => &[
1037 "Diameter",
1038 "Sides",
1039 "LineCount",
1040 "LineLength",
1041 "LineMaterial",
1042 ],
1043 "Streamer" => &["Width", "Length", "Thickness"],
1044 _ => return None,
1045 })
1046}
1047
1048impl PartKind {
1049 #[must_use]
1051 pub fn tube(&self) -> Option<&Tube> {
1052 match self {
1053 Self::BodyTube(tube)
1054 | Self::TubeCoupler(tube)
1055 | Self::EngineBlock(tube)
1056 | Self::CenteringRing(tube)
1057 | Self::LaunchLug(tube) => Some(tube),
1058 _ => None,
1059 }
1060 }
1061
1062 #[must_use]
1064 pub fn materials(&self) -> Vec<&MaterialRef> {
1065 match self {
1066 Self::BodyTube(tube)
1067 | Self::TubeCoupler(tube)
1068 | Self::EngineBlock(tube)
1069 | Self::CenteringRing(tube)
1070 | Self::LaunchLug(tube) => vec![&tube.material],
1071 Self::Bulkhead(bulkhead) => vec![&bulkhead.material],
1072 Self::NoseCone(nose) => vec![&nose.material],
1073 Self::Transition(transition) => vec![&transition.material],
1074 Self::Parachute(parachute) => {
1075 let mut list = vec![¶chute.material];
1076 list.extend(parachute.line_material.as_ref());
1077 list
1078 }
1079 Self::Streamer(streamer) => vec![&streamer.material],
1080 }
1081 }
1082}
1083
1084fn part<'a, 'input: 'a>(
1086 tag: &str,
1087 get: &dyn Fn(&str) -> Option<roxmltree::Node<'a, 'input>>,
1088 materials: &[CatalogMaterial],
1089 index: &MaterialIndex,
1090) -> Result<(PartKind, Option<f64>), Skip> {
1091 if get("Manufacturer").is_none() {
1092 return Err(Skip("it names no <Manufacturer>".to_owned()));
1093 }
1094 if get("PartNumber").is_none() {
1095 return Err(Skip("it has no <PartNumber>".to_owned()));
1096 }
1097 for name in ["Manufacturer", "PartNumber", "Description"] {
1100 if let Some(node) = get(name) {
1101 value_text(node, name).map_err(Skip)?;
1102 }
1103 }
1104 let mass_kg = get("Mass")
1105 .map(|node| measure(node, "Mass", mass_factor))
1106 .transpose()?;
1107 let length = |name: &str| -> Result<f64, Skip> {
1108 let node = get(name).ok_or_else(|| Skip(format!("it has no <{name}>")))?;
1109 measure(node, name, length_factor)
1110 };
1111 let optional_length = |name: &str| -> Result<Option<f64>, Skip> {
1112 get(name)
1113 .map(|node| measure(node, name, length_factor))
1114 .transpose()
1115 };
1116 let material = |name: &str, want: MaterialKind| -> Result<MaterialRef, Skip> {
1117 let node = get(name).ok_or_else(|| Skip(format!("it names no <{name}>")))?;
1118 material_ref(node, name, want, materials, index)
1119 };
1120 let word = |name: &str| -> Result<Option<String>, Skip> {
1121 get(name)
1122 .map(|node| value_text(node, name).map_err(Skip))
1123 .transpose()
1124 };
1125 let filled = || -> Result<Option<bool>, Skip> {
1126 word("Filled")?
1127 .map(|text| match text.trim() {
1128 "true" | "1" => Ok(true),
1129 "false" | "0" => Ok(false),
1130 other => Err(Skip(format!(
1131 "<Filled> is `{}`, not true or false",
1132 quote(other)
1133 ))),
1134 })
1135 .transpose()
1136 };
1137 let shape = || -> Result<Shape, Skip> {
1138 let text = word("Shape")?.ok_or_else(|| Skip("it has no <Shape>".to_owned()))?;
1139 Shape::parse(text.trim()).ok_or_else(|| {
1140 Skip(format!(
1141 "<Shape> is `{}`, not one of CONICAL, OGIVE, ELLIPSOID, PARABOLIC, HAACK or POWER",
1142 quote(&text)
1143 ))
1144 })
1145 };
1146 let count = |name: &str| -> Result<u32, Skip> {
1147 let text = word(name)?.ok_or_else(|| Skip(format!("it has no <{name}>")))?;
1148 text.trim().parse::<u32>().map_err(|_| {
1149 Skip(format!(
1150 "<{name}> is `{}`, not a whole number",
1151 quote(&text)
1152 ))
1153 })
1154 };
1155 let tube = || -> Result<Tube, Skip> {
1156 Ok(Tube {
1157 inner_diameter_m: length("InsideDiameter")?,
1158 outer_diameter_m: length("OutsideDiameter")?,
1159 length_m: length("Length")?,
1160 material: material("Material", MaterialKind::Bulk)?,
1161 })
1162 };
1163 let kind = match tag {
1164 "BodyTube" => PartKind::BodyTube(tube()?),
1165 "TubeCoupler" => PartKind::TubeCoupler(tube()?),
1166 "EngineBlock" => PartKind::EngineBlock(tube()?),
1167 "CenteringRing" => PartKind::CenteringRing(tube()?),
1168 "LaunchLug" => PartKind::LaunchLug(tube()?),
1169 "BulkHead" => PartKind::Bulkhead(Bulkhead {
1170 outer_diameter_m: length("OutsideDiameter")?,
1171 length_m: length("Length")?,
1172 filled: filled()?,
1173 material: material("Material", MaterialKind::Bulk)?,
1174 }),
1175 "NoseCone" => PartKind::NoseCone(NoseCone {
1176 shape: shape()?,
1177 length_m: length("Length")?,
1178 outer_diameter_m: length("OutsideDiameter")?,
1179 shoulder_diameter_m: length("ShoulderDiameter")?,
1180 shoulder_length_m: length("ShoulderLength")?,
1181 filled: filled()?,
1182 thickness_m: optional_length("Thickness")?,
1183 material: material("Material", MaterialKind::Bulk)?,
1184 }),
1185 "Transition" => PartKind::Transition(Transition {
1186 shape: shape()?,
1187 length_m: length("Length")?,
1188 fore_outer_diameter_m: length("ForeOutsideDiameter")?,
1189 fore_shoulder_diameter_m: length("ForeShoulderDiameter")?,
1190 fore_shoulder_length_m: length("ForeShoulderLength")?,
1191 aft_outer_diameter_m: length("AftOutsideDiameter")?,
1192 aft_shoulder_diameter_m: length("AftShoulderDiameter")?,
1193 aft_shoulder_length_m: length("AftShoulderLength")?,
1194 filled: filled()?,
1195 thickness_m: optional_length("Thickness")?,
1196 material: material("Material", MaterialKind::Bulk)?,
1197 }),
1198 "Parachute" => PartKind::Parachute(Parachute {
1199 diameter_m: length("Diameter")?,
1200 sides: count("Sides")?,
1201 line_count: count("LineCount")?,
1202 line_length_m: length("LineLength")?,
1203 material: material("Material", MaterialKind::Surface)?,
1204 line_material: get("LineMaterial")
1205 .map(|node| {
1206 material_ref(node, "LineMaterial", MaterialKind::Line, materials, index)
1207 })
1208 .transpose()?,
1209 }),
1210 "Streamer" => PartKind::Streamer(Streamer {
1211 length_m: length("Length")?,
1212 width_m: length("Width")?,
1213 thickness_m: length("Thickness")?,
1214 material: material("Material", MaterialKind::Surface)?,
1215 }),
1216 _ => return Err(Skip(format!("<{}> is not a kind of part", quote(tag)))),
1218 };
1219 Ok((kind, mass_kg))
1220}
1221
1222fn measure(
1225 node: roxmltree::Node<'_, '_>,
1226 name: &str,
1227 factor: fn(&str) -> Option<f64>,
1228) -> Result<f64, Skip> {
1229 let text = value_text(node, name).map_err(Skip)?;
1230 let value = number(&text)
1231 .ok_or_else(|| Skip(format!("<{name}> is `{}`, not a number", quote(&text))))?;
1232 if value < 0.0 {
1233 return Err(Skip(format!("<{name}> is {value}, less than zero")));
1234 }
1235 let scale = match node.attribute("Unit") {
1236 None => 1.0,
1237 Some(unit) => factor(unit).ok_or_else(|| {
1238 Skip(format!(
1239 "<{name}>'s unit `{}` is not one this reads",
1240 quote(unit)
1241 ))
1242 })?,
1243 };
1244 Ok(value * scale)
1245}
1246
1247fn material_ref(
1251 node: roxmltree::Node<'_, '_>,
1252 name: &str,
1253 want: MaterialKind,
1254 materials: &[CatalogMaterial],
1255 index: &MaterialIndex,
1256) -> Result<MaterialRef, Skip> {
1257 let kind = node
1258 .attribute("Type")
1259 .and_then(MaterialKind::parse)
1260 .ok_or_else(|| Skip(format!("<{name}>'s Type is not BULK, SURFACE or LINE")))?;
1261 if kind != want {
1262 return Err(Skip(format!(
1263 "<{name}> names a material of the wrong kind for the part"
1264 )));
1265 }
1266 let material_name = value_text(node, name).map_err(Skip)?;
1267 let density = index
1268 .get(&(kind, material_name.clone()))
1269 .and_then(|&first| materials.get(first))
1270 .map(|material| material.density);
1271 Ok(MaterialRef {
1272 name: material_name,
1273 kind,
1274 density,
1275 })
1276}