brep_kernel/feature_pipeline/features/import3d.rs
1//! IMPORT3D — Import 3D Model (STEP). Ported from the retired `Import3dModelFeature`.
2//!
3//! Three headless sources, tried in order:
4//! 0. **`inputParams.nativeBrep`** — a native [`crate::snapshot_solids`] payload
5//! (`io/snapshot.rs`): the exact solids of an earlier import, already carrying
6//! their final IMPORT3D names. Tried FIRST and EXCLUSIVE — a feature carrying
7//! it must not also carry `stepText`/`igesText` (an error, not a precedence
8//! puzzle). The solids register VERBATIM under their stored names: re-deriving
9//! them would break every scene-metadata record and every constraint keyed to a
10//! face name. This is the lane a STEP-assembly part document rides on, and the
11//! reason the snapshot container is a DURABLE format, not a cache (§6 there,
12//! and the `io/snapshot.rs` module doc).
13//! 1. **`inputParams.stepText`** — the raw ISO-10303-21 document, baked in by the
14//! toolbar Import lane ([`crate`]'s host: `EngineState::import_step_feature`).
15//! Runs the exact Rust STEP importer
16//! ([`crate::import_step_with_appearance`] — the colour-carrying form).
17//! 2. **`persistentData.importCache`** (`kind == "step-brep"`) — SUPERSEDED by
18//! `nativeBrep`. The JS-era persisted EXACT BREP records of a previous import
19//! (`serializeBrepSolid` was the serde `BrepSolid` JSON, so records deserialize
20//! directly) — verbose and unversioned. NOTHING in the Rust tree writes it; the
21//! reader stays only so a JS-era saved model still opens. New payloads go in
22//! `nativeBrep`.
23//!
24//! Name fidelity (contract rule 2, byte-matching `Import3dModelFeature`):
25//! - Body names (`importedSolidNames`): a single body keeps the feature name;
26//! several get `{feature}_SOLID_{N}` with N 1-based, zero-padded to
27//! `max(2, digits(count))`.
28//! - Faces (`importedBodyFaceNames` / the single-body fallback): a MULTI-body
29//! import names EVERY face `{bodyName}_Face_{f}` positionally (shell/face
30//! order) so faces stay unique across bodies; a SINGLE body prepends the
31//! (unique) feature name — `{feature}_{stepName}`, or `{feature}_Face_{f}` where
32//! the STEP file left the face unnamed — so two separate imports never share a
33//! face name (the cross-solid name-uniqueness guard's collision class). Edge
34//! names re-derive from the face names, so the derived edges are namespaced too.
35//!
36//! COLOUR rides the same names. What a STEP file's presentation entities assign
37//! (`io/step_import/styles.rs`) is stamped here as a `{"color": "#RRGGBB"}`
38//! scene-metadata record on the FINAL body/face names — see `io/appearance.rs`
39//! for the convention, [`stamp_appearance`] for the write, and
40//! [`native_import_payload_with_appearance`] for the lane that seals it into a
41//! part payload. The stamp is a NON-overwriting merge, so a colour edited in the
42//! caller's info panel survives a history replay.
43//!
44//! ONE convention, ONE implementation: [`stamp_imported_names`] holds it, and
45//! every lane that names imported bodies goes through it — the live import lanes
46//! (via [`add_named_bodies`]) and the payload encoder [`native_import_payload`].
47//! Names are stamped ONCE, at import, and then frozen in the payload; a later
48//! change here does NOT retro-rename already-imported parts, which is the point
49//! (a constraint keyed to a face name survives reload).
50//!
51//! The failed-import base64 retry lane (`persistentData.failedImportFile`) is
52//! not yet migrated — it errors loudly rather than silently skipping.
53
54use crate::feature_pipeline::features::common;
55use crate::feature_pipeline::{scene_metadata, AddedSolid, FeatureContext, FeatureResult};
56use crate::{
57 import_iges, import_step_with_appearance, restore_solids, BodyAppearance, BrepSolid,
58 ImportedColor, COLOR_METADATA_KEY,
59};
60
61pub fn execute(ctx: &FeatureContext) -> FeatureResult {
62 match build(ctx) {
63 Ok(result) => result,
64 Err(error) => ctx.fail(error),
65 }
66}
67
68fn build(ctx: &FeatureContext) -> Result<FeatureResult, String> {
69 let feature_name = if ctx.id.is_empty() {
70 "IMPORT3D".to_string()
71 } else {
72 ctx.id.clone()
73 };
74
75 // 0. Native payload — the exact solids of an earlier import, names frozen in.
76 // EXCLUSIVE by design (see the module doc): a document carrying both this
77 // and a text source is malformed, and answering it with a precedence rule
78 // would silently drop one of the two. Keyed on PRESENCE, not on a
79 // successful `as_str`, so a non-string `nativeBrep` errors here instead of
80 // falling through to a different source.
81 if let Some(native) = ctx.param("nativeBrep").filter(|value| !value.is_null()) {
82 if ctx.param("stepText").is_some() || ctx.param("igesText").is_some() {
83 return Err(
84 "import3d: `nativeBrep` is exclusive — a feature carrying it must not also carry `stepText`/`igesText`"
85 .into(),
86 );
87 }
88 let payload = native
89 .as_str()
90 .ok_or("import3d: param `nativeBrep` must be a base64 snapshot string")?;
91 return restore_native_bodies(ctx, payload);
92 }
93
94 // 1. Fresh STEP text (baked into `stepText` by the toolbar Import lane).
95 if let Some(step_text) = ctx.param("stepText").and_then(|v| v.as_str()) {
96 if step_text.contains("ISO-10303-21") {
97 let (solids, appearances) = import_step_with_appearance(step_text)
98 .map_err(|error| format!("import3d: STEP import failed: {error}"))?;
99 if solids.is_empty() {
100 return Err("import3d: STEP file contained no importable solids".into());
101 }
102 return Ok(add_named_bodies(ctx, solids, &appearances, &feature_name));
103 }
104 return Err(
105 "import3d: only STEP (ISO-10303-21) files are supported (STL/3MF mesh import was removed)"
106 .into(),
107 );
108 }
109
110 // 1b. Fresh IGES text (baked into `igesText` by the toolbar Import lane).
111 if let Some(iges_text) = ctx.param("igesText").and_then(|v| v.as_str()) {
112 let solids = import_iges(iges_text)
113 .map_err(|error| format!("import3d: IGES import failed: {error}"))?;
114 if solids.is_empty() {
115 return Err("import3d: IGES file contained no importable solids".into());
116 }
117 return Ok(add_named_bodies(ctx, solids, &[], &feature_name));
118 }
119
120 // 2. Persisted exact-BREP records from a previous import.
121 let cache = ctx.persistent.get("importCache");
122 if let Some(cache) = cache {
123 let kind = cache.get("kind").and_then(|v| v.as_str()).unwrap_or("");
124 if kind == "step-brep" {
125 let records = cache
126 .get("kernelSolidRecords")
127 .and_then(|v| v.as_array())
128 .ok_or("import3d: importCache has no kernelSolidRecords")?;
129 let mut solids = Vec::with_capacity(records.len());
130 for (index, record) in records.iter().enumerate() {
131 let solid: BrepSolid = serde_json::from_value(record.clone()).map_err(|error| {
132 format!("import3d: kernel record {index} failed to deserialize: {error}")
133 })?;
134 solids.push(solid);
135 }
136 if solids.is_empty() {
137 return Err("import3d: importCache is empty".into());
138 }
139 return Ok(add_named_bodies(ctx, solids, &[], &feature_name));
140 }
141 return Err(format!(
142 "import3d: unsupported importCache kind '{kind}' (only 'step-brep')"
143 ));
144 }
145
146 // A failed-import retry payload without a cache is a not-yet-migrated lane.
147 if ctx.persistent.get("failedImportFile").is_some() {
148 return Err(
149 "import3d: the failed-import base64 retry lane is not yet migrated to the Rust pipeline"
150 .into(),
151 );
152 }
153
154 Err(
155 "import3d: no model data (no `nativeBrep`/`stepText` param and no `importCache`)".into(),
156 )
157}
158
159/// Restore a native payload and register its solids VERBATIM — the `nativeBrep`
160/// lane. Nothing about the names is re-derived: they were stamped once, when the
161/// geometry was first imported, and every scene-metadata record and every
162/// constraint attached to a face is keyed to exactly those strings. (This is
163/// `component::create_component`'s phase 2 for the same reason — see its module
164/// doc: "do not `fix` this by routing members through `register_added`".)
165///
166/// The payload's captured metadata records are merged back into the scene store
167/// UN-namespaced, exactly as they were captured: an IMPORT3D feature is not a
168/// component boundary, so there is no instance prefix to apply. The ACOMP lane
169/// namespaces on insert if this document is later used as a part.
170fn restore_native_bodies(ctx: &FeatureContext, payload: &str) -> Result<FeatureResult, String> {
171 let restored = restore_solids(payload)
172 .map_err(|error| format!("import3d: native payload did not decode: {error}"))?;
173 if restored.solids.is_empty() {
174 return Err("import3d: native payload contained no solids".into());
175 }
176 let mut result = FeatureResult::empty(ctx.id.clone(), ctx.feature_type.clone());
177 for solid in restored.solids {
178 result.added.push(register_verbatim(solid.solid, &solid.name));
179 }
180 // Overwriting: the payload's records ARE the part's metadata. The pipeline's
181 // own `sourceFeatureId` seed runs after this feature returns and is
182 // NON-overwriting, so a face keeps the producing-feature id it was imported
183 // with rather than picking up this feature's.
184 for (name, record) in restored.metadata {
185 scene_metadata::merge_record(&name, &record, true);
186 }
187 Ok(result)
188}
189
190/// [`common::register_added`] WITHOUT its two name-deriving passes: collect the
191/// names the solid already carries and make it scene-resident.
192///
193/// The container groups are EMPTY, and that is the right answer rather than a
194/// stub: a group is the un-keyed alias a PROFILE-SWEPT feature publishes for its
195/// per-loop face families (`{cap_base}_START` standing for every
196/// `{cap_base}:L{id}_START` — see [`common::register_added_grouped`]). Imported
197/// geometry has no sketch loops behind it, so there is no family to alias; its
198/// names arrived stamped from outside and are already the final, unique ones.
199fn register_verbatim(solid: BrepSolid, name: &str) -> AddedSolid {
200 let face_names = common::collect_face_names(&solid);
201 let edge_names = common::collect_edge_names(&solid);
202 let handle = crate::register_solid_value(solid);
203 AddedSolid {
204 handle,
205 name: name.to_string(),
206 face_names,
207 edge_names,
208 face_groups: Vec::new(),
209 edge_groups: Vec::new(),
210 }
211}
212
213/// Stamp the established naming convention onto the imported bodies, register
214/// them, and stamp whatever COLOUR the file carried onto those same names.
215///
216/// `appearances` is parallel to `solids` (see [`crate::BodyAppearance`]); pass
217/// `&[]` from a lane whose format has no colour, which stamps nothing.
218fn add_named_bodies(
219 ctx: &FeatureContext,
220 mut solids: Vec<BrepSolid>,
221 appearances: &[BodyAppearance],
222 feature_name: &str,
223) -> FeatureResult {
224 let body_names = stamp_imported_names(&mut solids, feature_name);
225 let mut result = FeatureResult::empty(ctx.id.clone(), ctx.feature_type.clone());
226 for (index, (solid, body_name)) in solids.into_iter().zip(body_names).enumerate() {
227 // Colour is stamped AFTER `register_added`, which is where the names
228 // become final (it dedupes face names before deriving the edge names).
229 let added = common::register_added(solid, &body_name);
230 if let Some(appearance) = appearances.get(index) {
231 stamp_appearance(&added.name, &added.face_names, appearance);
232 }
233 result.added.push(added);
234 }
235 result
236}
237
238/// Write an imported body's colours into the scene-metadata store, keyed by the
239/// FINAL names — the one place the `{"color": "#RRGGBB"}` convention of
240/// `io/appearance.rs` is written.
241///
242/// `face_names` is `(face_id, name)` in shell/face order
243/// ([`common::collect_face_names`]), the same order `appearance.faces` is
244/// indexed by. A length disagreement means the two walks have drifted, so
245/// nothing per-face is stamped rather than colouring the wrong faces — the body
246/// colour, which is not positional, still lands.
247///
248/// Merged NON-overwriting: a history replay re-runs this feature, and a colour
249/// the user has since edited in the info panel must survive it.
250fn stamp_appearance(body_name: &str, face_names: &[(u64, String)], appearance: &BodyAppearance) {
251 if let Some(color) = appearance.body {
252 stamp_color(body_name, color);
253 }
254 if appearance.faces.is_empty() || appearance.faces.len() != face_names.len() {
255 return;
256 }
257 for ((_, face_name), color) in face_names.iter().zip(&appearance.faces) {
258 if let Some(color) = color {
259 stamp_color(face_name, *color);
260 }
261 }
262}
263
264fn stamp_color(name: &str, color: ImportedColor) {
265 let mut record = serde_json::Map::new();
266 record.insert(
267 COLOR_METADATA_KEY.to_string(),
268 serde_json::Value::String(color.to_hex()),
269 );
270 scene_metadata::merge_record(name, &record, false);
271}
272
273/// The naming half of [`add_named_bodies`]: stamp body + face names onto `solids`
274/// IN PLACE and return the body name chosen for each, WITHOUT registering
275/// anything. Shared by the live import lanes and the payload encoder
276/// [`native_import_payload`], so an imported part is named identically however it
277/// arrived.
278fn stamp_imported_names(solids: &mut [BrepSolid], feature_name: &str) -> Vec<String> {
279 let body_names = imported_solid_names(solids.len(), feature_name);
280 let multi_body = solids.len() > 1;
281 let mut chosen = Vec::with_capacity(solids.len());
282 for (index, solid) in solids.iter_mut().enumerate() {
283 let body_name = body_names
284 .get(index)
285 .cloned()
286 .unwrap_or_else(|| feature_name.to_string());
287 let mut face_index = 0usize;
288 for shell in &mut solid.shells {
289 for face in &mut shell.faces {
290 if multi_body {
291 // Multi-body: EVERY face namespaced under its body.
292 face.name = Some(format!("{body_name}_Face_{face_index}"));
293 } else {
294 // Single body: prepend the (unique) feature name so faces never
295 // collide with ANOTHER import's faces — two single-body imports
296 // both stamped bare `Face_N` before, which the cross-solid
297 // name-uniqueness guard flags. Keep any STEP-authored name as the
298 // stem, else the positional `Face_N` fallback. (`body_name` IS the
299 // feature name here — see `imported_solid_names`.) Edge names are
300 // re-derived from these face names downstream, so namespacing the
301 // faces namespaces the derived edges too.
302 let stem = face
303 .name
304 .as_deref()
305 .map(str::trim)
306 .filter(|name| !name.is_empty())
307 .map(str::to_string)
308 .unwrap_or_else(|| format!("Face_{face_index}"));
309 face.name = Some(format!("{body_name}_{stem}"));
310 }
311 face_index += 1;
312 }
313 }
314 chosen.push(body_name);
315 }
316 chosen
317}
318
319/// `importedSolidNames` port: 1 body keeps the feature name; several get a
320/// stable, zero-padded `{feature}_SOLID_0N` suffix.
321pub(crate) fn imported_solid_names(count: usize, feature_name: &str) -> Vec<String> {
322 if count == 0 {
323 return Vec::new();
324 }
325 if count == 1 {
326 return vec![feature_name.to_string()];
327 }
328 let digits = count.to_string().len().max(2);
329 (1..=count)
330 .map(|index| format!("{feature_name}_SOLID_{index:0width$}", width = digits))
331 .collect()
332}
333
334/// Encode `solids` as a native IMPORT3D payload: stamp the names this feature
335/// would stamp under `feature_name`, then seal them into the `io/snapshot`
336/// container. The result is exactly what the `nativeBrep` source above reads
337/// back, so a part is named identically however it arrived — imported live from
338/// a text source, or restored from a payload built here.
339///
340/// GENERIC, not STEP-specific: any producer of finished `BrepSolid`s that wants
341/// them to become an IMPORT3D part document uses this (the STEP-assembly import
342/// lane is the first caller).
343///
344/// The two passes after the stamping are `register_added`'s name-FINALIZING half
345/// ([`common::ensure_unique_face_names`] + [`common::stamp_derived_edge_names`]),
346/// applied HERE rather than at restore time: the `nativeBrep` lane registers
347/// verbatim, so whatever the payload carries IS the final name set. Without them
348/// a payload's edge names would be the importer's raw ones while the `stepText`
349/// lane's are the derived `{faceA}|{faceB}[n]` — the same geometry under two
350/// different name sets, which is exactly what this helper exists to prevent.
351///
352/// The payload is byte-deterministic for identical input (`snapshot_solids`), so
353/// two encodings of the same part collapse to ONE parts-library entry.
354pub fn native_import_payload(feature_name: &str, solids: &[BrepSolid]) -> Result<String, String> {
355 native_import_payload_with_appearance(feature_name, solids, &[])
356}
357
358/// [`native_import_payload`] carrying the import's COLOURS into the payload.
359///
360/// `appearances` is parallel to `solids` (see [`crate::BodyAppearance`]); `&[]`
361/// is the colourless case and makes this identical to [`native_import_payload`].
362///
363/// The colours are stamped into the AMBIENT scene-metadata store just before
364/// `snapshot_solids`, which is exactly how they get INTO the payload — the
365/// snapshot captures each stamped name's own record alongside the geometry. So a
366/// caller that runs this inside a `crate::IsolatedSceneMetadata` bracket (the
367/// STEP-assembly part-document lane does, and must) gets the colours sealed into
368/// the part and discarded from the live document, which is the whole point of
369/// that bracket: the part carries its own metadata, the open document is not
370/// touched.
371pub fn native_import_payload_with_appearance(
372 feature_name: &str,
373 solids: &[BrepSolid],
374 appearances: &[BodyAppearance],
375) -> Result<String, String> {
376 if solids.is_empty() {
377 return Err("import3d: native payload needs at least one solid".into());
378 }
379 let mut bodies = solids.to_vec();
380 let body_names = stamp_imported_names(&mut bodies, feature_name);
381 for solid in &mut bodies {
382 common::ensure_unique_face_names(solid);
383 common::stamp_derived_edge_names(solid);
384 }
385 // Names are FINAL from here, so this is where colour can be keyed to them.
386 for (index, (solid, body_name)) in bodies.iter().zip(&body_names).enumerate() {
387 if let Some(appearance) = appearances.get(index) {
388 stamp_appearance(body_name, &common::collect_face_names(solid), appearance);
389 }
390 }
391 let named: Vec<(&str, &BrepSolid)> = body_names
392 .iter()
393 .map(String::as_str)
394 .zip(bodies.iter())
395 .collect();
396 crate::snapshot_solids(&named)
397}
398
399
400/// Context-bar applicability ([`crate::feature_pipeline::context_offer`]):
401/// never offered from a selection (no reference inputs).
402pub fn context_applicable(_probe: &crate::feature_pipeline::SelectionProbe) -> bool {
403 false
404}
405
406///
407/// Only `id` is exposed: an IMPORT3D feature is created by an import lane that
408/// bakes its payload in — the toolbar Import lane
409/// ([`EngineState::import_step_feature`] / `import_iges_feature`) writes the raw
410/// document text into `inputParams.stepText` / `igesText`, and the native lane
411/// ([`native_import_payload`], the STEP-assembly part document) writes
412/// `inputParams.nativeBrep`. None of the three is form-editable, so none is
413/// exposed. (The former `fileToImport` "file" param was a JS-era vestige: nothing
414/// produced or consumed it and no form builder rendered it.)
415pub fn schema() -> serde_json::Value {
416 serde_json::json!({
417 "type": "IMPORT3D",
418 "shortName": "IMPORT3D",
419 "longName": "Import 3D Model",
420 "displayBuilder": false,
421 "inputParamsSchema": {
422 "id": {
423 "type": "string",
424 "default_value": null,
425 "hint": "unique identifier for the import feature"
426 }
427 }
428})
429}
430