Skip to main content

brep_kernel/io/solidworks/
mod.rs

1//! SolidWorks parts (`.sldprt`) and assemblies (`.sldasm`): import.
2//!
3//! A SolidWorks part keeps each configuration's body as a Parasolid partition
4//! in neutral binary (`Contents/Config-N-Partition`): a section of zlib
5//! chunks, then the partition's rollback deltas. The file around it is an OLE
6//! compound document (SolidWorks before 2015) or SolidWorks' own container
7//! (2015 and later: a ZIP-like archive with rotated stream names and raw
8//! DEFLATE). Import finds the partition and reads it with the Parasolid
9//! reader; nothing else in the file is needed.
10//!
11//! An assembly keeps no bodies: `swXmlContents/COMPINSTANCETREE` lists the
12//! files it uses, their models (file and configuration) and each instance
13//! (`swReference`) with its placement. `swTransform` is a row-vector matrix in
14//! metres: p' = p R + t, the rotation's rows first and the translation last
15//! (PSAS's canard machining assembly, exported by SolidWorks both as an
16//! assembly and as a Parasolid assembly, agrees so to 1e-14; read as columns
17//! it misses by 67 mm).
18//!
19//! Container notes: blussyya/sldprt-format-research (CC-BY-SA-4.0) and the
20//! OLE compound file format ([MS-CFB]).
21
22use crate::parasolid::ParasolidImportReport;
23
24mod container;
25
26
27pub use container::solidworks_streams;
28
29/// The partition of each configuration of a SolidWorks part, `Config-0` first.
30pub fn solidworks_part_partitions(bytes: &[u8]) -> Result<Vec<(String, Vec<u8>)>, String> {
31    let streams = solidworks_streams(bytes, &|name: &str| name.starts_with("Contents/Config-") && name.ends_with("-Partition") && !name.ends_with("GhostPartition"))?;
32    let mut out = Vec::new();
33    for (name, data) in streams {
34        let config = name.trim_start_matches("Contents/").trim_end_matches("-Partition").to_string();
35        let partition = first_section(&data).map_err(|e| format!("{name}: {e}"))?;
36        out.push((config, partition));
37    }
38    out.sort_by_key(|(config, _)| config.trim_start_matches("Config-").parse::<u32>().unwrap_or(u32::MAX));
39    if out.is_empty() {
40        return Err("the part holds no body (no Config-N-Partition stream)".into());
41    }
42    Ok(out)
43}
44
45/// The first section of a partition stream: a four-byte size, a 16-byte
46/// identifier, zlib chunks (each a four-byte uncompressed and compressed
47/// length, then the zlib data) and eight zero bytes. The partition's data is
48/// the chunks' concatenation; the sections after it are its rollback deltas.
49fn first_section(data: &[u8]) -> Result<Vec<u8>, String> {
50    let u32_at = |at: usize| data.get(at..at + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize).ok_or("the partition stream is cut short");
51    let size = u32_at(0)?;
52    let end = 4 + size;
53    if end > data.len() {
54        return Err(format!("its first section claims {size} bytes of {}", data.len()));
55    }
56    let mut at = 20;
57    let mut out = Vec::new();
58    while at + 8 <= end.saturating_sub(8) {
59        let (full, packed) = (u32_at(at)?, u32_at(at + 4)?);
60        if out.len() + full > MAX_PARTITION {
61            return Err(format!("the partition would be larger than {MAX_PARTITION} bytes"));
62        }
63        let chunk = data.get(at + 8..at + 8 + packed).ok_or("a chunk runs past its section")?;
64        out.extend(zlib(chunk, full)?);
65        at += 8 + packed;
66    }
67    Ok(out)
68}
69
70/// The bound on a partition's size: far above any part's body, and what a
71/// chunk's stated length may never take the total past.
72const MAX_PARTITION: usize = 1 << 30;
73
74/// A zlib stream (RFC 1950): a two-byte header, raw DEFLATE, then the
75/// Adler-32 of the data, which is checked.
76pub(crate) fn zlib(chunk: &[u8], expected: usize) -> Result<Vec<u8>, String> {
77    if expected > MAX_PARTITION {
78        return Err(format!("a chunk states {expected} bytes"));
79    }
80    if chunk.len() < 2 || chunk[0] & 0x0f != 8 || (u16::from(chunk[0]) << 8 | u16::from(chunk[1])) % 31 != 0 {
81        return Err("a chunk is not zlib data".into());
82    }
83    let out = crate::three_mf::inflate::inflate(&chunk[2..], expected.max(1)).map_err(|e| format!("a zlib chunk: {e}"))?;
84    if out.len() != expected {
85        return Err(format!("a chunk inflates to {} bytes, not the {expected} it states", out.len()));
86    }
87    // The checksum follows the DEFLATE data at the stream's end.
88    if let Some(tail) = chunk.len().checked_sub(4).and_then(|at| chunk.get(at..)) {
89        let stated = u32::from_be_bytes([tail[0], tail[1], tail[2], tail[3]]);
90        if adler32(&out) != stated {
91            return Err("a zlib chunk's checksum does not match its data".into());
92        }
93    }
94    Ok(out)
95}
96
97fn adler32(data: &[u8]) -> u32 {
98    let (mut a, mut b) = (1u32, 0u32);
99    for chunk in data.chunks(5552) {
100        for &x in chunk {
101            a += u32::from(x);
102            b += a;
103        }
104        a %= 65521;
105        b %= 65521;
106    }
107    b << 16 | a
108}
109
110/// The configuration a sub-assembly's instance tree was recorded for (its
111/// most recent one), when it says.
112fn recorded_configuration(bytes: &[u8]) -> Result<Option<u32>, String> {
113    let xml = instance_tree_xml(bytes)?;
114    Ok(elements(&xml, "swConfiguration")
115        .into_iter()
116        .find(|c| c.get("swMostRecentConfiguration").as_deref() == Some("YES"))
117        .and_then(|c| c.get("swID"))
118        .and_then(|id| id.parse().ok()))
119}
120
121/// A SolidWorks part's body (its first configuration), as the Parasolid
122/// import reads it. The other configurations are named in the error when
123/// there is more than one, so a caller can say which was taken.
124pub fn import_solidworks_part_report(bytes: &[u8]) -> Result<ParasolidImportReport, String> {
125    let partitions = solidworks_part_partitions(bytes).map_err(|e| format!("solidworks_import: {e}"))?;
126    crate::parasolid::import_parasolid_bytes_report(&partitions[0].1).map_err(|e| format!("solidworks_import: {}: {e}", partitions[0].0))
127}
128
129/// One instance an assembly places.
130#[derive(Clone, Debug, PartialEq)]
131pub struct SwComponent {
132    /// The instance's name in the assembly.
133    pub name: String,
134    /// The file it uses, as the assembly stored it (often an absolute
135    /// Windows path), and that file's base name.
136    pub path: String,
137    pub file_name: String,
138    /// Whether the file is a sub-assembly.
139    pub assembly: bool,
140    /// The configuration the instance uses: its index (`Config-N`) and name.
141    pub configuration: u32,
142    pub configuration_name: String,
143    /// Where the instance goes: row-major 4×4, mm.
144    pub transform: crate::Mat4,
145    pub suppressed: bool,
146}
147
148/// The instances a SolidWorks assembly places, from its instance tree.
149pub fn solidworks_assembly_components(bytes: &[u8]) -> Result<Vec<SwComponent>, String> {
150    parse_instance_tree(&instance_tree_xml(bytes)?)
151}
152
153/// The instance tree's XML.
154fn instance_tree_xml(bytes: &[u8]) -> Result<String, String> {
155    let streams = solidworks_streams(bytes, &|name: &str| name.starts_with("swXmlContents/COMPINSTANCETREE"))?;
156    let (name, data) = streams.into_iter().next().ok_or("the assembly has no instance tree (swXmlContents/COMPINSTANCETREE)")?;
157    let xml = if data.starts_with(b"<?xml") || data.starts_with(b"<sw") {
158        data
159    } else {
160        // `__ZLB`: a 16-byte identifier, the uncompressed and compressed
161        // lengths, then zlib.
162        let u32_at = |at: usize| data.get(at..at + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize).ok_or("the instance tree is cut short");
163        let (full, packed) = (u32_at(16)?, u32_at(20)?);
164        zlib(data.get(24..24 + packed).ok_or("the instance tree is cut short")?, full).map_err(|e| format!("{name}: {e}"))?
165    };
166    Ok(String::from_utf8_lossy(&xml).into_owned())
167}
168
169fn parse_instance_tree(xml: &str) -> Result<Vec<SwComponent>, String> {
170    let files: Vec<Element> = elements(xml, "swFile");
171    let models: Vec<Element> = elements(xml, "swModel");
172    let mut out = Vec::new();
173    for reference in elements(xml, "swReference") {
174        let model = models
175            .iter()
176            .find(|m| m.get("id") == reference.get("swModelRef"))
177            .ok_or_else(|| format!("instance {} names no model", reference.get("swName").unwrap_or_default()))?;
178        let file = files
179            .iter()
180            .find(|f| f.get("id") == model.get("swFileRef"))
181            .ok_or_else(|| format!("model {} names no file", model.get("swName").unwrap_or_default()))?;
182        let path = file.get("swPath").unwrap_or_default();
183        let numbers: Vec<f64> = reference
184            .get("swTransform")
185            .unwrap_or_default()
186            .split_whitespace()
187            .map(|t| t.parse::<f64>().map_err(|_| format!("a transform holds {t:?}")))
188            .collect::<Result<_, _>>()?;
189        if numbers.len() != 16 {
190            return Err(format!("instance {} has a transform of {} numbers", reference.get("swName").unwrap_or_default(), numbers.len()));
191        }
192        let s = &numbers;
193        if s[3] != 0.0 || s[7] != 0.0 || s[11] != 0.0 {
194            return Err("an instance's transform has a perspective part".into());
195        }
196        let scale = if s[15] != 0.0 { 1.0 / s[15] } else { return Err("an instance's transform has a zero weight".into()) };
197        let mm = 1000.0;
198        // p' = p R + t (rows): the column form takes R transposed.
199        let transform = [
200            s[0], s[4], s[8], s[12] * mm * scale,
201            s[1], s[5], s[9], s[13] * mm * scale,
202            s[2], s[6], s[10], s[14] * mm * scale,
203            0.0, 0.0, 0.0, 1.0,
204        ];
205        let file_name = path.rsplit(['\\', '/']).next().unwrap_or(&path).to_string();
206        out.push(SwComponent {
207            name: reference.get("swName").unwrap_or_default(),
208            assembly: file.get("swDocType").as_deref() == Some("ASSEMBLY"),
209            path,
210            file_name,
211            configuration: model.get("swConfigurationId").and_then(|c| c.parse().ok()).unwrap_or(0),
212            configuration_name: model.get("swConfigurationName").unwrap_or_default(),
213            transform,
214            suppressed: reference.get("swSuppressed").as_deref() == Some("YES"),
215        });
216    }
217    Ok(out)
218}
219
220/// An element's attributes, from its start tag.
221struct Element(Vec<(String, String)>);
222
223impl Element {
224    fn get(&self, key: &str) -> Option<String> {
225        self.0.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone())
226    }
227}
228
229/// The start tags `<tag ...>` of `xml`, attributes unescaped.
230fn elements(xml: &str, tag: &str) -> Vec<Element> {
231    let open = format!("<{tag} ");
232    let mut out = Vec::new();
233    let mut rest = xml;
234    while let Some(at) = rest.find(&open) {
235        let body = &rest[at + open.len()..];
236        let end = body.find('>').unwrap_or(body.len());
237        let attributes = &body[..end];
238        let mut pairs = Vec::new();
239        let mut a = attributes;
240        while let Some(eq) = a.find("=\"") {
241            let key = a[..eq].trim().to_string();
242            let after = &a[eq + 2..];
243            let close = after.find('"').unwrap_or(after.len());
244            pairs.push((key, unescape(&after[..close])));
245            a = &after[(close + 1).min(after.len())..];
246        }
247        out.push(Element(pairs));
248        rest = &body[end..];
249    }
250    out
251}
252
253fn unescape(value: &str) -> String {
254    value.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"").replace("&apos;", "'").replace("&amp;", "&")
255}
256
257/// A SolidWorks assembly's bodies, each instance's part read through
258/// `resolve` (given a file's base name, its bytes) and placed; sub-assemblies
259/// recursively. Suppressed instances are left out.
260pub fn import_solidworks_assembly_report(
261    bytes: &[u8],
262    resolve: &mut dyn FnMut(&str) -> Option<Vec<u8>>,
263) -> Result<ParasolidImportReport, String> {
264    let mut report: Option<ParasolidImportReport> = None;
265    let mut parts: rustc_hash::FxHashMap<(String, u32), ParasolidImportReport> = rustc_hash::FxHashMap::default();
266    place(bytes, crate::step_matrix::MAT4_IDENTITY, 0, resolve, &mut parts, &mut report)?;
267    report.ok_or_else(|| "solidworks_import: the assembly places no part".into())
268}
269
270fn place(
271    bytes: &[u8],
272    parent: crate::Mat4,
273    depth: usize,
274    resolve: &mut dyn FnMut(&str) -> Option<Vec<u8>>,
275    parts: &mut rustc_hash::FxHashMap<(String, u32), ParasolidImportReport>,
276    report: &mut Option<ParasolidImportReport>,
277) -> Result<(), String> {
278    if depth > 32 {
279        return Err("solidworks_import: assemblies nest more than 32 deep".into());
280    }
281    let components = solidworks_assembly_components(bytes).map_err(|e| format!("solidworks_import: {e}"))?;
282    for component in components.iter().filter(|c| !c.suppressed) {
283        let matrix = crate::step_matrix::mat4_mul(&parent, &component.transform);
284        let file = resolve(&component.file_name)
285            .ok_or_else(|| format!("solidworks_import: {} uses {}, which is not beside the assembly", component.name, component.file_name))?;
286        if component.assembly {
287            // A sub-assembly's file records the tree of one configuration;
288            // an instance of another is not read.
289            let recorded = recorded_configuration(&file).map_err(|e| format!("solidworks_import: {}: {e}", component.file_name))?;
290            if recorded.is_some_and(|c| c != component.configuration) {
291                return Err(format!(
292                    "solidworks_import: {} uses configuration {:?} of sub-assembly {}, whose file records only configuration {}",
293                    component.name,
294                    component.configuration_name,
295                    component.file_name,
296                    recorded.unwrap_or(0)
297                ));
298            }
299            place(&file, matrix, depth + 1, resolve, parts, report)?;
300            continue;
301        }
302        let key = (component.file_name.to_ascii_lowercase(), component.configuration);
303        if !parts.contains_key(&key) {
304            let partitions = solidworks_part_partitions(&file).map_err(|e| format!("solidworks_import: {}: {e}", component.file_name))?;
305            let wanted = format!("Config-{}", component.configuration);
306            let partition = partitions.iter().find(|(c, _)| *c == wanted).map(|(_, p)| p).ok_or_else(|| {
307                format!(
308                    "solidworks_import: {} uses configuration {:?} ({wanted}) of {}, which holds only {}",
309                    component.name,
310                    component.configuration_name,
311                    component.file_name,
312                    partitions.iter().map(|(c, _)| c.as_str()).collect::<Vec<_>>().join(", ")
313                )
314            })?;
315            let part = crate::parasolid::import_parasolid_bytes_report(partition).map_err(|e| format!("solidworks_import: {}: {e}", component.file_name))?;
316            parts.insert(key.clone(), part);
317        }
318        let part = &parts[&key];
319        let transform = crate::AffineTransform::new(matrix).map_err(|e| format!("solidworks_import: {}: {e}", component.name))?;
320        let out = report.get_or_insert_with(|| ParasolidImportReport {
321            solids: Vec::new(),
322            names: Vec::new(),
323            appearances: Vec::new(),
324            application: Some("SolidWorks".into()),
325            modeller_version: part.modeller_version.clone(),
326            stated_resolution_mm: part.stated_resolution_mm,
327            fitted_curves: 0,
328            unverified_curves: 0,
329            diagnostics: Default::default(),
330        });
331        for (k, solid) in part.solids.iter().enumerate() {
332            let placed = crate::transform_brep(solid, transform, transform.determinant3() < 0.0).map_err(|e| format!("solidworks_import: {}: {e}", component.name))?;
333            out.solids.push(placed);
334            out.names.push(if part.solids.len() == 1 { component.name.clone() } else { format!("{} ({})", component.name, k + 1) });
335            out.appearances.push(part.appearances.get(k).cloned().unwrap_or_default());
336        }
337        out.fitted_curves += part.fitted_curves;
338        out.unverified_curves += part.unverified_curves;
339    }
340    Ok(())
341}