Skip to main content

brep_render/engine_state/
ports_ops.rs

1//! The PORTS surface: what the ports tail resolved on the last applied run.
2//!
3//! A part's declared connection points are DATA, not features
4//! (`brep_kernel`'s `ports` module), and they are resolved at the TAIL of
5//! every history run. The tail is not a feature, so its result reaches no
6//! feature row: this is the only place a caller can read what it published,
7//! what name it refused and which reference it could not resolve.
8//!
9//! The block itself is read and written through `History` (`ports_block`,
10//! `set_ports_block`), which carries the pin/point follow inside the write —
11//! so a caller that edits a point here edits its pin too, in one undo step.
12
13use super::*;
14use brep_kernel::PortsReport;
15use serde_json::Value;
16
17
18/// Which of a connection point's two reference fields a pick is filling.
19///
20/// They are two different questions about the same seat — WHERE it sits and
21/// WHICH WAY it faces — so they admit different picks: a vertex locates a
22/// point and implies no direction, which is why it is offered to one and not
23/// the other.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum PortRefField {
26    /// `pointRef` — the geometry the point sits on.
27    Point,
28    /// `directionRef` — the geometry it faces along.
29    Direction,
30    /// `contactBody` — the SOLID that is the point's contact (a pin that is a
31    /// whole body). It seats what the two references leave empty.
32    Body,
33}
34
35impl PortRefField {
36    /// The block key this field writes.
37    pub fn key(self) -> &'static str {
38        match self {
39            PortRefField::Point => "pointRef",
40            PortRefField::Direction => "directionRef",
41            PortRefField::Body => "contactBody",
42        }
43    }
44
45    /// The picker's heading.
46    pub fn label(self) -> &'static str {
47        match self {
48            PortRefField::Point => "Seat this connection point on",
49            PortRefField::Direction => "Point it along",
50            PortRefField::Body => "The contact body of",
51        }
52    }
53
54    /// Which pick kinds this field admits. A VERTEX seats a position and
55    /// implies no direction, so it is offered to `pointRef` alone; SOLID is
56    /// offered to neither, because a click meant for a face that landed on the
57    /// body instead would seat the point at the body's centre, which is never
58    /// what the click meant. The contact body is the one field that wants a
59    /// SOLID, and only a solid.
60    pub fn filter(self) -> Vec<String> {
61        let kinds: &[&str] = match self {
62            PortRefField::Point => &["VERTEX", "EDGE", "FACE", "PLANE"],
63            PortRefField::Direction => &["EDGE", "FACE", "PLANE"],
64            PortRefField::Body => &["SOLID"],
65        };
66        kinds.iter().map(|kind| (*kind).to_string()).collect()
67    }
68}
69
70impl EngineState {
71    /// The tail's row for one point of THIS document, by part-local address —
72    /// its seat, where it resolved and which way it faces. `None` for a point
73    /// the last run did not resolve (one just typed in, or one whose group
74    /// name is refused).
75    pub fn port_point_row(&self, address: &str) -> Option<&brep_kernel::PortPointRow> {
76        self.ports_report()?
77            .points
78            .iter()
79            .find(|row| row.address == address)
80    }
81
82    /// The connection point of THIS DOCUMENT that the viewport selection
83    /// names, if any — the 3D half of "select it there, see it here".
84    ///
85    /// A declared point draws as a synthesized sheet keyed by its ADDRESS, and
86    /// its base vertex and line hang off that address, so a click anywhere on
87    /// it selects one of three names that all peel back to the same point.
88    ///
89    /// A NAMESPACED address (`ACOMP1:J1.VCC`) is deliberately not adopted: it
90    /// belongs to a component this assembly places, not to the document being
91    /// qualified, and selecting its row here would offer to edit a point this
92    /// document does not own.
93    pub fn selected_port_point(&self) -> Option<String> {
94        let declared: Vec<String> = self
95            .history
96            .declared_points()
97            .into_iter()
98            .map(|point| point.address())
99            .collect();
100        self.emphasis.selected_solids.iter().find_map(|name| {
101            let address = name
102                .strip_suffix(":Base")
103                .or_else(|| name.strip_suffix(":PortLine"))
104                .unwrap_or(name);
105            declared
106                .iter()
107                .find(|candidate| candidate.as_str() == address)
108                .cloned()
109        })
110    }
111
112    /// Edit ONE declared point's JSON object in place, by address, and write
113    /// the block back through `History::set_ports_block` (which carries the
114    /// pin/point follow and re-runs). Returns whether the point was found.
115    ///
116    /// The point is handed to `edit` as its RAW object, one key at a time, for
117    /// the reason the Qualify panel edits it that way: a round trip through
118    /// `PortDeclaration` drops any field the struct does not model, and no
119    /// lane may be the reason a later slice's field disappears when the field
120    /// beside it is touched.
121    pub fn edit_port_point(
122        &mut self,
123        address: &str,
124        coalesce: Option<&str>,
125        edit: impl FnOnce(&mut serde_json::Map<String, Value>),
126    ) -> bool {
127        let Some((port, point_name)) = brep_kernel::split_address(address) else {
128            return false;
129        };
130        let Some(mut block) = self
131            .history
132            .ports_block()
133            .and_then(Value::as_array)
134            .cloned()
135        else {
136            return false;
137        };
138        let mut found = false;
139        for group in block.iter_mut() {
140            if group.get("name").and_then(Value::as_str).map(str::trim) != Some(port) {
141                continue;
142            }
143            let Some(points) = group.get_mut("points").and_then(Value::as_array_mut) else {
144                continue;
145            };
146            for candidate in points.iter_mut() {
147                if candidate.get("name").and_then(Value::as_str).map(str::trim)
148                    != Some(point_name)
149                {
150                    continue;
151                }
152                let Some(object) = candidate.as_object_mut() else {
153                    continue;
154                };
155                edit(object);
156                found = true;
157                break;
158            }
159            break;
160        }
161        if found {
162            self.history.set_ports_block(Some(Value::Array(block)), coalesce);
163        }
164        found
165    }
166
167    // --- the reference picker's connection-point flavour ---------------------
168
169    /// Enter the reference picker to seat `address` on geometry.
170    ///
171    /// Unlike every feature field, this does NOT roll the history back: a
172    /// connection point resolves at the TAIL of the run, against the finished
173    /// part, so the geometry it may be seated on is exactly what is on screen.
174    /// Rolling would hide from the user the very faces the point can name.
175    pub fn begin_ref_select_for_port_point(&mut self, address: &str, field: PortRefField) {
176        // The handles come OFF first. The picker takes over the shell and the
177        // Qualify panel is not drawn while it is up, so nothing else would
178        // take them off — and `route_drag_start` puts the transform gizmo
179        // AHEAD of the camera with no picker guard, so a user dragging to
180        // orbit round to the face they want to pick would drag the point
181        // instead.
182        if self.transform_armed_port_point() == Some(address) {
183            self.disarm_transform();
184        }
185        let filter = field.filter();
186        self.selection_filter = SelectionFilter::from_ref_filter(&filter);
187        let seed = self
188            .declared_point_value(address)
189            .and_then(|point| {
190                point
191                    .get(field.key())
192                    .and_then(Value::as_str)
193                    .map(str::to_string)
194            })
195            .filter(|name| !name.trim().is_empty())
196            .into_iter()
197            .collect();
198        self.ref_select = Some(RefSelectState {
199            feature_id: address.to_string(),
200            path: vec![field.key().to_string()],
201            label: format!("{} \u{2014} {address}", field.label()),
202            filter,
203            multiple: false,
204            names: seed,
205            restore_index: self.history.rollback(),
206            target: RefSelectTarget::PortPoint { field },
207            picks: 0,
208            claimed: false,
209            finish_requested: false,
210        });
211        self.sync_ref_select_emphasis();
212    }
213
214    /// Unseat a connection point: clear one of its reference fields and
215    /// re-run. The OFFSET is deliberately left as it is — it is on screen, and
216    /// silently rewriting the numbers a user can see is worse than a point
217    /// that visibly moved to where those numbers say.
218    pub fn clear_port_point_ref(&mut self, address: &str, field: PortRefField) {
219        self.ports_commit_ref(address, field, "");
220        self.rerun_history();
221    }
222
223    /// One declared point's raw object, by address.
224    pub(super) fn declared_point_value(&self, address: &str) -> Option<Value> {
225        let (port, name) = brep_kernel::split_address(address)?;
226        self.history
227            .ports_block()?
228            .as_array()?
229            .iter()
230            .find(|group| group.get("name").and_then(Value::as_str).map(str::trim) == Some(port))?
231            .get("points")?
232            .as_array()?
233            .iter()
234            .find(|point| point.get("name").and_then(Value::as_str).map(str::trim) == Some(name))
235            .cloned()
236    }
237
238    /// Commit the picker's name into the point's reference field, WITHOUT
239    /// re-running — the picker's shared tail re-runs.
240    ///
241    /// Installing the FIRST reference on a point also zeroes its transform.
242    /// The numbers that were there described an absolute placement; the same
243    /// numbers in a seat mean somewhere else entirely, so keeping them would
244    /// fling the point off the face the user just picked. Clearing a reference
245    /// does NOT restore them: the offset stays as it is, now read in the world
246    /// frame, and it is on screen in the panel where the user can see it.
247    pub(super) fn ports_commit_ref(&mut self, address: &str, field: PortRefField, name: &str) {
248        let name = name.trim().to_string();
249        let was_seated = self
250            .declared_point_value(address)
251            .map(|point| {
252                ["pointRef", "directionRef", "contactBody"].iter().any(|key| {
253                    point
254                        .get(*key)
255                        .and_then(Value::as_str)
256                        .is_some_and(|value| !value.trim().is_empty())
257                })
258            })
259            .unwrap_or(false);
260        self.edit_port_point(address, None, |point| {
261            match name.is_empty() {
262                true => {
263                    point.remove(field.key());
264                }
265                false => {
266                    point.insert(field.key().into(), Value::String(name.clone()));
267                }
268            }
269            if !was_seated && !name.is_empty() {
270                point.insert(
271                    "transform".into(),
272                    serde_json::json!({
273                        "position": [0.0, 0.0, 0.0],
274                        "rotationEuler": [0.0, 0.0, 0.0],
275                    }),
276                );
277            }
278        });
279    }
280
281    /// The ports tail's report of the last APPLIED run: whether this document
282    /// is an encapsulation boundary, every point it resolved, and everything
283    /// about the block that does not hold. `None` before the first run, and
284    /// for a document that declares no `ports` block.
285    pub fn ports_report(&self) -> Option<&PortsReport> {
286        self.ports_report.as_ref()
287    }
288
289    /// The Qualify panel's verifier global: the declared block and the tail's
290    /// report, as one JSON object. `report` is null before the first run.
291    pub fn ports_state_json(&self) -> String {
292        serde_json::json!({
293            "block": self.history.ports_block(),
294            "report": self.ports_report,
295        })
296        .to_string()
297    }
298}
299