BREP_render 0.1.0

BREP Rust rendering engine: kernel-fed scene store + wgpu renderer (headless artifact, desktop window, and wasm canvas shells).
Documentation
//! [`EngineState`] — the windowing-agnostic viewer state machine the host UI
//! programs against (R3): scene + camera + controls + settings + emphasis, plus
//! the whole event/command/query surface (run-history feed, pointer/wheel
//! ingestion, camera commands, picking, world→screen, visibility). No GPU, no
//! canvas — the wasm `Engine` and the winit desktop shell both wrap this; it is
//! fully unit-testable on native.
//!
//! Everything crosses the R3 boundary as plain JSON/scalars: the host never holds a
//! renderer object, only names, ids, and JSON.

use crate::controls::ArcballControls;
use crate::history::History;
use crate::pick::{self, PickOptions};
use crate::scene::RenderScene;
use crate::style::{Emphasis, RenderSettings};
use crate::view::ViewCamera;
use crate::widgets::{gizmo_camera, WidgetOverlay, WidgetRegistry};
use brep_kernel::HistoryRequest;
use std::collections::HashMap;

pub struct EngineState {
    pub scene: RenderScene,
    pub camera: ViewCamera,
    pub controls: ArcballControls,
    pub settings: RenderSettings,
    pub emphasis: Emphasis,
    /// In-scene overlay widgets: datums/dimensions/curves, transform
    /// gizmo, ViewCube — fed as JSON, drawn by the render core's overlay pass.
    pub widgets: WidgetRegistry,
    /// The engine-owned editable model recipe (ordered features + rollback
    /// index) — the SINGLE source of truth for the model. The UI never keeps its
    /// own copy; it mutates/reads this through the `history_*` / feature methods.
    pub history: History,
    /// The build report (`{featureErrors, unresolved, displayErrors}`) of the
    /// last history run, so the UI can show it without re-running.
    history_report: String,
    /// The Properties-panel metadata store: user attributes keyed by OBJECT NAME
    /// (solid / face / edge kernel name), NOT feature id — so a record survives
    /// feature edits as long as the object's name persists. Persisted with the
    /// model (a top-level `metadata` field in the history document); see the
    /// [`crate::metadata`] module for the store + the object-info/measurement API.
    pub metadata: crate::metadata::MetadataStore,
    /// Bumped whenever settings change so the renderer re-derives per-solid
    /// base styles (a cheap key, not a per-frame diff).
    pub settings_generation: u64,
    /// The engine sets this whenever the camera/scene/emphasis changed; the
    /// presentation shell renders only when it is set (R22 on-demand render —
    /// the OrthoCameraIdle matrix-compare analogue, made explicit).
    pub dirty: bool,
    /// The modal reference-selection state (the ref-select widget). `Some` while
    /// the user is picking references for a feature-dialog field; `None`
    /// otherwise. The picked-name list here is the SINGLE source of truth while
    /// active (the UI reads it back; the viewport appends to it on a pick).
    pub ref_select: Option<RefSelectState>,
    /// Which entity KINDS a plain viewport click may select (the selection
    /// filter, mirroring the earlier `SelectionFilter.allowedSelectionTypes`). `select_top_at`
    /// consults it via `pick_filtered`; see the appended `SelectionFilter` impl
    /// block near the end of this file for the state + honoring logic.
    pub selection_filter: SelectionFilter,
    /// The transform-controls gizmo controller: which feature (if any) has the
    /// move/rotate gizmo armed (via the in-viewport center-sphere toggle), plus the
    /// in-flight handle drag. All the arm/drag/apply logic lives in the appended
    /// transform-gizmo impl block near the end of this file.
    pub transform_gizmo: TransformArm,
    /// The active engine-native sketch edit (`Some` while in sketch mode). Holds
    /// the live [`crate::sketch::SketchSession`] plus the pre-entry camera + roll
    /// to restore on exit. All the enter/exit/new logic lives in the appended
    /// sketch-mode impl block at the END of this file.
    sketch_edit: Option<SketchEdit>,
    /// Sketch-mode camera lock. When true (the default on every sketch entry), the
    /// camera is held flat-on to the sketch plane and an empty drag only PANS —
    /// no orbit. Toggling it back on re-faces the camera to the plane. Meaningful
    /// only while `sketch_edit` is `Some`. See the sketch-mode impl block.
    sketch_camera_locked: bool,
    /// Set for ONE frame when the sketch entity-LIST panel hovers a row (it calls
    /// [`sketch_hover_entity`](Self::sketch_hover_entity)). The viewport, which
    /// draws AFTER the panel and would otherwise `sketch_clear_hover` because the
    /// pointer is off the viewport, consumes this flag via
    /// [`take_sketch_list_hover`](Self::take_sketch_list_hover) and keeps the
    /// panel-set hover so list→canvas highlight survives the frame.
    sketch_list_hover_active: bool,
    /// Transient user-facing notices (e.g. a sketch solve that failed after an
    /// edit). The shell drains them each frame via [`take_notices`](Self::take_notices)
    /// into a toast overlay; the engine only queues. Replaces the swallowed
    /// `eprintln!` on the interactive re-solve paths.
    notices: Vec<String>,
    /// Committed-sketch visibility: the feature ids whose persistent committed-sketch
    /// overlay is HIDDEN (its Scene-tree checkbox off). Absent = visible. See the
    /// committed-sketch impl block appended at the END of this file.
    hidden_sketches: std::collections::HashSet<String>,
    /// The committed-sketch feature ids whose overlay groups were fed on the LAST
    /// [`refresh_committed_sketches`](Self::refresh_committed_sketches), so an id that
    /// is no longer shown (rolled back, deleted, hidden, or became the active edit)
    /// can have its now-stale groups cleared.
    shown_sketch_ids: Vec<String>,
    /// The named plane FRAMES the last history run resolved `(frame name, frame)`.
    /// Stored so [`refresh_construction_datums`](Self::refresh_construction_datums)
    /// (and datum selection) can display/pick the construction datum/plane frames
    /// without re-running. Filled from the run's
    /// [`crate::pipeline::SceneBuildReport::frames`]; the D/P filter is applied at
    /// display time (a frame name maps to its producing feature TYPE via the
    /// history). See the appended construction-datum impl block at the END.
    construction_frames: Vec<(String, brep_kernel::Frame)>,
    /// The solved sketch PROFILES the last history run produced `(sketch id,
    /// profile)`. Stored so [`refresh_committed_sketches`](Self::refresh_committed_sketches)
    /// can synthesize each committed sketch's SHEET SOLID (planar face + named
    /// boundary edges + corner vertices) without re-running. Filled from the run's
    /// [`crate::pipeline::SceneBuildReport::profiles`]; rollback / active-edit /
    /// visibility gating is applied at display time.
    sketch_profiles: Vec<(String, brep_kernel::SketchProfile)>,
    /// The named axis LINES the last history run produced `(axis name, line)`.
    /// Stored so the feature-dimension angle gizmo can resolve a revolve `axis`
    /// reference to a world line without re-running. Filled from the run's
    /// [`crate::pipeline::SceneBuildReport::axes`].
    sketch_axes: Vec<(String, brep_kernel::Axis)>,
    /// Construction datum/plane visibility: the frame NAMES whose datum plane is
    /// HIDDEN (its Scene-tree checkbox off). Absent = visible. Mirrors
    /// [`hidden_sketches`].
    hidden_datums: std::collections::HashSet<String>,
    /// The datum frame NAMES fed to the widget on the LAST
    /// [`refresh_construction_datums`](Self::refresh_construction_datums). The datum
    /// feed REPLACES its set wholesale each call, so this is a bookkeeping mirror of
    /// what is currently shown (parallels [`shown_sketch_ids`]).
    shown_datum_names: Vec<String>,
    /// The history-run seam (M2a of the off-thread runner). Owns the scene-free
    /// runner + its delta baseline (`name → last-emitted handle`) ACROSS reruns:
    /// [`rerun_history`](Self::rerun_history) SUBMITS a run tagged with
    /// [`run_generation`](Self::run_generation), and [`pump`](Self::pump) drains
    /// the completed reply and [`apply_run_output`](Self::apply_run_output)s its
    /// delta to [`Self::scene`]. The [`InlineRunner`](crate::runner::InlineRunner)
    /// default runs synchronously (submit → immediate poll, byte-identical to the
    /// old in-place reconcile); a background thread/worker impl slots in behind the
    /// same trait in M2b/M3. Reset on a document switch
    /// ([`set_history_json`](Self::set_history_json)) so a new model rebuilds fully.
    pub(crate) runner: Box<dyn crate::runner::HistoryRunner>,
    /// Monotonic run counter: bumped each time [`rerun_history`](Self::rerun_history)
    /// SUBMITS a run, and stamped onto the reply so a stale reply (a newer run that
    /// finished first) can be dropped. `run_generation != applied_generation` means
    /// a run is in flight (always equal for the synchronous Inline runner).
    run_generation: u64,
    /// The generation of the last reply [`pump`](Self::pump) APPLIED — the high-water
    /// mark that gates stale replies.
    applied_generation: u64,
    /// EAGER provenance `name → creating-feature id` for the current resident
    /// solids, shipped with each run ([`crate::pipeline::RunOutput::provenance`]) and
    /// replaced wholesale in [`apply_run_output`](Self::apply_run_output). Answers
    /// `creating_feature` + the Info tab's `creatingFeature` WITHOUT a cold
    /// `execute_history` — the freeze side-door once the run lives off-thread.
    pub(crate) provenance: std::collections::HashMap<String, String>,
    /// Object-info MEASUREMENT cache `name → merged object-info JSON`, filled by
    /// [`pump_queries`](crate::metadata) from the runner's replies and served every
    /// frame a selection persists (so `object_info_json` fires ONE query per
    /// selection, not one per frame). Invalidated on any geometry change
    /// (`apply_run_output`) or metadata edit (`set_metadata_attribute`).
    pub(crate) info_cache: std::collections::HashMap<String, String>,
    /// In-flight measurement queries `id → (object name, owning solid name)` — the
    /// data needed to MERGE a reply back into the info cache (inject `name` +
    /// `creatingFeature`). Cleared alongside `info_cache` on a geometry change so a
    /// stale reply is dropped rather than caching a superseded measurement.
    pub(crate) pending_query: std::collections::HashMap<u64, (String, String)>,
    /// Monotonic measurement-query id (pairs a [`crate::runner::MeasureReply`] back
    /// with its `pending_query` entry).
    pub(crate) next_query_id: u64,
}

/// The modal state of the reference-selection widget while it is ACTIVE: which
/// feature-dialog field is being filled, what it accepts, and the running list
/// of picked kernel names (the source of truth — added by picking in the view,
/// removed via the per-line X). See the ref-select methods below.
#[derive(Debug, Clone, Default)]
pub struct RefSelectState {
    /// The id of the feature whose param is being edited.
    pub feature_id: String,
    /// The JSON path into that feature's `inputParams` the names write to
    /// (`["targetSolid"]`, `["boolean","targets"]`, `["faceRef"]`, …).
    pub path: Vec<String>,
    /// A human label for the modal heading (the field's label).
    pub label: String,
    /// The allowed pick kinds (`["SOLID"]`, `["FACE"]`, …) — the type constraint.
    pub filter: Vec<String>,
    /// Whether the field takes a LIST of references (else a single one).
    pub multiple: bool,
    /// The picked kernel names — the running selection (source of truth).
    pub names: Vec<String>,
    /// The rollback step to restore on Finish/Cancel (the edited feature's own
    /// step): entering the mode rolls to the pre-feature "before" state, so we
    /// remember where to return.
    pub restore_index: usize,
}

impl Default for EngineState {
    fn default() -> Self {
        Self {
            scene: RenderScene::new(),
            camera: ViewCamera::default(),
            controls: ArcballControls::new(),
            settings: RenderSettings::default(),
            emphasis: Emphasis::default(),
            widgets: WidgetRegistry::new(),
            history: History::default(),
            history_report: String::new(),
            metadata: crate::metadata::MetadataStore::new(),
            settings_generation: 1,
            dirty: true,
            ref_select: None,
            selection_filter: SelectionFilter::default(),
            transform_gizmo: TransformArm::default(),
            sketch_edit: None,
            sketch_camera_locked: true,
            sketch_list_hover_active: false,
            notices: Vec::new(),
            hidden_sketches: std::collections::HashSet::new(),
            shown_sketch_ids: Vec::new(),
            construction_frames: Vec::new(),
            sketch_profiles: Vec::new(),
            sketch_axes: Vec::new(),
            hidden_datums: std::collections::HashSet::new(),
            shown_datum_names: Vec::new(),
            runner: Box::new(crate::runner::InlineRunner::new()),
            run_generation: 0,
            applied_generation: 0,
            provenance: std::collections::HashMap::new(),
            info_cache: std::collections::HashMap::new(),
            pending_query: std::collections::HashMap::new(),
            next_query_id: 0,
        }
    }
}

impl EngineState {
    pub fn new() -> Self {
        Self::default()
    }

    fn pick_options(&self) -> PickOptions {
        PickOptions {
            double_sided: self.settings.pick_double_sided,
            ..PickOptions::default()
        }
    }
}

// ============================================================================
// MODULE MAP — engine_state is split into topic children. THIS file is the
// module root: it keeps the EngineState/RefSelectState structs, Default, the
// constructor + shared pick_options, the child `mod` declarations, and the
// re-exports that preserve the original `engine_state::*` public paths.
// Append new work to the matching child (or add a new child + re-export here).
// ============================================================================

/// Camera & view commands (zoom-to-fit, resize, pointer/wheel ingestion,
/// projection, standard views, camera state/matrices, world→screen) plus the
/// widget-overlay feeds (datums/overlay/dimensions/transform JSON), the
/// ViewCube (incl. `apply_look_direction`), `datum_pick`, the widget
/// transform-handle hover/pick/drag path, and `dimension_anchors_json`.
mod camera_widgets;
/// Committed-sketch persistent overlays: sheet-solid synthesis from stored
/// profiles (`refresh_committed_sketches`), per-sketch visibility, the
/// Scene-tree rows + `sketch_entities_json`, and the committed-sketch tests.
mod committed_sketches;
/// Construction datum/plane display: frame→feature mapping,
/// `refresh_construction_datums`, datum visibility + selection + entity rows,
/// and the construction-datum tests.
mod construction_datums;
/// Expressions & configurator surface (`expressions_json`, `set_expressions`,
/// `configurator_json`, `expression_variables_json`) + parsing helpers + tests.
mod expressions;
/// The feature-dimension gizmo (dimension arrows / angle arc / center-sphere
/// toggle): arm state, `__brep`-style annotation JSON, overlay publishing,
/// drag + set-value writeback, `FEATURE_DIM_OVERLAY`, fd_* math helpers, tests.
mod feature_dims;
/// History runs & the feature CRUD surface: `run_history_json`, the
/// runner/pump/apply seam, history JSON accessors, roll/update/add/delete/
/// reorder, engine undo/redo, `load_model_and_fit`, `parse_color_overrides`,
/// and the history-cache rollback tests.
mod history_ops;
/// Model I/O: `import_step_feature`, `export_step_text`, `export_stl_text`,
/// `triangle_normal`, and the io tests.
mod model_io;
/// Scene & object queries: `pick_json`/`hover_json`, settings + emphasis +
/// visibility + color overrides, `scene_listing_json`, `depth_range_bbox`,
/// `scene_entities_json`/select-by-name, mass properties + object info, tests.
mod scene_query;
/// The selection-filter state + kind gating (`SelectionFilter`,
/// `select_filtered_at`, hide-selected) and its tests.
mod selection_filter;
/// Selection & hover UX: clear/select-top/selection JSON, the modal
/// ref-select widget (incl. `set_json_at`), hover/candidate cycling, and the
/// live sketch overlay feed (`set_sketch_overlay`/`clear_sketch_overlay`) +
/// selection UX tests.
mod selection_ux;
/// Sketch editing ops appended after dimensions: dimension labels/value/drag,
/// sketch undo/redo + diagnostics dump, trim, external edge refs
/// (pick/link/reproject), and hand-draw strokes.
mod sketch_edit_ops;
/// Sketch-mode viewport input: overlay refresh, uv picking, hover/click/drag,
/// the draw tools + pending-geometry helpers, and delete-selection.
mod sketch_input;
/// Sketch mode session: `SketchDrag`/`SketchEdit` state, plane-frame helpers,
/// enter/exit/new sketch, and the camera lock.
mod sketch_mode;
/// Sketch entity-list panel rows + notices + solver settings
/// (`SketchEntityRow`), and the constraint palette/actions
/// (`SketchConstraintAction`, add-constraint builders, ground/construction
/// toggles, cleanup).
mod sketch_panel;
/// The transform-controls gizmo: `GizmoMode`/`TransformArm`, arm/drag/apply,
/// pose ⇄ params JSON, quaternion helpers (`rotate_euler_xyz_f64`), tests.
mod transform_gizmo;

// Re-exports preserving the original `engine_state::*` public surface.
pub use selection_filter::SelectionFilter;
pub use sketch_mode::{SketchDrag, SketchEdit};
pub use sketch_panel::{SketchConstraintAction, SketchEntityRow};
pub use transform_gizmo::{GizmoMode, TransformArm};
pub(crate) use transform_gizmo::rotate_euler_xyz_f64;

#[cfg(test)]
mod tests;

#[cfg(test)]
mod sketch_mode_tests;