Skip to main content

brep_kernel/feature_pipeline/assembly/
exports.rs

1//! The assembly SESSION + exported ABI: constraint CRUD with auto-solve,
2//! manual solve, per-constraint status JSON, DOF summary JSON,
3//! overlay-geometry JSON, and the generic document fold that writes the solved
4//! state + poses back into the history document.
5//!
6//! The session is installed by the history-execution tail
7//! ([`super::finish_history_run`]) after EVERY run: the post-solve constraint
8//! state, a clone of the final scene map (names + resident handles — the
9//! handles stay owned by the history cache), and the expression sheet for
10//! expression-capable params. Constraint mutations between runs operate on the
11//! session and AUTO-SOLVE against the live resident geometry; the app folds
12//! the result back into its document via [`assembly_apply_document_json`]
13//! before the next history run (the pose-authority contract).
14
15use std::cell::RefCell;
16use std::collections::BTreeMap;
17
18use wasm_bindgen::prelude::*;
19
20use super::lifecycle::{self, LifecycleOutcome};
21use super::{constraints, mapping, AssemblyState, ConstraintEntry};
22use crate::feature_pipeline::{Env, SceneMap};
23
24#[derive(Clone, serde::Serialize, serde::Deserialize)]
25struct Session {
26    state: AssemblyState,
27    scene: SceneMap,
28    expressions: String,
29    configurator: serde_json::Value,
30    /// Component id → solved `inputParams.transform` JSON. ACCUMULATES across
31    /// mutation solves (later solves overwrite per id); replaced wholesale by
32    /// the next history run.
33    pose_updates: BTreeMap<String, serde_json::Value>,
34    /// Component id → grounded write-back from a migrated legacy Fixed row
35    /// (`inputParams.isFixed`; an occurrence path `A:B` → `flexibleFixed[B]` on `A`).
36    fixed_updates: BTreeMap<String, bool>,
37    /// The last solve's report (`ok` + diagnostics, or `error`).
38    report: serde_json::Value,
39}
40
41thread_local! {
42    static SESSION: RefCell<Option<Session>> = const { RefCell::new(None) };
43    /// Bumped by every install (a run's tail or an import): which session this
44    /// thread holds, so a holder can tell whether another document's run or
45    /// replay has replaced the one it installed.
46    static SESSION_SERIAL: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
47    /// Handles registered by the last [`assembly_session_import`]: owned by the
48    /// imported session alone, freed when any other session replaces it.
49    static IMPORTED: RefCell<Vec<u32>> = const { RefCell::new(Vec::new()) };
50}
51
52/// Replace this thread's session. What it replaces, and the solids a previous
53/// IMPORT owned (out of the registry already), are handed back for the caller
54/// to drop: freeing a few hundred solids costs milliseconds.
55fn replace_session(next: Session) -> RetiredSession {
56    let solids = IMPORTED
57        .with(|imported| std::mem::take(&mut *imported.borrow_mut()))
58        .into_iter()
59        .filter_map(crate::take_registered_solid)
60        .collect();
61    let session = SESSION.with(|session| session.borrow_mut().replace(next));
62    SESSION_SERIAL.with(|serial| serial.set(serial.get() + 1));
63    RetiredSession { _session: session, _solids: solids }
64}
65
66/// A replaced session and the solids only it owned, to drop where it costs
67/// nothing (another thread). Dropping it is all there is to do with it.
68pub struct RetiredSession {
69    _session: Option<Session>,
70    _solids: Vec<crate::BrepSolid>,
71}
72
73/// Which session this thread holds (see `SESSION_SERIAL`); 0 = none yet.
74pub fn assembly_session_serial() -> u64 {
75    SESSION_SERIAL.with(std::cell::Cell::get)
76}
77
78/// An owned, self-contained copy of a thread's assembly session: the session
79/// and a clone of every solid its scene names, keyed by the handle it had
80/// THERE. It shares nothing with the thread it came from, so that thread may
81/// free or reuse every handle afterwards ([`assembly_session_import`]).
82#[derive(serde::Serialize, serde::Deserialize)]
83pub struct SessionTransfer {
84    session: Session,
85    solids: Vec<(u32, crate::BrepSolid)>,
86}
87
88impl std::fmt::Debug for SessionTransfer {
89    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90        f.debug_struct("SessionTransfer").field("solids", &self.solids.len()).finish()
91    }
92}
93
94/// Copy this thread's session for another thread (`None` without one).
95pub fn assembly_session_export() -> Option<SessionTransfer> {
96    SESSION.with(|session| {
97        let session = session.borrow();
98        let session = session.as_ref()?;
99        let scene = &session.scene;
100        let mut handles: Vec<u32> = scene
101            .solids
102            .values()
103            .copied()
104            .chain(scene.faces.values().map(|face| face.handle))
105            .chain(scene.edges.values().map(|edge| edge.handle))
106            .collect();
107        handles.sort_unstable();
108        handles.dedup();
109        let solids = handles
110            .into_iter()
111            .filter_map(|handle| {
112                crate::with_registered_solid_str(handle, |solid| Ok(solid.clone())).ok().map(|solid| (handle, solid))
113            })
114            .collect();
115        Some(SessionTransfer { session: session.clone(), solids })
116    })
117}
118
119/// Install a [`SessionTransfer`] as this thread's session: every solid is
120/// registered HERE under a fresh handle and the scene is re-pointed at it.
121/// Returns what it replaced (the previous session and the solids a previous
122/// import owned) for the caller to drop.
123pub fn assembly_session_import(transfer: SessionTransfer) -> RetiredSession {
124    let SessionTransfer { mut session, solids } = transfer;
125    let mut fresh = std::collections::HashMap::with_capacity(solids.len());
126    let mut owned = Vec::with_capacity(solids.len());
127    for (old, solid) in solids {
128        let handle = crate::register_solid_value(solid);
129        fresh.insert(old, handle);
130        owned.push(handle);
131    }
132    // A handle with no copy (its solid was gone there) must not alias a
133    // solid that happens to hold the same number here.
134    let remap = |handle: &mut u32| *handle = fresh.get(handle).copied().unwrap_or(u32::MAX);
135    let scene = &mut session.scene;
136    scene.solids.values_mut().for_each(remap);
137    scene.faces.values_mut().for_each(|face| remap(&mut face.handle));
138    scene.edges.values_mut().for_each(|edge| remap(&mut edge.handle));
139    let retired = replace_session(session);
140    IMPORTED.with(|imported| *imported.borrow_mut() = owned);
141    retired
142}
143
144/// Install the post-run session (the history tail). Pose/fixed updates start
145/// from THIS run's outcome — the previous session's pending updates are
146/// dropped (the run consumed the document they were meant for).
147pub(super) fn install_session(
148    state: AssemblyState,
149    scene: SceneMap,
150    expressions: String,
151    configurator: serde_json::Value,
152    outcome: LifecycleOutcome,
153) {
154    drop(replace_session(Session {
155        state,
156        scene,
157        expressions,
158        configurator,
159        pose_updates: outcome.pose_updates,
160        fixed_updates: outcome.fixed_updates,
161        report: outcome.report,
162    }));
163}
164
165/// Publish post-solve weld anchors and notify display consumers of in-place motion.
166pub(crate) fn publish_weld_scene(scene: &SceneMap, moved: &[(String, u32)]) {
167    SESSION.with(|slot| {
168        if let Some(session) = slot.borrow_mut().as_mut() {
169            session.scene = scene.clone();
170            if !moved.is_empty() {
171                let entries = session.report.as_object_mut().expect("assembly report object")
172                    .entry("movedSolids").or_insert_with(|| serde_json::json!([]));
173                if let Some(entries) = entries.as_array_mut() {
174                    entries.extend(moved.iter().map(|(name, handle)| serde_json::json!({"name": name, "handle": handle})));
175                }
176            }
177        }
178    });
179}
180
181fn with_session<T>(f: impl FnOnce(&mut Session) -> Result<T, String>) -> Result<T, String> {
182    SESSION.with(|session| {
183        let mut session = session.borrow_mut();
184        let session = session
185            .as_mut()
186            .ok_or_else(|| "no assembly session (run a history first)".to_string())?;
187        f(session)
188    })
189}
190
191/// Re-solve the session state against the session scene, merging the
192/// outcome's write-backs (the auto-solve every mutation triggers). The
193/// returned report carries `movedSolids` (built by the lifecycle) — the
194/// display lane re-tessellates exactly those in-place-moved resident solids.
195fn solve_session(session: &mut Session) -> serde_json::Value {
196    let env = Env::build(&session.expressions, &session.configurator)
197        .unwrap_or_else(Env::poisoned);
198    let outcome = lifecycle::run_constraints(&mut session.state, &mut session.scene, &env);
199    session.pose_updates.extend(outcome.pose_updates);
200    session.fixed_updates.extend(outcome.fixed_updates);
201    session.report = outcome.report.clone();
202    outcome.report
203}
204
205// ===========================================================================
206// Read surface
207// ===========================================================================
208
209/// The current `assembly` block (post-solve) as JSON — the panel's list source
210/// and the state the app folds back into its document.
211#[wasm_bindgen]
212pub fn assembly_state_json() -> String {
213    SESSION.with(|session| {
214        session
215            .borrow()
216            .as_ref()
217            .map(|session| serde_json::to_value(&session.state).unwrap_or_default())
218            .unwrap_or_else(|| serde_json::to_value(AssemblyState::default()).unwrap_or_default())
219            .to_string()
220    })
221}
222
223/// Per-constraint status rows: `[{id, type, enabled, open, status, message,
224/// satisfied, error}]`.
225#[wasm_bindgen]
226pub fn assembly_statuses_json() -> String {
227    SESSION.with(|session| {
228        let rows: Vec<serde_json::Value> = session
229            .borrow()
230            .as_ref()
231            .map(|session| {
232                session
233                    .state
234                    .constraints
235                    .iter()
236                    .map(|entry| {
237                        serde_json::json!({
238                            "id": entry.id(),
239                            "type": entry.constraint_type,
240                            "enabled": entry.enabled,
241                            "open": entry.open,
242                            "status": entry.status(),
243                            "message": entry
244                                .persistent("message")
245                                .and_then(|value| value.as_str())
246                                .unwrap_or(""),
247                            "satisfied": entry
248                                .persistent("satisfied")
249                                .and_then(|value| value.as_bool())
250                                .unwrap_or(false),
251                            "error": entry.persistent("error").cloned(),
252                            "conflictWith": entry.persistent("conflictWith").cloned().unwrap_or(serde_json::json!([])),
253                            "suppressSuggested": entry
254                                .persistent("suppressSuggested")
255                                .and_then(|value| value.as_bool())
256                                .unwrap_or(false),
257                        })
258                    })
259                    .collect()
260            })
261            .unwrap_or_default();
262        serde_json::Value::Array(rows).to_string()
263    })
264}
265
266/// The last solve's DOF/diagnostics summary (`{ok, dof, rank, redundant,
267/// status, strategy, iterations, maxResidual, ...}` or `{ok:false, error}`).
268#[wasm_bindgen]
269pub fn assembly_dof_json() -> String {
270    SESSION.with(|session| {
271        session
272            .borrow()
273            .as_ref()
274            .map(|session| with_nested_constraints(&session.report, &session.scene).to_string())
275            .unwrap_or_else(|| serde_json::json!({ "ok": true, "mates": 0 }).to_string())
276    })
277}
278
279/// `report` plus `nestedConstraints`: the rows of every sub-assembly's own
280/// constraints (namespaced, every level), which solved inside the sub-assembly
281/// and are reported, not re-solved, here. Read from the session scene's
282/// component records, so a mutation re-solve (which replaces `report`) keeps
283/// them. Absent when no component carries any.
284fn with_nested_constraints(report: &serde_json::Value, scene: &SceneMap) -> serde_json::Value {
285    let rows: Vec<&crate::feature_pipeline::component::NestedConstraint> = scene
286        .iter_components()
287        .flat_map(|record| &record.nested_constraints)
288        .collect();
289    let mut report = report.clone();
290    if let (false, Some(map)) = (rows.is_empty(), report.as_object_mut()) {
291        map.insert(
292            "nestedConstraints".into(),
293            serde_json::to_value(rows).unwrap_or_default(),
294        );
295    }
296    report
297}
298
299/// The pending generic feature write-backs: `{"poses": {componentId:
300/// transformParam}, "isFixed": {componentId: bool}}`. The transform param is
301/// `{translate, rotateEulerDeg (deg, intrinsic XYZ)}` — exactly the shape the
302/// ACOMP feature's `inputParams.transform` reader expects.
303#[wasm_bindgen]
304pub fn assembly_pose_updates_json() -> String {
305    SESSION.with(|session| {
306        session
307            .borrow()
308            .as_ref()
309            .map(|session| {
310                serde_json::json!({
311                    "poses": session.pose_updates,
312                    "isFixed": session.fixed_updates,
313                })
314                .to_string()
315            })
316            .unwrap_or_else(|| serde_json::json!({ "poses": {}, "isFixed": {} }).to_string())
317    })
318}
319
320/// Fold the session's solved state into a history DOCUMENT: replaces the
321/// top-level `assembly` block and writes each pending pose / grounded flag
322/// into the owning feature's `inputParams` (matched by `inputParams.id` —
323/// generic JSON, no dependency on the ACOMP feature shape). The app calls this
324/// on its document before persisting or re-running (the pose-authority
325/// write-back).
326#[wasm_bindgen]
327pub fn assembly_apply_document_json(document_json: &str) -> Result<String, JsValue> {
328    assembly_apply_document_impl(document_json).map_err(|error| JsValue::from_str(&error))
329}
330
331pub fn assembly_apply_document_impl(document_json: &str) -> Result<String, String> {
332    let mut document: serde_json::Value = serde_json::from_str(document_json)
333        .map_err(|error| format!("assembly document fold: bad document: {error}"))?;
334    with_session(|session| {
335        let object = document
336            .as_object_mut()
337            .ok_or_else(|| "assembly document fold: document must be an object".to_string())?;
338        object.insert(
339            "assembly".into(),
340            serde_json::to_value(&session.state)
341                .map_err(|error| format!("assembly state serialize: {error}"))?,
342        );
343        if let Some(features) = object.get_mut("features").and_then(|v| v.as_array_mut()) {
344            for feature in features {
345                let Some(params) = feature
346                    .get_mut("inputParams")
347                    .and_then(|value| value.as_object_mut())
348                else {
349                    continue;
350                };
351                let Some(id) = params.get("id").and_then(|value| value.as_str()) else {
352                    continue;
353                };
354                let id = id.to_string();
355                if let Some(pose) = session.pose_updates.get(&id) {
356                    // Numeric solver write-back must not erase authored motion
357                    // expressions. The evaluated component record owns that pose.
358                    fn has_expression(value: &serde_json::Value) -> bool {
359                        match value {
360                            serde_json::Value::String(_) => true,
361                            serde_json::Value::Array(a) => a.iter().any(has_expression),
362                            serde_json::Value::Object(o) => o.values().any(has_expression),
363                            _ => false,
364                        }
365                    }
366                    if !params.get("transform").is_some_and(has_expression) {
367                        params.insert("transform".into(), pose.clone());
368                    }
369                }
370                // A flexible instance's occurrence poses (`ACOMP1:ACOMP2`),
371                // part-local, persist on the instance — never in the child
372                // document.
373                let prefix = format!("{id}:");
374                for (key, pose) in session.pose_updates.range(prefix.clone()..) {
375                    let Some(path) = key.strip_prefix(&prefix) else { break };
376                    let poses = params
377                        .entry("flexiblePoses")
378                        .or_insert_with(|| serde_json::Value::Object(Default::default()));
379                    if let Some(poses) = poses.as_object_mut() {
380                        poses.insert(path.to_string(), pose.clone());
381                    }
382                }
383                if let Some(&fixed) = session.fixed_updates.get(&id) {
384                    params.insert("isFixed".into(), serde_json::Value::Bool(fixed));
385                }
386                // A migrated Fixed row on a flexible instance's occurrence
387                // (`ACOMP1:ACOMP2`) is that instance's `flexibleFixed[ACOMP2]`.
388                for (key, &fixed) in session.fixed_updates.range(prefix.clone()..) {
389                    let Some(path) = key.strip_prefix(&prefix) else { break };
390                    let overrides = params
391                        .entry("flexibleFixed")
392                        .or_insert_with(|| serde_json::Value::Object(Default::default()));
393                    if !overrides.is_object() {
394                        *overrides = serde_json::Value::Object(Default::default());
395                    }
396                    if let Some(overrides) = overrides.as_object_mut() {
397                        overrides.insert(path.to_string(), serde_json::Value::Bool(fixed));
398                    }
399                }
400            }
401        }
402        Ok(())
403    })?;
404    Ok(document.to_string())
405}
406
407/// Overlay geometry for the viewport graphics lane: per enabled constraint,
408/// the resolved WORLD anchor points/directions/geometry classes (post-solve),
409/// the status, the evaluated value, and (multi-element types) the element
410/// role groups — `[{id, type, status, message, anchors, directions, geoms,
411/// value, unit, target, groups}]`. Constraints whose selections do not
412/// resolve emit status/message only (no anchors).
413#[wasm_bindgen]
414pub fn assembly_overlay_json() -> String {
415    SESSION.with(|session| {
416        let session = session.borrow();
417        let Some(session) = session.as_ref() else {
418            return serde_json::Value::Array(Vec::new()).to_string();
419        };
420        let env = Env::build(&session.expressions, &session.configurator)
421            .unwrap_or_else(Env::poisoned);
422        let rows: Vec<serde_json::Value> = session
423            .state
424            .constraints
425            .iter()
426            .filter(|entry| entry.enabled)
427            .map(|entry| overlay_row(entry, &session.scene, &env))
428            .collect();
429        serde_json::Value::Array(rows).to_string()
430    })
431}
432
433fn overlay_row(entry: &ConstraintEntry, scene: &SceneMap, env: &Env) -> serde_json::Value {
434    let mut row = serde_json::json!({
435        "id": entry.id(),
436        "type": entry.constraint_type,
437        "status": entry.status(),
438        "message": entry
439            .persistent("message")
440            .and_then(|value| value.as_str())
441            .unwrap_or(""),
442    });
443    let elements = entry.elements();
444    let resolved: Vec<_> = elements
445        .iter()
446        .filter_map(|name| mapping::resolve_element(scene, name).ok())
447        .collect();
448    if resolved.len() != elements.len() || resolved.is_empty() {
449        return row;
450    }
451    let object = row.as_object_mut().expect("row is an object");
452    object.insert(
453        "anchors".into(),
454        serde_json::Value::Array(
455            resolved
456                .iter()
457                .map(|element| {
458                    let p = element.world.representative_point();
459                    serde_json::json!([p.x, p.y, p.z])
460                })
461                .collect(),
462        ),
463    );
464    object.insert(
465        "directions".into(),
466        serde_json::Value::Array(
467            resolved
468                .iter()
469                .map(|element| match mapping::direction_of(&element.world) {
470                    Some(direction) => serde_json::json!([direction.x, direction.y, direction.z]),
471                    None => serde_json::Value::Null,
472                })
473                .collect(),
474        ),
475    );
476    // Per-element geometry class, aligned index-wise with anchors/directions —
477    // the render-side distance-arrow builder needs to identify the BASE PLANE
478    // (the perpendicular-foot construction); a direction alone is ambiguous
479    // (lines and circles carry one too).
480    object.insert(
481        "geoms".into(),
482        serde_json::Value::Array(
483            resolved
484                .iter()
485                .map(|element| serde_json::json!(geometry_tag(&element.world)))
486                .collect(),
487        ),
488    );
489    // Measured value/target — and the element ROLE groups a multi-element type
490    // inferred (center's `[width pair, tab]`) — via the mapper on a THROWAWAY
491    // clone (the mapper maintains the orientation-preference cache; an
492    // overlay read must not mutate persisted state).
493    let mut scratch = entry.clone();
494    if let Ok(mapped) = mapping::map_constraint(&mut scratch, &resolved, env) {
495        if let Some((value, unit)) = mapped.measured {
496            object.insert("value".into(), serde_json::json!(value));
497            object.insert("unit".into(), serde_json::json!(unit));
498        }
499        if let Some(axis) = mapped.angle_axis {
500            object.insert("angleAxis".into(), serde_json::json!([axis.x, axis.y, axis.z]));
501        }
502        if let Some(target) = mapped.target {
503            object.insert("target".into(), serde_json::json!(target));
504        }
505        if !mapped.groups.is_empty() {
506            object.insert("groups".into(), serde_json::json!(mapped.groups));
507        }
508    }
509    row
510}
511
512/// One resolved element as the replace-component remap reads it: the geometry
513/// class plus the frame in the owning component's LOCAL space (a component
514/// swap keeps the ACOMP pose, so local frames of the old and the new part are
515/// directly comparable).
516fn local_element_json(element: &mapping::ResolvedElement) -> serde_json::Value {
517    let point = mapping::local_point(element);
518    let direction = mapping::direction_of(&element.local)
519        .map(|d| serde_json::json!([d.x, d.y, d.z]))
520        .unwrap_or(serde_json::Value::Null);
521    let radius = match element.local {
522        crate::SelectionGeometry::Axis { radius, .. } => radius,
523        crate::SelectionGeometry::Sphere { radius, .. }
524        | crate::SelectionGeometry::Circle { radius, .. } => Some(radius),
525        _ => None,
526    };
527    serde_json::json!({
528        "ref": element.name,
529        "component": element.component,
530        "geom": geometry_tag(&element.local),
531        "point": point,
532        "direction": direction,
533        "radius": radius,
534    })
535}
536
537/// Resolve selection refs against the live session WITHOUT touching any
538/// constraint: `refs_json` is `["ACOMP2:Part_PZ", …]`; the reply is one row
539/// per ref, `{ref, ok: true, component, geom, point, direction, radius}` in
540/// the owning component's local frame, or `{ref, ok: false, status, error}`.
541/// Read-only — the replace-component lane snapshots a mate's references
542/// before the swap with it.
543#[wasm_bindgen]
544pub fn assembly_resolve_refs_json(refs_json: &str) -> String {
545    let refs: Vec<String> = match serde_json::from_str(refs_json) {
546        Ok(refs) => refs,
547        Err(error) => return refusal(&format!("refs: {error}")),
548    };
549    SESSION.with(|session| {
550        let session = session.borrow();
551        let Some(session) = session.as_ref() else {
552            return refusal("no assembly session (run a history first)");
553        };
554        let rows: Vec<serde_json::Value> = refs
555            .iter()
556            .map(|name| match mapping::resolve_element(&session.scene, name) {
557                Ok(element) => {
558                    let mut row = local_element_json(&element);
559                    row["ok"] = serde_json::Value::Bool(true);
560                    row
561                }
562                Err(failure) => serde_json::json!({
563                    "ref": name,
564                    "ok": false,
565                    "status": failure.status,
566                    "error": failure.message,
567                }),
568            })
569            .collect();
570        serde_json::Value::Array(rows).to_string()
571    })
572}
573
574/// Every NAMED face and edge of one component, resolved like
575/// [`assembly_resolve_refs_json`] (component-local frames). Entities without
576/// an analytic frame are skipped: a mate could never have referenced them.
577/// An unknown component is an empty list.
578#[wasm_bindgen]
579pub fn assembly_component_entities_json(component_id: &str) -> String {
580    SESSION.with(|session| {
581        let session = session.borrow();
582        let Some(session) = session.as_ref() else {
583            return serde_json::Value::Array(Vec::new()).to_string();
584        };
585        let mut names: Vec<(&'static str, String)> = Vec::new();
586        for (_, handle) in session.scene.component_solids(component_id) {
587            let _ = crate::with_registered_solid_str(handle, |solid| {
588                for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
589                    if let Some(name) = &face.name {
590                        names.push(("face", name.clone()));
591                    }
592                }
593                for edge in &solid.edges {
594                    if let Some(name) = &edge.name {
595                        names.push(("edge", name.clone()));
596                    }
597                }
598                Ok(())
599            });
600        }
601        let rows: Vec<serde_json::Value> = names
602            .into_iter()
603            .filter_map(|(kind, name)| {
604                let element = mapping::resolve_element(&session.scene, &name).ok()?;
605                let mut row = local_element_json(&element);
606                row["kind"] = serde_json::Value::String(kind.into());
607                Some(row)
608            })
609            .collect();
610        serde_json::Value::Array(rows).to_string()
611    })
612}
613
614/// The coarse geometry class of a resolved selection (the overlay row's
615/// `geoms` vocabulary — lowercase `SelectionGeometry` variant names).
616fn geometry_tag(geometry: &crate::SelectionGeometry) -> &'static str {
617    match geometry {
618        crate::SelectionGeometry::Plane { .. } => "plane",
619        crate::SelectionGeometry::Line { .. } => "line",
620        crate::SelectionGeometry::Axis { .. } => "axis",
621        crate::SelectionGeometry::Circle { .. } => "circle",
622        crate::SelectionGeometry::Sphere { .. } => "sphere",
623        crate::SelectionGeometry::Point { .. } => "point",
624    }
625}
626
627// ===========================================================================
628// Mutation surface
629// ===========================================================================
630
631/// Add a constraint of `constraint_type` with the given `inputParams` JSON
632/// (elements etc.; `id` is minted from the type's short name + the persistent
633/// counter when absent). Auto-solves; returns `{id, report}`.
634#[wasm_bindgen]
635pub fn assembly_add_constraint_json(
636    constraint_type: &str,
637    params_json: &str,
638) -> Result<String, JsValue> {
639    assembly_add_constraint_impl(constraint_type, params_json).map_err(|error| JsValue::from_str(&error))
640}
641
642pub fn assembly_add_constraint_impl(constraint_type: &str, params_json: &str) -> Result<String, String> {
643    if constraint_type == "fixed" {
644        return Err(super::FIXED_IS_NOT_A_CONSTRAINT.to_string());
645    }
646    let def = constraints::constraint_type(constraint_type)
647        .ok_or_else(|| format!("Unknown constraint type: {constraint_type}"))?;
648    let mut params: serde_json::Value = serde_json::from_str(params_json)
649        .map_err(|error| format!("constraint params: {error}"))?;
650    if !params.is_object() {
651        return Err("constraint params must be a JSON object".to_string());
652    }
653    with_session(|session| {
654        let id = match params.get("id").and_then(|value| value.as_str()) {
655            Some(id) if !id.is_empty() => id.to_string(),
656            _ => {
657                session.state.id_counter += 1;
658                let id = format!("{}{}", def.short_name, session.state.id_counter);
659                params
660                    .as_object_mut()
661                    .expect("checked object above")
662                    .insert("id".into(), serde_json::Value::String(id.clone()));
663                id
664            }
665        };
666        session.state.constraints.push(ConstraintEntry {
667            constraint_type: constraint_type.to_string(),
668            input_params: params.clone(),
669            persistent_data: serde_json::Value::Object(serde_json::Map::new()),
670            enabled: true,
671            open: true,
672        });
673        let report = solve_session(session);
674        Ok(serde_json::json!({ "id": id, "report": report }).to_string())
675    })
676}
677
678/// Replace a constraint's `inputParams` (the dialog commit). Auto-solves;
679/// returns the solve report.
680#[wasm_bindgen]
681pub fn assembly_update_constraint_json(id: &str, params_json: &str) -> Result<String, JsValue> {
682    assembly_update_constraint_impl(id, params_json).map_err(|error| JsValue::from_str(&error))
683}
684
685pub fn assembly_update_constraint_impl(id: &str, params_json: &str) -> Result<String, String> {
686    let mut params: serde_json::Value = serde_json::from_str(params_json)
687        .map_err(|error| format!("constraint params: {error}"))?;
688    if !params.is_object() {
689        return Err("constraint params must be a JSON object".to_string());
690    }
691    if params.get("id").and_then(|value| value.as_str()).is_none() {
692        params
693            .as_object_mut()
694            .expect("checked object above")
695            .insert("id".into(), serde_json::Value::String(id.to_string()));
696    }
697    with_session(|session| {
698        let entry = find_entry(session, id)?;
699        entry.input_params = params.clone();
700        Ok(solve_session(session).to_string())
701    })
702}
703
704/// Delete a constraint. Auto-solves; returns the solve report.
705#[wasm_bindgen]
706pub fn assembly_remove_constraint_json(id: &str) -> Result<String, JsValue> {
707    assembly_remove_constraint_impl(id).map_err(|error| JsValue::from_str(&error))
708}
709
710pub fn assembly_remove_constraint_impl(id: &str) -> Result<String, String> {
711    with_session(|session| {
712        let index = find_index(session, id)?;
713        session.state.constraints.remove(index);
714        Ok(solve_session(session).to_string())
715    })
716}
717
718/// Enable/disable a constraint. Auto-solves; returns the solve report.
719#[wasm_bindgen]
720pub fn assembly_set_constraint_enabled_json(id: &str, enabled: bool) -> Result<String, JsValue> {
721    assembly_set_constraint_enabled_impl(id, enabled).map_err(|error| JsValue::from_str(&error))
722}
723
724pub fn assembly_set_constraint_enabled_impl(id: &str, enabled: bool) -> Result<String, String> {
725    with_session(|session| {
726        find_entry(session, id)?.enabled = enabled;
727        Ok(solve_session(session).to_string())
728    })
729}
730
731/// Persist a constraint row's dialog expansion state (view state — no solve).
732#[wasm_bindgen]
733pub fn assembly_set_constraint_open_json(id: &str, open: bool) -> Result<(), JsValue> {
734    assembly_set_constraint_open_impl(id, open).map_err(|error| JsValue::from_str(&error))
735}
736
737pub fn assembly_set_constraint_open_impl(id: &str, open: bool) -> Result<(), String> {
738    with_session(|session| {
739        find_entry(session, id)?.open = open;
740        Ok(())
741    })
742}
743
744/// Reorder a constraint to `index` (clamped). Auto-solves; returns the report.
745#[wasm_bindgen]
746pub fn assembly_move_constraint_json(id: &str, index: usize) -> Result<String, JsValue> {
747    assembly_move_constraint_impl(id, index).map_err(|error| JsValue::from_str(&error))
748}
749
750pub fn assembly_move_constraint_impl(id: &str, index: usize) -> Result<String, String> {
751    with_session(|session| {
752        let from = find_index(session, id)?;
753        let entry = session.state.constraints.remove(from);
754        let to = index.min(session.state.constraints.len());
755        session.state.constraints.insert(to, entry);
756        Ok(solve_session(session).to_string())
757    })
758}
759
760// ===========================================================================
761// Automatic inference (super::infer)
762// ===========================================================================
763
764/// The inferable constraint types, joined to the catalogue: `[{type, label,
765/// icon, longName, detects, defaultOn}]`. Session-free — the dialog can list
766/// what the button offers before any document is open.
767#[wasm_bindgen]
768pub fn assembly_inferable_types_json() -> String {
769    super::infer::inferable_types_json().to_string()
770}
771
772/// SCAN the live scene for constraints its component placement implies, without
773/// creating anything. `options_json` is `super::infer::InferOptions` (`{}` for
774/// the defaults). Never `Err`: a missing session or a bad options object comes
775/// back as `{ok: false, error}` — a `JsValue` error aborts a native build.
776#[wasm_bindgen]
777pub fn assembly_infer_constraints_json(options_json: &str) -> String {
778    match infer_scan(options_json) {
779        Ok(report) => report.to_string(),
780        Err(error) => refusal(&error),
781    }
782}
783
784/// Scan and CREATE: every accepted candidate becomes a constraint, then ONE
785/// solve runs for the whole batch (each inferred constraint is already
786/// satisfied at the pose it was read from, so a healthy assembly does not
787/// move). Returns `{ok, created: [id…], report, solve}`.
788#[wasm_bindgen]
789pub fn assembly_apply_inferred_constraints_json(options_json: &str) -> String {
790    match infer_apply(options_json) {
791        Ok(report) => report.to_string(),
792        Err(error) => refusal(&error),
793    }
794}
795
796fn refusal(error: &str) -> String {
797    serde_json::json!({ "ok": false, "error": error }).to_string()
798}
799
800fn infer_scan(options_json: &str) -> Result<serde_json::Value, String> {
801    let options = super::infer::InferOptions::parse(options_json)?;
802    with_session(|session| Ok(super::infer::scan(&session.state, &session.scene, &options).report()))
803}
804
805fn infer_apply(options_json: &str) -> Result<serde_json::Value, String> {
806    let options = super::infer::InferOptions::parse(options_json)?;
807    with_session(|session| {
808        let scan = super::infer::scan(&session.state, &session.scene, &options);
809        let report = scan.report();
810        let created = super::infer::apply(&mut session.state, &scan.candidates);
811        let solve = if created.is_empty() {
812            serde_json::Value::Null
813        } else {
814            solve_session(session)
815        };
816        Ok(serde_json::json!({
817            "ok": true,
818            "created": created,
819            "report": report,
820            "solve": solve,
821        }))
822    })
823}
824
825/// Manual solve (the panel's Solve button). Returns the solve report.
826#[wasm_bindgen]
827pub fn assembly_run_solve_json() -> Result<String, JsValue> {
828    assembly_run_solve_impl().map_err(|error| JsValue::from_str(&error))
829}
830
831pub fn assembly_run_solve_impl() -> Result<String, String> {
832    with_session(|session| Ok(solve_session(session).to_string()))
833}
834
835/// The live-drag dry run against the session (`lifecycle::drag_solve`).
836/// Request `{poses: {componentId: {translate, rotateEulerDeg}}, unfix?: [id],
837/// reference?: {componentId: pose}, explain?: bool}` — the dragged components at their
838/// dragged poses, and the last good live poses to re-base mechanical mates at. Reply `{ok: true, poses:
839/// {componentId: {translate, rotateEulerDeg}}, blocking: [constraintId]}` for every movable body
840/// (`blocking`: with `explain`, the constraints that would not let the dragged
841/// components reach the drag pose; empty otherwise);
842/// `Err` when the mates cannot hold at this drag. Nothing in the session (the
843/// state, the scene, the pending write-backs, the report) changes.
844#[wasm_bindgen]
845pub fn assembly_drag_solve_json(request_json: &str) -> Result<String, JsValue> {
846    assembly_drag_solve_impl(request_json).map_err(|error| JsValue::from_str(&error))
847}
848
849pub fn assembly_drag_solve_impl(request_json: &str) -> Result<String, String> {
850    let request: serde_json::Value =
851        serde_json::from_str(request_json).map_err(|error| format!("drag solve request: {error}"))?;
852    let mut drag = BTreeMap::new();
853    for (id, pose) in request
854        .get("poses")
855        .and_then(|poses| poses.as_object())
856        .ok_or("drag solve request: missing poses")?
857    {
858        drag.insert(id.clone(), mapping::pose_params_to_transform(pose)?);
859    }
860    let mut reference = BTreeMap::new();
861    for (id, pose) in request.get("reference").and_then(|poses| poses.as_object()).into_iter().flatten() {
862        reference.insert(id.clone(), mapping::pose_params_to_transform(pose)?);
863    }
864    let unfix: Vec<String> = request
865        .get("unfix")
866        .and_then(|unfix| unfix.as_array())
867        .map(|ids| ids.iter().filter_map(|id| id.as_str().map(str::to_string)).collect())
868        .unwrap_or_default();
869    let explain = request.get("explain").and_then(|explain| explain.as_bool()).unwrap_or(false);
870    with_session(|session| {
871        let env = Env::build(&session.expressions, &session.configurator)
872            .unwrap_or_else(Env::poisoned);
873        let (poses, blocking) =
874            lifecycle::drag_solve(&session.state, &mut session.scene, &env, &drag, &unfix, &reference, explain)?;
875        let poses: serde_json::Map<String, serde_json::Value> = poses
876            .iter()
877            .map(|(id, transform)| (id.clone(), mapping::transform_to_pose_params(transform)))
878            .collect();
879        Ok(serde_json::json!({ "ok": true, "poses": poses, "blocking": blocking }).to_string())
880    })
881}
882
883/// One frame of a motion study against the session (`lifecycle::frame_solve`).
884/// Request `{overrides: {constraintId: {value?: number, enabled?: bool}},
885/// reference?: {componentId: {translate, rotateEulerDeg}}}`: `value` drives a
886/// distance or angle constraint to it (model units or degrees; an angle may
887/// run past 360), `enabled` switches a constraint off or on for the frame, and
888/// `reference` is the previous frame's poses (the warm start). Reply `{ok:
889/// true, poses: {componentId: {translate, rotateEulerDeg}}}` for every movable
890/// body; `Err` when the mates cannot hold the frame or an override names a
891/// constraint the session lacks or drives one that is not a distance or angle.
892/// Nothing in the session changes.
893#[wasm_bindgen]
894pub fn assembly_frame_solve_json(request_json: &str) -> Result<String, JsValue> {
895    assembly_frame_solve_impl(request_json).map_err(|error| JsValue::from_str(&error))
896}
897
898pub fn assembly_frame_solve_impl(request_json: &str) -> Result<String, String> {
899    let request: serde_json::Value =
900        serde_json::from_str(request_json).map_err(|error| format!("frame solve request: {error}"))?;
901    let mut reference = BTreeMap::new();
902    for (id, pose) in request.get("reference").and_then(|poses| poses.as_object()).into_iter().flatten() {
903        reference.insert(id.clone(), mapping::pose_params_to_transform(pose)?);
904    }
905    with_session(|session| {
906        let mut overrides = BTreeMap::new();
907        for (id, change) in request.get("overrides").and_then(|o| o.as_object()).into_iter().flatten() {
908            let mut entry = lifecycle::FrameOverride::default();
909            if let Some(value) = change.get("value").filter(|v| !v.is_null()) {
910                let value = value.as_f64().ok_or_else(|| format!("frame solve: '{id}' value is not a number"))?;
911                let kind = session
912                    .state
913                    .constraints
914                    .iter()
915                    .find(|c| c.id() == id)
916                    .map(|c| c.constraint_type.as_str())
917                    .ok_or_else(|| format!("frame solve: unknown constraint '{id}'"))?;
918                let param = match kind {
919                    "distance" => "distance",
920                    "angle" => "angle",
921                    other => return Err(format!("frame solve: '{id}' is a {other} constraint; a motor drives a distance or angle")),
922                };
923                entry.value = Some((param.to_string(), value));
924            }
925            entry.enabled = change.get("enabled").and_then(|e| e.as_bool());
926            overrides.insert(id.clone(), entry);
927        }
928        let env = Env::build(&session.expressions, &session.configurator).unwrap_or_else(Env::poisoned);
929        let poses = lifecycle::frame_solve(&session.state, &mut session.scene, &env, &overrides, &reference)?;
930        let poses: serde_json::Map<String, serde_json::Value> = poses
931            .iter()
932            .map(|(id, transform)| (id.clone(), mapping::transform_to_pose_params(transform)))
933            .collect();
934        Ok(serde_json::json!({ "ok": true, "poses": poses }).to_string())
935    })
936}
937
938/// Refresh the mechanical mates' stored references at the released poses of
939/// a live drag (`lifecycle::rebase_mechanical`). Request `{poses:
940/// {componentId: {translate, rotateEulerDeg}}}`. Reply: the updated
941/// `assembly` block JSON when a mechanical mate was refreshed, else `null`.
942/// The caller writes the block in the SAME undo step as the poses, so the
943/// next run maps a multi-turn drag from where it ended.
944pub fn assembly_rebase_mechanical_impl(request_json: &str) -> Result<String, String> {
945    let request: serde_json::Value =
946        serde_json::from_str(request_json).map_err(|error| format!("rebase request: {error}"))?;
947    let mut poses = BTreeMap::new();
948    for (id, pose) in request.get("poses").and_then(|poses| poses.as_object()).into_iter().flatten() {
949        poses.insert(id.clone(), mapping::pose_params_to_transform(pose)?);
950    }
951    with_session(|session| {
952        let env = Env::build(&session.expressions, &session.configurator).unwrap_or_else(Env::poisoned);
953        let changed = lifecycle::rebase_mechanical(&mut session.state, &mut session.scene, &env, &poses);
954        Ok(if changed {
955            serde_json::to_string(&session.state).map_err(|error| error.to_string())?
956        } else {
957            "null".to_string()
958        })
959    })
960}
961
962/// What **Flip** would do to constraint `id`, read from the live session:
963/// `{ok: true, patch, seed, elements: [{component, fixed, anchor, direction,
964/// geom}], value, angleAxis}` (world frame, pick order), or `{ok: false,
965/// reason}` for a type with no other solution. Read-only: the caller writes the
966/// patch and the seeded pose as one edit (`constraints::flip_rule`).
967#[wasm_bindgen]
968pub fn assembly_flip_plan_json(id: &str) -> String {
969    SESSION.with(|session| {
970        let session = session.borrow();
971        let Some(session) = session.as_ref() else {
972            return refusal("no assembly session (run a history first)");
973        };
974        let Some(entry) = session.state.constraints.iter().find(|entry| entry.id() == id) else {
975            return refusal(&format!("unknown constraint '{id}'"));
976        };
977        let env = Env::build(&session.expressions, &session.configurator).unwrap_or_else(Env::poisoned);
978        let row = overlay_row(entry, &session.scene, &env);
979        let geoms: Vec<&str> = row["geoms"].as_array().into_iter().flatten().filter_map(|g| g.as_str()).collect();
980        let (patch, seed) = match constraints::flip_rule(&entry.constraint_type, &entry.input_params, &geoms) {
981            Ok(rule) => rule,
982            Err(reason) => return serde_json::json!({ "ok": false, "reason": reason }).to_string(),
983        };
984        let elements: Vec<serde_json::Value> = entry
985            .elements()
986            .iter()
987            .enumerate()
988            .map(|(index, name)| {
989                let component = mapping::resolve_element(&session.scene, name).map(|element| element.component).unwrap_or_default();
990                serde_json::json!({
991                    "component": component,
992                    "fixed": session.scene.component_fixed(&component).unwrap_or(false),
993                    "anchor": row["anchors"].get(index).cloned().unwrap_or(serde_json::Value::Null),
994                    "direction": row["directions"].get(index).cloned().unwrap_or(serde_json::Value::Null),
995                    "geom": row["geoms"].get(index).cloned().unwrap_or(serde_json::Value::Null),
996                })
997            })
998            .collect();
999        serde_json::json!({
1000            "ok": true,
1001            "patch": patch,
1002            "seed": seed,
1003            "elements": elements,
1004            "value": row["value"],
1005            "angleAxis": row["angleAxis"],
1006        })
1007        .to_string()
1008    })
1009}
1010
1011fn find_index(session: &Session, id: &str) -> Result<usize, String> {
1012    session
1013        .state
1014        .constraints
1015        .iter()
1016        .position(|entry| entry.id() == id)
1017        .ok_or_else(|| format!("unknown constraint '{id}'"))
1018}
1019
1020fn find_entry<'a>(session: &'a mut Session, id: &str) -> Result<&'a mut ConstraintEntry, String> {
1021    let index = find_index(session, id)?;
1022    Ok(&mut session.state.constraints[index])
1023}