Skip to main content

brep_kernel/feature_pipeline/pmi/annotations/
balloon.rs

1//! BOM find-number callout, resolved live from the owning occurrence.
2//!
3//! The arrow head lands ON the occurrence as the owning view DISPLAYS it: by
4//! default at the point of its visible, posed, un-sectioned surface nearest
5//! the bubble in screen space, or — with the optional `anchor` reference — on a picked edge
6//! (nearest the bubble) or exactly at a picked vertex. A target the view
7//! cannot show (every member hidden, or sectioned away; an anchor on a
8//! hidden member or on the cut-away side) is an error row with no leader,
9//! never a leader into space. See [`crate::feature_pipeline::pmi::anchor`]
10//! for the projection, the per-solid explode stages, the section half-space
11//! and the recipe the viewport re-derives the head with while the bubble is
12//! dragged.
13use std::collections::BTreeMap;
14
15use super::{id_field, params, reference_field, schema_entry, string_field, PmiTypeDef};
16use crate::feature_pipeline::pmi::anchor::{
17    nearest_screen_point, head_distance, nearest_displayed_point_on_edge, pose_apply, pose_unapply, BalloonAnchor,
18    BalloonAnchorMode, HalfSpace, HeadScope, PmiPose, SolidPoses,
19};
20use crate::feature_pipeline::pmi::resolve::{a3, solid_bbox, v3};
21use crate::feature_pipeline::pmi::{PmiAnnotation, PmiContext, PmiGeometry, PmiView, Resolved};
22use crate::feature_pipeline::SelectionProbe;
23use crate::{resolve_vertex_selection, SelectionGeometry, Vec3};
24
25pub const DEF: PmiTypeDef = PmiTypeDef {
26    type_id: "balloon",
27    short_name: "BAL",
28    icon: "\u{2460}",
29    long_name: "\u{2460} Find-number balloon",
30    label: "Find-number balloon",
31    applicable: |p: &SelectionProbe| p.components > 0,
32    schema,
33    resolve,
34};
35fn schema() -> serde_json::Value {
36    schema_entry(
37        &DEF,
38        params(vec![
39            ("id", id_field()),
40            (
41                "target",
42                reference_field(
43                    "Component or geometry",
44                    &["COMPONENT", "SOLID", "FACE", "EDGE", "VERTEX"],
45                    false,
46                    1,
47                    1,
48                    "The occurrence whose BOM Find Number is displayed",
49                ),
50            ),
51            (
52                "anchor",
53                reference_field(
54                    "Arrow anchor",
55                    &["VERTEX", "EDGE"],
56                    false,
57                    0,
58                    1,
59                    "Optional: a vertex or an edge of the component the arrow head lands on; empty puts it on the nearest point of the surface in screen space",
60                ),
61            ),
62            (
63                "occurrence",
64                string_field(
65                    "Occurrence",
66                    "",
67                    "Optional: a placement inside a sub-assembly (ACOMP1:ACOMP3) to balloon instead of the top-level component; its Find Number is the one its sub-assembly gives it",
68                ),
69            ),
70        ]),
71    )
72}
73
74/// The view the annotation belongs to, from the PMI block being resolved.
75fn owning_view<'a>(annotation: &PmiAnnotation, context: &'a PmiContext<'_>) -> Option<&'a PmiView> {
76    context.state.find_annotation(annotation.id()).map(|(view, _)| view)
77}
78
79/// The explode stages the owning view displays each of `solids` through:
80/// every enabled, resolved explode row naming the solid, in the view's row
81/// order — the order the viewport poses the display in.
82fn explode_stages(view: Option<&PmiView>, context: &PmiContext<'_>, solids: &[String]) -> BTreeMap<String, Vec<PmiPose>> {
83    let mut stages: BTreeMap<String, Vec<PmiPose>> = BTreeMap::new();
84    let Some(view) = view else {
85        return stages;
86    };
87    for explode in view
88        .annotations
89        .iter()
90        .filter(|a| a.enabled && a.kind == "explode")
91    {
92        let Ok(resolved) = (super::explode::DEF.resolve)(explode, context) else { continue };
93        if let PmiGeometry::Explode {
94            solids: exploded,
95            center,
96            translate,
97            rotate_deg,
98            scale,
99            ..
100        } = resolved.geometry
101        {
102            let pose = PmiPose {
103                center,
104                translate,
105                rotate_deg,
106                scale,
107            };
108            for name in solids.iter().filter(|name| exploded.contains(name)) {
109                stages.entry(name.clone()).or_default().push(pose);
110            }
111        }
112    }
113    stages
114}
115
116/// The view's section half-space (all its planes), kept where the display
117/// clip keeps.
118fn section_of(view: Option<&PmiView>) -> Option<HalfSpace> {
119    HalfSpace::of(&view?.section_planes())
120}
121
122/// Parse a `{solid}@x,y,z` vertex reference.
123fn parse_vertex_ref(name: &str) -> Option<(&str, Vec3)> {
124    let (solid, coords) = name.split_once('@')?;
125    let mut parts = coords.split(',').map(|part| part.trim().parse::<f64>());
126    let x = parts.next()?.ok()?;
127    let y = parts.next()?.ok()?;
128    let z = parts.next()?.ok()?;
129    if parts.next().is_some() {
130        return None;
131    }
132    Some((solid, Vec3::new(x, y, z)))
133}
134
135/// The occurrence a balloon names, with what the owning view makes of it.
136struct Occurrence {
137    id: String,
138    /// Every member `(scene name, handle)`.
139    members: Vec<(String, u32)>,
140    /// The members the view shows (`PmiView::hides` says no).
141    visible: Vec<(String, u32)>,
142    stages: BTreeMap<String, Vec<PmiPose>>,
143    section: Option<HalfSpace>,
144    /// Members the view's section leaves whole: never sectioned away.
145    exempt: Vec<String>,
146    /// The bubble a balloon without a stored one gets: off the displayed
147    /// box's +X+Y corner at mid height, outside the body.
148    default_label: [f64; 3],
149}
150
151fn occurrence(annotation: &PmiAnnotation, context: &PmiContext<'_>) -> Result<Occurrence, String> {
152    let targets = annotation.references("target");
153    if targets.len() != 1 {
154        return Err("select exactly one component or element".into());
155    }
156    let target = targets
157        .first()
158        .ok_or("select a component or its geometry")?;
159    let component = context
160        .scene
161        .owning_component(target)
162        .ok_or("select geometry belonging to an assembly component")?;
163    let (id, members) = match nested_path(annotation) {
164        Some(path) => {
165            if !path.starts_with(&format!("{}:", component.id)) {
166                return Err(format!("occurrence '{path}' is not inside component {}", component.id));
167            }
168            let members = context.scene.occurrence_solids(path);
169            if members.is_empty() {
170                return Err(format!("occurrence '{path}' no longer exists"));
171            }
172            if !target.starts_with(&format!("{path}:")) && target != path {
173                return Err(format!("the target is not part of occurrence '{path}'"));
174            }
175            (path.to_string(), members)
176        }
177        None => (component.id.clone(), context.scene.component_solids(&component.id)),
178    };
179    if members.is_empty() {
180        return Err("component has no geometry".into());
181    }
182    let view = owning_view(annotation, context);
183    let names: Vec<String> = members.iter().map(|(name, _)| name.clone()).collect();
184    let stages = explode_stages(view, context, &names);
185    let section = section_of(view);
186    let exempt: Vec<String> = match view.and_then(|view| view.display.section.as_ref()) {
187        Some(cut) => names.iter().filter(|name| cut.excludes(name)).cloned().collect(),
188        None => Vec::new(),
189    };
190    // Hidden by the view: its captured baseline or one of its hide steps.
191    let visible: Vec<(String, u32)> = members
192        .iter()
193        .filter(|(name, _)| !view.is_some_and(|view| view.hides(name)))
194        .cloned()
195        .collect();
196    // The DISPLAYED box of the occurrence: each member's box corners posed
197    // through its own stages (so a half-exploded occurrence's bubble still
198    // sits beside what is shown).
199    let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
200    let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
201    for (name, handle) in if visible.is_empty() { &members } else { &visible } {
202        let (lo, hi) = solid_bbox(*handle)?;
203        let stages = stages.get(name).map_or(&[][..], Vec::as_slice);
204        for corner in 0..8 {
205            let point = [
206                if corner & 1 == 0 { lo.x } else { hi.x },
207                if corner & 2 == 0 { lo.y } else { hi.y },
208                if corner & 4 == 0 { lo.z } else { hi.z },
209            ];
210            let posed = pose_apply(stages, point);
211            low = Vec3::new(low.x.min(posed[0]), low.y.min(posed[1]), low.z.min(posed[2]));
212            high = Vec3::new(high.x.max(posed[0]), high.y.max(posed[1]), high.z.max(posed[2]));
213        }
214    }
215    let extent = high.sub(low);
216    let reach = extent.x.max(extent.y).max(extent.z).max(1.0) * 0.35;
217    let default_label = [high.x + reach, high.y + reach, (low.z + high.z) * 0.5];
218    Ok(Occurrence {
219        id,
220        members,
221        visible,
222        stages,
223        section,
224        exempt,
225        default_label,
226    })
227}
228
229/// The nested occurrence path a balloon names, when it names one.
230fn nested_path(annotation: &PmiAnnotation) -> Option<&str> {
231    annotation
232        .params
233        .get("occurrence")
234        .and_then(serde_json::Value::as_str)
235        .map(str::trim)
236        .filter(|path| !path.is_empty())
237}
238
239/// The `bom` record of the placement `path` names: the top-level component's
240/// own for one segment, else the placing component's inside the owning
241/// sub-assembly's definition, walked down the parts libraries.
242fn placement_bom(context: &PmiContext<'_>, path: &str) -> Result<serde_json::Value, String> {
243    let mut segments = path.split(':');
244    let first = segments.next().unwrap_or_default();
245    let mut params = context
246        .request
247        .features
248        .iter()
249        .find(|f| f.input_params["id"].as_str() == Some(first))
250        .map(|f| f.input_params.clone())
251        .ok_or("component no longer exists")?;
252    // `None` is the open document's own library.
253    let mut library: Option<serde_json::Value> = None;
254    for segment in segments {
255        let part = params["partName"].as_str().unwrap_or_default().to_string();
256        let document = match &library {
257            None => crate::feature_pipeline::parts_library::active_entry(&part)
258                .map(|entry| entry.document)
259                .or_else(|| context.request.parts_library.get(&part).map(|entry| entry.document.clone())),
260            Some(library) => library.get(&part).map(|entry| entry["document"].clone()),
261        }
262        .ok_or_else(|| format!("occurrence '{path}': part '{part}' is not in the parts library"))?;
263        params = document["features"]
264            .as_array()
265            .and_then(|features| features.iter().find(|f| f["inputParams"]["id"].as_str() == Some(segment)))
266            .map(|f| f["inputParams"].clone())
267            .ok_or_else(|| format!("occurrence '{path}' no longer exists"))?;
268        library = Some(document["partsLibrary"].clone());
269    }
270    Ok(params["bom"].clone())
271}
272
273/// Where an error row's chip sits for a balloon without a stored bubble:
274/// the default bubble beside the occurrence, when the occurrence resolves
275/// at all — so a refused balloon is red NEXT TO its part, not at the origin.
276pub fn error_bubble(annotation: &PmiAnnotation, context: &PmiContext<'_>) -> Option<[f64; 3]> {
277    occurrence(annotation, context).ok().map(|occurrence| occurrence.default_label)
278}
279
280fn resolve(annotation: &PmiAnnotation, context: &PmiContext<'_>) -> Result<Resolved, String> {
281    let targets = annotation.references("target");
282    let occurrence = occurrence(annotation, context)?;
283    let bom = placement_bom(context, &occurrence.id)?;
284    let find = &bom["Find_Number"];
285    let text = match find {
286        serde_json::Value::String(s) => s.trim().to_owned(),
287        serde_json::Value::Number(n) => n.to_string(),
288        _ => String::new(),
289    };
290    if text.is_empty() {
291        return Err("set the component's Find Number in the BOM before adding a balloon".into());
292    }
293    let component_id = occurrence.id.clone();
294    if occurrence.visible.is_empty() {
295        return Err(format!("component {component_id} is hidden in this view: show it or move the balloon to another view"));
296    }
297    let default_label = occurrence.default_label;
298    // The bubble the head is derived from, in the displayed frame.
299    let bubble = annotation.label_world.unwrap_or(default_label);
300    let camera = owning_view(annotation, context).and_then(|view| view.camera.as_ref());
301    let stages_of = |name: &str| occurrence.stages.get(name).map_or(&[][..], Vec::as_slice);
302    let scope_of = |name: &str| HeadScope {
303        stages: stages_of(name),
304        section: occurrence.section.as_ref().filter(|_| !occurrence.exempt.iter().any(|exempt| exempt == name)),
305    };
306    // The anchor: nothing (the surface), a vertex ref, or an edge name — on
307    // this occurrence, and on a member the view shows.
308    let anchors = annotation.references("anchor");
309    if anchors.len() > 1 {
310        return Err("pick at most one anchor".into());
311    }
312    let owner_of = |name: &str| -> Result<(), String> {
313        match context.scene.owning_component(name) {
314            Some(owner) if owner.id == component_id => Ok(()),
315            _ if component_id.contains(':') && name.starts_with(&format!("{component_id}:")) => Ok(()),
316            _ => Err(format!("anchor '{name}' is not on component {component_id}")),
317        }
318    };
319    let shown = |solid: &str, name: &str| -> Result<(), String> {
320        if occurrence.visible.iter().any(|(member, _)| member == solid) {
321            Ok(())
322        } else {
323            Err(format!("anchor '{name}' is on '{solid}', which is hidden in this view"))
324        }
325    };
326    let (head, mode) = match anchors.first().map(String::as_str) {
327        None => {
328            let mut best: Option<(f64, [f64; 3])> = None;
329            for (name, handle) in &occurrence.visible {
330                let scope = scope_of(name);
331                let candidate = crate::with_registered_solid_str(*handle, |solid| nearest_screen_point(solid, scope, bubble, camera))?;
332                if let Some(display) = candidate {
333                    let d2 = head_distance(camera, display, bubble);
334                    if best.is_none_or(|(b, _)| d2 < b) {
335                        best = Some((d2, display));
336                    }
337                }
338            }
339            let head = best.map(|(_, p)| p).ok_or_else(|| {
340                format!("component {component_id} is sectioned away in this view: move the section or the balloon")
341            })?;
342            (head, BalloonAnchorMode::Surface)
343        }
344        Some(name) if name.contains('@') => {
345            let (solid_name, position) = parse_vertex_ref(name)
346                .ok_or_else(|| format!("anchor '{name}': a vertex ref is '{{solid}}@x,y,z'"))?;
347            owner_of(solid_name)?;
348            shown(solid_name, name)?;
349            let handle = context
350                .scene
351                .resolve_solid(solid_name)
352                .ok_or_else(|| format!("anchor '{name}': unknown solid '{solid_name}'"))?;
353            // A vertex is picked on the DISPLAYED (posed) geometry; snap in
354            // the modeling frame.
355            let stages = stages_of(solid_name);
356            let picked = v3(pose_unapply(stages, a3(position)));
357            let geometry = crate::with_registered_solid_str(handle, |solid| Ok(resolve_vertex_selection(solid, picked)))?
358                .map_err(|error| format!("anchor '{name}': {error}"))?;
359            let SelectionGeometry::Point { position } = geometry else {
360                return Err(format!("anchor '{name}' is not a vertex"));
361            };
362            let head = pose_apply(stages, a3(position));
363            let exempt = occurrence.exempt.iter().any(|exempt| exempt == solid_name);
364            if !exempt && occurrence.section.as_ref().is_some_and(|section| !section.keeps(head, 1e-7)) {
365                return Err(format!("anchor '{name}' is sectioned away in this view"));
366            }
367            (head, BalloonAnchorMode::Point)
368        }
369        Some(name) => {
370            let edge = context
371                .scene
372                .resolve_edge(name)
373                .ok_or_else(|| format!("anchor '{name}' must be a vertex or an edge of component {component_id}"))?;
374            owner_of(name)?;
375            let solid_name = occurrence
376                .members
377                .iter()
378                .find(|(_, handle)| *handle == edge.handle)
379                .map(|(name, _)| name.clone())
380                .ok_or_else(|| format!("anchor '{name}' is not on component {component_id}"))?;
381            shown(&solid_name, name)?;
382            let scope = scope_of(&solid_name);
383            let head = crate::with_registered_solid_str(edge.handle, |solid| {
384                let record = solid
385                    .edges
386                    .iter()
387                    .find(|record| record.id == edge.edge_id)
388                    .ok_or_else(|| format!("anchor edge '{name}' has no record"))?;
389                nearest_displayed_point_on_edge(record, scope, bubble)
390            })?
391            .ok_or_else(|| format!("anchor '{name}' is sectioned away in this view"))?;
392            (
393                head,
394                BalloonAnchorMode::Edge {
395                    solid: solid_name,
396                    edge_id: edge.edge_id,
397                },
398            )
399        }
400    };
401    let solids: Vec<String> = occurrence.visible.iter().map(|(name, _)| name.clone()).collect();
402    let poses: Vec<SolidPoses> = occurrence
403        .stages
404        .iter()
405        .filter(|(_, stages)| !stages.is_empty())
406        .map(|(solid, stages)| SolidPoses {
407            solid: solid.clone(),
408            stages: stages.clone(),
409        })
410        .collect();
411    Ok(Resolved {
412        text,
413        value: None,
414        unit: "",
415        references: targets,
416        geometry: PmiGeometry::Leader {
417            targets: vec![head],
418            dot: false,
419            balloon: true,
420            anchor: Some(BalloonAnchor {
421                camera: camera.cloned(),
422                solids,
423                mode,
424                poses,
425                // A component the cut leaves whole re-projects uncut.
426                section: occurrence.section.clone().filter(|_| occurrence.exempt.len() < occurrence.members.len()),
427            }),
428        },
429        default_label,
430    })
431}