Skip to main content

brep_render/engine_state/
assembly_ops.rs

1use super::*;
2use serde_json::Value;
3
4/// What an assembly action answers while the main-side session is still on
5/// its way from the background runner (see `EngineState::ensure_assembly_session`):
6/// nothing was changed, and the same action succeeds once the copy lands, a
7/// frame or so later.
8pub const ASSEMBLY_SESSION_PENDING: &str = "the assembly is still updating; try again in a moment";
9
10// Assembly sessions are thread-local. The runner reads its session at the end of
11// every run and ships it (`pipeline::AssemblySync`); the main thread ADOPTS that
12// — the component projection, the solved constraint state, the statuses, the DOF
13// summary and the overlay rows — instead of executing the history a second time.
14// Componentless histories ship nothing and the projection is cleared.
15//
16// The ONE main-side replay left is `ensure_assembly_session`: a constraint
17// mutation auto-solves against the resident geometry of the thread that asks, and
18// the kernel's registry is thread-local, so the session has to exist HERE. That
19// is per USER constraint edit, not per run. Mutations then call the kernel ABI,
20// adopt the result with an undo checkpoint, and re-snapshot so the panels read
21// the mutation before the rerun's reply lands. Auto-solve reruns the display
22// history; otherwise manual Solve does.
23
24/// What a component-insert names: an EXISTING parts-library entry (skip the
25/// store read — just add an instance) or a NEW part payload to hand to
26/// `add_part_to_library` (which dedups by sourceKey+signature and returns the
27/// EFFECTIVE entry name the instance must reference).
28pub enum ComponentInsert<'a> {
29    Existing {
30        part_name: &'a str,
31    },
32    New {
33        name: &'a str,
34        source_key: &'a str,
35        source_signature: &'a str,
36        document_json: &'a str,
37    },
38}
39
40/// A STABLE content signature of a document: a sorted-key JSON walk hashed
41/// with the (fixed-key, cross-process-deterministic) std SipHash. The ONE
42/// signature fn, at the ENGINE altitude so app-side and engine-side writers
43/// share one copy: the app's insert flow (`panels::file`), the edit-in-place
44/// Finish (`panels::assembly_edit::refresh_library_entry`) and the
45/// update-components comparison (`panels::update_components`) all write/compare
46/// a parts-library `sourceSignature` with THIS function — a freshly inserted,
47/// unchanged part must always compare up-to-date, which a second copy would
48/// break the moment either drifted.
49/// Uses the kernel's shared sorted-key hash, also used for in-memory library
50/// fingerprints. Invalid JSON retains the raw-text hashing fallback.
51pub fn document_signature(doc_json: &str) -> String {
52    use std::hash::{Hash, Hasher};
53    let hash = match serde_json::from_str::<serde_json::Value>(doc_json) {
54        Ok(value) => brep_kernel::stable_json_hash(&value),
55        Err(_) => {
56            let mut hasher = std::collections::hash_map::DefaultHasher::new();
57            doc_json.hash(&mut hasher);
58            hasher.finish()
59        }
60    };
61    format!("{hash:016x}")
62}
63
64/// A nested occurrence's Fix/Float as the assembly solve reads it.
65///
66/// `top_params` is the top-level instance's `inputParams`, `rest` the
67/// occurrence's path inside it (`ACOMP2`, `ACOMP1:ACOMP2`) and `document` the
68/// definition that instance places. Only an occurrence the solve moves can be
69/// fixed or freed here: every instance above it must be flexible (a rigid
70/// sub-assembly moves as one body, its parts never move on their own). The
71/// state is the instance's own `flexibleFixed[rest]`, else the grounding of
72/// the definition that places it (an explicit `isFixed`, else the first
73/// component, else a legacy Fixed row that definition still carries — an
74/// embedded copy keeps it until the part is saved again), as
75/// `assembly::flexible` decides it.
76pub fn nested_fixed_state(top_params: &Value, rest: &str, document: &Value) -> Result<bool, String> {
77    let acomp = |document: &'_ Value, id: &str| -> Option<Value> {
78        document["features"].as_array()?.iter().find(|f| {
79            matches!(f["type"].as_str(), Some("ACOMP" | "ASSEMBLY COMPONENT")) && f["inputParams"]["id"].as_str() == Some(id)
80        }).cloned()
81    };
82    let rigid = |name: &str| {
83        format!("'{name}' is a rigid sub-assembly: it moves as one body, so its parts are not fixed or freed here. Tick Flexible on it, or edit it as the Work part")
84    };
85    let segments: Vec<&str> = rest.split(':').collect();
86    let (last, above) = segments.split_last().ok_or("empty occurrence path")?;
87    let top_name = top_params["partName"].as_str().unwrap_or_default();
88    if top_params["flexible"] != Value::Bool(true) {
89        return Err(rigid(top_name));
90    }
91    let mut document = document;
92    for id in above {
93        let feature = acomp(document, id).ok_or_else(|| format!("component '{id}' is missing"))?;
94        let name = feature["inputParams"]["partName"].as_str().unwrap_or_default().to_string();
95        if feature["inputParams"]["flexible"] != Value::Bool(true) {
96            return Err(rigid(&name));
97        }
98        document = &document["partsLibrary"][&name]["document"];
99    }
100    acomp(document, last).ok_or_else(|| format!("component '{last}' is missing"))?;
101    if let Some(fixed) = top_params["flexibleFixed"][rest].as_bool() {
102        return Ok(fixed);
103    }
104    let components: Vec<&Value> = document["features"]
105        .as_array()
106        .into_iter()
107        .flatten()
108        .filter(|f| matches!(f["type"].as_str(), Some("ACOMP" | "ASSEMBLY COMPONENT")))
109        .collect();
110    let feature = components.iter().find(|f| f["inputParams"]["id"].as_str() == Some(last));
111    if let Some(fixed) = feature.and_then(|f| f["inputParams"]["isFixed"].as_bool()) {
112        return Ok(fixed);
113    }
114    if components.first().and_then(|f| f["inputParams"]["id"].as_str()) == Some(last) {
115        return Ok(true);
116    }
117    let fixed_by_constraint = document["assembly"]["constraints"].as_array().into_iter().flatten().any(|c| {
118        c["type"].as_str() == Some("fixed")
119            && c["inputParams"]["elements"].as_array().into_iter().flatten().filter_map(Value::as_str).any(|e| e.split(':').next() == Some(*last))
120    });
121    Ok(fixed_by_constraint)
122}
123
124/// Rigid inverse `[Rᵀ | −Rᵀ·t]` of a component pose — used to express a picked
125/// WORLD point in COMPONENT-LOCAL coordinates (the vertex-ref contract).
126fn rigid_inverse_point(transform: &brep_kernel::AffineTransform, world: [f64; 3]) -> [f64; 3] {
127    let m = &transform.elements;
128    let d = [world[0] - m[3], world[1] - m[7], world[2] - m[11]];
129    [
130        m[0] * d[0] + m[4] * d[1] + m[8] * d[2],
131        m[1] * d[0] + m[5] * d[1] + m[9] * d[2],
132        m[2] * d[0] + m[6] * d[1] + m[10] * d[2],
133    ]
134}
135
136impl EngineState {
137    // --- read surface ------------------------------------------------------
138
139    /// Whether the current document is an ASSEMBLY document: any ACOMP-typed
140    /// feature, or a present `assembly` constraint block. Componentless
141    /// documents skip every main-side sync (zero cost for modeling files).
142    pub fn history_has_assembly(&self) -> bool {
143        let has_acomp = (0..self.history.len()).any(|index| {
144            matches!(
145                self.history.feature_type(index).as_deref(),
146                Some("ACOMP") | Some("ASSEMBLY COMPONENT")
147            )
148        });
149        has_acomp
150            || self
151                .history
152                .assembly_block()
153                .map(|block| !block.is_null())
154                .unwrap_or(false)
155    }
156
157    /// The scene's component records (deterministic id order) as of the last
158    /// applied run — the Assembly Structure tree's projection source. A VIEW
159    /// over the scene, never an owning structure.
160    pub fn assembly_components(&self) -> &[crate::pipeline::ComponentSnapshot] {
161        &self.assembly_components
162    }
163
164    /// The assembly tail of the last applied run, or an empty stand-in for a
165    /// componentless document / a document that has not run yet.
166    fn assembly_sync(&self) -> std::borrow::Cow<'_, crate::pipeline::AssemblySync> {
167        match &self.assembly_sync {
168            Some(sync) => std::borrow::Cow::Borrowed(sync),
169            None => std::borrow::Cow::Owned(crate::pipeline::AssemblySync::default()),
170        }
171    }
172
173    /// The per-constraint status rows (`[{id, type, enabled, open, status,
174    /// message, satisfied, error}]`) the run reported.
175    pub fn assembly_statuses_value(&mut self) -> Value {
176        match &self.assembly_sync().statuses {
177            Value::Null => Value::Array(Vec::new()),
178            value => value.clone(),
179        }
180    }
181
182    /// The current `assembly` block (post-solve): `{constraints, idCounter}`.
183    pub fn assembly_state_value(&mut self) -> Value {
184        match &self.assembly_sync().state {
185            // Before the first run there is no state at all; answer with the
186            // empty block every caller expects rather than a bare null.
187            Value::Null => serde_json::json!({ "constraints": [], "idCounter": 0 }),
188            value => value.clone(),
189        }
190    }
191
192    /// The last solve's DOF/diagnostics summary (`{ok, dof, rank, redundant,
193    /// …}` — `movedSolids` may be absent; tolerate it).
194    pub fn assembly_dof_value(&mut self) -> Value {
195        self.assembly_sync().dof.clone()
196    }
197
198    /// Per-constraint overlay rows (world anchors/directions/status/value) —
199    /// the constraints panel reads the evaluated value/unit for the
200    /// distance/angle label suffix; lane G's viewport graphics read the rest.
201    pub fn assembly_overlay_value(&mut self) -> Value {
202        match &self.assembly_sync().overlay {
203            Value::Null => Value::Array(Vec::new()),
204            value => value.clone(),
205        }
206    }
207
208    /// The parts-library entry names currently resident (insert-flow "existing
209    /// entries first" list). The main-side store, seeded by document ingest and
210    /// kept current by the runs that heal or GC it (`apply_run_output` installs
211    /// the store a run moved), and grown by [`insert_component`](Self::insert_component).
212    pub fn parts_library_names(&mut self) -> Vec<String> {
213        serde_json::from_str::<Value>(&brep_kernel::parts_library_json())
214            .ok()
215            .and_then(|value| {
216                value
217                    .as_object()
218                    .map(|map| map.keys().cloned().collect::<Vec<_>>())
219            })
220            .unwrap_or_default()
221    }
222
223    // --- the adopt + fold (pose-authority contract) -------------------------
224
225    /// Adopt the assembly tail the runner shipped with the applied run: the
226    /// component projection, and the post-solve constraint state folded back
227    /// into the document (silent — a solver write-back is not a user edit; the
228    /// pose/`isFixed` half was already folded in `apply_run_output`, and the
229    /// parts-library store the run moved was installed there too).
230    /// Componentless documents just clear the projection.
231    ///
232    /// This is the call that used to be `sync_assembly`, a second full
233    /// `execute_history` on the UI thread. See `pipeline::AssemblySync`.
234    pub(crate) fn adopt_assembly_sync(&mut self) {
235        let Some(sync) = &self.assembly_sync else {
236            self.assembly_components.clear();
237            // No ACOMP references left ⇒ any partsLibrary block is orphaned
238            // payload (the kernel GCs the store the same way at the end of
239            // every run) — drop it so deleting the last instance never leaves
240            // a dangling entry in the saved document. Gated on the WHOLE
241            // history, not on the run: the run executes the rolled-to PREFIX,
242            // so rolling back behind the first ACOMP ships no tail while the
243            // document's components — and therefore its library — are still
244            // very much there.
245            if !self.history_has_assembly() {
246                self.history
247                    .set_parts_library(Value::Object(serde_json::Map::new()));
248            }
249            return;
250        };
251        self.assembly_components = sync.components.clone();
252        let state = sync.state.clone();
253        // Legacy Fixed rows this run turned into the instance setting (the
254        // kernel lifecycle's migration): say so once — the fold below drops
255        // them from the document, so the next run carries none.
256        let migrated: Vec<String> = sync.dof["migratedFixed"]
257            .as_array()
258            .into_iter()
259            .flatten()
260            .map(|row| {
261                let id = row["id"].as_str().unwrap_or("Fixed");
262                match row["component"].as_str() {
263                    Some(component) => format!(
264                        "Fixed constraint {id} is now {component}'s Fixed setting: a part is fixed on its own row, not by a constraint"
265                    ),
266                    None => format!(
267                        "Fixed constraint {id} was removed: it fixed nothing ({}); fix a part on its own row",
268                        if row["enabled"] == false { "it was disabled".to_string() } else { format!("'{}' names no component", row["element"].as_str().unwrap_or("")) }
269                    ),
270                }
271            })
272            .collect();
273        for notice in migrated {
274            self.push_notice(notice);
275        }
276        self.fold_assembly_state(state, false);
277    }
278
279    /// Write the post-solve `assembly` block into the document — the state half
280    /// of the pose-authority write-back, which the kernel's
281    /// `assembly_apply_document_json` performs alongside the pose half.
282    /// `checkpoint` = true for a USER mutation (undoable), false for the silent
283    /// post-run adopt. A null state (no session / no constraints yet) writes
284    /// nothing.
285    fn fold_assembly_state(&mut self, state: Value, checkpoint: bool) {
286        if state.is_null() {
287            return;
288        }
289        if self.history.assembly_block() == Some(&state) {
290            return;
291        }
292        self.history.set_assembly_block(state, checkpoint);
293    }
294
295    /// Make sure a main-side kernel assembly SESSION exists for the last applied
296    /// run — the one thing the runner's reply cannot carry. Returns whether it
297    /// does; `false` means "not yet": the copy has been asked for and lands on
298    /// a later pump, and the caller answers [`ASSEMBLY_SESSION_PENDING`] (or
299    /// waits a frame) instead of acting on a session that is not there.
300    ///
301    /// A constraint mutation auto-solves immediately, against the resident
302    /// geometry of whichever thread holds it, and the kernel's registry and
303    /// session are both thread-local; so a mutation needs the session HERE.
304    /// That is per USER constraint edit — adding, editing, enabling,
305    /// reordering or removing a mate, inferring constraints, or pressing Solve —
306    /// not per run, which is the whole difference from the old `sync_assembly`.
307    /// Cheap no-op when the session is already current, and for a componentless
308    /// document (nothing to solve).
309    ///
310    /// The runner's own session comes first: a copy asked for earlier
311    /// ([`crate::runner::HistoryRunner::request_session`]) and answered for the
312    /// run applied here, else the native thread's bounded hand-over
313    /// ([`crate::runner::HistoryRunner::session_for_main`]) while no newer run
314    /// is in flight. Only a runner that runs on this thread anyway (the inline
315    /// runner) may REPLAY the history here instead: a background runner's
316    /// document is never rebuilt on the UI thread — that replay ran the whole
317    /// assembly, every part with a stale snapshot included, and froze the page
318    /// (the wasm worker can never hand its session over synchronously).
319    pub(crate) fn ensure_assembly_session(&mut self) -> bool {
320        if self.assembly_session_generation == Some(self.applied_generation)
321            && self.assembly_session_serial == brep_kernel::assembly_session_serial()
322        {
323            return true;
324        }
325        if !self.history_has_assembly() {
326            return true;
327        }
328        self.session_wanted = true;
329        if self.session_transfer {
330            self.take_session_copies();
331            if self.session_current() {
332                return true;
333            }
334            if !self.run_pending() {
335                let mut _trace = crate::run_trace::span("assembly_session_import");
336                match self.runner.session_for_main(self.applied_generation) {
337                    crate::runner::SessionOnMain::Resident => {
338                        self.session_imports += 1;
339                        self.mark_session_current();
340                        return true;
341                    }
342                    crate::runner::SessionOnMain::Copied(transfer) => {
343                        self.import_session(transfer);
344                        return true;
345                    }
346                    crate::runner::SessionOnMain::Unavailable => {}
347                }
348            }
349        }
350        if !self.runner.session_replay_on_main() {
351            self.ask_for_session();
352            return false;
353        }
354        self.session_replays += 1;
355        let request: brep_kernel::HistoryRequest =
356            match serde_json::from_value(self.run_request_value()) {
357                Ok(request) => request,
358                Err(_) => return false, // unparseable mid-edit document — retry next frame
359            };
360        let mut _trace = crate::run_trace::span("assembly_session");
361        let result = self.execute_plugin_history(&request);
362        if let Some(trace) = _trace.as_mut() {
363            trace.result(&result);
364        }
365        self.mark_session_current();
366        true
367    }
368
369    pub(crate) fn session_current(&self) -> bool {
370        self.assembly_session_generation == Some(self.applied_generation)
371            && self.assembly_session_serial == brep_kernel::assembly_session_serial()
372    }
373
374    /// Install a runner's session copy as this thread's session.
375    fn import_session(&mut self, transfer: brep_kernel::SessionTransfer) {
376        let retired = brep_kernel::assembly_session_import(transfer);
377        // Dropping the replaced copy costs milliseconds: not here.
378        #[cfg(not(target_arch = "wasm32"))]
379        std::thread::spawn(move || drop(retired));
380        #[cfg(target_arch = "wasm32")]
381        drop(retired);
382        self.session_imports += 1;
383        self.mark_session_current();
384    }
385
386    /// Ask the runner for a copy of the applied run's session, once per
387    /// generation, and only while no newer run is in flight (that run replaces
388    /// the session; the pump asks again when it lands).
389    fn ask_for_session(&mut self) {
390        if self.run_pending() || self.session_requested == Some(self.applied_generation) {
391            return;
392        }
393        if self.runner.request_session(self.applied_generation) {
394            self.session_requested = Some(self.applied_generation);
395        }
396    }
397
398    /// Pump side: import an answered copy of the applied run's session, drop
399    /// one of an older run, and — once this document has needed its session —
400    /// ask for the copy of each run that lands, once.
401    pub(crate) fn take_session_copies(&mut self) {
402        while let Some((generation, transfer)) = self.runner.poll_session() {
403            if self.session_requested == Some(generation) {
404                self.session_requested = None;
405            }
406            if generation != self.applied_generation {
407                continue; // an older run's copy: superseded
408            }
409            match transfer {
410                Some(transfer) => {
411                    if !self.session_current() {
412                        self.import_session(transfer);
413                    }
414                    self.session_recoveries = 0;
415                }
416                // The runner no longer holds the applied run's session (a
417                // cancel replaced it, or it ran something since): one rerun
418                // installs a fresh one there — a cache hit — and its copy is
419                // asked for as it lands. A second refusal is left standing:
420                // the actions keep answering pending rather than replay here.
421                None if self.session_recoveries == 0 && !self.run_pending() => {
422                    self.session_recoveries += 1;
423                    self.rerun_history();
424                }
425                None => {}
426            }
427        }
428        if self.session_wanted
429            && self.session_prefetched != Some(self.applied_generation)
430            && !self.run_pending()
431            && !self.session_current()
432            && self.history_has_assembly()
433            && !self.runner.session_replay_on_main()
434        {
435            self.session_prefetched = Some(self.applied_generation);
436            self.ask_for_session();
437        }
438    }
439
440    /// How often this document's session came from a main-side REPLAY of its
441    /// history, and how often from the runner (automation readback; a
442    /// background runner must never replay).
443    pub fn assembly_session_counts(&self) -> (u64, u64) {
444        (self.session_replays, self.session_imports)
445    }
446
447    /// Whether the main-side session is in place for the applied run, asking
448    /// the runner for it when it is not (see `Self::ensure_assembly_session`).
449    /// For a caller outside the engine that must read it on a later frame
450    /// rather than act without it (a Work part push, Update components).
451    pub fn assembly_session_ready(&mut self) -> bool {
452        self.ensure_assembly_session()
453    }
454
455    fn mark_session_current(&mut self) {
456        self.assembly_session_generation = Some(self.applied_generation);
457        self.assembly_session_serial = brep_kernel::assembly_session_serial();
458    }
459
460    /// Re-read the main-side session into [`Self::assembly_sync`] after a
461    /// MUTATION solved against it, so the panels (which read the snapshot, not
462    /// the kernel) show the mutation immediately instead of lagging until the
463    /// rerun's reply lands. The component projection is unchanged by a
464    /// constraint mutation — only the solve moves poses, and the rerun brings
465    /// those — so it is carried over.
466    pub(crate) fn snapshot_assembly_from_session(&mut self) {
467        let parse = |json: String| serde_json::from_str::<Value>(&json).unwrap_or(Value::Null);
468        let components = self.assembly_components.clone();
469        self.assembly_sync = Some(crate::pipeline::AssemblySync {
470            components,
471            state: parse(brep_kernel::assembly_state_json()),
472            statuses: parse(brep_kernel::assembly_statuses_json()),
473            dof: parse(brep_kernel::assembly_dof_json()),
474            overlay: parse(brep_kernel::assembly_overlay_json()),
475            parts_library: None,
476        });
477    }
478
479    /// Run the document fold: `assembly_apply_document_json(document)` →
480    /// adopt the returned document (assembly block replaced; solved poses +
481    /// isFixed folded into features by `inputParams.id`). `checkpoint` = true
482    /// for USER mutations (undoable), false for the silent post-run fold.
483    /// A missing session (no run yet) is tolerated silently.
484    fn apply_assembly_fold(&mut self, checkpoint: bool) {
485        // The fold only rewrites the `assembly` block and per-feature
486        // `inputParams` — it never reads `partsLibrary` — so hand it the
487        // document WITHOUT the library. Otherwise every edit serialized,
488        // parsed and re-serialized the whole embedded part payload three times
489        // over for nothing. `adopt_document` keeps the field when the adopted
490        // document carries no block, so the library survives the round trip.
491        let document = self.history.request_json_without_parts_library();
492        match brep_kernel::assembly_apply_document_impl(&document) {
493            Ok(folded) => {
494                let adopted = if checkpoint {
495                    self.history.adopt_document_checkpointed(&folded)
496                } else {
497                    self.history.adopt_document(&folded)
498                };
499                if let Err(error) = adopted {
500                    self.push_notice(format!("assembly fold failed: {error}"));
501                }
502                // The panels read the SHIPPED snapshot, not the kernel, so a
503                // mutation that solved against the live session has to refresh
504                // it — otherwise the constraint the user just added shows its
505                // pre-solve status until the rerun's reply lands a frame or more
506                // later. ONLY on the Ok arm: with no session the kernel's reads
507                // answer with defaults, which would blank a good snapshot.
508                self.snapshot_assembly_from_session();
509            }
510            Err(_) => {} // no session yet (fresh document before its first run)
511        }
512    }
513
514    /// Shared tail of every USER constraint mutation: fold (checkpointed) and,
515    /// when auto-solve is on, re-run the display history so the viewport
516    /// re-poses (changed ACOMP transforms dirty their fingerprints → those
517    /// instances re-execute + re-tessellate; the runner's tail re-solves).
518    ///
519    /// `pub(super)` because a constraint mutation also arrives from the VIEWPORT:
520    /// an overlay handle drag commits on release
521    /// ([`EngineState::constraint_drag_release`]) and needs the same two things
522    /// this gives every panel edit — an undo entry for the drag, and a rerun
523    /// that re-keys the moved instance's cache entry to its new pose.
524    pub(super) fn after_constraint_mutation(&mut self) {
525        self.apply_assembly_fold(true);
526        if self.settings.assembly_auto_solve {
527            self.rerun_history();
528        } else {
529            self.dirty = true;
530        }
531    }
532
533    // --- constraint mutations (kernel ABI + fold + optional rerun) ----------
534
535    /// Add a constraint (`params_json` = inputParams; the kernel mints the id
536    /// from the type's short name when absent). Returns the minted id.
537    pub fn assembly_add_constraint(
538        &mut self,
539        constraint_type: &str,
540        params_json: &str,
541    ) -> Result<String, String> {
542        if constraint_type == "fixed" {
543            return Err(brep_kernel::FIXED_IS_NOT_A_CONSTRAINT.to_string());
544        }
545        if !self.ensure_assembly_session() {
546            return Err(ASSEMBLY_SESSION_PENDING.into());
547        }
548        let reply =
549            brep_kernel::assembly_add_constraint_impl(constraint_type, params_json)?;
550        self.after_constraint_mutation();
551        let id = serde_json::from_str::<Value>(&reply)
552            .ok()
553            .and_then(|value| value.get("id").and_then(|id| id.as_str()).map(String::from))
554            .unwrap_or_default();
555        Ok(id)
556    }
557
558    /// Replace a constraint's `inputParams` (the dialog commit).
559    pub fn assembly_update_constraint(&mut self, id: &str, params_json: &str) -> Result<(), String> {
560        if !self.ensure_assembly_session() {
561            return Err(ASSEMBLY_SESSION_PENDING.into());
562        }
563        brep_kernel::assembly_update_constraint_impl(id, params_json)?;
564        self.after_constraint_mutation();
565        Ok(())
566    }
567
568    /// Update WITHOUT the rerun tail — for callers whose own continuation
569    /// re-runs anyway (the ref-select Finish, whose `end_ref_select` reruns).
570    /// Still folds (checkpointed) so the document is current before that run.
571    pub(crate) fn assembly_update_constraint_no_rerun(
572        &mut self,
573        id: &str,
574        params_json: &str,
575    ) -> Result<(), String> {
576        if !self.ensure_assembly_session() {
577            return Err(ASSEMBLY_SESSION_PENDING.into());
578        }
579        brep_kernel::assembly_update_constraint_impl(id, params_json)?;
580        self.apply_assembly_fold(true);
581        Ok(())
582    }
583
584    /// Delete a constraint.
585    pub fn assembly_remove_constraint(&mut self, id: &str) -> Result<(), String> {
586        if !self.ensure_assembly_session() {
587            return Err(ASSEMBLY_SESSION_PENDING.into());
588        }
589        brep_kernel::assembly_remove_constraint_impl(id)?;
590        self.after_constraint_mutation();
591        Ok(())
592    }
593
594    /// Enable/disable a constraint (the row checkbox).
595    pub fn assembly_set_constraint_enabled(&mut self, id: &str, enabled: bool) -> Result<(), String> {
596        if !self.ensure_assembly_session() {
597            return Err(ASSEMBLY_SESSION_PENDING.into());
598        }
599        brep_kernel::assembly_set_constraint_enabled_impl(id, enabled)?;
600        self.after_constraint_mutation();
601        Ok(())
602    }
603
604    /// Persist WHICH constraint has its dialog open (view state — SILENT fold,
605    /// no solve, no rerun, no undo entry). An open COUNTS
606    /// ([`Self::assembly_constraint_opens`]) — including a re-open of the
607    /// constraint already open, which is what the dialog door needs to surface
608    /// the pane for a label click on a form the user cannot see. ACCORDION: at
609    /// most ONE constraint is open — opening one first closes every other inside the same silent fold,
610    /// so the panel toggle, the context bar's add-from-selection, and a viewport
611    /// label click all converge on a single open constraint. The constraints
612    /// PANEL reads this flag as its mode: open one and its form replaces the
613    /// tree (`panels::assembly_constraints`), which is why every one of those
614    /// surfaces opens the dialog without knowing the panel exists.
615    pub fn assembly_set_constraint_open(&mut self, id: &str, open: bool) -> Result<(), String> {
616        if !self.ensure_assembly_session() {
617            return Err(ASSEMBLY_SESSION_PENDING.into());
618        }
619        if open {
620            let others: Vec<String> =
621                serde_json::from_str::<Value>(&brep_kernel::assembly_state_json())
622                    .ok()
623                    .and_then(|state| {
624                        state.get("constraints").and_then(|l| l.as_array()).map(|entries| {
625                            entries
626                                .iter()
627                                .filter_map(|entry| {
628                                    let cid =
629                                        entry.get("inputParams")?.get("id")?.as_str()?;
630                                    let is_open =
631                                        entry.get("open").and_then(|v| v.as_bool()).unwrap_or(false);
632                                    (is_open && cid != id).then(|| cid.to_string())
633                                })
634                                .collect()
635                        })
636                    })
637                    .unwrap_or_default();
638            for other in others {
639                brep_kernel::assembly_set_constraint_open_impl(&other, false)?;
640            }
641        }
642        brep_kernel::assembly_set_constraint_open_impl(id, open)?;
643        if open {
644            self.constraint_opens = self.constraint_opens.wrapping_add(1);
645        }
646        self.apply_assembly_fold(false);
647        Ok(())
648    }
649
650    /// How many constraint dialogs this engine has OPENED through
651    /// [`Self::assembly_set_constraint_open`] — the app's dialog door reads it
652    /// beside [`Self::assembly_open_constraint`] so a re-open of the constraint
653    /// already open is still an open (the id alone does not move: a viewport
654    /// label click on the constraint whose form is up, made precisely because
655    /// the user is on another tab).
656    ///
657    /// It counts the OPENS, not the flag's history. The flag itself lives in
658    /// the kernel and a freshly minted constraint arrives `open: true` without
659    /// passing through the setter — that one needs no count, because a new
660    /// constraint brings a new id and the door's id half already sees it.
661    pub fn assembly_constraint_opens(&self) -> u64 {
662        self.constraint_opens
663    }
664
665    /// The id of the constraint whose DIALOG is open, or `None`.
666    ///
667    /// The accordion keeps at most one (`assembly_set_constraint_open` closes
668    /// every other), so this is the panel's mode as ONE value. Reads the same
669    /// two fields the Constraints panel's row builder reads — `inputParams.id`
670    /// and `open` — off the borrowed fold state, without cloning the whole
671    /// assembly block the way `assembly_state_value` does: the app's dialog
672    /// door calls this every frame.
673    pub fn assembly_open_constraint(&self) -> Option<String> {
674        self.assembly_sync()
675            .state
676            .get("constraints")?
677            .as_array()?
678            .iter()
679            .find(|entry| entry.get("open").and_then(Value::as_bool).unwrap_or(false))
680            .and_then(|entry| entry.get("inputParams")?.get("id")?.as_str())
681            .map(str::to_string)
682    }
683
684    /// Reorder a constraint to `index` (drag-reorder).
685    pub fn assembly_move_constraint(&mut self, id: &str, index: usize) -> Result<(), String> {
686        if !self.ensure_assembly_session() {
687            return Err(ASSEMBLY_SESSION_PENDING.into());
688        }
689        brep_kernel::assembly_move_constraint_impl(id, index)?;
690        self.after_constraint_mutation();
691        Ok(())
692    }
693
694    // --- automatic inference (the Auto Constraints button) ------------------
695
696    /// The constraint types the inference lane can produce — `[{type, label,
697    /// icon, longName, detects, defaultOn}]`, straight off the kernel's rule
698    /// table. The dialog lists THIS; it keeps no roster of its own, so a rule
699    /// added in the kernel shows up as a row without an app change.
700    pub fn assembly_inferable_types(&self) -> Value {
701        serde_json::from_str(&brep_kernel::assembly_inferable_types_json())
702            .unwrap_or_else(|_| Value::Array(Vec::new()))
703    }
704
705    /// SCAN the placed components for the constraints their placement implies,
706    /// creating nothing. `options` is the kernel's `InferOptions` JSON (`{}` for
707    /// the defaults; the dialog sends the ticked `types`).
708    pub fn assembly_infer_constraints(&mut self, options: &str) -> Value {
709        if !self.ensure_assembly_session() {
710            return serde_json::json!({ "error": ASSEMBLY_SESSION_PENDING, "pending": true });
711        }
712        serde_json::from_str(&brep_kernel::assembly_infer_constraints_json(options))
713            .unwrap_or(Value::Null)
714    }
715
716    /// Scan and CREATE, as one undoable step: the kernel adds every accepted
717    /// candidate and solves the batch once, then the usual mutation tail folds
718    /// the result into the document and re-runs the display. A scan that found
719    /// nothing skips the tail entirely (no checkpoint, no rerun).
720    pub fn assembly_apply_inferred_constraints(&mut self, options: &str) -> Value {
721        if !self.ensure_assembly_session() {
722            return serde_json::json!({ "error": ASSEMBLY_SESSION_PENDING, "pending": true });
723        }
724        let reply: Value =
725            serde_json::from_str(&brep_kernel::assembly_apply_inferred_constraints_json(options))
726                .unwrap_or(Value::Null);
727        let created = reply
728            .get("created")
729            .and_then(|value| value.as_array())
730            .map(|list| list.len())
731            .unwrap_or(0);
732        if created > 0 {
733            self.after_constraint_mutation();
734        }
735        reply
736    }
737
738    /// Manual solve (the panel's Solve button): solve the session, fold, and
739    /// ALWAYS re-run the display (that is the point of pressing Solve — it
740    /// works with auto-solve disabled).
741    pub fn assembly_run_solve(&mut self) -> Result<(), String> {
742        if !self.ensure_assembly_session() {
743            return Err(ASSEMBLY_SESSION_PENDING.into());
744        }
745        // Nothing to solve without components — bail BEFORE the kernel solve:
746        // an empty assembly solving to a no-op is the correct result. (This
747        // bail was once also the only thing between a missing session and a
748        // native abort; the `_impl` doors now return that error as text.)
749        if self.assembly_components().is_empty() {
750            return Ok(());
751        }
752        brep_kernel::assembly_run_solve_impl()?;
753        self.apply_assembly_fold(true);
754        self.rerun_history();
755        Ok(())
756    }
757
758    // --- component actions (route to the owning ACOMP feature) --------------
759
760    /// Insert a component instance (the palette/insert flow): resolve the
761    /// parts-library entry (add or reuse), refresh the document's
762    /// `partsLibrary` block, append an ACOMP feature referencing the RETURNED
763    /// effective part name with an identity transform, and re-run. The FIRST
764    /// component of the document writes `isFixed: true` EXPLICITLY (dialog-
765    /// visible); later instances write `false`. Returns the new feature id
766    /// (`ACOMP<digits>` — the history's global counter mints that exact form).
767    pub fn insert_component(&mut self, insert: ComponentInsert<'_>) -> Result<String, String> {
768        let part_name = self.resolve_component_insert(insert)?;
769        let first = !(0..self.history.len()).any(|index| {
770            matches!(
771                self.history.feature_type(index).as_deref(),
772                Some("ACOMP") | Some("ASSEMBLY COMPONENT")
773            )
774        });
775        let id = self.history.next_feature_id("ACOMP");
776        let feature = serde_json::json!({
777            "type": "ACOMP",
778            "inputParams": {
779                "id": id,
780                "partName": part_name,
781                "transform": { "translate": [0, 0, 0], "rotateEulerDeg": [0, 0, 0] },
782                "isFixed": first,
783            },
784            "persistentData": {}
785        });
786        self.add_feature(&feature.to_string())?;
787        Ok(id)
788    }
789
790    /// The parts-library entry an insert (or a replace) names: an existing
791    /// entry as is, or a new payload added (deduplicated by
792    /// sourceKey+signature) — with the document's `partsLibrary` block
793    /// refreshed so the next run ingests it. Returns the EFFECTIVE entry name.
794    pub(crate) fn resolve_component_insert(&mut self, insert: ComponentInsert<'_>) -> Result<String, String> {
795        let part_name = match insert {
796            ComponentInsert::Existing { part_name } => {
797                if !self.parts_library_names().iter().any(|name| name == part_name) {
798                    return Err(format!("part '{part_name}' is not in the parts library"));
799                }
800                part_name.to_string()
801            },
802            ComponentInsert::New {
803                name,
804                source_key,
805                source_signature,
806                document_json,
807            } => match brep_kernel::add_part_to_library_impl(
808                name,
809                source_key,
810                source_signature,
811                document_json,
812            ) {
813                Ok(part_name) => part_name,
814                Err(error) => {
815                    // The Insert component dialog closes on Insert, so its
816                    // status line never shows this; the toast is what the user
817                    // sees (a file that is not a part document, for one).
818                    self.push_notice(format!("Could not insert '{name}': {error}"));
819                    return Err(error);
820                }
821            },
822        };
823        // The block must ride the request so the display runner ingests the
824        // (new) entry on the very next run.
825        if let Ok(library) = serde_json::from_str::<Value>(&brep_kernel::parts_library_json()) {
826            self.history.set_parts_library(library);
827        }
828        Ok(part_name)
829    }
830
831    /// Fix/Unfix a component: toggles the OWNING ACOMP feature's
832    /// `inputParams.isFixed` (one truth, one undo lane) and re-runs. A nested
833    /// occurrence (`ACOMP1:ACOMP2`) is fixed or freed on the top instance that
834    /// lends it (`inputParams.flexibleFixed`, by instance-local path), never in
835    /// the sub-assembly's document; [`nested_fixed_state`] says when that is
836    /// not possible.
837    pub fn set_component_fixed(&mut self, component_id: &str, fixed: bool) -> Result<(), String> {
838        if let Some((top, rest)) = component_id.split_once(':') {
839            self.occurrence_fixed(component_id)?;
840            let index = self.history.index_of(top).ok_or_else(|| format!("no component feature '{top}'"))?;
841            let mut params = self.history.feature_params(index).unwrap_or_else(|| serde_json::json!({}));
842            let Some(map) = params.as_object_mut() else {
843                return Err(format!("component '{top}': malformed inputParams"));
844            };
845            let overrides = map.entry("flexibleFixed").or_insert_with(|| serde_json::json!({}));
846            if !overrides.is_object() {
847                *overrides = serde_json::json!({});
848            }
849            overrides[rest] = Value::Bool(fixed);
850            self.update_feature_params(top, &params.to_string())?;
851            return Ok(());
852        }
853        self.set_components_fixed(&[component_id.to_string()], fixed)
854    }
855
856    /// Fix/Unfix several top-level components at once (a packed BOM row's
857    /// placements): every owning ACOMP's `inputParams.isFixed`, ONE undo step,
858    /// one re-run. The same write [`Self::set_component_fixed`] makes for one.
859    pub fn set_components_fixed(&mut self, component_ids: &[String], fixed: bool) -> Result<(), String> {
860        let mut edits = Vec::with_capacity(component_ids.len());
861        for component_id in component_ids {
862            if component_id.contains(':') {
863                return Err(format!("'{component_id}' is a nested occurrence: fix or unfix it on its own"));
864            }
865            let index = self
866                .history
867                .index_of(component_id)
868                .ok_or_else(|| format!("no component feature '{component_id}'"))?;
869            let mut params = self
870                .history
871                .feature_params(index)
872                .unwrap_or_else(|| serde_json::json!({}));
873            let Some(map) = params.as_object_mut() else {
874                return Err(format!("component '{component_id}': malformed inputParams"));
875            };
876            map.insert("isFixed".into(), Value::Bool(fixed));
877            edits.push((component_id.clone(), params));
878        }
879        self.update_many_feature_params(&edits)?;
880        Ok(())
881    }
882
883    /// Whether a nested occurrence (`ACOMP1:ACOMP2`) is fixed, or why it
884    /// cannot be fixed or freed from this assembly ([`nested_fixed_state`]).
885    pub fn occurrence_fixed(&self, path: &str) -> Result<bool, String> {
886        let (top, rest) = path.split_once(':').ok_or_else(|| format!("'{path}' is not a nested occurrence"))?;
887        let index = self.history.index_of(top).ok_or_else(|| format!("no component feature '{top}'"))?;
888        let params = self.history.feature_params(index).unwrap_or_default();
889        let part = params["partName"].as_str().unwrap_or_default();
890        nested_fixed_state(&params, rest, &self.history.parts_library()[part]["document"])
891    }
892
893    /// Select a component in the viewport: emphasis over exactly its member
894    /// solids (the tree↔viewport sync lane; a viewport pick of any member
895    /// lights the tree row through the same emphasis set).
896    pub fn select_component(&mut self, component_id: &str) {
897        self.select_components(&[component_id.to_string()]);
898    }
899
900    /// A component's member SOLID scene names (empty for an unknown id) — the
901    /// selection/hover unit COMPONENT entries resolve to.
902    pub fn component_member_solids(&self, component_id: &str) -> Vec<String> {
903        self.assembly_components
904            .iter()
905            .filter(|record| record.id == component_id)
906            .flat_map(|record| record.solids.iter().cloned())
907            .collect()
908    }
909
910    /// TOGGLE a component in the current selection as ONE unit (the additive
911    /// Ctrl/Cmd+click under COMPONENT promotion): when EVERY member solid is
912    /// already selected the whole set deselects, otherwise the whole set joins
913    /// the selection — the rest of the selection stays.
914    pub fn toggle_component_selection(&mut self, component_id: &str) {
915        let members = self.component_member_solids(component_id);
916        if members.is_empty() {
917            return;
918        }
919        let all_selected = members
920            .iter()
921            .all(|name| self.emphasis.selected_solids.contains(name));
922        for name in members {
923            if all_selected {
924                self.emphasis.selected_solids.remove(&name);
925            } else {
926                self.emphasis.selected_solids.insert(name);
927            }
928        }
929        self.emphasis.generation = self.emphasis.generation.wrapping_add(1);
930        self.dirty = true;
931    }
932
933    /// Select SEVERAL components at once: emphasis over the union of their
934    /// member solids (the interference window's row click highlights both
935    /// participants of a pair through this).
936    pub fn select_components(&mut self, component_ids: &[String]) {
937        // An id may be a nested occurrence (`ACOMP2:ACOMP1`): the solids of
938        // its top component under that path.
939        let members: Vec<String> = self
940            .assembly_components
941            .iter()
942            .flat_map(|record| {
943                record.solids.iter().filter(move |solid| {
944                    component_ids.iter().any(|id| {
945                        id == &record.id
946                            || (id.split(':').next() == Some(record.id.as_str()) && solid.starts_with(&format!("{id}:")))
947                    })
948                })
949            })
950            .cloned()
951            .collect();
952        let json = serde_json::json!({ "selected": { "solids": members } }).to_string();
953        let _ = self.emphasis.apply_json(&json);
954        self.dirty = true;
955    }
956
957    // --- constraint reference selection (the ref-select reuse) --------------
958
959    /// Enter the modal reference picker for an ASSEMBLY CONSTRAINT's
960    /// `elements`-style field (same widget, different commit target — Finish
961    /// routes through `Self::assembly_update_constraint_no_rerun` instead of
962    /// feature params). No roll-to-before: constraints pick against the FULL
963    /// assembly.
964    pub fn begin_ref_select_for_constraint(
965        &mut self,
966        constraint_id: &str,
967        path: Vec<String>,
968        label: String,
969        filter: Vec<String>,
970        multiple: bool,
971        seed_names: Vec<String>,
972    ) {
973        let restore_index = self.history.rollback();
974        self.selection_filter = SelectionFilter::from_ref_filter(&filter);
975        self.ref_select = Some(RefSelectState {
976            feature_id: constraint_id.to_string(),
977            path,
978            label,
979            filter,
980            multiple,
981            names: seed_names,
982            restore_index,
983            target: RefSelectTarget::AssemblyConstraint,
984            picks: 0,
985            claimed: false,
986            finish_requested: false,
987        });
988        self.sync_ref_select_emphasis();
989    }
990
991    /// Commit a finished constraint ref-select: read the constraint's params
992    /// from the session state, write the picked names at the field path, and
993    /// update (fold only — the caller's continuation reruns).
994    pub(crate) fn assembly_commit_constraint_refs(
995        &mut self,
996        constraint_id: &str,
997        path: &[String],
998        names: &[String],
999        multiple: bool,
1000    ) {
1001        let state = self.assembly_state_value();
1002        let Some(entry) = state
1003            .get("constraints")
1004            .and_then(Value::as_array)
1005            .and_then(|constraints| {
1006                constraints.iter().find(|entry| {
1007                    entry
1008                        .get("inputParams")
1009                        .and_then(|params| params.get("id"))
1010                        .and_then(Value::as_str)
1011                        == Some(constraint_id)
1012                })
1013            })
1014        else {
1015            self.push_notice(format!("unknown constraint '{constraint_id}'"));
1016            return;
1017        };
1018        let mut params = entry
1019            .get("inputParams")
1020            .cloned()
1021            .unwrap_or_else(|| serde_json::json!({}));
1022        let value = if multiple {
1023            Value::Array(names.iter().cloned().map(Value::String).collect())
1024        } else {
1025            Value::String(names.first().cloned().unwrap_or_default())
1026        };
1027        super::selection_ux::set_json_at(&mut params, path, value);
1028        if let Err(error) = self.assembly_update_constraint_no_rerun(constraint_id, &params.to_string())
1029        {
1030            self.push_notice(format!("constraint update failed: {error}"));
1031        }
1032    }
1033
1034    /// Build the `{solidName}@x,y,z` COMPONENT-LOCAL vertex ref for a vertex
1035    /// pick on a component member (lane-E contract: world pick transformed by
1036    /// the owning component's inverse pose). `None` when the solid belongs to
1037    /// no component (vertex refs only exist for constraint selection).
1038    pub(crate) fn component_vertex_ref(
1039        &self,
1040        solid_name: &str,
1041        world_position: [f64; 3],
1042    ) -> Option<String> {
1043        let record = self.assembly_components.iter().find(|record| {
1044            record.solids.iter().any(|member| member == solid_name)
1045        })?;
1046        let local = rigid_inverse_point(&record.affine(), world_position);
1047        Some(format!(
1048            "{solid_name}@{},{},{}",
1049            local[0], local[1], local[2]
1050        ))
1051    }
1052}
1053