Skip to main content

brep_kernel/feature_pipeline/assembly/
exports.rs

1//! The assembly SESSION + exported ABI (build-spec §10 item 5): constraint
2//! CRUD with auto-solve, manual solve, per-constraint status JSON, DOF summary
3//! JSON, overlay-geometry JSON, and the generic document fold that writes the
4//! solved 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
24struct Session {
25    state: AssemblyState,
26    scene: SceneMap,
27    expressions: String,
28    configurator: serde_json::Value,
29    /// Component id → solved `inputParams.transform` JSON. ACCUMULATES across
30    /// mutation solves (later solves overwrite per id); replaced wholesale by
31    /// the next history run.
32    pose_updates: BTreeMap<String, serde_json::Value>,
33    /// Component id → grounded write-back (`inputParams.isFixed`).
34    fixed_updates: BTreeMap<String, bool>,
35    /// The last solve's report (`ok` + diagnostics, or `error`).
36    report: serde_json::Value,
37}
38
39thread_local! {
40    static SESSION: RefCell<Option<Session>> = const { RefCell::new(None) };
41}
42
43/// Install the post-run session (the history tail). Pose/fixed updates start
44/// from THIS run's outcome — the previous session's pending updates are
45/// dropped (the run consumed the document they were meant for).
46pub(super) fn install_session(
47    state: AssemblyState,
48    scene: SceneMap,
49    expressions: String,
50    configurator: serde_json::Value,
51    outcome: LifecycleOutcome,
52) {
53    SESSION.with(|session| {
54        *session.borrow_mut() = Some(Session {
55            state,
56            scene,
57            expressions,
58            configurator,
59            pose_updates: outcome.pose_updates,
60            fixed_updates: outcome.fixed_updates,
61            report: outcome.report,
62        });
63    });
64}
65
66fn with_session<T>(f: impl FnOnce(&mut Session) -> Result<T, String>) -> Result<T, String> {
67    SESSION.with(|session| {
68        let mut session = session.borrow_mut();
69        let session = session
70            .as_mut()
71            .ok_or_else(|| "no assembly session (run a history first)".to_string())?;
72        f(session)
73    })
74}
75
76/// Re-solve the session state against the session scene, merging the
77/// outcome's write-backs (the auto-solve every mutation triggers). The
78/// returned report carries `movedSolids` (built by the lifecycle) — the
79/// display lane re-tessellates exactly those in-place-moved resident solids.
80fn solve_session(session: &mut Session) -> serde_json::Value {
81    let env = Env::build(&session.expressions, &session.configurator)
82        .unwrap_or_else(Env::poisoned);
83    let outcome = lifecycle::run_constraints(&mut session.state, &mut session.scene, &env);
84    session.pose_updates.extend(outcome.pose_updates);
85    session.fixed_updates.extend(outcome.fixed_updates);
86    session.report = outcome.report.clone();
87    outcome.report
88}
89
90// ===========================================================================
91// Read surface
92// ===========================================================================
93
94/// The current `assembly` block (post-solve) as JSON — the panel's list source
95/// and the state the app folds back into its document.
96#[wasm_bindgen]
97pub fn assembly_state_json() -> String {
98    SESSION.with(|session| {
99        session
100            .borrow()
101            .as_ref()
102            .map(|session| serde_json::to_value(&session.state).unwrap_or_default())
103            .unwrap_or_else(|| serde_json::to_value(AssemblyState::default()).unwrap_or_default())
104            .to_string()
105    })
106}
107
108/// Per-constraint status rows: `[{id, type, enabled, open, status, message,
109/// satisfied, error}]` (requirements §5 vocabulary).
110#[wasm_bindgen]
111pub fn assembly_statuses_json() -> String {
112    SESSION.with(|session| {
113        let rows: Vec<serde_json::Value> = session
114            .borrow()
115            .as_ref()
116            .map(|session| {
117                session
118                    .state
119                    .constraints
120                    .iter()
121                    .map(|entry| {
122                        serde_json::json!({
123                            "id": entry.id(),
124                            "type": entry.constraint_type,
125                            "enabled": entry.enabled,
126                            "open": entry.open,
127                            "status": entry.status(),
128                            "message": entry
129                                .persistent("message")
130                                .and_then(|value| value.as_str())
131                                .unwrap_or(""),
132                            "satisfied": entry
133                                .persistent("satisfied")
134                                .and_then(|value| value.as_bool())
135                                .unwrap_or(false),
136                            "error": entry.persistent("error").cloned(),
137                        })
138                    })
139                    .collect()
140            })
141            .unwrap_or_default();
142        serde_json::Value::Array(rows).to_string()
143    })
144}
145
146/// The last solve's DOF/diagnostics summary (`{ok, dof, rank, redundant,
147/// status, strategy, iterations, maxResidual, ...}` or `{ok:false, error}`).
148#[wasm_bindgen]
149pub fn assembly_dof_json() -> String {
150    SESSION.with(|session| {
151        session
152            .borrow()
153            .as_ref()
154            .map(|session| session.report.to_string())
155            .unwrap_or_else(|| serde_json::json!({ "ok": true, "mates": 0 }).to_string())
156    })
157}
158
159/// The pending generic feature write-backs: `{"poses": {componentId:
160/// transformParam}, "isFixed": {componentId: bool}}`. The transform param is
161/// `{translate, rotateEulerDeg (deg, intrinsic XYZ)}` — exactly the shape the
162/// ACOMP feature's `inputParams.transform` reader expects.
163#[wasm_bindgen]
164pub fn assembly_pose_updates_json() -> String {
165    SESSION.with(|session| {
166        session
167            .borrow()
168            .as_ref()
169            .map(|session| {
170                serde_json::json!({
171                    "poses": session.pose_updates,
172                    "isFixed": session.fixed_updates,
173                })
174                .to_string()
175            })
176            .unwrap_or_else(|| serde_json::json!({ "poses": {}, "isFixed": {} }).to_string())
177    })
178}
179
180/// Fold the session's solved state into a history DOCUMENT: replaces the
181/// top-level `assembly` block and writes each pending pose / grounded flag
182/// into the owning feature's `inputParams` (matched by `inputParams.id` —
183/// generic JSON, no dependency on the ACOMP feature shape). The app calls this
184/// on its document before persisting or re-running (the pose-authority
185/// write-back, spec §6 step 4).
186#[wasm_bindgen]
187pub fn assembly_apply_document_json(document_json: &str) -> Result<String, JsValue> {
188    apply_document(document_json).map_err(|error| JsValue::from_str(&error))
189}
190
191fn apply_document(document_json: &str) -> Result<String, String> {
192    let mut document: serde_json::Value = serde_json::from_str(document_json)
193        .map_err(|error| format!("assembly document fold: bad document: {error}"))?;
194    with_session(|session| {
195        let object = document
196            .as_object_mut()
197            .ok_or_else(|| "assembly document fold: document must be an object".to_string())?;
198        object.insert(
199            "assembly".into(),
200            serde_json::to_value(&session.state)
201                .map_err(|error| format!("assembly state serialize: {error}"))?,
202        );
203        if let Some(features) = object.get_mut("features").and_then(|v| v.as_array_mut()) {
204            for feature in features {
205                let Some(params) = feature
206                    .get_mut("inputParams")
207                    .and_then(|value| value.as_object_mut())
208                else {
209                    continue;
210                };
211                let Some(id) = params.get("id").and_then(|value| value.as_str()) else {
212                    continue;
213                };
214                let id = id.to_string();
215                if let Some(pose) = session.pose_updates.get(&id) {
216                    params.insert("transform".into(), pose.clone());
217                }
218                if let Some(&fixed) = session.fixed_updates.get(&id) {
219                    params.insert("isFixed".into(), serde_json::Value::Bool(fixed));
220                }
221            }
222        }
223        Ok(())
224    })?;
225    Ok(document.to_string())
226}
227
228/// Overlay geometry for the viewport graphics lane: per enabled constraint,
229/// the resolved WORLD anchor points/directions/geometry classes (post-solve),
230/// the status, and the evaluated value — `[{id, type, status, message,
231/// anchors, directions, geoms, value, unit, target}]`. Constraints whose
232/// selections do not resolve emit status/message only (no anchors).
233#[wasm_bindgen]
234pub fn assembly_overlay_json() -> String {
235    SESSION.with(|session| {
236        let session = session.borrow();
237        let Some(session) = session.as_ref() else {
238            return serde_json::Value::Array(Vec::new()).to_string();
239        };
240        let env = Env::build(&session.expressions, &session.configurator)
241            .unwrap_or_else(Env::poisoned);
242        let rows: Vec<serde_json::Value> = session
243            .state
244            .constraints
245            .iter()
246            .filter(|entry| entry.enabled)
247            .map(|entry| overlay_row(entry, &session.scene, &env))
248            .collect();
249        serde_json::Value::Array(rows).to_string()
250    })
251}
252
253fn overlay_row(entry: &ConstraintEntry, scene: &SceneMap, env: &Env) -> serde_json::Value {
254    let mut row = serde_json::json!({
255        "id": entry.id(),
256        "type": entry.constraint_type,
257        "status": entry.status(),
258        "message": entry
259            .persistent("message")
260            .and_then(|value| value.as_str())
261            .unwrap_or(""),
262    });
263    let elements = entry.elements();
264    let resolved: Vec<_> = elements
265        .iter()
266        .filter_map(|name| mapping::resolve_element(scene, name).ok())
267        .collect();
268    if resolved.len() != elements.len() || resolved.is_empty() {
269        return row;
270    }
271    let object = row.as_object_mut().expect("row is an object");
272    object.insert(
273        "anchors".into(),
274        serde_json::Value::Array(
275            resolved
276                .iter()
277                .map(|element| {
278                    let p = element.world.representative_point();
279                    serde_json::json!([p.x, p.y, p.z])
280                })
281                .collect(),
282        ),
283    );
284    object.insert(
285        "directions".into(),
286        serde_json::Value::Array(
287            resolved
288                .iter()
289                .map(|element| match mapping::direction_of(&element.world) {
290                    Some(direction) => serde_json::json!([direction.x, direction.y, direction.z]),
291                    None => serde_json::Value::Null,
292                })
293                .collect(),
294        ),
295    );
296    // Per-element geometry class, aligned index-wise with anchors/directions —
297    // the render-side distance-arrow builder needs to identify the BASE PLANE
298    // (the perpendicular-foot construction); a direction alone is ambiguous
299    // (lines and circles carry one too).
300    object.insert(
301        "geoms".into(),
302        serde_json::Value::Array(
303            resolved
304                .iter()
305                .map(|element| serde_json::json!(geometry_tag(&element.world)))
306                .collect(),
307        ),
308    );
309    // Measured value/target via the mapper on a THROWAWAY clone (the mapper
310    // maintains the orientation-preference cache; an overlay read must not
311    // mutate persisted state).
312    if resolved.len() == 2 {
313        let mut scratch = entry.clone();
314        if let Ok(mapped) = mapping::map_constraint(&mut scratch, &resolved[0], &resolved[1], env) {
315            if let Some((value, unit)) = mapped.measured {
316                object.insert("value".into(), serde_json::json!(value));
317                object.insert("unit".into(), serde_json::json!(unit));
318            }
319            if let Some(target) = mapped.target {
320                object.insert("target".into(), serde_json::json!(target));
321            }
322        }
323    }
324    row
325}
326
327/// The coarse geometry class of a resolved selection (the overlay row's
328/// `geoms` vocabulary — lowercase `SelectionGeometry` variant names).
329fn geometry_tag(geometry: &crate::SelectionGeometry) -> &'static str {
330    match geometry {
331        crate::SelectionGeometry::Plane { .. } => "plane",
332        crate::SelectionGeometry::Line { .. } => "line",
333        crate::SelectionGeometry::Axis { .. } => "axis",
334        crate::SelectionGeometry::Circle { .. } => "circle",
335        crate::SelectionGeometry::Sphere { .. } => "sphere",
336        crate::SelectionGeometry::Point { .. } => "point",
337    }
338}
339
340// ===========================================================================
341// Mutation surface (spec §6 scheduling: every mutation auto-solves)
342// ===========================================================================
343
344/// Add a constraint of `constraint_type` with the given `inputParams` JSON
345/// (elements etc.; `id` is minted from the type's short name + the persistent
346/// counter when absent). Auto-solves; returns `{id, report}`.
347#[wasm_bindgen]
348pub fn assembly_add_constraint_json(
349    constraint_type: &str,
350    params_json: &str,
351) -> Result<String, JsValue> {
352    add_constraint(constraint_type, params_json).map_err(|error| JsValue::from_str(&error))
353}
354
355fn add_constraint(constraint_type: &str, params_json: &str) -> Result<String, String> {
356    let def = constraints::constraint_type(constraint_type)
357        .ok_or_else(|| format!("Unknown constraint type: {constraint_type}"))?;
358    let mut params: serde_json::Value = serde_json::from_str(params_json)
359        .map_err(|error| format!("constraint params: {error}"))?;
360    if !params.is_object() {
361        return Err("constraint params must be a JSON object".to_string());
362    }
363    with_session(|session| {
364        let id = match params.get("id").and_then(|value| value.as_str()) {
365            Some(id) if !id.is_empty() => id.to_string(),
366            _ => {
367                session.state.id_counter += 1;
368                let id = format!("{}{}", def.short_name, session.state.id_counter);
369                params
370                    .as_object_mut()
371                    .expect("checked object above")
372                    .insert("id".into(), serde_json::Value::String(id.clone()));
373                id
374            }
375        };
376        session.state.constraints.push(ConstraintEntry {
377            constraint_type: constraint_type.to_string(),
378            input_params: params.clone(),
379            persistent_data: serde_json::Value::Object(serde_json::Map::new()),
380            enabled: true,
381            open: true,
382        });
383        let report = solve_session(session);
384        Ok(serde_json::json!({ "id": id, "report": report }).to_string())
385    })
386}
387
388/// Replace a constraint's `inputParams` (the dialog commit). Auto-solves;
389/// returns the solve report.
390#[wasm_bindgen]
391pub fn assembly_update_constraint_json(id: &str, params_json: &str) -> Result<String, JsValue> {
392    update_constraint(id, params_json).map_err(|error| JsValue::from_str(&error))
393}
394
395fn update_constraint(id: &str, params_json: &str) -> Result<String, String> {
396    let mut params: serde_json::Value = serde_json::from_str(params_json)
397        .map_err(|error| format!("constraint params: {error}"))?;
398    if !params.is_object() {
399        return Err("constraint params must be a JSON object".to_string());
400    }
401    if params.get("id").and_then(|value| value.as_str()).is_none() {
402        params
403            .as_object_mut()
404            .expect("checked object above")
405            .insert("id".into(), serde_json::Value::String(id.to_string()));
406    }
407    with_session(|session| {
408        let entry = find_entry(session, id)?;
409        entry.input_params = params.clone();
410        Ok(solve_session(session).to_string())
411    })
412}
413
414/// Delete a constraint. Auto-solves; returns the solve report.
415#[wasm_bindgen]
416pub fn assembly_remove_constraint_json(id: &str) -> Result<String, JsValue> {
417    remove_constraint(id).map_err(|error| JsValue::from_str(&error))
418}
419
420fn remove_constraint(id: &str) -> Result<String, String> {
421    with_session(|session| {
422        let index = find_index(session, id)?;
423        session.state.constraints.remove(index);
424        Ok(solve_session(session).to_string())
425    })
426}
427
428/// Enable/disable a constraint. Auto-solves; returns the solve report.
429#[wasm_bindgen]
430pub fn assembly_set_constraint_enabled_json(id: &str, enabled: bool) -> Result<String, JsValue> {
431    set_enabled(id, enabled).map_err(|error| JsValue::from_str(&error))
432}
433
434fn set_enabled(id: &str, enabled: bool) -> Result<String, String> {
435    with_session(|session| {
436        find_entry(session, id)?.enabled = enabled;
437        Ok(solve_session(session).to_string())
438    })
439}
440
441/// Persist a constraint row's dialog expansion state (view state — no solve).
442#[wasm_bindgen]
443pub fn assembly_set_constraint_open_json(id: &str, open: bool) -> Result<(), JsValue> {
444    with_session(|session| {
445        find_entry(session, id)?.open = open;
446        Ok(())
447    })
448    .map_err(|error| JsValue::from_str(&error))
449}
450
451/// Reorder a constraint to `index` (clamped). Auto-solves; returns the report.
452#[wasm_bindgen]
453pub fn assembly_move_constraint_json(id: &str, index: usize) -> Result<String, JsValue> {
454    move_constraint(id, index).map_err(|error| JsValue::from_str(&error))
455}
456
457fn move_constraint(id: &str, index: usize) -> Result<String, String> {
458    with_session(|session| {
459        let from = find_index(session, id)?;
460        let entry = session.state.constraints.remove(from);
461        let to = index.min(session.state.constraints.len());
462        session.state.constraints.insert(to, entry);
463        Ok(solve_session(session).to_string())
464    })
465}
466
467/// Manual solve (the panel's Solve button). Returns the solve report.
468#[wasm_bindgen]
469pub fn assembly_run_solve_json() -> Result<String, JsValue> {
470    with_session(|session| Ok(solve_session(session).to_string()))
471        .map_err(|error| JsValue::from_str(&error))
472}
473
474fn find_index(session: &Session, id: &str) -> Result<usize, String> {
475    session
476        .state
477        .constraints
478        .iter()
479        .position(|entry| entry.id() == id)
480        .ok_or_else(|| format!("unknown constraint '{id}'"))
481}
482
483fn find_entry<'a>(session: &'a mut Session, id: &str) -> Result<&'a mut ConstraintEntry, String> {
484    let index = find_index(session, id)?;
485    Ok(&mut session.state.constraints[index])
486}