Skip to main content

brep_render/
engine_state.rs

1//! [`EngineState`] — the windowing-agnostic viewer state machine the host UI
2//! programs against (R3): scene + camera + controls + settings + emphasis, plus
3//! the whole event/command/query surface (run-history feed, pointer/wheel
4//! ingestion, camera commands, picking, world→screen, visibility). No GPU, no
5//! canvas — the wasm `Engine` and the winit desktop shell both wrap this; it is
6//! fully unit-testable on native.
7//!
8//! Everything crosses the R3 boundary as plain JSON/scalars: the host never holds a
9//! renderer object, only names, ids, and JSON.
10
11use crate::controls::ArcballControls;
12use crate::history::History;
13use crate::pick::{self, PickOptions};
14use crate::scene::RenderScene;
15use crate::style::{Emphasis, RenderSettings};
16use crate::view::ViewCamera;
17use crate::widgets::{gizmo_camera, WidgetOverlay, WidgetRegistry};
18use brep_kernel::HistoryRequest;
19use std::collections::HashMap;
20
21/// One DIALOG row's hover state — which panel lit it, the row's own TEXT, and
22/// what that text resolved to in the scene.
23///
24/// The row text is the memo key rather than the candidate's name because the two
25/// differ whenever the derived-face fallback fires (a fillet's `Edges` row reads
26/// `A|B[0]` while the face it lights is `F1:BLEND:A|B[0]` — see
27/// [`EngineState::hover_entity_by_name`]). An unresolvable row memoizes as
28/// `candidate: None`, so a held hover over a name the scene does not carry scans
29/// the scene ONCE, not once per frame.
30#[derive(Clone)]
31pub(crate) struct DialogHover {
32    /// Which panel set it (`"history"`, `"constraints"`, `"pmi"`, `"refsel"`) —
33    /// [`EngineState::dialog_hover_end`] acts only for the owner that set it, so a
34    /// pane that never hovered a row cannot end another pane's hover.
35    pub(crate) owner: &'static str,
36    /// The row's TEXT, exactly as the dialog listed it.
37    pub(crate) row: String,
38    /// What it resolved to, or `None` for a row the scene does not carry.
39    pub(crate) candidate: Option<pick::PickCandidate>,
40}
41
42pub struct EngineState {
43    pub scene: RenderScene,
44    /// Display-only assembly surroundings in the active work part frame. Never picked or saved.
45    pub context_scene: RenderScene,
46    /// The Work part CONTEXT face clicked / hovered ([`Self::context_hit_at`]):
47    /// kept apart from [`Self::emphasis`], so no selection consumer (feature
48    /// prefill, references, plugins, metadata) ever sees a name the part's own
49    /// kernel cannot resolve.
50    pub(crate) context_selected: Option<crate::pick::PickCandidate>,
51    pub(crate) context_hovered: Option<crate::pick::PickCandidate>,
52    /// Ghosts (context solids) lit WHOLE by a running instructions occurrence
53    /// pick whose names they are (`sync_ref_select_emphasis`): every face of
54    /// each goes into the context highlight. Cleared when the pick ends.
55    pub(crate) context_pick_lit: Vec<String>,
56    /// How the context is shown: kept across context rebuilds and Work parts.
57    pub(crate) context_display: crate::engine_state::context_pick::ContextDisplay,
58    pub camera: ViewCamera,
59    pub controls: ArcballControls,
60    pub settings: RenderSettings,
61    pub emphasis: Emphasis,
62    /// In-scene overlay widgets: datums/dimensions/curves, transform
63    /// gizmo, ViewCube — fed as JSON, drawn by the render core's overlay pass.
64    pub widgets: WidgetRegistry,
65    /// The engine-owned editable model recipe (ordered features + rollback
66    /// index) — the SINGLE source of truth for the model. The UI never keeps its
67    /// own copy; it mutates/reads this through the `history_*` / feature methods.
68    pub history: History,
69    interference_sessions: std::collections::BTreeMap<String, interference::InterferenceCursor>,
70    interference_sequence: u64,
71    illustration_snapshot: Option<illustration::IllustrationSnapshot>,
72    geometry_diagnostics: std::collections::BTreeMap<String, serde_json::Value>,
73    /// The build report (`{featureErrors, unresolved, displayErrors}`) of the
74    /// last history run, so the UI can show it without re-running.
75    history_report: String,
76    /// The Properties-panel metadata store: user attributes keyed by OBJECT NAME
77    /// (solid / face / edge kernel name), NOT feature id — so a record survives
78    /// feature edits as long as the object's name persists. Persisted with the
79    /// model (a top-level `metadata` field in the history document); see the
80    /// [`crate::metadata`] module for the store + the object-info/measurement API.
81    pub metadata: crate::metadata::MetadataStore,
82    /// Derived preview data stays outside the recipe and undo history: the
83    /// document's own picture at a history edit serial (opened with it, or the
84    /// last one a save rendered), and the last picture a save produced by key.
85    document_thumbnail: std::cell::RefCell<Option<(u64, serde_json::Value)>>,
86    thumbnail_cache: std::cell::RefCell<Option<(Vec<u64>, serde_json::Value)>>,
87    /// Bumped whenever settings change so the renderer re-derives per-solid
88    /// base styles (a cheap key, not a per-frame diff).
89    pub settings_generation: u64,
90    /// The engine sets this whenever the camera/scene/emphasis changed; the
91    /// presentation shell renders only when it is set (R22 on-demand render —
92    /// the OrthoCameraIdle matrix-compare analogue, made explicit).
93    pub dirty: bool,
94    /// The modal reference-selection state (the ref-select widget). `Some` while
95    /// the user is picking references for a feature-dialog field; `None`
96    /// otherwise. The picked-name list here is the SINGLE source of truth while
97    /// active (the UI reads it back; the viewport appends to it on a pick).
98    pub ref_select: Option<RefSelectState>,
99    /// Which entity KINDS a plain viewport click may select (the selection
100    /// filter, mirroring the earlier `SelectionFilter.allowedSelectionTypes`). `select_top_at`
101    /// consults it via `pick_filtered`; see the appended `SelectionFilter` impl
102    /// block near the end of this file for the state + honoring logic.
103    pub selection_filter: SelectionFilter,
104    /// The transform-controls gizmo controller: which feature (if any) has the
105    /// move/rotate gizmo armed (via the in-viewport center-sphere toggle), plus the
106    /// in-flight handle drag. All the arm/drag/apply logic lives in the appended
107    /// transform-gizmo impl block near the end of this file.
108    pub transform_gizmo: TransformArm,
109    /// The COMPONENT Move gizmo controller (assemblies §8.5): which ACOMP
110    /// instance has the bbox-center move/rotate gizmo armed, the translate/
111    /// rotate cycle mode, and the commit-on-release drag. Exclusive with
112    /// `transform_gizmo` (shared widget slot). See `component_move.rs`.
113    pub component_move: ComponentMoveArm,
114    /// The active engine-native sketch edit (`Some` while in sketch mode). Holds
115    /// the live [`crate::sketch::SketchSession`] plus the pre-entry camera + roll
116    /// to restore on exit. All the enter/exit/new logic lives in the appended
117    /// sketch-mode impl block at the END of this file.
118    sketch_edit: Option<SketchEdit>,
119    /// The active engine-native 3D SKETCH edit (`Some` while in 3D sketch
120    /// mode): the live [`crate::sketch3d::Sketch3dSession`] plus the pre-entry
121    /// camera + roll. See `sketch3d_mode.rs`.
122    sketch3d_edit: Option<Sketch3dEdit>,
123    /// The `world_per_pixel` the 3D sketch overlay was last baked at (its
124    /// working-plane and reference-plane squares are pixel-sized); `0.0` =
125    /// not in 3D sketch mode.
126    pub(crate) sketch3d_overlay_wpp: f64,
127    /// Sketch-mode camera lock. When true (the default on every sketch entry), the
128    /// camera is held flat-on to the sketch plane and an empty drag only PANS —
129    /// no orbit. Toggling it back on re-faces the camera to the plane. Meaningful
130    /// only while `sketch_edit` is `Some`. See the sketch-mode impl block.
131    sketch_camera_locked: bool,
132    /// Set for ONE frame when the sketch entity-LIST panel hovers a row (it calls
133    /// [`sketch_hover_entity`](Self::sketch_hover_entity)). The viewport, which
134    /// draws AFTER the panel and would otherwise `sketch_clear_hover` because the
135    /// pointer is off the viewport, consumes this flag via
136    /// [`take_sketch_list_hover`](Self::take_sketch_list_hover) and keeps the
137    /// panel-set hover so list→canvas highlight survives the frame.
138    sketch_list_hover_active: bool,
139    /// Transient user-facing notices (e.g. a sketch solve that failed after an
140    /// edit). The shell drains them each frame via [`take_notices`](Self::take_notices)
141    /// into a toast overlay; the engine only queues. Replaces the swallowed
142    /// `eprintln!` on the interactive re-solve paths.
143    notices: Vec<String>,
144    /// Notices that are NOT errors — a warning, or a success such as "Updated 2
145    /// part(s)" — with their severity, queued by
146    /// [`push_notice_as`](Self::push_notice_as). Beside [`Self::notices`] rather
147    /// than in it, so every existing `push_notice` stays an error unchanged.
148    graded_notices: Vec<(NoticeSeverity, String)>,
149    /// Committed-sketch visibility: the feature ids whose persistent committed-sketch
150    /// overlay is HIDDEN (its Scene-tree checkbox off). Absent = visible. See the
151    /// committed-sketch impl block appended at the END of this file.
152    hidden_sketches: std::collections::HashSet<String>,
153    /// The committed-sketch feature ids whose overlay groups were fed on the LAST
154    /// [`refresh_committed_sketches`](Self::refresh_committed_sketches), so an id that
155    /// is no longer shown (rolled back, deleted, hidden, or became the active edit)
156    /// can have its now-stale groups cleared.
157    shown_sketch_ids: Vec<String>,
158    /// The board bodies fed on the LAST
159    /// [`refresh_board_geometry`](Self::refresh_board_geometry), in stack order,
160    /// so a body this build did not produce can be swept out of the scene.
161    /// Parallels [`shown_sketch_ids`].
162    shown_board_ids: Vec<String>,
163    /// The eCAD board those bodies were built from — the rebuild test. A
164    /// SCHEMATIC edit rewrites the whole `pcb` block with the same board inside
165    /// it, and this is what makes that edit free.
166    board_built_from: Option<brep_ecad_core::board::Board>,
167    /// The pin-to-net map those bodies' NET COLOURS were built from. The board
168    /// alone does not decide them — a copper island carries the net of the pads
169    /// it touches, and which net a pad carries is the SCHEMATIC's answer — so
170    /// this is the second half of the rebuild test. Empty for a board with no
171    /// placements, which can carry no net at all.
172    board_pin_nets: std::collections::BTreeMap<(brep_ecad_core::Uuid, String), String>,
173    /// What that build cost, for the Scene tree and the tests.
174    board_build: board_geometry::BoardBuild,
175    /// The built bodies themselves, KEPT across runs. The scene reconcile drops
176    /// every derived body, so without this a dense board would be re-meshed on
177    /// every history run; a clone of these is what goes back in instead.
178    board_displays: Vec<crate::scene::SolidDisplay>,
179    /// The named plane FRAMES the last history run resolved `(frame name, frame)`.
180    /// Stored so [`refresh_construction_datums`](Self::refresh_construction_datums)
181    /// (and datum selection) can display/pick the construction datum/plane frames
182    /// without re-running. Filled from the run's
183    /// [`crate::pipeline::SceneBuildReport::frames`]; the D/P filter is applied at
184    /// display time (a frame name maps to its producing feature TYPE via the
185    /// history). See the appended construction-datum impl block at the END.
186    construction_frames: Vec<(String, brep_kernel::Frame)>,
187    /// The solved sketch PROFILES the last history run produced `(sketch id,
188    /// profile)`. Stored so [`refresh_committed_sketches`](Self::refresh_committed_sketches)
189    /// can synthesize each committed sketch's SHEET SOLID (planar face + named
190    /// boundary edges + corner vertices) without re-running. Filled from the run's
191    /// [`crate::pipeline::SceneBuildReport::profiles`]; rollback / active-edit /
192    /// visibility gating is applied at display time.
193    sketch_profiles: Vec<(String, brep_kernel::SketchProfile)>,
194    /// The named PATH chains the last history run produced `(path name, curves)`.
195    /// Stored alongside [`sketch_profiles`](Self::sketch_profiles) so
196    /// [`refresh_committed_sketches`](Self::refresh_committed_sketches) can draw the
197    /// sketch geometry no closed profile covers: a sketch's OPEN chain publishes no
198    /// profile, so the sheet builder had nothing to draw it from and an open sketch
199    /// was invisible in 3D. Filled from the run's
200    /// [`crate::pipeline::SceneBuildReport::paths`]; the per-segment `{id}:G{gid}`
201    /// entries are the display input (the whole-chain `{id}` entry duplicates them
202    /// and `{id}:REF:{source}` is projected reference geometry).
203    sketch_paths: Vec<(String, Vec<brep_kernel::NurbsCurve>)>,
204    /// The named world POINTS the last history run produced `(point name, point)`.
205    /// Stored alongside [`sketch_paths`](Self::sketch_paths) so
206    /// [`refresh_committed_sketches`](Self::refresh_committed_sketches) can draw the
207    /// sketch points no segment covers: a points-only sketch (a hole-placement
208    /// sketch) publishes no profile and no path, so it had nothing to draw from
209    /// and was invisible in 3D. Filled from the run's
210    /// [`crate::pipeline::SceneBuildReport::points`]; the per-point `{id}:P{pid}`
211    /// entries are the display input (construction points are skipped at draw
212    /// time, like construction geometry).
213    sketch_points: Vec<(String, brep_kernel::ScenePoint)>,
214    /// The named axis LINES the last history run produced `(axis name, line)`.
215    /// Stored so the feature-dimension angle gizmo can resolve a revolve `axis`
216    /// reference to a world line without re-running. Filled from the run's
217    /// [`crate::pipeline::SceneBuildReport::axes`].
218    sketch_axes: Vec<(String, brep_kernel::Axis)>,
219    /// The wire-harness routing report of the last APPLIED run (`None` before
220    /// the first run). Filled from [`crate::pipeline::SceneBuildReport::wire_harness`];
221    /// the harness panel reads it, the committed-curve display reads the port
222    /// kinds off it. See the appended wire-harness impl block.
223    wire_harness_report: Option<brep_kernel::WireHarnessReport>,
224    /// The PORTS tail's report of the last APPLIED run (`None` before the first
225    /// run, and for a document that declares no `ports` block). Filled from
226    /// [`crate::pipeline::SceneBuildReport::ports`]; the Qualify panel reads it,
227    /// and it is the only place the tail's refused names and unresolved
228    /// references surface, the tail not being a feature.
229    ports_report: Option<brep_kernel::PortsReport>,
230    /// The PMI tail's report of the last APPLIED run (`pmi_ops.rs`).
231    pub(crate) pmi_report: Option<brep_kernel::PmiReport>,
232    /// The ACTIVE PMI view (engine memory, never persisted): its camera,
233    /// display state and explode poses are applied; its annotations drawn.
234    pub(crate) pmi_active_view: Option<String>,
235    /// The annotation whose form the PMI panel shows (engine memory). Never
236    /// assign `Some` here: go through [`EngineState::open_pmi_annotation`], the
237    /// one place that counts the open.
238    pub(crate) pmi_open_annotation: Option<String>,
239    /// The VIEW whose form the PMI panel shows (engine memory) — exclusive
240    /// with [`Self::pmi_open_annotation`], since the pane shows one dialog.
241    /// Never assign `Some` here: go through [`EngineState::open_pmi_view`].
242    pub(crate) pmi_open_view: Option<String>,
243    /// The annotation SELECTED in the PMI tree or by its viewport label: the
244    /// tree row's highlight and the label's accent. Cleared with the selection
245    /// (Esc / Clear / a click on empty space); read through
246    /// [`EngineState::pmi_selected_annotation`], which prunes a stale id.
247    pub(crate) pmi_selected_annotation: Option<String>,
248    /// The VIEW selected in the PMI tree — its row's highlight. Selecting a
249    /// view never ACTIVATES it (a double click does); exclusive with
250    /// [`Self::pmi_selected_annotation`], since the tree selects one row.
251    /// Read through [`EngineState::pmi_selected_view`], which prunes a stale id.
252    pub(crate) pmi_selected_view: Option<String>,
253    /// How many times a PMI dialog — an annotation's or a view's — has been
254    /// OPENED: monotonic, never reset, closes do not count. The app's dialog
255    /// door keys on it beside the subject so a re-open of the dialog that is
256    /// ALREADY open is still one open event (a viewport label double click on the
257    /// annotation whose form is up, which a user makes precisely because they
258    /// are on another tab).
259    pub(crate) pmi_dialog_opens: u64,
260    /// The modeling camera / visibility / wireframe remembered on entering
261    /// the PMI workbench, restored when a view deactivates or the workbench
262    /// is left.
263    pub(crate) pmi_modeling: Option<pmi_ops::PmiModelingSnapshot>,
264    /// The un-exploded displays of the solids the active view's explode
265    /// annotations posed, for an exact restore.
266    pub(crate) pmi_explode_originals: std::collections::HashMap<String, crate::scene::SolidDisplay>,
267    /// How far the active view's explode steps are shown, and any Explode /
268    /// Collapse animation (`exploded_ops`). Display state, never saved.
269    pub(crate) explode_playback: exploded_ops::ExplodePlayback,
270    /// The motion study being played or scrubbed and its bake
271    /// (`simulation_play`). Display state, never saved.
272    pub(crate) simulation_play: Option<simulation_play::SimulationPlayback>,
273    /// Solids the active view's section removes whole: hidden (no copy, no
274    /// re-upload) rather than clipped, and shown again on restore.
275    pub(crate) pmi_section_hidden: Vec<String>,
276    /// Bumped when an un-posed original's `visible` changes (a user or view
277    /// hide while the active view poses or sections that solid): sheets
278    /// draw from the originals, so their cache key carries it.
279    pub(crate) pmi_unposed_visibility: u64,
280    /// The `pmi` block parsed, keyed by the history revision it was parsed
281    /// at ([`Self::pmi_state_shared`]): every write to the saved document,
282    /// undo and redo included, moves that revision.
283    pub(crate) pmi_state_cache: std::cell::RefCell<Option<(u64, std::rc::Rc<brep_kernel::PmiState>)>>,
284    /// A balloon whose dragged bubble could not be re-projected yet because
285    /// the scene did not hold its occurrence's exact solids: re-derived when
286    /// the topology reply lands (`pmi_refresh_stale_balloon`).
287    pub(crate) pmi_balloon_stale: Option<String>,
288    /// `(world_per_pixel, view direction)` the PMI overlay was last baked at.
289    pub(crate) pmi_overlay_key: Option<(f64, [f64; 3])>,
290    pub(crate) pmi_hovered: Option<String>,
291    pub(crate) pmi_label_hover_active: bool,
292    /// The sheet the sheet viewport shows (engine memory, never persisted).
293    /// `None` = the 3D view (`sheet_ops.rs`).
294    pub(crate) sheet_open: Option<String>,
295    /// The sheet or placed view whose form the Sheets pane shows. Never assign
296    /// `Some` here: go through [`EngineState::open_sheet_object`], the one
297    /// place that counts the open.
298    pub(crate) sheet_open_object: Option<String>,
299    /// How many times a sheet object's form has been OPENED — the sheet half
300    /// of the same counter as [`Self::pmi_dialog_opens`], read by the
301    /// app's dialog door so a re-open of the object already open still counts.
302    pub(crate) sheet_object_opens: u64,
303    /// The placed view, sheet dimension or ordinate set SELECTED in the Sheets
304    /// tree or on the paper: the tree row's highlight and the object's accent
305    /// on the sheet. Cleared with the selection; read through
306    /// [`EngineState::sheet_selected_object`], which prunes a stale id.
307    pub(crate) sheet_selected_object: Option<String>,
308    /// The last projected sheet, kept until the model or the block moves: a
309    /// sheet is a hidden-line pass over the whole model and must never run
310    /// per frame.
311    pub(crate) sheet_cache: Option<sheet_ops::SheetCache>,
312    /// The sheet's exact passes on the runner and waiting for it.
313    pub(crate) sheet_lines: sheet_ops::SheetLinesWork,
314    /// The open document's name, as the shell means it (the tab, the file, the
315    /// root PRODUCT of a STEP export). Engine memory, never persisted: the
316    /// document does not carry its own name, the SHELL owns it, and it is here
317    /// because a drawing sheet's TITLE BLOCK prints it. Set every frame by the
318    /// app from the active tab (a no-op when unchanged).
319    pub(crate) document_name: String,
320    /// What the spline-anchor cage overlay was last fed for — `(spline id,
321    /// selected anchor, applied run generation)` — so the per-frame refresh
322    /// the history panel makes while an SP form is open is a no-op until one
323    /// of those moves. See `spline_edit.rs`.
324    spline_overlay_key: Option<(String, Option<usize>, u64)>,
325    /// The CAM workbench's generation queue and results (`cam_ops.rs`).
326    pub cam: cam_ops::CamGeneration,
327    /// Whether the ports placed components carry (`ACOMP1:PORT1`) draw their
328    /// sheets. The app sets it from the active workbench — one that shows the
329    /// Wire Harness panel; a document's own PORT features always draw.
330    component_ports_visible: bool,
331    /// The spline whose anchor editor is open (fed by the history panel with
332    /// the cage overlay), so a viewport click on one of its anchor dots selects
333    /// that anchor; the index of the last such pick, until the panel takes it.
334    spline_edit_feature: Option<String>,
335    spline_anchor_picked: Option<usize>,
336    /// The NURBS solid whose control-cage editor is open (fed by the history
337    /// panel with the cage overlay) and what that overlay was last fed for —
338    /// `(feature id, selected points, applied run generation)`. The selection
339    /// itself is the transform gizmo's (`TransformArm::cage`). See
340    /// `cage_edit.rs`.
341    cage_edit_feature: Option<String>,
342    cage_overlay_key: Option<(String, Vec<usize>, u64)>,
343    /// Construction datum/plane visibility: the frame NAMES whose datum plane is
344    /// HIDDEN (its Scene-tree checkbox off). Absent = visible. Mirrors
345    /// [`hidden_sketches`].
346    hidden_datums: std::collections::HashSet<String>,
347    /// The datum frame NAMES fed to the widget on the LAST
348    /// [`refresh_construction_datums`](Self::refresh_construction_datums). The datum
349    /// feed REPLACES its set wholesale each call, so this is a bookkeeping mirror of
350    /// what is currently shown (parallels [`shown_sketch_ids`]).
351    shown_datum_names: Vec<String>,
352    /// The history-run seam (M2a of the off-thread runner). Owns the scene-free
353    /// runner + its delta baseline (`name → last-emitted handle`) ACROSS reruns:
354    /// [`rerun_history`](Self::rerun_history) SUBMITS a run tagged with
355    /// [`run_generation`](Self::run_generation), and [`pump`](Self::pump) drains
356    /// the completed reply and [`apply_run_output`](Self::apply_run_output)s its
357    /// delta to [`Self::scene`]. The [`InlineRunner`](crate::runner::InlineRunner)
358    /// default runs synchronously (submit → immediate poll, byte-identical to the
359    /// old in-place reconcile); a background thread/worker impl slots in behind the
360    /// same trait in M2b/M3. Reset on a document switch
361    /// ([`set_history_json`](Self::set_history_json)) so a new model rebuilds fully.
362    pub(crate) runner: Box<dyn crate::runner::HistoryRunner>,
363    plugins: plugins::Plugins,
364    /// Monotonic run counter: bumped each time [`rerun_history`](Self::rerun_history)
365    /// SUBMITS a run, and stamped onto the reply so a stale reply (a newer run that
366    /// finished first) can be dropped. `run_generation != applied_generation` means
367    /// a run is in flight (always equal for the synchronous Inline runner).
368    run_generation: u64,
369    /// The generation of the last reply [`pump`](Self::pump) APPLIED — the high-water
370    /// mark that gates stale replies.
371    applied_generation: u64,
372    /// The latest [`crate::runner::RunProgress`] of the run in flight (a
373    /// background runner posts one before each feature it executes), or
374    /// `None` when nothing is running. Names what the spinner is waiting on.
375    run_progress: Option<crate::runner::RunProgress>,
376    /// The feature the last CANCELLED run was executing (`Some("")` when the
377    /// run was cancelled before any progress arrived), cleared by the next
378    /// submit. The history header shows it until the model is rebuilt.
379    cancelled_run: Option<String>,
380    /// A TRANSIENT expressions source the runs evaluate instead of the
381    /// document's own (the family table's row preview). Never written into
382    /// the history: not saved, not undone, not dirty. See
383    /// [`Self::set_expression_preview`].
384    expression_preview: Option<ExpressionPreview>,
385    /// How many run replies came back from the runner (applied or dropped as
386    /// stale). A run the runner coalesced away never replies, so this counts
387    /// the runs actually EXECUTED.
388    runs_replied: u64,
389    /// Displays shipped by replies [`pump`](Self::pump) DROPPED as superseded,
390    /// by solid name, latest wins. A background runner executes every run it
391    /// is handed and its delta baseline (`name → last-emitted handle`) advances
392    /// on each, so a later reply can say "unchanged, keep yours" about a
393    /// display that only ever travelled in a dropped reply (the reporter's
394    /// arrow-head drag: the frame that built the new radius was superseded by
395    /// the still-pointer frames that replayed its handle). The keep is served
396    /// from here when the scene's display is not the handle it names. Cleared
397    /// with the runner's baseline (document switch, cancel) and whenever a
398    /// fresh display for the name is applied.
399    superseded_displays: HashMap<String, crate::scene::SolidDisplay>,
400    /// A pending one-shot "frame the scene once the in-flight run lands" request.
401    /// Import / Open SUBMIT an async run (native [`ThreadRunner`], wasm worker) and
402    /// want to `zoom_to_fit` the RESULT — but the scene is still empty when they
403    /// return, so an immediate fit frames nothing (bbox empty → no-op). Instead they
404    /// set this flag and [`pump`](Self::pump) performs the fit on the first apply that
405    /// leaves the run no longer pending. Under the synchronous Inline runner the run
406    /// applies inside the submitting call's own `pump`, so the fit is still immediate.
407    pending_fit: bool,
408    /// The instructions wizard waits for the run that places the wrapper:
409    /// its step views read the solids that run makes. [`pump`](Self::pump)
410    /// runs it once no run is pending.
411    instructions_wizard_pending: bool,
412    /// A re-target folded new steps in: their views wait for the run that
413    /// builds the new revision's solids, like the wizard's.
414    instructions_views_pending: bool,
415    /// The in-app player's insertion motion: the shown step's arrowed parts
416    /// moving home ([`instructions_ops::Insertion`]).
417    pub(crate) instructions_insertion: Option<instructions_ops::Insertion>,
418    /// EAGER provenance `name → creating-feature id` for the current resident
419    /// solids, shipped with each run ([`crate::pipeline::RunOutput::provenance`]) and
420    /// replaced wholesale in [`apply_run_output`](Self::apply_run_output). Answers
421    /// `creating_feature` + the Info tab's `creatingFeature` WITHOUT a cold
422    /// `execute_history` — the freeze side-door once the run lives off-thread.
423    pub(crate) provenance: std::collections::HashMap<String, String>,
424    /// EAGER ENTITY ORIGIN `face/edge NAME → ORIGINATING feature id` (FIRST writer in
425    /// timeline order), shipped with each run
426    /// ([`crate::pipeline::RunOutput::entity_origin`]) and replaced wholesale in
427    /// [`apply_run_output`](Self::apply_run_output). Unlike `provenance` (the SOLID's
428    /// LAST writer) this is the feature that gave the face/edge its NAME — the answer
429    /// `creating_feature` returns for a face/edge (the "Edit owning feature" action +
430    /// the Info tab's `creatingFeature`), so it rolls to the entity's origin, not the
431    /// owning solid's last producer.
432    pub(crate) entity_origin: std::collections::HashMap<String, String>,
433    /// Object-info MEASUREMENT cache `name → merged object-info JSON`, filled by
434    /// [`pump_queries`](crate::metadata) from the runner's replies and served every
435    /// frame a selection persists (so `object_info_json` fires ONE query per
436    /// selection, not one per frame). Invalidated on any geometry change
437    /// (`apply_run_output`) or metadata edit (`set_metadata_attribute`).
438    pub(crate) info_cache: std::collections::HashMap<String, String>,
439    /// In-flight measurement queries `id → object NAME` — the key needed to MERGE a
440    /// reply back into the info cache (inject `name` + `creatingFeature`, the latter
441    /// now resolved by the entity name itself). Cleared alongside `info_cache` on a
442    /// geometry change so a stale reply is dropped rather than caching a superseded
443    /// measurement.
444    pub(crate) pending_query: std::collections::HashMap<u64, String>,
445    /// Monotonic measurement-query id (pairs a [`crate::runner::MeasureReply`] back
446    /// with its `pending_query` entry).
447    pub(crate) next_query_id: u64,
448    /// Off-thread mesh reconstructions awaiting a runner reply.
449    pub(crate) pending_mesh_imports: std::collections::HashMap<u64, MeshImportDestination>,
450    pub(crate) mesh_preview_results: std::collections::VecDeque<crate::runner::MeshImportReply>,
451    /// Monotonic id for pairing mesh import replies with submissions.
452    pub(crate) next_mesh_import_id: u64,
453    /// Topology requests in flight (see [`crate::runner::TopologyRequest`]).
454    pub(crate) pending_topology: std::collections::HashSet<u64>,
455    /// Every resident handle asked for since the last applied run, answered or
456    /// not: a handle the runner could not clone is not asked for again until a
457    /// run brings new handles.
458    pub(crate) topology_asked: std::collections::HashSet<u32>,
459    /// Monotonic id for pairing topology replies with requests.
460    pub(crate) next_topology_id: u64,
461    /// The run's ASSEMBLY tail as the runner read it
462    /// ([`crate::pipeline::AssemblySync`]) — the constraint state, statuses, DOF
463    /// and overlay rows every assembly panel reads, adopted from the reply of the
464    /// last applied run. `None` for a componentless document. This is what
465    /// replaced the second, main-side `execute_history`: see `assembly_ops`.
466    pub(crate) assembly_sync: Option<crate::pipeline::AssemblySync>,
467    /// The scene's assembly COMPONENT records (deterministic id order), adopted
468    /// from [`Self::assembly_sync`] — the Assembly Structure tree's source.
469    /// Empty for componentless documents.
470    pub(crate) assembly_components: Vec<crate::pipeline::ComponentSnapshot>,
471    /// The [`Self::applied_generation`] the main-side kernel assembly SESSION was
472    /// last installed for (`None` = never). Only a constraint MUTATION needs one
473    /// — its solve runs against the resident geometry of the thread that asks —
474    /// so only `ensure_assembly_session` sets this. See `assembly_ops`.
475    pub(crate) assembly_session_generation: Option<u64>,
476    /// The kernel's session serial when this document's session was put in
477    /// place: the kernel session is one per thread, shared by every open
478    /// document, so a moved serial means another one replaced it.
479    pub(crate) assembly_session_serial: u64,
480    /// Take the runner's session copy instead of replaying (tests switch it
481    /// off to compare the two lanes), and how often each lane served.
482    pub(crate) session_transfer: bool,
483    pub(crate) session_imports: u64,
484    pub(crate) session_replays: u64,
485    /// A component replace whose run has not landed yet (see
486    /// `replace_component`), and the last finished replace's report.
487    pub(crate) replace_pending: Option<replace_component::PendingReplace>,
488    pub(crate) last_replace_report: Option<serde_json::Value>,
489    /// Every output name the last applied run CONSUMED
490    /// ([`crate::pipeline::RunOutput::consumed`]) — what the committed-sketch
491    /// refresh hides a consumed sketch by, and what it used to re-execute the
492    /// whole history on the UI thread to learn.
493    pub(crate) consumed_names: std::collections::HashSet<String>,
494    /// Re-entrancy guard for the parts-library resync in [`Self::pump`] (a
495    /// refused run re-runs, and `rerun_history` pumps).
496    pub(crate) library_resync: bool,
497    /// A run just RELEASED a sketch's edge links whose edges it could not
498    /// resolve (see [`Self::release_unresolved_sketch_links`]): the history
499    /// changed under the applied report, so [`Self::pump`] re-runs it once and
500    /// the report stops naming edges the sketch no longer lists.
501    pub(crate) sketch_links_released: bool,
502    /// The assembly-constraint viewport overlays — the cached
503    /// [`crate::constraint_overlays::ConstraintOverlay`] records the engine last
504    /// built from the kernel session (`assembly_overlay_json` + state), the source
505    /// of the drawn leader/arrow group, the label feed, and the grabbable-handle
506    /// hit regions. Refreshed after every history apply and every constraint
507    /// mutation; see the appended assembly-overlay impl block.
508    pub(crate) constraint_overlays: Vec<crate::constraint_overlays::ConstraintOverlay>,
509    /// A live GRAB on a constraint's distance-arrow / angle-arc handle (`Some`
510    /// between `constraint_drag_begin` and `constraint_drag_release`): the drag
511    /// previews the value locally and COMMITS on release via
512    /// `assembly_update_constraint_json` (which auto-solves).
513    pub(crate) constraint_drag: Option<ConstraintDrag>,
514    /// The `world_per_pixel` the constraint overlay buffers were last baked at
515    /// (screen-constant arc/rod sizing): `ensure_constraint_overlay_current`
516    /// re-bakes when the camera zoom moves it materially. `0.0` = never baked.
517    constraint_overlay_wpp: f64,
518    /// What the free-motion glyph group was last baked from (component,
519    /// its freedom row, centre), and at which `world_per_pixel`.
520    freedom_glyph_key: Option<String>,
521    freedom_glyph_wpp: f64,
522    /// The `world_per_pixel` the FEATURE-DIMENSION gizmo group
523    /// (`feature-dim-leaders`) was last baked at. The leaders' rod/cone/origin
524    /// sphere — and the angular arc's whole world RADIUS — are
525    /// `pixels × world_per_pixel`, so a zoom makes the drawn gizmo stale;
526    /// `ensure_feature_dimension_overlay_current` re-bakes on a material move.
527    /// `0.0` = nothing baked (gizmo disarmed / not in dimension mode).
528    /// See `feature_dims`.
529    pub(crate) feature_dim_overlay_wpp: f64,
530    /// The `world_per_pixel` the live SKETCH overlay groups (geometry, points,
531    /// preview, `sketch-dim-leaders`, `sketch-constraint-glyphs`) were last baked
532    /// at — construction dashes, dimension arrowheads and constraint glyphs are
533    /// all screen-constant. `ensure_sketch_overlay_current` re-bakes on a material
534    /// zoom. `0.0` = nothing baked (not in sketch mode). See `sketch_input`.
535    pub(crate) sketch_overlay_wpp: f64,
536    /// The constraint id whose referenced ELEMENTS the panel/label hover is
537    /// currently highlighting (dedupe key so a held hover doesn't re-bump the
538    /// emphasis generation every frame).
539    constraint_hovered: Option<String>,
540    /// Set for ONE frame when a constraint LABEL hover applied the element
541    /// highlight; the viewport's modeling hover branch consumes it (mirrors
542    /// [`Self::take_sketch_list_hover`]) so the scene hover doesn't clobber it.
543    constraint_label_hover_active: bool,
544    /// The SCENE-TREE row the pointer is over, as the pick candidate its hover
545    /// lit (the row→viewport highlight). Kept so
546    /// [`scene_tree_hover_end`](Self::scene_tree_hover_end) clears ONLY a hover
547    /// the tree itself set — never one the viewport lit in the meantime — and as
548    /// the dedupe key that keeps a held row hover from re-bumping the emphasis
549    /// generation every frame. See `scene_query.rs`.
550    scene_tree_hovered: Option<pick::PickCandidate>,
551    /// Set for ONE frame while a Scene-tree row is hovered; the viewport's
552    /// modeling hover branch consumes it via
553    /// [`take_scene_tree_hover`](Self::take_scene_tree_hover) and skips the
554    /// pointer-off-viewport `clear_hover` (mirrors
555    /// [`Self::take_sketch_list_hover`]) so the row-set highlight survives.
556    scene_tree_hover_active: bool,
557    /// The DIALOG row the pointer is over — a feature form's reference line, its
558    /// read-only `Outputs` line, or the reference picker card's picked-name line
559    /// (the row→viewport highlight, the twin of the Scene tree's above). Its OWN
560    /// slot, not the tree's: History, Constraints, PMI and the Scene tree can all
561    /// be on screen at once in a split dock, and a shared slot would let the pane
562    /// that draws second end the hover the pane that drew first had just set. See
563    /// [`DialogHover`] for what it memoizes and `scene_query.rs` for the API.
564    dialog_hovered: Option<DialogHover>,
565    /// Set for ONE frame while a dialog row is hovered; the viewport's modeling
566    /// hover branch consumes it via [`take_dialog_hover`](Self::take_dialog_hover)
567    /// and skips the pointer-off-viewport `clear_hover` (mirrors
568    /// [`Self::take_scene_tree_hover`]) so the row-set highlight survives.
569    dialog_hover_active: bool,
570    /// The constraint SELECTED via its viewport label chip (`Some` = selected):
571    /// drives the chip's selected accent, the context bar's Delete-constraint
572    /// action, and clears with the selection (Esc / Clear / delete). Read
573    /// through [`Self::selected_constraint`], which prunes a stale id.
574    selected_constraint: Option<String>,
575    /// The feature SELECTED in the history tree, beside the geometry selection
576    /// that selecting it made. It stays selected only while that geometry
577    /// selection is unchanged — a viewport pick, Esc or Clear replaces the
578    /// geometry and so deselects the feature. Read through
579    /// [`Self::selected_feature`].
580    selected_feature: Option<(String, selection_ux::FeatureSelection)>,
581    /// How many times a constraint's dialog has been OPENED through
582    /// [`Self::assembly_set_constraint_open`] — the constraint half of the same
583    /// counter as [`Self::pmi_dialog_opens`], read by the app's dialog door
584    /// so a re-open of the constraint already open still counts. The flag
585    /// itself lives in the kernel (it is part of the saved document), so this
586    /// counts the OPENS this engine performed, not the flag's history.
587    pub(crate) constraint_opens: u64,
588    /// The STEP product structure a [`Self::probe_step_assembly`] parsed, held
589    /// until the import dialog's button decides its fate: consumed by
590    /// [`Self::import_probed_step_assembly`], dropped by
591    /// [`Self::discard_probed_step_assembly`] (Cancel), by the next probe, or by
592    /// a document switch. The ONE parse of a structured STEP import lives here —
593    /// the dialog needs the counts BEFORE the user chooses, and re-parsing
594    /// multi-MB Part-21 text on the way back would double the most expensive step
595    /// of the import. See `model_io`'s import block.
596    pub(crate) pending_step_assembly: Option<brep_kernel::StepAssembly>,
597    /// STEP probes submitted to the runner and not yet answered (their ids).
598    pub(crate) pending_step_probes: std::collections::HashSet<u64>,
599    /// Answered probes awaiting [`Self::take_step_probe`], oldest first.
600    pub(crate) step_probe_results: std::collections::VecDeque<(u64, StepProbeOutcome)>,
601    /// Monotonic id pairing a probe reply with its submission.
602    pub(crate) next_step_probe_id: u64,
603}
604
605/// What a STEP probe found, as the file panel consumes it (see
606/// [`EngineState::submit_step_probe`]).
607#[derive(Debug, Clone, PartialEq)]
608pub enum StepProbeOutcome {
609    /// Product structure: the parsed assembly is stashed for
610    /// [`EngineState::import_probed_step_assembly`]; these are its counts.
611    Structure(model_io::StepAssemblyProbe),
612    /// No structure worth keeping — take the flat lane.
613    Flat,
614    /// The text did not parse as Part 21; the flat lane refuses it with its
615    /// own wording.
616    Failed(String),
617}
618
619/// A live constraint-handle drag: which constraint + which `inputParams` field
620/// (`distance` / `angle`), the params snapshot the commit mutates, and the live
621/// preview value the overlay/label show while dragging.
622#[derive(Debug, Clone)]
623pub struct ConstraintDrag {
624    pub id: String,
625    pub field: &'static str,
626    pub params: serde_json::Value,
627    pub preview: f64,
628}
629
630/// WHO a finished reference-selection commits to: a history FEATURE's params
631/// (the original widget) or an ASSEMBLY CONSTRAINT's `inputParams` (same modal,
632/// different commit lane — see `assembly_ops::begin_ref_select_for_constraint`).
633#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
634pub enum RefSelectTarget {
635    #[default]
636    Feature,
637    AssemblyConstraint,
638    /// ONE SPLINE ANCHOR's port attachment: `path` is unused, the picked name
639    /// must be a PORT feature id (a click on a port's drawn sheet), and Finish
640    /// writes `persistentData.spline.points[index].attachment` (see
641    /// `spline_edit.rs`).
642    SplineAnchor { index: usize },
643    /// A PMI annotation's reference field: `feature_id` is the annotation id;
644    /// Finish writes the picked names into its params through the PMI block
645    /// (`pmi_ops.rs`). Vertex picks are `{solid}@x,y,z` in WORLD coordinates.
646    Pmi,
647    /// ONE CONNECTION POINT's reference field: `feature_id` is the point's
648    /// part-local ADDRESS (`J1.VCC`) — a connection point is data, not a
649    /// feature, so there is no id to carry — and `path` is the block key the
650    /// pick writes (`pointRef` / `directionRef`). Finish writes it through
651    /// `ports_ops::ports_commit_ref`, and NOTHING ROLLS: a point resolves at
652    /// the tail of the run, so the geometry it may name is what is on screen.
653    PortPoint { field: ports_ops::PortRefField },
654    /// A drawing-sheet object's reference field — a dimension's anchors, an
655    /// ordinate set's datum or members, a section's cutting line, a detail's
656    /// centre or rim: `feature_id` is the object id, the picks are ANCHORS
657    /// clicked on the open sheet's paper (`sheet_ops.rs`), and nothing rolls.
658    Sheet,
659    /// A CAM record's reference field (a setup's orientation picks and
660    /// bodies, an operation's targets): `feature_id` is the record id and
661    /// `path` addresses the field from the `cam` block's ROOT, a `#<id>`
662    /// segment selecting the array element with that id
663    /// (`["setups", "#SETUP1", "targets"]`). Finish writes it through
664    /// `cam_ops::cam_commit_refs`, and nothing rolls: CAM references name the
665    /// finished model, which is what is on screen.
666    Cam,
667    /// A manufacturing-instructions step's OCCURRENCE field — an insertion
668    /// arrow's part or a callout's: `feature_id` is the step id and `field`
669    /// says which row. The pick is a SOLID of the placed assembly; Finish
670    /// derives the occurrence (the solid's name without its member) and writes
671    /// it through `instructions_ops::instructions_commit_ref`, one undo step,
672    /// and nothing rolls.
673    Instructions { field: InstructionsRefField },
674    /// A motion-study CLIP's parts field: `feature_id` is the clip id and
675    /// `path` its list field (`["occurrences"]`). Finish writes the picked
676    /// names, as the components that hold them, through
677    /// `simulation_refs::simulation_commit_refs`; nothing rolls.
678    Simulation,
679}
680
681/// Which occurrence field of a step a pick fills ([`RefSelectTarget::Instructions`]).
682#[derive(Debug, Clone, Copy, PartialEq, Eq)]
683pub enum InstructionsRefField {
684    /// The part insertion arrow `index` animates (one of the step's own adds).
685    Arrow(usize),
686    /// The part callout `index` points at (any part of the assembly).
687    Callout(usize),
688}
689
690/// The modal state of the reference-selection widget while it is ACTIVE: which
691/// feature-dialog field is being filled, what it accepts, and the running list
692/// of picked kernel names (the source of truth — added by picking in the view,
693/// removed via the per-line X). See the ref-select methods below.
694#[derive(Debug, Clone, Default)]
695pub struct RefSelectState {
696    /// The id of the feature whose param is being edited.
697    pub feature_id: String,
698    /// The JSON path into that feature's `inputParams` the names write to
699    /// (`["targetSolid"]`, `["boolean","targets"]`, `["faceRef"]`, …).
700    pub path: Vec<String>,
701    /// A human label for the modal heading (the field's label).
702    pub label: String,
703    /// The allowed pick kinds (`["SOLID"]`, `["FACE"]`, …) — the type constraint.
704    pub filter: Vec<String>,
705    /// Whether the field takes a LIST of references (else a single one).
706    pub multiple: bool,
707    /// The picked kernel names — the running selection (source of truth).
708    pub names: Vec<String>,
709    /// The rollback step to restore on Finish/Cancel (the edited feature's own
710    /// step): entering the mode rolls to the pre-feature "before" state, so we
711    /// remember where to return.
712    pub restore_index: usize,
713    /// Which surface Finish commits the names to (feature params vs an
714    /// assembly constraint's `inputParams`). Defaults to [`RefSelectTarget::Feature`].
715    pub target: RefSelectTarget,
716    /// How many picks landed since the field was activated (a viewport click,
717    /// a fed name, a sheet anchor). A SINGLE-valued field drawn IN ITS FORM
718    /// finishes on its first pick — the form's consumer has nothing to wait
719    /// for once the one reference is in — and this is what says one landed,
720    /// as opposed to the seed the field opened with.
721    pub picks: usize,
722    /// Whether the field's own form drew the pick this frame. An in-form pick
723    /// has no card of its own, so a form that stops being drawn (its pane
724    /// tabbed away or closed, its subject gone) would strand the pick with
725    /// nothing on screen to end it; the shell finishes a pick nobody claimed.
726    pub claimed: bool,
727    /// The form asked for the pick to finish at the END of this frame rather
728    /// than now: an edit elsewhere on a feature's form while its pick runs.
729    /// Deferred because the viewport pane may draw AFTER the form in the same
730    /// frame and the click that caused the edit (a text field losing focus)
731    /// may itself be the pick — finishing at once would hand that click to
732    /// the ordinary selection instead.
733    pub finish_requested: bool,
734}
735
736impl Default for EngineState {
737    fn default() -> Self {
738        Self {
739            scene: RenderScene::new(),
740            context_scene: RenderScene::new(),
741            context_selected: None,
742            context_hovered: None,
743            context_pick_lit: Vec::new(),
744            context_display: Default::default(),
745            camera: ViewCamera::default(),
746            controls: ArcballControls::new(),
747            settings: RenderSettings::default(),
748            emphasis: Emphasis::default(),
749            widgets: WidgetRegistry::new(),
750            history: History::default(),
751            history_report: String::new(),
752            metadata: crate::metadata::MetadataStore::new(),
753            document_thumbnail: std::cell::RefCell::new(None),
754            thumbnail_cache: std::cell::RefCell::new(None),
755            settings_generation: 1,
756            dirty: true,
757            ref_select: None,
758            selection_filter: SelectionFilter::default(),
759            transform_gizmo: TransformArm::default(),
760            component_move: ComponentMoveArm::default(),
761            sketch_edit: None,
762            sketch3d_edit: None,
763            sketch3d_overlay_wpp: 0.0,
764            sketch_camera_locked: true,
765            sketch_list_hover_active: false,
766            notices: Vec::new(),
767            graded_notices: Vec::new(),
768            hidden_sketches: std::collections::HashSet::new(),
769            shown_sketch_ids: Vec::new(),
770            shown_board_ids: Vec::new(),
771            board_built_from: None,
772            board_pin_nets: Default::default(),
773            board_build: board_geometry::BoardBuild::default(),
774            board_displays: Vec::new(),
775            construction_frames: Vec::new(),
776            sketch_profiles: Vec::new(),
777            sketch_paths: Vec::new(),
778            sketch_points: Vec::new(),
779            sketch_axes: Vec::new(),
780            wire_harness_report: None,
781            ports_report: None,
782            sheet_open: None,
783            sheet_open_object: None,
784            sheet_object_opens: 0,
785            sheet_selected_object: None,
786            sheet_cache: None,
787            sheet_lines: Default::default(),
788            document_name: String::new(),
789            pmi_report: None,
790            pmi_active_view: None,
791            pmi_open_annotation: None,
792            pmi_open_view: None,
793            pmi_selected_annotation: None,
794            pmi_selected_view: None,
795            pmi_dialog_opens: 0,
796            pmi_modeling: None,
797            pmi_explode_originals: std::collections::HashMap::new(),
798            explode_playback: Default::default(),
799            simulation_play: None,
800            pmi_section_hidden: Vec::new(),
801            pmi_unposed_visibility: 0,
802            pmi_state_cache: Default::default(),
803            pmi_balloon_stale: None,
804            pmi_overlay_key: None,
805            pmi_hovered: None,
806            pmi_label_hover_active: false,
807            spline_overlay_key: None,
808            cam: cam_ops::CamGeneration::default(),
809            component_ports_visible: false,
810            spline_edit_feature: None,
811            spline_anchor_picked: None,
812            cage_edit_feature: None,
813            cage_overlay_key: None,
814            hidden_datums: std::collections::HashSet::new(),
815            shown_datum_names: Vec::new(),
816            runner: Box::new(crate::runner::InlineRunner::new()),
817            plugins: plugins::Plugins::default(),
818            interference_sessions: Default::default(),
819            interference_sequence: 0,
820            illustration_snapshot: None,
821            geometry_diagnostics: Default::default(),
822            run_generation: 0,
823            applied_generation: 0,
824            run_progress: None,
825            cancelled_run: None,
826            expression_preview: None,
827            runs_replied: 0,
828            superseded_displays: HashMap::new(),
829            pending_fit: false,
830            instructions_wizard_pending: false,
831            instructions_views_pending: false,
832            instructions_insertion: None,
833            provenance: std::collections::HashMap::new(),
834            entity_origin: std::collections::HashMap::new(),
835            info_cache: std::collections::HashMap::new(),
836            pending_query: std::collections::HashMap::new(),
837            next_query_id: 0,
838            pending_mesh_imports: std::collections::HashMap::new(),
839            mesh_preview_results: std::collections::VecDeque::new(),
840            next_mesh_import_id: 0,
841            pending_topology: std::collections::HashSet::new(),
842            topology_asked: std::collections::HashSet::new(),
843            next_topology_id: 0,
844            assembly_components: Vec::new(),
845            assembly_sync: None,
846            assembly_session_generation: None,
847            assembly_session_serial: 0,
848            session_transfer: true,
849            session_imports: 0,
850            session_replays: 0,
851            replace_pending: None,
852            last_replace_report: None,
853            consumed_names: std::collections::HashSet::new(),
854            library_resync: false,
855            sketch_links_released: false,
856            constraint_overlays: Vec::new(),
857            constraint_drag: None,
858            constraint_overlay_wpp: 0.0,
859            freedom_glyph_key: None,
860            freedom_glyph_wpp: 0.0,
861            feature_dim_overlay_wpp: 0.0,
862            sketch_overlay_wpp: 0.0,
863            constraint_hovered: None,
864            constraint_label_hover_active: false,
865            scene_tree_hovered: None,
866            scene_tree_hover_active: false,
867            dialog_hovered: None,
868            dialog_hover_active: false,
869            selected_constraint: None,
870            selected_feature: None,
871            constraint_opens: 0,
872            pending_step_assembly: None,
873            pending_step_probes: std::collections::HashSet::new(),
874            step_probe_results: std::collections::VecDeque::new(),
875            next_step_probe_id: 1,
876        }
877    }
878}
879
880impl EngineState {
881    pub fn new() -> Self {
882        Self::default()
883    }
884
885    fn pick_options(&self) -> PickOptions {
886        PickOptions {
887            double_sided: self.settings.pick_double_sided,
888            ..PickOptions::default()
889        }
890    }
891}
892
893/// Has the camera's `world_per_pixel` moved MATERIALLY (>0.5%) away from the
894/// value an overlay group's screen-constant sizing was baked at?
895///
896/// The ONE judgement every camera-keyed overlay re-bake shares
897/// (`ensure_overlays_current` and the per-group ensures it drives), so
898/// "what counts as a zoom" cannot drift between them. `baked == 0.0` means
899/// "never baked" — a state each caller handles itself, so it reads as NOT
900/// stale here. The band is what keeps a quiet frame quiet: float jitter in the
901/// camera never trips it, so there is no per-frame re-bake loop.
902pub(crate) fn overlay_wpp_stale(baked: f64, now: f64) -> bool {
903    baked > 0.0 && (now - baked).abs() > baked * 0.005
904}
905
906// ============================================================================
907// MODULE MAP — engine_state is split into topic children. THIS file is the
908// module root: it keeps the EngineState/RefSelectState structs, Default, the
909// constructor + shared pick_options, the child `mod` declarations, and the
910// re-exports that preserve the original `engine_state::*` public paths.
911// Append new work to the matching child (or add a new child + re-export here).
912// ============================================================================
913
914/// The assembly surface (Wave-3): main-side session sync + component
915/// projection, constraint CRUD with the document fold (pose-authority
916/// contract), the insert-component flow, component fix/select actions, the
917/// constraint flavor of the reference picker, and `document_signature` — the
918/// ONE parts-library `sourceSignature` hash every writer shares.
919mod assembly_ops;
920mod context_pick;
921/// Assembly-constraint viewport overlays: overlay refresh from the kernel
922/// session, the grabbable distance/angle handle pick + drag preview +
923/// `assembly_update_constraint_json` commit, movedSolids re-tessellation, the
924/// drag-path document fold, label feed + element hover, and tests.
925mod assembly_overlay;
926/// Replace component (swap an occurrence's part, keep its mates by name when
927/// the parts share lineage; mark the rest unresolved) — `replace_components`,
928/// the report, repair, and the Save As lineage stamp.
929pub mod replace_component;
930/// BOM export: the `{partName, sourceKey, quantity}` parts list off the
931/// main-side parts library + live component projection, serialized as CSV /
932/// JSON for the file dialog's Export modal.
933mod bom;
934/// Camera & view commands (zoom-to-fit, resize, pointer/wheel ingestion,
935/// projection, standard views, camera state/matrices, world→screen) plus the
936/// widget-overlay feeds (datums/overlay/dimensions/transform JSON), the
937/// ViewCube (incl. `apply_look_direction`), `datum_pick`, the widget
938/// transform-handle hover/pick/drag path, and `dimension_anchors_json`.
939mod camera_widgets;
940/// Committed-sketch persistent overlays: sheet-solid synthesis from stored
941/// profiles (`refresh_committed_sketches`), per-sketch visibility, the
942/// Scene-tree rows + `sketch_entities_json`, and the committed-sketch tests.
943/// The board's 3D bodies (substrate + copper + via barrels), derived from the
944/// document's `pcb` block after every run — see the module notes.
945mod board_geometry;
946mod committed_sketches;
947/// The COMPONENT Move gizmo (assemblies §8.5): translate→rotate→off cycle at
948/// the member-bbox center, fixed-refusal, free-move drag with the pose commit
949/// (and re-solve) on release. See `ComponentMoveArm`.
950mod component_move;
951/// Flip a constraint to its other solution (one undo step, a seeded pose).
952mod assembly_flip;
953/// Assembly COMPONENT read surface: the app-side component projection derived
954/// from the history's ACOMP features + the scene's namespaced solid names
955/// (`component_of_solid` / `component_info` / `component_bbox_center`), and its
956/// tests + shared assembly fixtures.
957mod components;
958/// Construction datum/plane display: frame→feature mapping,
959/// `refresh_construction_datums`, datum visibility + selection + entity rows,
960/// and the construction-datum tests.
961mod construction_datums;
962/// Expressions & configurator surface (`expressions_json`, `set_expressions`,
963/// `configurator_json`, `expression_variables_json`) + parsing helpers + tests.
964mod expressions;
965pub use expressions::ExpressionPreview;
966/// The feature-dimension gizmo (dimension arrows / angle arc / center-sphere
967/// toggle): arm state, `__brep`-style annotation JSON, overlay publishing,
968/// drag + set-value writeback, `FEATURE_DIM_OVERLAY`, fd_* math helpers, tests.
969mod feature_dims;
970/// The assembly interference check: the bbox-prefiltered pairwise
971/// non-destructive INTERSECT sweep over component instances
972/// (`interference_check`), its report types, and the pure pair planner.
973mod interference;
974mod batch;
975mod plugins;
976mod illustration;
977/// History runs & the feature CRUD surface: `run_history_json`, the
978/// runner/pump/apply seam, history JSON accessors, roll/update/add/delete/
979/// reorder, engine undo/redo, `load_model_and_fit`,
980/// and the history-cache rollback tests.
981mod history_ops;
982/// Model I/O: `import_step_feature`, `export_step_text`, `export_stl_text`,
983/// `triangle_normal`, and the io tests.
984mod model_io;
985/// Construction PLANES as ordinary pick candidates: the combined
986/// scene+plane-card candidate list (`pick_candidates_at`), the planes-aware
987/// single-hit pick (`pick_top_at`), the shared candidate ordering, and the
988/// plane-pick tests. Read its header for how a plane competes for a pick.
989mod plane_pick;
990/// Scene & object queries: `pick_json`/`hover_json`, settings + emphasis +
991/// visibility + color overrides, `scene_listing_json`, `depth_range_bbox`,
992/// `scene_entities_json`/select-by-name, mass properties + object info, tests.
993mod scene_query;
994/// The selection-filter state + kind gating (`SelectionFilter`,
995/// `select_filtered_at`, hide-selected) and its tests.
996mod selection_filter;
997/// Selection & hover UX: clear/select-top/selection JSON, the modal
998/// ref-select widget (incl. `set_json_at`), hover/candidate cycling, and the
999/// live sketch overlay feed (`set_sketch_overlay`/`clear_sketch_overlay`) +
1000/// selection UX tests.
1001mod selection_ux;
1002/// Sketch editing ops appended after dimensions: dimension labels/value/drag,
1003/// sketch undo/redo + diagnostics dump, trim, external edge refs
1004/// (pick/link/reproject), and hand-draw strokes.
1005mod sketch_edit_ops;
1006/// Sketch-mode viewport input: overlay refresh, uv picking, hover/click/drag,
1007/// the draw tools + pending-geometry helpers, and delete-selection.
1008mod sketch_input;
1009/// Sketch mode session: `SketchDrag`/`SketchEdit` state, plane-frame helpers,
1010/// enter/exit/new sketch, and the camera lock.
1011mod sketch_mode;
1012/// 3D sketch mode: `Sketch3dEdit`, enter/exit/new, the cursor-to-3D mapping,
1013/// the draw tools, reference linking, constraint edits and undo.
1014mod sketch3d_mode;
1015pub use sketch3d_mode::{Sketch3dCursorHit, Sketch3dEdit};
1016/// Sketch entity-list panel rows + notices + solver settings
1017/// (`SketchEntityRow`), and the constraint palette/actions
1018/// (`SketchConstraintAction`, add-constraint builders, ground/construction
1019/// toggles, cleanup).
1020mod sketch_panel;
1021/// The transform-controls gizmo: `GizmoMode`/`TransformArm`, arm/drag/apply,
1022/// pose ⇄ params JSON, quaternion helpers (`rotate_euler_xyz_f64`), tests.
1023mod transform_gizmo;
1024/// The wire-harness surface: the document's `wireHarness` block (connection
1025/// add / edit / remove / bundles toggle — checkpointed document edits that
1026/// re-run the history, whose tail routes them), the applied run's routing
1027/// report, the endpoint list, and the panel's hover highlight.
1028mod wire_harness_ops;
1029/// The PORTS surface: the ports tail's report of the last applied run — the
1030/// one place the tail's resolved points, refused names and unresolved
1031/// references reach a caller, the tail not being a feature.
1032mod ports_ops;
1033pub use ports_ops::PortRefField;
1034pub use selection_ux::RefSelectField;
1035// Every harness wire as a BOM line with its cut length (MF QTY), or the reason
1036// the last applied run cannot give one.
1037mod wire_bom;
1038mod pmi_ops;
1039mod pmi_section;
1040// Assembly exploded views: PMI views whose explode rows are ordered steps.
1041mod exploded_ops;
1042pub use exploded_ops::{ExplodePlayback, ExplodeStep, ExplodedView};
1043// Manufacturing instructions: the wrapper assembly, the wizard, step views and the player.
1044mod instructions_ops;
1045pub use instructions_ops::{Insertion, PlayTo};
1046// Motion studies: the simulation block, motors and clips.
1047mod simulation_ops;
1048pub use simulation_ops::MotorMate;
1049// Motion-study playback: bake the frames through the kernel, pose the displays.
1050mod simulation_play;
1051pub use simulation_play::{BakedFrame, SimulationPlayback};
1052// Motion-study player data: the study's frames for the instructions player
1053// template (the offline .html, and what the PLM serves).
1054mod simulation_player;
1055pub use simulation_player::assembly_signature;
1056// A clip's parts picked in the viewport: the reference-selection lane of
1057// the Simulation pane's forms.
1058mod simulation_refs;
1059// A study's published motion on a manufacturing-instructions step.
1060mod instructions_motion;
1061pub use instructions_motion::PublishedMotion;
1062// Their printed PDF, per-step PNG and SVG, and the print settings.
1063mod instructions_export;
1064pub use instructions_export::IMAGE_PX as INSTRUCTIONS_IMAGE_PX;
1065pub use instructions_export::{TOPOLOGY_WAIT, InstructionsPdfExport};
1066pub mod cam_ops;
1067pub use pmi_ops::{pmi_view_params, pmi_view_schema, world_vertex_ref, PmiModelingSnapshot, PmiViewPatch};
1068// Drawing sheets: the `sheets` block, the open sheet and the projection cache.
1069mod sheet_ops;
1070pub(crate) mod pmi_overlay;
1071pub use pmi_overlay::PmiLabel;
1072/// The 3D spline-anchor editor: the resolved anchor list, the value edits
1073/// (position / distances / flip / side / add / remove / reorder / detach),
1074/// the anchor flavour of the transform gizmo, the port-attach flavour of the
1075/// reference picker, and the direction-cage overlay.
1076mod spline_edit;
1077/// The NURBS Solid CONTROL-CAGE editor: the cage's points through the
1078/// kernel's resolver, the multi-point selection that arms the transform
1079/// gizmo at its centroid, the drag write-back, loop insertion, reset and the
1080/// cage overlay.
1081mod cage_edit;
1082
1083// Re-exports preserving the original `engine_state::*` public surface.
1084pub use assembly_ops::{document_signature, nested_fixed_state, ComponentInsert};
1085pub use board_geometry::{
1086    default_color as board_default_color, BoardBuild, BOARD_SOLID_PREFIX, SUBSTRATE_SOLID,
1087    VIAS_SOLID,
1088};
1089pub use bom::{OCCURRENCE_ATTRIBUTES, PART_ATTRIBUTES};
1090pub use component_move::{ComponentMoveArm, TypedMove};
1091pub use components::ComponentInfo;
1092pub use interference::{ClearancePair, InterferencePair, InterferenceReport, INTERFERENCE_OVERLAY_GROUP};
1093pub use model_io::{
1094    EmbeddedOnly, PartSink, StepAssemblyImport, StepAssemblyProbe, StepAssemblyReport,
1095};
1096pub use selection_filter::SelectionFilter;
1097pub use sketch_mode::{SketchDrag, SketchEdit};
1098pub use sketch_panel::{NoticeSeverity, SketchConstraintAction, SketchEntityRow};
1099pub use wire_harness_ops::ConnectionPatch;
1100pub use wire_bom::{WireBomLine, WireLengthState};
1101pub use spline_edit::SplineAnchorRow;
1102pub use cage_edit::{CageArm, CageSelect, CageSummary, CAGE_PICK_RADIUS_PX};
1103pub use transform_gizmo::{GizmoMode, TransformArm};
1104pub(crate) use transform_gizmo::rotate_euler_xyz_f64;
1105
1106
1107
1108
1109
1110
1111/// Reconstruction results either append to a document or remain uncommitted.
1112#[derive(Clone, Copy, PartialEq, Eq)]
1113pub(crate) enum MeshImportDestination {
1114    Document,
1115    Preview,
1116}