1pub mod anchor;
68pub mod annotations;
69pub mod font;
70pub mod layout;
71pub mod resolve;
72pub mod weld_symbol;
73mod plugin;
74pub use plugin::{PluginAnnotationOutput, PluginAnnotationReplay};
75
76use serde::{Deserialize, Serialize};
77use serde_json::Value;
78use std::collections::BTreeMap;
79
80use crate::feature_pipeline::{Env, HistoryRequest, SceneMap};
81
82pub use anchor::{
83 balloon_head, nearest_displayed_point, nearest_displayed_point_on_edge, nearest_point_on_edge, nearest_point_on_solid,
84 pose_apply, pose_unapply, BalloonAnchor, BalloonAnchorMode, HalfSpace, HeadScope, PmiPose, SolidPoses,
85};
86pub use annotations::{pmi_schema_catalogue, pmi_type, PmiTypeDef, PMI_TYPES};
87
88#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
97#[serde(from = "PmiStateWire")]
98pub struct PmiState {
99 #[serde(default)]
100 pub views: Vec<PmiView>,
101 #[serde(default, rename = "idCounter")]
104 pub id_counter: u64,
105}
106
107#[derive(Deserialize)]
109struct PmiStateWire {
110 #[serde(default)]
111 views: Vec<PmiView>,
112 #[serde(default, rename = "idCounter")]
113 id_counter: u64,
114}
115
116impl From<PmiStateWire> for PmiState {
117 fn from(wire: PmiStateWire) -> Self {
118 let mut state = PmiState { views: wire.views, id_counter: wire.id_counter };
119 for index in 0..state.views.len() {
120 let legacy = std::mem::take(&mut state.views[index].display.legacy_hidden);
121 if legacy.is_empty() {
122 continue;
123 }
124 let mut names = state.views[index].baseline_hidden();
125 for name in legacy {
126 if !names.contains(&name) {
127 names.push(name);
128 }
129 }
130 let id = state.views[index].id.clone();
131 state.set_view_baseline(&id, &names);
132 }
133 state
134 }
135}
136
137#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
139pub struct PmiView {
140 pub id: String,
141 #[serde(default)]
142 pub name: String,
143 #[serde(default, skip_serializing_if = "Option::is_none")]
144 pub camera: Option<PmiCamera>,
145 #[serde(default)]
146 pub display: PmiDisplay,
147 #[serde(default)]
148 pub annotations: Vec<PmiAnnotation>,
149}
150
151#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
156pub struct PmiCamera {
157 pub eye: [f64; 3],
158 pub target: [f64; 3],
159 pub up: [f64; 3],
160 pub projection: PmiProjection,
161 #[serde(default = "default_viewport")]
163 pub viewport: [f64; 2],
164}
165
166fn default_viewport() -> [f64; 2] {
167 [1280.0, 800.0]
168}
169
170impl PmiCamera {
171 pub fn view_direction(&self) -> [f64; 3] {
173 let d = [
174 self.target[0] - self.eye[0],
175 self.target[1] - self.eye[1],
176 self.target[2] - self.eye[2],
177 ];
178 let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
179 if len < 1e-12 {
180 [0.0, 0.0, -1.0]
181 } else {
182 [d[0] / len, d[1] / len, d[2] / len]
183 }
184 }
185}
186
187#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
188#[serde(tag = "kind", rename_all = "camelCase")]
189pub enum PmiProjection {
190 Orthographic {
191 #[serde(rename = "halfHeight")]
192 half_height: f64,
193 },
194 Perspective {
195 #[serde(rename = "fovYDeg")]
196 fov_y_deg: f64,
197 },
198}
199
200#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
202pub struct PmiDisplay {
203 #[serde(default = "default_text_size", rename = "textSizePt")]
205 pub text_size_pt: f64,
206 #[serde(default)]
207 pub wireframe: bool,
208 #[serde(default, rename = "hidden", skip_serializing)]
213 legacy_hidden: Vec<String>,
214 #[serde(default, skip_serializing_if = "Option::is_none")]
215 pub section: Option<PmiSection>,
216}
217
218impl PmiDisplay {
219 pub fn new(text_size_pt: f64, wireframe: bool, section: Option<PmiSection>) -> Self {
221 Self { text_size_pt, wireframe, legacy_hidden: Vec::new(), section }
222 }
223}
224
225#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
233pub struct PmiSection {
234 pub axis: String,
235 pub offset: f64,
236 #[serde(default)]
237 pub flip: bool,
238 #[serde(default, skip_serializing_if = "Option::is_none")]
239 pub origin: Option<[f64; 3]>,
240 #[serde(default, skip_serializing_if = "Option::is_none")]
241 pub normal: Option<[f64; 3]>,
242 #[serde(default, skip_serializing_if = "Option::is_none")]
243 pub plane: Option<String>,
244 #[serde(default, skip_serializing_if = "Vec::is_empty")]
247 pub exclude: Vec<String>,
248 #[serde(default, skip_serializing_if = "Vec::is_empty")]
253 pub planes: Vec<PmiSectionPlane>,
254}
255
256#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
260pub struct PmiSectionPlane {
261 pub axis: String,
262 #[serde(default)]
263 pub offset: f64,
264 #[serde(default)]
265 pub flip: bool,
266 #[serde(default, skip_serializing_if = "Option::is_none")]
267 pub normal: Option<[f64; 3]>,
268}
269
270impl PmiSectionPlane {
271 pub fn axis_normal(&self, camera: Option<&PmiCamera>) -> Option<[f64; 3]> {
274 match self.axis.as_str() {
275 "X" => Some([1., 0., 0.]),
276 "Y" => Some([0., 1., 0.]),
277 "Z" => Some([0., 0., 1.]),
278 "View" => self.normal.or_else(|| camera.map(PmiCamera::view_direction)),
279 _ => None,
280 }
281 }
282}
283pub fn entry_names_solid(entry: &str, solid: &str) -> bool {
289 let entry = entry.trim();
290 !entry.is_empty() && (solid == entry || solid.strip_prefix(entry).is_some_and(|rest| rest.starts_with(':')))
291}
292
293impl PmiSection {
294 pub fn excludes(&self, solid: &str) -> bool {
298 self.exclude.iter().any(|entry| entry_names_solid(entry, solid))
299 }
300
301 pub fn axis_normal(&self, camera: Option<&PmiCamera>) -> Option<[f64; 3]> {
304 match self.axis.as_str() {
305 "X" => Some([1., 0., 0.]),
306 "Y" => Some([0., 1., 0.]),
307 "Z" => Some([0., 0., 1.]),
308 "Plane" => self.normal,
309 _ => self.normal.or_else(|| camera.map(PmiCamera::view_direction)),
310 }
311 }
312
313 pub fn freeze(&mut self, camera: Option<&PmiCamera>) {
316 if self.axis == "Plane" {
317 self.origin = None;
319 self.normal = None;
320 return;
321 }
322 self.plane = None;
323 let Some(camera) = camera else { return };
324 for plane in &mut self.planes {
325 if plane.axis == "View" {
326 plane.normal.get_or_insert(camera.view_direction());
327 } else {
328 plane.normal = None;
329 }
330 }
331 self.origin.get_or_insert(camera.target);
332 if self.axis == "View" {
333 self.normal.get_or_insert(camera.view_direction());
334 } else {
335 self.normal = None;
336 }
337 }
338}
339impl PmiView {
340 pub fn section_plane(&self) -> Option<([f64; 3], [f64; 3])> {
341 let section = self.display.section.as_ref()?;
342 let camera = self.camera.as_ref();
343 let mut normal = section.axis_normal(camera)?;
344 let origin = section.origin.or_else(|| camera.filter(|_| section.axis != "Plane").map(|c| c.target))?;
345 let point = std::array::from_fn(|i| origin[i] + normal[i] * section.offset);
346 if section.flip {
347 normal = normal.map(|v| -v);
348 }
349 Some((point, normal))
350 }
351
352 pub fn section_plane_in(&self, report: Option<&PmiViewReport>) -> Option<([f64; 3], [f64; 3])> {
355 match self.display.section.as_ref() {
356 Some(section) if section.axis == "Plane" => report.and_then(|report| report.section_plane),
357 _ => self.section_plane(),
358 }
359 }
360
361 pub fn section_planes_in(&self, report: Option<&PmiViewReport>) -> Vec<([f64; 3], [f64; 3])> {
367 self.section_plane_in(report).map_or_else(Vec::new, |first| self.with_further_planes(first))
368 }
369
370 pub fn section_planes(&self) -> Vec<([f64; 3], [f64; 3])> {
373 self.section_plane().map_or_else(Vec::new, |first| self.with_further_planes(first))
374 }
375
376 fn with_further_planes(&self, first: ([f64; 3], [f64; 3])) -> Vec<([f64; 3], [f64; 3])> {
377 let mut planes = vec![first];
378 let Some(section) = self.display.section.as_ref() else { return planes };
379 let camera = self.camera.as_ref();
380 let origin = section.origin.or_else(|| camera.filter(|_| section.axis != "Plane").map(|c| c.target)).unwrap_or(first.0);
381 for plane in §ion.planes {
382 let Some(mut normal) = plane.axis_normal(camera) else { continue };
383 let point = std::array::from_fn(|i| origin[i] + normal[i] * plane.offset);
384 if plane.flip {
385 normal = normal.map(|v| -v);
386 }
387 planes.push((point, normal));
388 }
389 planes
390 }
391}
392
393pub const HIDE_BASELINE_PARAM: &str = "baseline";
398
399pub fn baseline_hide_id(view_id: &str) -> String {
403 format!("{}-{view_id}", annotations::hide::DEF.short_name)
404}
405
406impl PmiAnnotation {
407 pub fn hide_step(id: &str, targets: &[String], baseline: bool) -> Self {
410 let mut params = serde_json::json!({ "id": id, "targets": targets });
411 if baseline {
412 params[HIDE_BASELINE_PARAM] = Value::Bool(true);
413 }
414 Self {
415 kind: annotations::hide::DEF.type_id.to_string(),
416 enabled: true,
417 params,
418 persistent_data: Value::Null,
419 plugin_replay: None,
420 label_world: None,
421 }
422 }
423
424 pub fn is_baseline_hide(&self) -> bool {
426 self.kind == annotations::hide::DEF.type_id && self.flag(HIDE_BASELINE_PARAM)
427 }
428}
429
430impl PmiView {
431 pub fn hides(&self, solid: &str) -> bool {
438 self.hide_targets().any(|entry| entry_names_solid(entry, solid))
439 }
440
441 pub fn baseline_hidden(&self) -> Vec<String> {
443 self.annotations.iter().filter(|a| a.is_baseline_hide()).flat_map(|a| a.references("targets")).collect()
444 }
445
446 pub fn hide_targets(&self) -> impl Iterator<Item = &str> {
448 self.annotations
449 .iter()
450 .filter(|annotation| annotation.enabled && annotation.kind == annotations::hide::DEF.type_id)
451 .flat_map(|annotation| match annotation.params.get("targets") {
452 Some(Value::String(name)) => std::slice::from_ref(name).iter().map(String::as_str).collect::<Vec<_>>(),
453 Some(Value::Array(items)) => items.iter().filter_map(Value::as_str).collect(),
454 _ => Vec::new(),
455 })
456 .map(str::trim)
457 .filter(|name| !name.is_empty())
458 }
459}
460
461fn default_text_size() -> f64 {
462 12.0
463}
464
465impl Default for PmiDisplay {
466 fn default() -> Self {
467 Self {
468 text_size_pt: default_text_size(),
469 wireframe: false,
470 legacy_hidden: Vec::new(),
471 section: None,
472 }
473 }
474}
475
476pub fn clamp_text_size(size: f64) -> f64 {
478 if !size.is_finite() {
479 return default_text_size();
480 }
481 size.clamp(1.0, 288.0)
482}
483
484#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
486pub struct PmiAnnotation {
487 #[serde(rename = "type")]
488 pub kind: String,
489 #[serde(default = "default_true")]
490 pub enabled: bool,
491 #[serde(default, rename = "inputParams")]
492 pub params: Value,
493 #[serde(default, rename = "persistentData", skip_serializing_if = "Value::is_null")]
494 pub persistent_data: Value,
495 #[serde(default, rename = "pluginReplay", skip_serializing_if = "Option::is_none")]
497 pub plugin_replay: Option<PluginAnnotationReplay>,
498 #[serde(default, rename = "labelWorld", skip_serializing_if = "Option::is_none")]
501 pub label_world: Option<[f64; 3]>,
502}
503
504fn is_false(value: &bool) -> bool { !value }
505
506fn default_true() -> bool {
507 true
508}
509
510impl PmiAnnotation {
511 pub fn id(&self) -> &str {
513 self.params
514 .get("id")
515 .and_then(Value::as_str)
516 .unwrap_or("")
517 }
518
519 pub fn text(&self, key: &str) -> &str {
521 self.params
522 .get(key)
523 .and_then(Value::as_str)
524 .map(str::trim)
525 .unwrap_or("")
526 }
527
528 pub fn flag(&self, key: &str) -> bool {
530 self.params
531 .get(key)
532 .and_then(Value::as_bool)
533 .unwrap_or(false)
534 }
535
536 pub fn number(&self, key: &str, env: &Env, default: f64) -> Result<f64, String> {
539 match self.params.get(key) {
540 None | Some(Value::Null) => Ok(default),
541 Some(Value::Number(number)) => Ok(number.as_f64().unwrap_or(default)),
542 Some(Value::Bool(flag)) => Ok(if *flag { 1.0 } else { 0.0 }),
543 Some(Value::String(source)) => {
544 let source = source.trim();
545 if source.is_empty() {
546 return Ok(default);
547 }
548 env.eval(source)
549 .map_err(|error| format!("{key}: {error}"))
550 }
551 Some(other) => Err(format!("{key}: expected a number, got {other}")),
552 }
553 }
554
555 pub fn plane_ref(&self) -> Option<&str> {
558 let name = self.text("plane").trim();
559 (!name.is_empty()).then_some(name)
560 }
561
562 pub fn references(&self, key: &str) -> Vec<String> {
565 match self.params.get(key) {
566 Some(Value::String(name)) => {
567 let name = name.trim();
568 if name.is_empty() {
569 Vec::new()
570 } else {
571 vec![name.to_string()]
572 }
573 }
574 Some(Value::Array(items)) => items
575 .iter()
576 .filter_map(Value::as_str)
577 .map(str::trim)
578 .filter(|name| !name.is_empty())
579 .map(String::from)
580 .collect(),
581 _ => Vec::new(),
582 }
583 }
584}
585
586impl PmiState {
587 pub fn set_view_baseline(&mut self, view_id: &str, names: &[String]) -> bool {
591 let Some(view) = self.find_view(view_id) else { return false };
592 if view.baseline_hidden() == names && view.annotations.iter().filter(|a| a.is_baseline_hide()).count() <= 1 {
593 return false;
594 }
595 let at = view.annotations.iter().position(PmiAnnotation::is_baseline_hide);
596 let kept_id = at.map(|at| view.annotations[at].id().to_string()).filter(|id| !id.is_empty());
597 let id = kept_id.unwrap_or_else(|| baseline_hide_id(view_id));
598 let view = self.find_view_mut(view_id).expect("found above");
599 view.annotations.retain(|a| !a.is_baseline_hide());
600 if !names.is_empty() {
601 let step = PmiAnnotation::hide_step(&id, names, true);
602 let at = at.unwrap_or(view.annotations.len()).min(view.annotations.len());
603 view.annotations.insert(at, step);
604 }
605 true
606 }
607
608 pub fn hide_in_view(&mut self, view_id: &str, names: &[String]) -> Option<String> {
612 let view = self.find_view(view_id)?;
613 let mut targets: Vec<String> = Vec::new();
614 for name in names {
615 if !view.hides(name) && !targets.contains(name) {
616 targets.push(name.clone());
617 }
618 }
619 if targets.is_empty() {
620 return None;
621 }
622 let id = self.next_id(annotations::hide::DEF.short_name);
623 self.find_view_mut(view_id)?.annotations.push(PmiAnnotation::hide_step(&id, &targets, false));
624 Some(id)
625 }
626
627 pub fn show_in_view(&mut self, view_id: &str, names: &[String], solids: &[String]) -> bool {
633 let Some(view) = self.find_view_mut(view_id) else { return false };
634 let shown = |solid: &str| names.iter().any(|name| name == solid);
635 let mut changed = false;
636 let mut emptied: Vec<usize> = Vec::new();
637 for (index, annotation) in view.annotations.iter_mut().enumerate() {
638 if !annotation.enabled || annotation.kind != annotations::hide::DEF.type_id {
639 continue;
640 }
641 let targets = annotation.references("targets");
642 if !targets.iter().any(|entry| names.iter().any(|name| entry_names_solid(entry, name))) {
643 continue;
644 }
645 let mut kept: Vec<String> = Vec::new();
646 for entry in targets {
647 if !names.iter().any(|name| entry_names_solid(&entry, name)) {
648 kept.push(entry);
649 continue;
650 }
651 for solid in solids.iter().filter(|solid| entry_names_solid(&entry, solid) && !shown(solid)) {
652 if !kept.contains(solid) {
653 kept.push(solid.clone());
654 }
655 }
656 }
657 changed = true;
658 if kept.is_empty() {
659 emptied.push(index);
660 } else {
661 annotation.params["targets"] = serde_json::json!(kept);
662 }
663 }
664 for index in emptied.into_iter().rev() {
665 view.annotations.remove(index);
666 }
667 changed
668 }
669
670 pub fn set_view_hidden(&mut self, view_id: &str, names: &[String], solids: &[String]) -> bool {
675 let Some(view) = self.find_view(view_id) else { return false };
676 let extra: Vec<String> = solids.iter().filter(|solid| view.hides(solid) && !names.contains(solid)).cloned().collect();
677 let mut changed = !extra.is_empty() && self.show_in_view(view_id, &extra, solids);
678 let view = self.find_view(view_id).expect("found above");
679 let mut baseline = view.baseline_hidden();
680 let missing: Vec<String> = names.iter().filter(|name| !view.hides(name)).cloned().collect();
681 if !missing.is_empty() {
682 if view.annotations.iter().any(|step| step.is_baseline_hide() && !step.enabled) {
683 changed |= self.hide_in_view(view_id, &missing).is_some();
686 } else {
687 baseline.extend(missing);
688 changed |= self.set_view_baseline(view_id, &baseline);
689 }
690 }
691 changed
692 }
693
694 pub fn next_id(&mut self, prefix: &str) -> String {
698 let seen = self.max_numeric_suffix();
699 if seen > self.id_counter {
700 self.id_counter = seen;
701 }
702 loop {
703 self.id_counter += 1;
704 let candidate = format!("{prefix}{}", self.id_counter);
705 if self.find_view(&candidate).is_none() && self.find_annotation(&candidate).is_none() {
706 return candidate;
707 }
708 }
709 }
710
711 fn max_numeric_suffix(&self) -> u64 {
712 let mut best = 0u64;
713 let mut consider = |id: &str| {
714 let digits = id
715 .bytes()
716 .rev()
717 .take_while(u8::is_ascii_digit)
718 .count();
719 if digits > 0 {
720 if let Ok(value) = id[id.len() - digits..].parse::<u64>() {
721 best = best.max(value);
722 }
723 }
724 };
725 for view in &self.views {
726 consider(&view.id);
727 for annotation in &view.annotations {
728 consider(annotation.id());
729 }
730 }
731 best
732 }
733
734 pub fn find_view(&self, id: &str) -> Option<&PmiView> {
735 self.views.iter().find(|view| view.id == id)
736 }
737
738 pub fn find_view_mut(&mut self, id: &str) -> Option<&mut PmiView> {
739 self.views.iter_mut().find(|view| view.id == id)
740 }
741
742 pub fn find_annotation(&self, id: &str) -> Option<(&PmiView, &PmiAnnotation)> {
744 self.views.iter().find_map(|view| {
745 view.annotations
746 .iter()
747 .find(|annotation| annotation.id() == id)
748 .map(|annotation| (view, annotation))
749 })
750 }
751
752 pub fn locate_annotation(&self, id: &str) -> Option<(usize, usize)> {
754 self.views.iter().enumerate().find_map(|(view_index, view)| {
755 view.annotations
756 .iter()
757 .position(|annotation| annotation.id() == id)
758 .map(|index| (view_index, index))
759 })
760 }
761
762 pub fn find_annotation_mut(&mut self, id: &str) -> Option<&mut PmiAnnotation> {
763 self.views.iter_mut().find_map(|view| {
764 view.annotations
765 .iter_mut()
766 .find(|annotation| annotation.id() == id)
767 })
768 }
769
770 pub fn datum_letters(&self) -> Vec<(String, String)> {
774 let mut out = Vec::new();
775 for view in &self.views {
776 for annotation in &view.annotations {
777 if annotation.kind == annotations::datum::DEF.type_id {
778 let letter = annotation.text("letter").to_uppercase();
779 if !letter.is_empty() {
780 out.push((letter, annotation.id().to_string()));
781 }
782 }
783 }
784 }
785 out
786 }
787
788 pub fn next_datum_letter(&self) -> Option<String> {
791 let used: Vec<String> = self.datum_letters().into_iter().map(|(l, _)| l).collect();
792 let alphabet: Vec<char> = ('A'..='Z').filter(|c| !matches!(c, 'I' | 'O' | 'Q')).collect();
793 for letter in &alphabet {
794 let candidate = letter.to_string();
795 if !used.contains(&candidate) {
796 return Some(candidate);
797 }
798 }
799 for first in &alphabet {
800 for second in &alphabet {
801 let candidate = format!("{first}{second}");
802 if !used.contains(&candidate) {
803 return Some(candidate);
804 }
805 }
806 }
807 None
808 }
809
810 pub fn is_empty(&self) -> bool {
812 self.views.is_empty() && self.id_counter == 0
813 }
814}
815
816#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
822pub struct PmiReport {
823 pub views: Vec<PmiViewReport>,
824}
825
826impl PmiReport {
827 pub fn view(&self, id: &str) -> Option<&PmiViewReport> {
828 self.views.iter().find(|view| view.id == id)
829 }
830
831 pub fn annotation(&self, id: &str) -> Option<&PmiAnnotationReport> {
832 self.views
833 .iter()
834 .find_map(|view| view.annotations.iter().find(|a| a.id == id))
835 }
836
837 pub fn annotation_mut(&mut self, id: &str) -> Option<&mut PmiAnnotationReport> {
838 self.views
839 .iter_mut()
840 .find_map(|view| view.annotations.iter_mut().find(|a| a.id == id))
841 }
842}
843
844#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
845pub struct PmiViewReport {
846 pub id: String,
847 pub annotations: Vec<PmiAnnotationReport>,
848 #[serde(default, rename = "sectionPlane", skip_serializing_if = "Option::is_none")]
851 pub section_plane: Option<([f64; 3], [f64; 3])>,
852 #[serde(default, rename = "sectionError", skip_serializing_if = "String::is_empty")]
854 pub section_error: String,
855 #[serde(default, skip_serializing_if = "Vec::is_empty")]
859 pub hidden: Vec<String>,
860}
861
862#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
863#[serde(rename_all = "kebab-case")]
864pub enum PmiStatus {
865 Ok,
867 Error,
870}
871
872#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
874pub struct PmiAnnotationReport {
875 #[serde(default, rename = "persistentData", skip_serializing_if = "Option::is_none")]
877 pub persistent_data: Option<Value>,
878 #[serde(default, rename = "pluginReplay", skip_serializing_if = "Option::is_none")]
879 pub plugin_replay: Option<PluginAnnotationReplay>,
880 pub id: String,
881 #[serde(rename = "type")]
882 pub kind: String,
883 pub enabled: bool,
884 pub status: PmiStatus,
885 #[serde(default)]
886 pub message: String,
887 #[serde(default)]
890 pub text: String,
891 #[serde(default, skip_serializing_if = "Option::is_none")]
893 pub value: Option<f64>,
894 #[serde(default)]
896 pub unit: String,
897 #[serde(default)]
900 pub references: Vec<String>,
901 #[serde(rename = "labelWorld")]
904 pub label_world: [f64; 3],
905 #[serde(default, skip_serializing_if = "Option::is_none")]
907 pub plane: Option<PmiPlane>,
908 pub geometry: PmiGeometry,
909 #[serde(default, rename = "weldSymbol", skip_serializing_if = "Option::is_none")]
913 pub weld_symbol: Option<weld_symbol::WeldSymbol>,
914}
915
916#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
923pub struct PmiPlane {
924 pub origin: [f64; 3],
925 pub normal: [f64; 3],
926 #[serde(rename = "xAxis")]
927 pub x_axis: [f64; 3],
928}
929
930impl PmiPlane {
931 pub fn project(&self, point: [f64; 3]) -> [f64; 3] {
933 let n = self.normal;
934 let d = (point[0] - self.origin[0]) * n[0] + (point[1] - self.origin[1]) * n[1] + (point[2] - self.origin[2]) * n[2];
935 [point[0] - n[0] * d, point[1] - n[1] * d, point[2] - n[2] * d]
936 }
937
938 pub fn y_axis(&self) -> [f64; 3] {
940 let n = self.normal;
941 let x = self.x_axis;
942 [n[1] * x[2] - n[2] * x[1], n[2] * x[0] - n[0] * x[2], n[0] * x[1] - n[1] * x[0]]
943 }
944
945 pub fn hit(&self, origin: [f64; 3], dir: [f64; 3]) -> Option<[f64; 3]> {
947 let n = self.normal;
948 let denominator = dir[0] * n[0] + dir[1] * n[1] + dir[2] * n[2];
949 if denominator.abs() < 1e-12 {
950 return None;
951 }
952 let diff = [self.origin[0] - origin[0], self.origin[1] - origin[1], self.origin[2] - origin[2]];
953 let t = (diff[0] * n[0] + diff[1] * n[1] + diff[2] * n[2]) / denominator;
954 Some([origin[0] + dir[0] * t, origin[1] + dir[1] * t, origin[2] + dir[2] * t])
955 }
956}
957
958#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
961#[serde(tag = "kind", rename_all = "camelCase")]
962pub enum PmiGeometry {
963 None,
964 Linear {
967 a: [f64; 3],
968 b: [f64; 3],
969 #[serde(default, skip_serializing_if = "Option::is_none")]
970 component: Option<char>,
971 },
972 Radial {
973 center: [f64; 3],
974 axis: [f64; 3],
975 radius: f64,
976 diameter: bool,
977 sphere: bool,
978 },
979 Angular {
982 vertex: [f64; 3],
983 #[serde(rename = "dirA")]
984 dir_a: [f64; 3],
985 #[serde(rename = "dirB")]
986 dir_b: [f64; 3],
987 axis: [f64; 3],
988 degrees: f64,
989 },
990 Leader {
991 targets: Vec<[f64; 3]>,
992 dot: bool,
993 #[serde(default, skip_serializing_if = "is_false")]
994 balloon: bool,
995 #[serde(default, skip_serializing_if = "Option::is_none")]
998 anchor: Option<BalloonAnchor>,
999 },
1000 Note {
1001 position: [f64; 3],
1002 },
1003 Hole {
1004 anchor: [f64; 3],
1005 normal: [f64; 3],
1006 },
1007 Hide {
1010 solids: Vec<String>,
1011 },
1012 Explode {
1014 solids: Vec<String>,
1015 translate: [f64; 3],
1016 #[serde(rename = "rotateDeg")]
1017 rotate_deg: [f64; 3],
1018 scale: [f64; 3],
1019 center: [f64; 3],
1021 trace: bool,
1022 },
1023 Datum {
1024 anchor: [f64; 3],
1025 normal: [f64; 3],
1026 letter: String,
1027 },
1028 Fcf {
1029 anchor: [f64; 3],
1030 normal: [f64; 3],
1031 frame: FcfFrame,
1032 },
1033 CenterMark {
1036 marks: Vec<CenterCircle>,
1037 extension: f64,
1038 },
1039 CenterLine {
1041 a: [f64; 3],
1042 b: [f64; 3],
1043 },
1044}
1045
1046#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1061pub struct CenterCircle {
1062 pub center: [f64; 3],
1063 pub axis: [f64; 3],
1064 pub radius: f64,
1065 #[serde(default, skip_serializing_if = "is_zero")]
1066 pub depth: f64,
1067 #[serde(default, rename = "xDir", skip_serializing_if = "is_zero_vector")]
1068 pub x_dir: [f64; 3],
1069}
1070
1071fn is_zero_vector(value: &[f64; 3]) -> bool {
1072 value.iter().all(|c| *c == 0.0)
1073}
1074
1075fn is_zero(value: &f64) -> bool {
1076 *value == 0.0
1077}
1078
1079#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1081pub struct FcfFrame {
1082 pub characteristic: String,
1084 pub symbol: String,
1086 pub zone: String,
1088 pub datums: Vec<String>,
1090}
1091
1092#[derive(Debug, Clone, Copy, PartialEq)]
1099pub struct ToleranceBlock {
1100 pub mode: ToleranceMode,
1101 pub upper: f64,
1102 pub lower: f64,
1103}
1104
1105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1106pub enum ToleranceMode {
1107 None,
1108 Symmetric,
1109 Deviation,
1110 Limits,
1111}
1112
1113impl ToleranceMode {
1114 pub fn parse(text: &str) -> Self {
1115 match text.trim().to_ascii_lowercase().as_str() {
1116 "symmetric" => ToleranceMode::Symmetric,
1117 "deviation" => ToleranceMode::Deviation,
1118 "limits" => ToleranceMode::Limits,
1119 _ => ToleranceMode::None,
1120 }
1121 }
1122
1123 pub fn as_str(self) -> &'static str {
1124 match self {
1125 ToleranceMode::None => "none",
1126 ToleranceMode::Symmetric => "symmetric",
1127 ToleranceMode::Deviation => "deviation",
1128 ToleranceMode::Limits => "limits",
1129 }
1130 }
1131}
1132
1133impl ToleranceBlock {
1134 pub fn read(annotation: &PmiAnnotation, env: &Env) -> Result<Self, String> {
1136 Ok(Self {
1137 mode: ToleranceMode::parse(annotation.text("tolMode")),
1138 upper: annotation.number("tolUpper", env, 0.0)?.abs(),
1139 lower: annotation.number("tolLower", env, 0.0)?.abs(),
1140 })
1141 }
1142
1143 pub fn bounds(&self) -> Option<(f64, f64)> {
1146 match self.mode {
1147 ToleranceMode::None => None,
1148 ToleranceMode::Symmetric => Some((-self.upper, self.upper)),
1149 ToleranceMode::Deviation | ToleranceMode::Limits => Some((-self.lower, self.upper)),
1150 }
1151 }
1152}
1153
1154pub fn format_number(value: f64, decimals: usize) -> String {
1156 let decimals = decimals.min(8);
1157 let text = format!("{:.*}", decimals, value);
1158 if text.starts_with('-') && text[1..].bytes().all(|b| b == b'0' || b == b'.') {
1160 text[1..].to_string()
1161 } else {
1162 text
1163 }
1164}
1165
1166pub fn format_dimension(
1170 value: f64,
1171 decimals: usize,
1172 tolerance: &ToleranceBlock,
1173 is_reference: bool,
1174 prefix: &str,
1175 suffix: &str,
1176) -> String {
1177 let nominal = format!("{prefix}{}{suffix}", format_number(value, decimals));
1178 if is_reference {
1179 return format!("({nominal})");
1180 }
1181 match tolerance.mode {
1182 ToleranceMode::None => nominal,
1183 ToleranceMode::Symmetric => format!(
1184 "{nominal} \u{00B1}{}{suffix}",
1185 format_number(tolerance.upper, decimals)
1186 ),
1187 ToleranceMode::Deviation => format!(
1188 "{nominal} +{}{suffix}/\u{2212}{}{suffix}",
1189 format_number(tolerance.upper, decimals),
1190 format_number(tolerance.lower, decimals)
1191 ),
1192 ToleranceMode::Limits => format!(
1193 "{prefix}{}{suffix} / {prefix}{}{suffix}",
1194 format_number(value + tolerance.upper, decimals),
1195 format_number(value - tolerance.lower, decimals)
1196 ),
1197 }
1198}
1199
1200pub struct PmiContext<'a> {
1207 pub scene: &'a SceneMap,
1208 pub request: &'a HistoryRequest,
1209 pub env: &'a Env,
1210 pub state: &'a PmiState,
1212 pub datums: BTreeMap<String, String>,
1214}
1215
1216pub struct Resolved {
1218 pub text: String,
1219 pub value: Option<f64>,
1220 pub unit: &'static str,
1221 pub references: Vec<String>,
1222 pub geometry: PmiGeometry,
1223 pub default_label: [f64; 3],
1225}
1226
1227pub(crate) fn finish_history_run(
1230 request: &HistoryRequest,
1231 scene: &SceneMap,
1232 env: &Env,
1233) -> Option<PmiReport> {
1234 let state = request.pmi.as_ref()?;
1235 Some(resolve_state(state, scene, request, env))
1236}
1237
1238pub fn resolve_state(
1240 state: &PmiState,
1241 scene: &SceneMap,
1242 request: &HistoryRequest,
1243 env: &Env,
1244) -> PmiReport {
1245 let mut datums: BTreeMap<String, String> = BTreeMap::new();
1248 for (letter, id) in state.datum_letters() {
1249 datums.entry(letter).or_insert(id);
1250 }
1251 let mut state = state.clone();
1254 let mut section_errors: BTreeMap<String, String> = BTreeMap::new();
1255 for view in &mut state.views {
1256 if let Err(error) = resolve_section_plane(view, scene) {
1257 section_errors.insert(view.id.clone(), error);
1258 }
1259 }
1260 let state = &state;
1261 let context = PmiContext {
1262 scene,
1263 request,
1264 env,
1265 state,
1266 datums,
1267 };
1268 PmiReport {
1269 views: state
1270 .views
1271 .iter()
1272 .map(|view| {
1273 let section = section_half_space(view);
1274 let exempt = |reference: &str| {
1275 let section = view.display.section.as_ref();
1276 section.is_some_and(|section| reference_solid(scene, reference).is_some_and(|solid| section.excludes(&solid)))
1277 };
1278 let mut hidden: Vec<String> = scene.solids.keys().filter(|name| view.hides(name)).cloned().collect();
1279 hidden.sort();
1280 PmiViewReport {
1281 section_plane: view.display.section.as_ref().filter(|s| s.axis == "Plane").and_then(|_| view.section_plane()),
1282 section_error: section_errors.remove(&view.id).unwrap_or_default(),
1283 hidden,
1284 id: view.id.clone(),
1285 annotations: view
1286 .annotations
1287 .iter()
1288 .map(|annotation| {
1289 let report = resolve_annotation(annotation, &context, view.camera.as_ref());
1290 match §ion {
1291 Some(section) => sectioned_away(report, section, &exempt),
1292 None => report,
1293 }
1294 })
1295 .collect(),
1296 }
1297 })
1298 .collect(),
1299 }
1300}
1301
1302fn resolve_section_plane(view: &mut PmiView, scene: &SceneMap) -> Result<(), String> {
1305 let Some(section) = view.display.section.as_mut().filter(|s| s.axis == "Plane") else {
1306 return Ok(());
1307 };
1308 let name = section.plane.clone().unwrap_or_default();
1309 if name.trim().is_empty() {
1310 return Err("pick a planar face or a datum plane to cut on".into());
1311 }
1312 match resolve::resolve_reference(scene, &name) {
1313 Ok(crate::SelectionGeometry::Plane { origin, normal }) => {
1314 section.origin = Some(resolve::a3(origin));
1315 section.normal = Some(resolve::a3(normal));
1316 Ok(())
1317 }
1318 Ok(_) => Err(format!("section plane '{name}' is not planar: pick a planar face or a datum plane")),
1319 Err(error) => Err(format!("section plane '{name}': {error}")),
1320 }
1321}
1322
1323fn section_half_space(view: &PmiView) -> Option<anchor::HalfSpace> {
1328 if view.annotations.iter().any(|a| a.enabled && a.kind == "explode") {
1329 return None;
1330 }
1331 anchor::HalfSpace::of(&view.section_planes())
1332}
1333
1334fn sectioned_away(mut report: PmiAnnotationReport, section: &anchor::HalfSpace, exempt: &dyn Fn(&str) -> bool) -> PmiAnnotationReport {
1342 if report.status != PmiStatus::Ok {
1343 return report;
1344 }
1345 let points: Vec<[f64; 3]> = match &report.geometry {
1346 PmiGeometry::Linear { a, b, component: None } => vec![*a, *b],
1347 PmiGeometry::Linear { a, component: Some(_), .. } => vec![*a],
1349 PmiGeometry::Leader { targets, balloon: false, .. } => targets.clone(),
1350 PmiGeometry::Hole { anchor, .. } | PmiGeometry::Datum { anchor, .. } | PmiGeometry::Fcf { anchor, .. } => vec![*anchor],
1351 _ => return report,
1352 };
1353 let references = &report.references;
1356 let point_exempt = |index: usize| match references.len() == points.len() {
1357 true => exempt(&references[index]),
1358 false => !references.is_empty() && references.iter().all(|reference| exempt(reference)),
1359 };
1360 if points.iter().enumerate().all(|(index, point)| point_exempt(index) || section.keeps(*point, 1e-6)) {
1361 return report;
1362 }
1363 report.status = PmiStatus::Error;
1364 report.message = "it is on geometry the section removes in this view: move the section, Reverse it, or re-attach the annotation".into();
1365 report.text = String::new();
1366 report.value = None;
1367 report.geometry = PmiGeometry::None;
1368 report.plane = None;
1369 report
1370}
1371
1372fn reference_solid(scene: &SceneMap, reference: &str) -> Option<String> {
1375 let reference = reference.trim();
1376 if let Some((solid, _)) = reference.split_once('@') {
1377 return Some(solid.to_string());
1378 }
1379 let handle = scene
1380 .resolve_face(reference)
1381 .map(|face| face.handle)
1382 .or_else(|| scene.resolve_edge(reference).map(|edge| edge.handle))
1383 .or_else(|| scene.resolve_solid(reference))?;
1384 scene.solids.iter().find(|(_, h)| **h == handle).map(|(name, _)| name.clone())
1385}
1386
1387pub fn resolve_annotation(
1391 annotation: &PmiAnnotation,
1392 context: &PmiContext<'_>,
1393 camera: Option<&PmiCamera>,
1394) -> PmiAnnotationReport {
1395 let mut persistent_data = None;
1396 let mut plugin_replay = None;
1397 let outcome = match pmi_type(&annotation.kind) {
1398 None if annotation.kind.contains('/') && !annotation.enabled => Ok(Resolved {
1399 text: String::new(), value: None, unit: "", references: Vec::new(),
1400 geometry: PmiGeometry::None, default_label: annotation.label_world.unwrap_or([0.; 3]),
1401 }),
1402 Some(def) => (def.resolve)(annotation, context),
1403 None if annotation.kind.contains('/') => plugin::resolve(annotation, context).map(|(resolved, data, replay)| {
1404 persistent_data = Some(data);
1405 plugin_replay = Some(replay);
1406 resolved
1407 }),
1408 None => Err(format!("unknown PMI annotation type '{}'", annotation.kind)),
1409 }
1410 .and_then(|resolved| {
1411 let plane = annotation_plane(annotation, context, camera, &resolved.geometry)?;
1412 Ok((resolved, plane))
1413 });
1414 match outcome {
1415 Ok((resolved, plane)) => {
1416 let label = annotation.label_world.unwrap_or(resolved.default_label);
1417 let weld_symbol = (annotation.kind == annotations::weld_callout::DEF.type_id)
1419 .then(|| annotations::weld_callout::symbol(annotation, context).ok().flatten())
1420 .flatten();
1421 PmiAnnotationReport {
1422 persistent_data,
1423 plugin_replay,
1424 id: annotation.id().to_string(),
1425 kind: annotation.kind.clone(),
1426 enabled: annotation.enabled,
1427 status: PmiStatus::Ok,
1428 message: String::new(),
1429 text: resolved.text,
1430 value: resolved.value,
1431 unit: resolved.unit.to_string(),
1432 references: resolved.references,
1433 label_world: plane.map_or(label, |plane| plane.project(label)),
1434 plane,
1435 geometry: resolved.geometry,
1436 weld_symbol,
1437 }
1438 }
1439 Err(message) => PmiAnnotationReport {
1440 persistent_data: None,
1441 plugin_replay: None,
1442 id: annotation.id().to_string(),
1443 kind: annotation.kind.clone(),
1444 enabled: annotation.enabled,
1445 status: PmiStatus::Error,
1446 message,
1447 text: String::new(),
1448 value: None,
1449 unit: String::new(),
1450 references: Vec::new(),
1451 label_world: annotation
1454 .label_world
1455 .or_else(|| (annotation.kind == "balloon").then(|| annotations::balloon::error_bubble(annotation, context)).flatten())
1456 .unwrap_or([0.0; 3]),
1457 plane: None,
1458 geometry: PmiGeometry::None,
1459 weld_symbol: None,
1460 },
1461 }
1462}
1463
1464fn annotation_plane(
1472 annotation: &PmiAnnotation,
1473 context: &PmiContext<'_>,
1474 camera: Option<&PmiCamera>,
1475 geometry: &PmiGeometry,
1476) -> Result<Option<PmiPlane>, String> {
1477 use crate::SelectionGeometry;
1478 use resolve::{a3, perpendicular_in_plane, v3};
1479 let Some(name) = annotation.plane_ref() else {
1480 return Ok(None);
1481 };
1482 let (origin, normal) = match resolve::resolve_reference(context.scene, name)? {
1483 SelectionGeometry::Plane { origin, normal } => (origin, normal),
1484 _ => return Err(format!("annotation plane '{name}' must be a planar face or a reference plane")),
1485 };
1486 let mut normal = normal
1487 .normalized()
1488 .map_err(|_| format!("annotation plane '{name}' has no normal"))?;
1489 const PARALLEL: f64 = 1e-3;
1491 match geometry {
1492 PmiGeometry::Linear { a, b, .. } => {
1493 let span = v3(*b).sub(v3(*a));
1494 if span.length() > 1e-9 && span.normalized().map(|d| d.dot(normal).abs()).unwrap_or(0.0) > PARALLEL {
1495 return Err(format!("annotation plane '{name}' is not parallel to the measured direction"));
1496 }
1497 }
1498 PmiGeometry::Angular { axis, .. } => {
1499 if v3(*axis).cross(normal).length() > PARALLEL {
1500 return Err(format!("annotation plane '{name}' is not parallel to the angle's plane"));
1501 }
1502 }
1503 PmiGeometry::Radial { axis, sphere: false, .. } => {
1504 if v3(*axis).cross(normal).length() > PARALLEL {
1505 return Err(format!("annotation plane '{name}' is not parallel to the circle's plane"));
1506 }
1507 }
1508 PmiGeometry::CenterMark { marks, .. } => {
1509 if marks.iter().any(|mark| v3(mark.axis).length() > 1e-12 && v3(mark.axis).cross(normal).length() > PARALLEL) {
1510 return Err(format!("annotation plane '{name}' is not parallel to the marked circle's plane"));
1511 }
1512 }
1513 PmiGeometry::CenterLine { a, b } => {
1514 let span = v3(*b).sub(v3(*a));
1515 if span.length() > 1e-9 && span.normalized().map(|d| d.dot(normal).abs()).unwrap_or(0.0) > PARALLEL {
1516 return Err(format!("annotation plane '{name}' is not parallel to the centerline"));
1517 }
1518 }
1519 _ => {}
1520 }
1521 let x_axis = match camera {
1522 Some(camera) => {
1523 let view = v3(camera.view_direction());
1524 if normal.dot(view) > 0.0 {
1525 normal = normal.scale(-1.0);
1526 }
1527 perpendicular_in_plane(normal, view.cross(v3(camera.up)))
1528 }
1529 None => perpendicular_in_plane(normal, crate::Vec3::new(1.0, 0.0, 0.0)),
1530 };
1531 Ok(Some(PmiPlane {
1532 origin: a3(origin),
1533 normal: a3(normal),
1534 x_axis: a3(x_axis),
1535 }))
1536}
1537