1use super::*;
36use serde_json::Value;
37
38pub const PART_ONLY_KEYS: [&str; 4] = ["Mass", "Material", "Density", "Volume"];
41
42pub const VOLUME_KEY: &str = "Volume";
44pub const MASS_KEY: &str = "Mass";
46pub const DENSITY_KEY: &str = "Density";
48pub const MATERIAL_KEY: &str = "Material";
50
51pub const DENSITY_UNIT: &str = "g/cm³";
52pub const MASS_UNIT: &str = "kg";
53pub const VOLUME_UNIT: &str = "mm³";
54
55const MM3_G_CM3_TO_KG: f64 = 1e-6;
57
58const MATERIAL_DENSITIES: &[(&str, f64)] = &[
63 ("stainless", 7.93),
64 ("cast iron", 7.20),
65 ("tool steel", 7.80),
66 ("steel", 7.85),
67 ("iron", 7.87),
68 ("aluminium", 2.70),
69 ("aluminum", 2.70),
70 ("6061", 2.70),
71 ("6063", 2.69),
72 ("7075", 2.81),
73 ("2024", 2.78),
74 ("brass", 8.50),
75 ("bronze", 8.80),
76 ("copper", 8.96),
77 ("titanium", 4.43),
78 ("magnesium", 1.74),
79 ("zinc", 7.14),
80 ("nickel", 8.90),
81 ("lead", 11.34),
82 ("abs", 1.04),
83 ("pla", 1.24),
84 ("petg", 1.27),
85 ("nylon", 1.14),
86 ("polycarbonate", 1.20),
87 ("acetal", 1.41),
88 ("delrin", 1.41),
89 ("pom", 1.41),
90 ("hdpe", 0.95),
91 ("polypropylene", 0.90),
92 ("pvc", 1.38),
93 ("acrylic", 1.18),
94 ("pmma", 1.18),
95 ("ptfe", 2.20),
96 ("glass", 2.50),
97 ("oak", 0.75),
98 ("pine", 0.50),
99 ("plywood", 0.60),
100 ("wood", 0.60),
101];
102
103pub fn material_density(material: &str) -> Option<f64> {
107 let words: Vec<String> = material
108 .to_lowercase()
109 .split(|c: char| !c.is_alphanumeric())
110 .filter(|word| !word.is_empty())
111 .map(str::to_string)
112 .collect();
113 if words.is_empty() {
114 return None;
115 }
116 let padded = format!(" {} ", words.join(" "));
117 MATERIAL_DENSITIES
118 .iter()
119 .find(|(key, _)| padded.contains(&format!(" {key} ")))
120 .map(|&(_, density)| density)
121}
122
123pub fn format_mass_kg(kg: f64) -> String {
125 if kg.abs() >= 1.0 {
126 format!("{kg:.3} kg")
127 } else {
128 format!("{:.3} g", kg * 1000.0)
129 }
130}
131
132pub fn format_volume_mm3(mm3: f64) -> String {
134 if mm3.abs() >= 1000.0 {
135 format!("{:.3} cm³", mm3 / 1000.0)
136 } else {
137 format!("{mm3:.3} mm³")
138 }
139}
140
141pub fn format_derived(field: &str, value: &Value) -> Option<String> {
144 let number = value.as_f64()?;
145 match field {
146 MASS_KEY => Some(format_mass_kg(number)),
147 VOLUME_KEY => Some(format_volume_mm3(number)),
148 _ => None,
149 }
150}
151
152#[derive(Clone, Copy, Debug, PartialEq, Eq)]
154pub enum DensitySource {
155 Solid,
157 Part,
159 Material,
161}
162
163impl DensitySource {
164 pub fn as_str(self) -> &'static str {
165 match self {
166 DensitySource::Solid => "solid",
167 DensitySource::Part => "part",
168 DensitySource::Material => "material",
169 }
170 }
171}
172
173fn positive_number(value: &Value) -> Option<f64> {
175 let number = match value {
176 Value::Number(number) => number.as_f64(),
177 Value::String(text) => text.trim().parse::<f64>().ok(),
178 _ => None,
179 }?;
180 (number.is_finite() && number > 0.0).then_some(number)
181}
182
183pub fn part_density(attributes: &Value) -> Option<(f64, DensitySource)> {
186 if let Some(density) = attributes.get(DENSITY_KEY).and_then(positive_number) {
187 return Some((density, DensitySource::Part));
188 }
189 attributes
190 .get(MATERIAL_KEY)
191 .and_then(Value::as_str)
192 .and_then(material_density)
193 .map(|density| (density, DensitySource::Material))
194}
195
196#[derive(Clone, Debug, PartialEq)]
198pub enum MassStatus {
199 Computed,
201 Override,
203 Pending,
205 NoDensity,
207 NoGeometry,
209 Failed(String),
211}
212
213impl MassStatus {
214 pub fn as_str(&self) -> &'static str {
215 match self {
216 MassStatus::Computed => "computed",
217 MassStatus::Override => "override",
218 MassStatus::Pending => "pending",
219 MassStatus::NoDensity => "no-density",
220 MassStatus::NoGeometry => "no-geometry",
221 MassStatus::Failed(_) => "failed",
222 }
223 }
224
225 pub fn note(&self) -> Option<String> {
227 match self {
228 MassStatus::Computed | MassStatus::Override => None,
229 MassStatus::Pending => Some("measuring".into()),
230 MassStatus::NoDensity => {
231 Some("no density: set the part's Material or Density".into())
232 }
233 MassStatus::NoGeometry => {
234 Some("no geometry: set the part's Mass".into())
235 }
236 MassStatus::Failed(message) => Some(format!("not measurable: {message}")),
237 }
238 }
239}
240
241#[derive(Clone, Debug, PartialEq)]
243pub struct MassReport {
244 pub volume_mm3: Option<f64>,
246 pub mass_kg: Option<f64>,
248 pub density_g_cm3: Option<f64>,
251 pub density_source: Option<DensitySource>,
253 pub solid_count: usize,
255 pub status: MassStatus,
256}
257
258impl MassReport {
259 pub fn to_json(&self) -> Value {
262 serde_json::json!({
263 "volumeMm3": self.volume_mm3,
264 "massKg": self.mass_kg,
265 "densityGcm3": self.density_g_cm3,
266 "densitySource": self.density_source.map(DensitySource::as_str),
267 "solidCount": self.solid_count,
268 "massStatus": self.status.as_str(),
269 "massNote": self.status.note(),
270 })
271 }
272}
273
274impl EngineState {
275 pub(crate) fn owning_part_attributes(&self, solid: &str) -> Option<Value> {
280 let namespace = self.component_namespace();
281 let (chain, _local) = namespace.split(solid);
282 let Some((&head, rest)) = chain.split_first() else {
283 return Some(self.document_part_attributes());
284 };
285 let part_name = self
286 .assembly_components
287 .iter()
288 .find(|component| component.id == head)
289 .map(|component| component.part_name.clone())
290 .or_else(|| {
291 let index = self.history.index_of(head)?;
292 self.history
293 .feature_params(index)?
294 .get("partName")?
295 .as_str()
296 .map(str::to_string)
297 })?;
298 let mut document = self
299 .history
300 .parts_library()
301 .get(&part_name)?
302 .get("document")?;
303 for segment in rest {
304 let inner = document
305 .get("features")?
306 .as_array()?
307 .iter()
308 .find(|feature| feature["inputParams"]["id"].as_str() == Some(segment))?;
309 let inner_part = inner["inputParams"]["partName"].as_str()?;
310 document = document
311 .get("partsLibrary")?
312 .get(inner_part)?
313 .get("document")?;
314 }
315 Some(
316 document
317 .get(PART_ATTRIBUTES)
318 .filter(|value| value.is_object())
319 .cloned()
320 .unwrap_or_else(|| Value::Object(serde_json::Map::new())),
321 )
322 }
323
324 pub fn solid_density(&self, solid: &str) -> Option<(f64, DensitySource)> {
327 if let Some(density) = self
328 .metadata
329 .attribute(solid, "density")
330 .and_then(|text| text.trim().parse::<f64>().ok())
331 .filter(|density| density.is_finite() && *density > 0.0)
332 {
333 return Some((density, DensitySource::Solid));
334 }
335 part_density(&self.owning_part_attributes(solid)?)
336 }
337
338 fn measurable_solids<'a>(&'a self, filter: impl Fn(&str) -> bool + 'a) -> Vec<String> {
340 self.scene
341 .solids()
342 .iter()
343 .filter(|solid| !solid.is_sketch && filter(&solid.name))
344 .map(|solid| solid.name.clone())
345 .collect()
346 }
347
348 fn part_solids(&self, part_name: &str) -> Vec<String> {
351 let Some(first) = self
352 .assembly_components
353 .iter()
354 .find(|component| component.part_name == part_name)
355 .map(|component| component.id.clone())
356 else {
357 return Vec::new();
358 };
359 self.chain_solids(&first)
360 }
361
362 fn chain_solids(&self, chain: &str) -> Vec<String> {
364 let prefix = format!("{chain}:");
365 self.measurable_solids(|name| name.starts_with(&prefix))
366 }
367
368 pub fn chain_mass(&mut self, chain: &str) -> MassReport {
373 let solids = self.chain_solids(chain);
374 self.measure_solids(&solids);
375 self.chain_mass_cached(chain)
376 }
377
378 pub fn chain_mass_cached(&self, chain: &str) -> MassReport {
380 let solids = self.chain_solids(chain);
381 let attributes = self
383 .owning_part_attributes(&format!("{chain}:_"))
384 .unwrap_or_else(|| Value::Object(serde_json::Map::new()));
385 self.mass_over(&solids, &attributes)
386 }
387
388 pub fn bom_mass_pending(&mut self) -> bool {
391 let parts: Vec<String> =
392 self.assembly_components.iter().map(|c| c.part_name.clone()).collect();
393 self.measure_parts(parts.iter().map(String::as_str));
394 parts
395 .iter()
396 .any(|part| self.part_mass_cached(part).status == MassStatus::Pending)
397 }
398
399 pub fn part_has_geometry(&self, part_name: &str) -> bool {
402 !self.part_solids(part_name).is_empty()
403 }
404
405 pub fn document_has_geometry(&self) -> bool {
407 !self.measurable_solids(|_| true).is_empty()
408 }
409
410 fn solid_volume_cached(&self, solid: &str) -> Result<Option<f64>, String> {
413 let Some(text) = self.info_cache.get(solid) else {
414 return Ok(None);
415 };
416 let info: Value = serde_json::from_str(text).unwrap_or(Value::Null);
417 if info.get("ok").and_then(Value::as_bool) != Some(true) {
418 return Err(info
419 .get("message")
420 .and_then(Value::as_str)
421 .unwrap_or("no measurement")
422 .to_string());
423 }
424 info.get("volume")
425 .and_then(Value::as_f64)
426 .map(Some)
427 .ok_or_else(|| "no volume".to_string())
428 }
429
430 fn measure_solids(&mut self, solids: &[String]) {
434 for solid in solids {
435 if !self.info_cache.contains_key(solid) {
436 let _ = self.object_info_raw_json(solid);
437 }
438 }
439 }
440
441 pub fn measure_parts<'a>(&mut self, parts: impl IntoIterator<Item = &'a str>) {
444 for part in parts {
445 let solids = self.part_solids(part);
446 self.measure_solids(&solids);
447 }
448 }
449
450 fn mass_over(&self, solids: &[String], attributes: &Value) -> MassReport {
453 if solids.is_empty() {
454 let stored = attributes.get(MASS_KEY).and_then(positive_number);
455 return MassReport {
456 volume_mm3: None,
457 mass_kg: stored,
458 density_g_cm3: None,
459 density_source: None,
460 solid_count: 0,
461 status: if stored.is_some() {
462 MassStatus::Override
463 } else {
464 MassStatus::NoGeometry
465 },
466 };
467 }
468 let mut volume = 0.0;
469 let mut mass = 0.0;
470 let mut pending = false;
471 let mut failure: Option<String> = None;
472 let mut missing_density = false;
473 let mut densities: Vec<(f64, DensitySource)> = Vec::new();
474 for solid in solids {
475 match self.solid_volume_cached(solid) {
476 Ok(Some(v)) => {
477 volume += v;
478 match self.solid_density(solid) {
479 Some((density, source)) => {
480 mass += v * density * MM3_G_CM3_TO_KG;
481 densities.push((density, source));
482 }
483 None => missing_density = true,
484 }
485 }
486 Ok(None) => pending = true,
487 Err(message) => {
488 failure.get_or_insert(format!("{solid}: {message}"));
489 }
490 }
491 }
492 let uniform = densities
493 .first()
494 .copied()
495 .filter(|(first, _)| densities.iter().all(|(d, _)| (d - first).abs() <= 1e-12));
496 let status = if let Some(message) = failure {
497 MassStatus::Failed(message)
498 } else if pending {
499 MassStatus::Pending
500 } else if missing_density {
501 MassStatus::NoDensity
502 } else {
503 MassStatus::Computed
504 };
505 MassReport {
506 volume_mm3: matches!(status, MassStatus::Computed | MassStatus::NoDensity)
507 .then_some(volume),
508 mass_kg: (status == MassStatus::Computed).then_some(mass),
509 density_g_cm3: uniform.map(|(density, _)| density),
510 density_source: uniform.map(|(_, source)| source),
511 solid_count: solids.len(),
512 status,
513 }
514 }
515
516 pub fn part_mass(&mut self, part_name: &str) -> MassReport {
519 let solids = self.part_solids(part_name);
520 self.measure_solids(&solids);
521 self.part_mass_cached(part_name)
522 }
523
524 pub fn part_mass_cached(&self, part_name: &str) -> MassReport {
527 let solids = self.part_solids(part_name);
528 let attributes = self.part_attributes(part_name);
529 let mut report = self.mass_over(&solids, &attributes);
530 if solids.is_empty() {
531 if let Some((density, source)) = part_density(&attributes) {
533 report.density_g_cm3 = Some(density);
534 report.density_source = Some(source);
535 }
536 }
537 report
538 }
539
540 pub fn document_mass(&mut self) -> MassReport {
544 let solids = self.measurable_solids(|_| true);
545 self.measure_solids(&solids);
546 self.document_mass_cached()
547 }
548
549 pub fn document_mass_cached(&self) -> MassReport {
551 let solids = self.measurable_solids(|_| true);
552 let attributes = self.document_part_attributes();
553 let mut report = self.mass_over(&solids, &attributes);
554 if solids.is_empty() {
555 if let Some((density, source)) = part_density(&attributes) {
556 report.density_g_cm3 = Some(density);
557 report.density_source = Some(source);
558 }
559 }
560 report
561 }
562
563 pub fn part_bom_record(&mut self, part_name: &str) -> Value {
569 let report = self.part_mass(part_name);
570 fold_mass(self.part_attributes(part_name), &report)
571 }
572
573 pub fn part_bom_record_cached(&self, part_name: &str) -> (Value, MassReport) {
576 let report = self.part_mass_cached(part_name);
577 (fold_mass(self.part_attributes(part_name), &report), report)
578 }
579
580 pub fn document_bom_record(&mut self) -> Value {
583 let attributes = self.document_part_attributes();
584 let report = self.document_mass();
585 fold_mass(attributes, &report)
586 }
587
588 pub(crate) fn check_part_attribute_write(
591 &self,
592 key: &str,
593 value: &Value,
594 has_geometry: bool,
595 ) -> Result<(), String> {
596 let clearing =
597 value.is_null() || matches!(value, Value::String(text) if text.is_empty());
598 if key == VOLUME_KEY && !clearing {
599 return Err("Volume is computed from the part's geometry and cannot be set".into());
600 }
601 if key == MASS_KEY && !clearing && has_geometry {
602 return Err(
603 "Mass is computed from the part's geometry and density: set the part's Material or Density instead (a Mass can be typed only for a part with no geometry)"
604 .into(),
605 );
606 }
607 Ok(())
608 }
609}
610
611fn fold_mass(mut attributes: Value, report: &MassReport) -> Value {
614 let Some(record) = attributes.as_object_mut() else {
615 return attributes;
616 };
617 record.remove(VOLUME_KEY);
618 if report.status != MassStatus::Override {
619 record.remove(MASS_KEY);
620 }
621 if let Some(volume) = report.volume_mm3 {
622 record.insert(VOLUME_KEY.into(), Value::from(volume));
623 }
624 if let Some(mass) = report.mass_kg {
625 record.insert(MASS_KEY.into(), Value::from(mass));
626 }
627 if !record.contains_key(DENSITY_KEY) {
628 if let (Some(density), Some(DensitySource::Material)) =
629 (report.density_g_cm3, report.density_source)
630 {
631 record.insert(DENSITY_KEY.into(), Value::from(density));
632 }
633 }
634 attributes
635}
636
637pub fn migrate_occurrence_part_attributes(document: &mut Value) -> Vec<String> {
654 let mut notices = Vec::new();
655 migrate_level(document, "", &mut notices);
656 notices
657}
658
659fn migrate_level(document: &mut Value, path: &str, notices: &mut Vec<String>) {
660 let mut found: Vec<(String, String, Vec<(String, Value)>)> = Vec::new();
662 if let Some(features) = document.get_mut("features").and_then(Value::as_array_mut) {
663 for feature in features {
664 let is_acomp = feature
665 .get("type")
666 .and_then(Value::as_str)
667 .is_some_and(super::components::is_acomp_feature_type);
668 if !is_acomp {
669 continue;
670 }
671 let Some(params) = feature.get_mut("inputParams").and_then(Value::as_object_mut) else {
672 continue;
673 };
674 let id = params.get("id").and_then(Value::as_str).unwrap_or("").to_string();
675 let part = params.get("partName").and_then(Value::as_str).unwrap_or("").to_string();
676 if let Some(Value::Object(legacy)) = params.remove("occurrenceAttributes") {
678 let record = params
679 .entry(super::bom::OCCURRENCE_ATTRIBUTES.to_string())
680 .or_insert_with(|| Value::Object(serde_json::Map::new()));
681 if !record.is_object() {
682 *record = Value::Object(serde_json::Map::new());
683 }
684 let record = record.as_object_mut().expect("normalized");
685 for (key, value) in legacy {
686 record.entry(key).or_insert(value);
687 }
688 }
689 let Some(record) = params
690 .get_mut(super::bom::OCCURRENCE_ATTRIBUTES)
691 .and_then(Value::as_object_mut)
692 else {
693 continue;
694 };
695 for key in ["Mass", "Material", "Density", "Volume"] {
696 let Some(value) = record.remove(key) else { continue };
697 let blank = value.is_null() || matches!(&value, Value::String(t) if t.trim().is_empty());
698 if blank || key == VOLUME_KEY || part.is_empty() {
699 continue;
700 }
701 match found.iter_mut().find(|(p, k, _)| *p == part && k == key) {
702 Some((_, _, values)) => values.push((id.clone(), value)),
703 None => found.push((part.clone(), key.to_string(), vec![(id.clone(), value)])),
704 }
705 }
706 if record.is_empty() {
707 params.remove(super::bom::OCCURRENCE_ATTRIBUTES);
708 }
709 }
710 }
711
712 let mut moved: Vec<String> = Vec::new();
713 let mut touched: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
714 for (part, key, values) in &found {
715 let label = if path.is_empty() { part.clone() } else { format!("{path}/{part}") };
716 let Some(entry) = document
717 .get_mut("partsLibrary")
718 .and_then(|library| library.get_mut(part))
719 .filter(|entry| entry.get("document").is_some_and(Value::is_object))
720 else {
721 notices.push(format!(
722 "BOM: {key} on {} occurrence(s) of '{label}' was dropped: the part is not in the parts library",
723 values.len()
724 ));
725 continue;
726 };
727 let first = &values[0].1;
728 let disagree = values.iter().any(|(_, value)| value != first);
729 let part_document = entry.get_mut("document").expect("filtered");
730 let existing = part_document
731 .get(PART_ATTRIBUTES)
732 .and_then(|record| record.get(key))
733 .cloned();
734 let shown = |value: &Value| match value {
735 Value::String(text) => format!("'{text}'"),
736 other => other.to_string(),
737 };
738 match existing {
739 Some(existing) if &existing != first || disagree => {
740 notices.push(format!(
741 "BOM: '{label}' occurrences carried {key} {} — the part keeps its own {key} {}",
742 values.iter().map(|(id, value)| format!("{id}={}", shown(value))).collect::<Vec<_>>().join(", "),
743 shown(&existing),
744 ));
745 }
746 Some(_) => {}
747 None => {
748 let object = part_document.as_object_mut().expect("filtered");
749 let record = object
750 .entry(PART_ATTRIBUTES.to_string())
751 .or_insert_with(|| Value::Object(serde_json::Map::new()));
752 if !record.is_object() {
753 *record = Value::Object(serde_json::Map::new());
754 }
755 record
756 .as_object_mut()
757 .expect("normalized")
758 .insert(key.clone(), first.clone());
759 touched.insert(part.clone());
760 if disagree {
761 notices.push(format!(
762 "BOM: '{label}' occurrences disagreed on {key} ({}) — the part takes {} from {}",
763 values.iter().map(|(id, value)| format!("{id}={}", shown(value))).collect::<Vec<_>>().join(", "),
764 shown(first),
765 values[0].0,
766 ));
767 } else {
768 moved.push(format!("{key} {} → part '{label}'", shown(first)));
769 }
770 }
771 }
772 }
773
774 if let Some(library) = document.get_mut("partsLibrary").and_then(Value::as_object_mut) {
776 for (name, entry) in library.iter_mut() {
777 let Some(part_document) = entry.get_mut("document").filter(|d| d.is_object()) else {
778 continue;
779 };
780 let before = notices.len();
781 let label = if path.is_empty() { name.clone() } else { format!("{path}/{name}") };
782 let changed_inside = migrate_level_changed(part_document, &label, notices);
783 if changed_inside || notices.len() != before {
784 touched.insert(name.clone());
785 }
786 }
787 for name in &touched {
788 if let Some(entry) = library.get_mut(name) {
789 let text = entry["document"].to_string();
790 entry["sourceSignature"] = Value::String(super::document_signature(&text));
791 }
792 }
793 }
794
795 if !moved.is_empty() {
796 notices.push(format!(
797 "BOM: mass properties moved from occurrences to their parts: {} (save to keep)",
798 moved.join("; ")
799 ));
800 }
801}
802
803fn migrate_level_changed(document: &mut Value, path: &str, notices: &mut Vec<String>) -> bool {
805 let before = document.clone();
806 migrate_level(document, path, notices);
807 *document != before
808}
809