use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicUsize, Ordering};
use super::{
WRITER,
geometry::{Geometry, Placing},
heal::Healed,
part21::{self, File, Param},
topology,
};
use crate::{
Error, Result, check,
math::Point3,
topo::{Brep, FaceId, FaceName, SolidId},
};
#[derive(Debug)]
pub struct Import {
pub brep: Brep,
pub rejected: Vec<String>,
pub healed: Vec<Healing>,
pub tolerant: Vec<Tolerant>,
pub crossed: Vec<Crossed>,
pub bodies: Vec<Body>,
pub face_colours: Vec<(FaceId, [f64; 3])>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Body {
pub solid: SolidId,
pub step_id: u64,
pub name: Option<String>,
pub instance: Vec<String>,
pub colour: Option<[f64; 3]>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Crossed {
pub index: usize,
pub step_id: u64,
pub faces: (FaceId, FaceId),
pub at: Point3,
pub depth: f64,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Tolerant {
pub index: usize,
pub step_id: u64,
pub vertices: usize,
pub edges: usize,
pub largest: f64,
pub stated: Option<f64>,
pub past_stated: usize,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Healing {
pub index: usize,
pub step_id: u64,
pub moved: f64,
pub at: Point3,
pub what: String,
pub surfaces: f64,
}
const SOLIDS: [&str; 4] = [
"MANIFOLD_SOLID_BREP",
"BREP_WITH_VOIDS",
"FACETED_BREP",
"TESSELLATED_SOLID",
];
const MAX_PLACEMENTS: usize = 1_000_000;
fn cyclic<T>(id: u64, what: &str) -> Result<T> {
Err(Error::InvalidInput(format!("STEP #{id}: {what}")))
}
struct Placement {
solid: u64,
context: Option<u64>,
at: Placing,
product: Option<u64>,
uses: Vec<u64>,
}
impl Placement {
fn key(&self) -> Key {
(self.solid, self.context, self.at.scale.to_bits())
}
}
type Key = (u64, Option<u64>, u64);
fn params(f: &File, id: u64, kind: &str) -> Option<Vec<Param>> {
f.get(id)?.part(kind).map(<[Param]>::to_vec)
}
fn refs(p: Option<&Param>) -> Vec<u64> {
p.and_then(Param::as_list)
.map(|l| l.iter().filter_map(Param::as_ref).collect())
.unwrap_or_default()
}
fn representation(f: &File, id: u64) -> Option<(Vec<u64>, Option<u64>)> {
let e = f.get(id)?;
let (_, p) = e.parts.iter().find(|(k, p)| {
k.ends_with("REPRESENTATION") && !k.contains("RELATIONSHIP") && p.len() >= 3
})?;
Some((refs(p.get(1)), p.get(2).and_then(Param::as_ref)))
}
struct Assembly<'a> {
file: &'a File,
links: HashMap<u64, Vec<u64>>,
reps: HashMap<u64, Vec<u64>>,
children: HashMap<u64, Vec<(u64, u64, u64)>>,
related: HashSet<u64>,
}
impl<'a> Assembly<'a> {
fn new(file: &'a File) -> Assembly<'a> {
let mut a = Assembly {
file,
links: HashMap::new(),
reps: HashMap::new(),
children: HashMap::new(),
related: HashSet::new(),
};
let mut nauo_place: HashMap<u64, u64> = HashMap::new();
for e in &file.entities {
if let Some(p) = e.part("SHAPE_DEFINITION_REPRESENTATION") {
let (Some(pds), Some(rep)) = (
p.first().and_then(Param::as_ref),
p.get(1).and_then(Param::as_ref),
) else {
continue;
};
if let Some(pd) = params(file, pds, "PRODUCT_DEFINITION_SHAPE")
.and_then(|q| q.get(2).and_then(Param::as_ref))
{
a.reps.entry(pd).or_default().push(rep);
}
} else if let Some(p) = e.part("CONTEXT_DEPENDENT_SHAPE_REPRESENTATION") {
let (Some(rel), Some(pds)) = (
p.first().and_then(Param::as_ref),
p.get(1).and_then(Param::as_ref),
) else {
continue;
};
if let Some(nauo) = params(file, pds, "PRODUCT_DEFINITION_SHAPE")
.and_then(|q| q.get(2).and_then(Param::as_ref))
{
nauo_place.insert(nauo, rel);
}
} else if !e.has("REPRESENTATION_RELATIONSHIP_WITH_TRANSFORMATION")
&& let Some(p) = e.part("REPRESENTATION_RELATIONSHIP").or_else(|| {
e.part("SHAPE_REPRESENTATION_RELATIONSHIP")
.filter(|p| p.len() >= 4)
})
&& let (Some(r1), Some(r2)) = (
p.get(2).and_then(Param::as_ref),
p.get(3).and_then(Param::as_ref),
)
{
a.links.entry(r1).or_default().push(r2);
a.links.entry(r2).or_default().push(r1);
}
}
for (i, e) in file.entities.iter().enumerate() {
if let Some(p) = e.part("NEXT_ASSEMBLY_USAGE_OCCURRENCE") {
let id = file.ids[i];
let (Some(parent), Some(child)) = (
p.get(3).and_then(Param::as_ref),
p.get(4).and_then(Param::as_ref),
) else {
continue;
};
if let Some(&rel) = nauo_place.get(&id) {
a.children.entry(parent).or_default().push((child, rel, id));
a.related.insert(child);
}
}
}
a
}
fn linked(&self, rep: u64) -> Vec<u64> {
let mut seen = vec![rep];
let mut i = 0;
while i < seen.len() {
for &r in self.links.get(&seen[i]).into_iter().flatten() {
if !seen.contains(&r) {
seen.push(r);
}
}
i += 1;
}
seen
}
fn rep_solids(
&self,
geo: &mut Geometry,
rep: u64,
at: &Placing,
path: &mut Vec<u64>,
out: &mut Vec<Placement>,
) -> Result<()> {
if path.contains(&rep) {
return cyclic(rep, "a mapped representation contains itself");
}
path.push(rep);
let r = self.rep_solids_in(geo, rep, at, path, out);
path.pop();
r
}
fn rep_solids_in(
&self,
geo: &mut Geometry,
rep: u64,
at: &Placing,
path: &mut Vec<u64>,
out: &mut Vec<Placement>,
) -> Result<()> {
for r in self.linked(rep) {
let Some((items, context)) = representation(self.file, r) else {
continue;
};
for it in items {
let Some(e) = self.file.get(it) else { continue };
if SOLIDS.contains(&e.kind()) {
if out.len() >= MAX_PLACEMENTS {
return cyclic(it, "the assembly places too many solids");
}
out.push(Placement {
solid: it,
context,
at: *at,
product: None,
uses: Vec::new(),
});
} else if let Some(p) = e.part("MAPPED_ITEM") {
let _ = (geo.use_context(context), p);
if let Some(t) = self.mapped(geo, p) {
let (src, place) = t;
self.rep_solids(geo, src, &place.then(at), path, out)?;
}
}
}
}
Ok(())
}
fn mapped(&self, geo: &mut Geometry, p: &[Param]) -> Option<(u64, Placing)> {
let map = params(self.file, p.get(1)?.as_ref()?, "REPRESENTATION_MAP")?;
let origin = geo.transform_of(map.first()?.as_ref()?).ok()?;
let src = map.get(1)?.as_ref()?;
let target = geo.transform_of(p.get(2)?.as_ref()?).ok()?;
Some((src, origin.inverse().then(&target)))
}
fn placement(&self, geo: &mut Geometry, child: u64, rel: u64) -> Option<Placing> {
let e = self.file.get(rel)?;
let rr = e.part("REPRESENTATION_RELATIONSHIP")?;
let (r1, r2) = (rr.get(2)?.as_ref()?, rr.get(3)?.as_ref()?);
let op = e
.part("REPRESENTATION_RELATIONSHIP_WITH_TRANSFORMATION")?
.first()?
.as_ref()?;
let child_reps: Vec<u64> = self
.reps
.get(&child)
.into_iter()
.flatten()
.flat_map(|&r| self.linked(r))
.collect();
let child_is_r1 = child_reps.contains(&r1) || !child_reps.contains(&r2);
let context = |r: u64| representation(self.file, r).and_then(|x| x.1);
let oe = self.file.get(op)?;
if let Some(it) = oe.part("ITEM_DEFINED_TRANSFORMATION") {
geo.use_context(context(r1)).ok()?;
let a = geo.transform_of(it.get(2)?.as_ref()?).ok()?;
geo.use_context(context(r2)).ok()?;
let b = geo.transform_of(it.get(3)?.as_ref()?).ok()?;
let (from, to) = if child_is_r1 { (a, b) } else { (b, a) };
Some(from.inverse().then(&to))
} else {
geo.use_context(context(if child_is_r1 { r2 } else { r1 }))
.ok()?;
let t = geo.transform_of(op).ok()?;
Some(if child_is_r1 { t } else { t.inverse() })
}
}
fn walk(
&self,
geo: &mut Geometry,
pd: u64,
at: &Placing,
path: &mut Vec<u64>,
seen: &mut HashSet<u64>,
out: &mut Vec<Placement>,
) -> Result<()> {
if path.contains(&pd) {
return cyclic(pd, "the assembly contains itself");
}
seen.insert(pd);
path.push(pd);
let own = out.len();
for &rep in self.reps.get(&pd).into_iter().flatten() {
self.rep_solids(geo, rep, at, &mut Vec::new(), out)?;
}
for p in &mut out[own..] {
p.product = Some(pd);
}
for &(child, rel, used) in self.children.get(&pd).into_iter().flatten() {
if let Some(t) = self.placement(geo, child, rel) {
let below = out.len();
self.walk(geo, child, &t.then(at), path, seen, out)?;
for p in &mut out[below..] {
p.uses.insert(0, used);
}
}
}
path.pop();
Ok(())
}
fn placements(&self, geo: &mut Geometry) -> Result<Vec<Placement>> {
let mut out = Vec::new();
let mut roots: Vec<u64> = self
.reps
.keys()
.chain(self.children.keys())
.copied()
.filter(|pd| !self.related.contains(pd))
.collect();
roots.sort_unstable();
roots.dedup();
let mut seen = HashSet::new();
for pd in roots {
self.walk(
geo,
pd,
&Placing::IDENTITY,
&mut Vec::new(),
&mut seen,
&mut out,
)?;
}
let mut unreached: Vec<u64> = self
.children
.keys()
.copied()
.filter(|pd| !seen.contains(pd))
.collect();
unreached.sort_unstable();
match unreached.first() {
Some(&pd) => cyclic(pd, "the assembly contains itself"),
None => Ok(out),
}
}
}
pub fn read_part(text: &[u8], feature: &str) -> Result<Brep> {
let import = read(text, feature)?;
if !import.rejected.is_empty() {
return Err(Error::InvalidResult(import.rejected));
}
let b = &import.brep;
let pieces: Vec<Brep> = b
.solid_ids()
.map(|s| crate::boolean::solids_of(b, &[s]))
.collect();
match &pieces[..] {
[one] => Ok(one.clone()),
_ => crate::boolean::union_all(&pieces.iter().collect::<Vec<_>>()),
}
}
pub fn read(text: &[u8], feature: &str) -> Result<Import> {
let file = part21::parse(text)?;
let ours = file.originating_system() == Some(WRITER);
let mut geo = Geometry::new(&file);
let mut placements = Assembly::new(&file).placements(&mut geo)?;
if placements.is_empty() {
let mut contexts: HashMap<u64, u64> = HashMap::new();
for &id in &file.ids {
if let Some((items, Some(ctx))) = representation(&file, id) {
for it in items {
contexts.entry(it).or_insert(ctx);
}
}
}
for (i, e) in file.entities.iter().enumerate() {
if SOLIDS.contains(&e.kind()) {
placements.push(Placement {
solid: file.ids[i],
context: contexts.get(&file.ids[i]).copied(),
at: Placing::IDENTITY,
product: None,
uses: Vec::new(),
});
}
}
}
if placements.is_empty() {
return Err(Error::InvalidInput("STEP: the file holds no solids".into()));
}
let mut keys: Vec<Key> = placements.iter().map(Placement::key).collect();
keys.sort_unstable();
keys.dedup();
let built = build_all(&file, &keys);
let mut out = Brep::new();
let mut rejected = Vec::new();
let mut healed = Vec::new();
let mut tolerant = Vec::new();
let mut crossed = Vec::new();
let mut crossings: HashMap<Key, Vec<check::SelfCrossing>> = HashMap::new();
let mut counter = 0usize;
let mut index = 0usize;
let colours = colours(&file);
let mut bodies = Vec::new();
let mut face_colours = Vec::new();
for pl in placements {
match &built[&pl.key()] {
Err(e) => rejected.push(format!("#{}: {e}", pl.solid)),
Ok((b, names, heal, stated)) => {
if let Some(h) = heal {
healed.push(Healing {
index,
step_id: pl.solid,
moved: h.moved,
at: pl.at.rigid.point(h.at),
what: h.what.clone(),
surfaces: h.surfaces,
});
}
if b.has_tolerances() {
let (vs, es) = b.tolerant();
let all = vs.iter().map(|x| x.1).chain(es.iter().map(|x| x.1));
let past = |t: &f64| stated.is_some_and(|s| *t > s);
tolerant.push(Tolerant {
index,
step_id: pl.solid,
vertices: vs.len(),
edges: es.len(),
largest: vs.iter().map(|x| x.1).fold(0.0, f64::max),
stated: *stated,
past_stated: all.filter(past).count(),
});
}
let first = out.face_count();
let found = crossings
.entry(pl.key())
.or_insert_with(|| check::self_crossings(b))
.clone();
let solid_index = index;
index += 1;
let mut copy = b.clone();
copy.transform(&pl.at.rigid);
let mut own_colours = Vec::new();
let faces = copy.face_ids().collect::<Vec<_>>();
for (k, (f, (step, name))) in faces.into_iter().zip(names).enumerate() {
if let Some(&c) = colours.get(step) {
own_colours.push((k, c));
}
let parsed = if ours { parse_names(name) } else { Vec::new() };
copy.face_mut(f).names = if parsed.is_empty() {
[FaceName::new(feature, format!("face_{counter}"))].into()
} else {
parsed.into_iter().collect()
};
counter += 1;
}
let solids = out.append(©);
let ids: Vec<FaceId> = out.face_ids().skip(first).collect();
face_colours.extend(own_colours.into_iter().map(|(k, c)| (ids[k], c)));
bodies.extend(solids.into_iter().map(|solid| Body {
solid,
step_id: pl.solid,
name: pl.product.and_then(|pd| product_name(&file, pd)),
instance: pl.uses.iter().map(|&u| use_name(&file, u)).collect(),
colour: colours.get(&pl.solid).copied(),
}));
for x in found {
crossed.push(Crossed {
index: solid_index,
step_id: pl.solid,
faces: (ids[x.a.index()], ids[x.b.index()]),
at: pl.at.rigid.point(x.at),
depth: x.depth,
});
}
}
}
}
Ok(Import {
brep: out,
rejected,
healed,
tolerant,
crossed,
bodies,
face_colours,
})
}
fn text(p: Option<&Param>) -> Option<String> {
p.and_then(Param::as_str)
.filter(|s| !s.is_empty())
.map(str::to_string)
}
fn product_name(file: &File, pd: u64) -> Option<String> {
let formation = params(file, pd, "PRODUCT_DEFINITION")?.get(2)?.as_ref()?;
let formed = file.get(formation)?;
let product = formed
.parts
.iter()
.find(|(k, _)| k.starts_with("PRODUCT_DEFINITION_FORMATION"))?
.1
.get(2)?
.as_ref()?;
let p = params(file, product, "PRODUCT")?;
text(p.get(1)).or_else(|| text(p.first()))
}
fn use_name(file: &File, used: u64) -> String {
params(file, used, "NEXT_ASSEMBLY_USAGE_OCCURRENCE")
.and_then(|p| text(p.get(1)).or_else(|| text(p.first())))
.unwrap_or_else(|| format!("#{used}"))
}
fn all_refs(p: &Param, out: &mut Vec<u64>) {
match p {
Param::Ref(r) => out.push(*r),
Param::List(l) => l.iter().for_each(|x| all_refs(x, out)),
Param::Typed(_, inner) => all_refs(inner, out),
_ => {}
}
}
fn colour_under(file: &File, id: u64, depth: usize) -> Option<[f64; 3]> {
let e = file.get(id)?;
if let Some(p) = e.part("COLOUR_RGB") {
let at = |i: usize| p.get(i).and_then(Param::as_f64);
return Some([at(1)?, at(2)?, at(3)?]);
}
if let Some(p) = e
.part("DRAUGHTING_PRE_DEFINED_COLOUR")
.or_else(|| e.part("PRE_DEFINED_COLOUR"))
{
return Some(match p.first().and_then(Param::as_str)? {
"red" => [1.0, 0.0, 0.0],
"green" => [0.0, 1.0, 0.0],
"blue" => [0.0, 0.0, 1.0],
"yellow" => [1.0, 1.0, 0.0],
"magenta" => [1.0, 0.0, 1.0],
"cyan" => [0.0, 1.0, 1.0],
"black" => [0.0, 0.0, 0.0],
"white" => [1.0, 1.0, 1.0],
_ => return None,
});
}
if depth == 0 {
return None;
}
let mut below = Vec::new();
for (_, ps) in &e.parts {
ps.iter().for_each(|p| all_refs(p, &mut below));
}
below
.into_iter()
.find_map(|r| colour_under(file, r, depth - 1))
}
fn colours(file: &File) -> HashMap<u64, [f64; 3]> {
const DEPTH: usize = 6;
let mut out = HashMap::new();
for e in &file.entities {
let Some(p) = e
.part("STYLED_ITEM")
.or_else(|| e.part("OVER_RIDING_STYLED_ITEM"))
else {
continue;
};
let Some(item) = p.get(2).and_then(Param::as_ref) else {
continue;
};
let mut styles = Vec::new();
for assignment in refs(p.get(1)) {
if let Some(a) = file.get(assignment) {
for (_, ps) in &a.parts {
ps.iter().for_each(|x| all_refs(x, &mut styles));
}
}
}
let colour = styles
.into_iter()
.filter(|&s| file.get(s).is_some_and(|x| x.has("SURFACE_STYLE_USAGE")))
.find_map(|s| colour_under(file, s, DEPTH));
if let Some(c) = colour {
out.entry(item).or_insert(c);
}
}
out
}
type Built = std::result::Result<(Brep, Vec<(u64, String)>, Option<Healed>, Option<f64>), String>;
fn weight(file: &File, solid: u64) -> usize {
let refs_of = |id: u64, at: usize| -> Vec<u64> {
let Some(e) = file.get(id) else {
return Vec::new();
};
let Some(p) = e.parts.first().map(|p| &p.1) else {
return Vec::new();
};
match p.get(at) {
Some(Param::List(l)) => l.iter().filter_map(Param::as_ref).collect(),
Some(x) => x.as_ref().into_iter().collect(),
None => Vec::new(),
}
};
let mut shells = refs_of(solid, 1);
shells.extend(refs_of(solid, 2));
let mut total = 0;
for sh in shells {
let sh = match file.get(sh).and_then(|e| e.part("ORIENTED_CLOSED_SHELL")) {
Some(p) => p.get(2).and_then(Param::as_ref).unwrap_or(sh),
None => sh,
};
for f in refs_of(sh, 1) {
total += 1;
let Some(face) = file.get(f) else { continue };
let Some(s) = face.parts[0].1.get(2).and_then(Param::as_ref) else {
continue;
};
let Some(e) = file.get(s) else { continue };
let net = match (
e.part("B_SPLINE_SURFACE"),
e.part("B_SPLINE_SURFACE_WITH_KNOTS"),
) {
(Some(p), _) => p.get(2),
(None, Some(p)) => p.get(3),
_ => None,
};
total += net.and_then(Param::as_list).map_or(0, |rows| {
rows.iter().filter_map(Param::as_list).map(<[_]>::len).sum()
});
}
}
total
}
fn build_all(file: &File, keys: &[Key]) -> HashMap<Key, Built> {
let threads = std::thread::available_parallelism()
.map_or(1, |n| n.get())
.min(keys.len().max(1));
let mut order: Vec<(usize, usize)> = keys
.iter()
.enumerate()
.map(|(k, key)| (weight(file, key.0), k))
.collect();
order.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
let next = AtomicUsize::new(0);
let results: Vec<Vec<(usize, Built)>> = std::thread::scope(|scope| {
let workers: Vec<_> = (0..threads)
.map(|_| {
scope.spawn(|| {
let mut geo = Geometry::new(file);
let mut mine = Vec::new();
while let Some(&(_, k)) = order.get(next.fetch_add(1, Ordering::Relaxed)) {
let (solid, context, scale) = keys[k];
let r = geo
.use_scaled(context, f64::from_bits(scale))
.and_then(|_| topology::solid(&mut geo, solid))
.map(|(b, names, healed)| (b, names, healed, geo.uncertainty()))
.map_err(|e| e.to_string());
mine.push((k, r));
}
mine
})
})
.collect();
workers
.into_iter()
.map(|w| w.join().unwrap_or_default())
.collect()
});
let mut out = HashMap::new();
for (k, r) in results.into_iter().flatten() {
out.insert(keys[k], r);
}
for &k in keys {
out.entry(k)
.or_insert_with(|| Err("the thread building it failed".to_string()));
}
out
}
fn parse_names(s: &str) -> Vec<FaceName> {
s.split(';')
.filter_map(|n| {
let (f, face) = n.split_once('.')?;
Some(FaceName::new(f, face))
})
.collect()
}