use cxx::UniquePtr;
use ferrocad_curves::{
Arc, ArcOfHyperbola, ArcOfParabola, BezierCurve, Circle, EdgeCurve, Ellipse, EllipticalArc,
Hyperbola, Line, NurbsCurve, OffsetCurve, Parabola, Vector3,
};
use ferrocad_geom::{
BsplineSurfaceData, Capabilities, Continuity, ElementId, ElementKind, ElementRef, FailureKind,
GeomError, GeometryBackend, History, Lineage, MapVersion, MassProperties, OpResult, OperandId,
PrincipalProperties, Shape, ShapeDistance, SurfaceData, SurfaceSpec, Tessellation,
TessellationOptions, ToleranceKind, unsupported,
};
use ferrocad_types::{Matrix4, Placement};
use opencascade_sys as ffi;
use std::collections::BTreeSet;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use ffi::top_abs::TopAbs_Orientation;
use crate::surface_ops;
use ffi::top_abs::TopAbs_ShapeEnum;
use ffi::top_tools::TopTools_IndexedMapOfShape;
use ffi::top_tools::TopTools_ListOfShape;
use ffi::topo_ds::{TopoDS, TopoDS_Shape};
use crate::error::OcctError;
use crate::history;
use crate::policy;
use crate::shape::{downcast, erase, find_index_same, new_map, sub_shape_map};
use crate::topology;
type Map = TopTools_IndexedMapOfShape;
#[derive(Debug, Default, Clone, Copy)]
pub struct OcctBackend;
impl OcctBackend {
pub fn new() -> Self {
OcctBackend
}
pub fn name_every_element(&self, shape: &Shape) -> History {
let mut history = History::default();
let Ok(occt) = downcast(shape) else {
return history;
};
let guard = occt.borrow();
let Some(inner) = guard.as_ref() else {
return history;
};
if inner.IsNull() {
return history;
}
for (kind, occt_kind) in HISTORY_KINDS {
let map = sub_shape_map(inner, occt_kind);
for ordinal in 1..=map.Extent() {
let element = element_ref(kind, ordinal, map.FindKey(ordinal));
history.push_identity(element.clone(), element);
}
}
history
}
pub fn intrinsic_history(&self, shape: &Shape) -> Option<History> {
let occt = downcast(shape).ok()?;
let guard = occt.borrow();
let inner = guard.as_ref()?;
if inner.IsNull() {
return None;
}
if inner.ShapeType() != TopAbs_ShapeEnum::TopAbs_COMPOUND {
return None;
}
let solids = sub_shape_map(inner, TopAbs_ShapeEnum::TopAbs_SOLID);
if solids.Extent() == 0 {
return None;
}
Some(self.name_every_element(shape))
}
fn without_dangling_wires(&self, shape: &Shape) -> Shape {
let Ok(occt) = downcast(shape) else {
return shape.clone();
};
let guard = occt.borrow();
let Some(inner) = guard.as_ref() else {
return shape.clone();
};
if !is_face(inner) {
return shape.clone();
}
let wires = sub_shape_map(inner, TopAbs_ShapeEnum::TopAbs_WIRE);
if wires.Extent() <= 1 {
return shape.clone();
}
let Some(outer) = self.outer_wire(shape) else {
return shape.clone();
};
let Ok(outer_occt) = downcast(&outer) else {
return shape.clone();
};
let outer_guard = outer_occt.borrow();
let Some(outer_inner) = outer_guard.as_ref() else {
return shape.clone();
};
let outer_index = find_index_same(&wires, outer_inner);
let area = |shape: &Shape| {
self.mass_properties(shape)
.map(|mass| mass.area)
.unwrap_or(0.0)
};
let mut dangling = 0;
for index in 1..=wires.Extent() {
if index == outer_index {
continue;
}
let wire = erase(wires.FindKey(index));
let enclosed = {
let Ok(wire_occt) = downcast(&wire) else {
return shape.clone();
};
let wire_guard = wire_occt.borrow();
let Some(wire_inner) = wire_guard.as_ref() else {
return shape.clone();
};
match crate::shape_ops::split_wire_into_faces(wire_inner).as_ref() {
Some(enclosed) => {
let faces = sub_shape_map(enclosed, TopAbs_ShapeEnum::TopAbs_FACE);
(1..=faces.Extent())
.map(|face| area(&erase(faces.FindKey(face))))
.sum::<f64>()
}
None => 0.0,
}
};
if enclosed <= 1e-9 {
dangling += 1;
}
}
if dangling == 0 || dangling != wires.Extent() - 1 {
return shape.clone();
}
let Ok(cleaned) = self.make_face(&[outer]) else {
return shape.clone();
};
let cleaned_area = area(&cleaned);
let original_area = area(shape);
if cleaned_area > 0.0
&& (cleaned_area - original_area).abs() <= 1e-9 * original_area.max(1.0)
{
cleaned
} else {
shape.clone()
}
}
#[allow(clippy::too_many_arguments)]
pub fn make_bspline_poles_mults_knots(
&self,
poles: &[Vector3],
weights: &[f64],
knots: &[f64],
multiplicities: &[i32],
degree: i32,
periodic: bool,
check_rational: bool,
) -> Result<Shape, GeomError> {
let mut coords = Vec::with_capacity(poles.len() * 3);
for pole in poles {
coords.extend_from_slice(&[pole.x, pole.y, pole.z]);
}
let Some(curve) = crate::curve::build(
&coords,
weights,
knots,
multiplicities,
degree,
periodic,
check_rational,
) else {
return Err(OcctError::NotDone {
operation: "make_bspline_poles_mults_knots",
}
.into());
};
let curve = ffi::geom::new_HandleGeomCurve_from_HandleGeom_BSplineCurve(&curve);
let mut make = ffi::b_rep_builder_api::BRepBuilderAPI_MakeEdge_HandleGeomCurve(&curve);
let edge = erase(ffi::topo_ds::cast_edge_to_shape(make.pin_mut().Edge()));
if !make.IsDone() {
return Err(OcctError::NotDone {
operation: "make_bspline_poles_mults_knots",
}
.into());
}
Ok(edge)
}
#[allow(clippy::too_many_arguments)]
pub fn bspline_state(
&self,
poles: &[Vector3],
weights: &[f64],
knots: &[f64],
multiplicities: &[i32],
degree: i32,
periodic: bool,
check_rational: bool,
) -> Option<crate::curve::BsplineState> {
let coords = flatten(poles);
crate::curve::probe(
&coords,
weights,
knots,
multiplicities,
degree,
periodic,
check_rational,
)
}
pub fn bspline_interpolated_state(
&self,
points: &[Vector3],
periodic: bool,
) -> Option<crate::curve::BsplineState> {
crate::curve::interpolated(&flatten(points), periodic)
}
#[allow(clippy::too_many_arguments)]
pub fn bspline_periodic_state(
&self,
poles: &[Vector3],
weights: &[f64],
knots: &[f64],
multiplicities: &[i32],
degree: i32,
periodic: bool,
check_rational: bool,
target_periodic: bool,
) -> Option<crate::curve::BsplineState> {
crate::curve::set_periodic(
&flatten(poles),
weights,
knots,
multiplicities,
degree,
periodic,
check_rational,
target_periodic,
)
}
#[allow(clippy::too_many_arguments)]
pub fn bspline_resolution(
&self,
poles: &[Vector3],
weights: &[f64],
knots: &[f64],
multiplicities: &[i32],
degree: i32,
periodic: bool,
check_rational: bool,
tolerance: f64,
) -> Option<f64> {
let resolution = crate::curve::resolution(
&flatten(poles),
weights,
knots,
multiplicities,
degree,
periodic,
check_rational,
tolerance,
);
resolution
}
#[allow(clippy::too_many_arguments)]
pub fn bspline_segment(
&self,
poles: &[Vector3],
weights: &[f64],
knots: &[f64],
multiplicities: &[i32],
degree: i32,
periodic: bool,
check_rational: bool,
u1: f64,
u2: f64,
) -> Option<crate::curve::BsplineState> {
crate::curve::segment(
&flatten(poles),
weights,
knots,
multiplicities,
degree,
periodic,
check_rational,
u1,
u2,
)
}
#[allow(clippy::too_many_arguments)]
pub fn bspline_point(
&self,
poles: &[Vector3],
weights: &[f64],
knots: &[f64],
multiplicities: &[i32],
degree: i32,
periodic: bool,
check_rational: bool,
u: f64,
) -> Option<Vector3> {
crate::curve::bspline_point(
&flatten(poles),
weights,
knots,
multiplicities,
degree,
periodic,
check_rational,
u,
)
}
#[allow(clippy::too_many_arguments)]
pub fn conic_spline_state(
&self,
kind: i32,
center: Vector3,
normal: Vector3,
x_axis: Vector3,
major: f64,
minor: f64,
first: f64,
last: f64,
nurbs: bool,
) -> Option<crate::curve::BsplineState> {
crate::curve::conic_to_spline(kind, center, normal, x_axis, major, minor, first, last, nurbs)
}
#[allow(clippy::too_many_arguments)]
pub fn bspline_parameter(
&self,
poles: &[Vector3],
weights: &[f64],
knots: &[f64],
multiplicities: &[i32],
degree: i32,
periodic: bool,
check_rational: bool,
point: Vector3,
) -> Option<f64> {
let parameter = crate::curve::parameter(
&flatten(poles),
weights,
knots,
multiplicities,
degree,
periodic,
check_rational,
point.x,
point.y,
point.z,
);
parameter
}
#[allow(clippy::too_many_arguments)]
pub fn bspline_remove_knot_state(
&self,
poles: &[Vector3],
weights: &[f64],
knots: &[f64],
multiplicities: &[i32],
degree: i32,
periodic: bool,
check_rational: bool,
index: i32,
mult: i32,
tolerance: f64,
) -> Option<crate::curve::BsplineState> {
crate::curve::remove_knot(
&flatten(poles),
weights,
knots,
multiplicities,
degree,
periodic,
check_rational,
index,
mult,
tolerance,
)
}
pub fn bspline_approximated_state(
&self,
points: &[Vector3],
degree_min: i32,
degree_max: i32,
tolerance: f64,
) -> Option<crate::curve::BsplineState> {
crate::curve::approximated(&flatten(points), degree_min, degree_max, tolerance)
}
#[allow(clippy::too_many_arguments)]
pub fn bspline_insert_knot_state(
&self,
poles: &[Vector3],
weights: &[f64],
knots: &[f64],
multiplicities: &[i32],
degree: i32,
periodic: bool,
check_rational: bool,
u: f64,
mult: i32,
tolerance: f64,
) -> Option<crate::curve::BsplineState> {
crate::curve::insert_knot(
&flatten(poles),
weights,
knots,
multiplicities,
degree,
periodic,
check_rational,
u,
mult,
tolerance,
)
}
pub fn face_normal_at(&self, face: &Shape, u: f64, v: f64) -> Option<Vector3> {
let occt = downcast(face).ok()?;
let guard = occt.borrow();
let inner = guard.as_ref()?;
if !is_face(inner) {
return None;
}
crate::curve::face_normal(ffi::topo_ds::TopoDS::Face(inner), u, v)
}
pub fn face_tangents_at(
&self,
face: &Shape,
u: f64,
v: f64,
) -> Option<(Vector3, Vector3)> {
let occt = downcast(face).ok()?;
let guard = occt.borrow();
let inner = guard.as_ref()?;
if !is_face(inner) {
return None;
}
let raw = crate::curve::face_tangents(ffi::topo_ds::TopoDS::Face(inner), u, v);
raw
}
pub fn face_derivatives_at(
&self,
face: &Shape,
u: f64,
v: f64,
order: i32,
) -> Option<(Vector3, Vector3)> {
let occt = downcast(face).ok()?;
let guard = occt.borrow();
let inner = guard.as_ref()?;
if !is_face(inner) {
return None;
}
crate::curve::face_derivatives(ffi::topo_ds::TopoDS::Face(inner), u, v, order)
}
pub fn face_curvature_at(&self, face: &Shape, u: f64, v: f64) -> Option<(f64, f64)> {
let occt = downcast(face).ok()?;
let guard = occt.borrow();
let inner = guard.as_ref()?;
if !is_face(inner) {
return None;
}
crate::curve::face_curvature(ffi::topo_ds::TopoDS::Face(inner), u, v)
}
#[allow(clippy::too_many_arguments)]
pub fn wire_discretize(
&self,
wire: &Shape,
mode: i32,
value: f64,
curvature: f64,
minimum: i32,
first: f64,
last: f64,
) -> Result<Vec<Vector3>, GeomError> {
let occt = downcast(wire)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null wire" })?;
if !is_wire(inner) {
return Err(OcctError::InvalidInput {
what: "not a wire",
}
.into());
}
let points = crate::part_ops::wire_discretize(inner, mode, value, curvature, minimum, first, last);
if points.is_empty() {
return Err(OcctError::NotDone {
operation: "wire_discretize",
}
.into());
}
Ok(points)
}
pub fn face_surface_bounds(&self, face: &Shape) -> Option<(f64, f64, f64, f64)> {
let occt = downcast(face).ok()?;
let guard = occt.borrow();
let inner = guard.as_ref()?;
if !is_face(inner) {
return None;
}
crate::curve::face_surface_bounds(ffi::topo_ds::TopoDS::Face(inner))
}
pub fn edge_normal_at(&self, edge: &Shape, parameter: f64) -> Option<Vector3> {
let occt = downcast(edge).ok()?;
let guard = occt.borrow();
let inner = guard.as_ref()?;
if !is_edge(inner) {
return None;
}
crate::curve::edge_normal(ffi::topo_ds::TopoDS::Edge(inner), parameter)
}
pub fn edge_derivatives_at(
&self,
edge: &Shape,
parameter: f64,
order: i32,
) -> Option<Vector3> {
let occt = downcast(edge).ok()?;
let guard = occt.borrow();
let inner = guard.as_ref()?;
if !is_edge(inner) {
return None;
}
crate::curve::edge_derivatives(ffi::topo_ds::TopoDS::Edge(inner), parameter, order)
}
pub fn edge_curvature_at(&self, edge: &Shape, parameter: f64) -> Option<f64> {
let occt = downcast(edge).ok()?;
let guard = occt.borrow();
let inner = guard.as_ref()?;
if !is_edge(inner) {
return None;
}
crate::curve::edge_curvature(ffi::topo_ds::TopoDS::Edge(inner), parameter)
}
pub fn edge_pcurve_state(&self, edge: &Shape, face: &Shape) -> Option<crate::curve::BsplineState> {
let edge = downcast(edge).ok()?;
let face = downcast(face).ok()?;
let edge = edge.borrow();
let face = face.borrow();
let state = crate::curve::edge_pcurve(edge.as_ref()?, face.as_ref()?);
state
}
#[allow(clippy::too_many_arguments)]
pub fn make_bspline2d_edge(
&self,
poles: &[(f64, f64)],
weights: &[f64],
knots: &[f64],
multiplicities: &[i32],
degree: i32,
periodic: bool,
surface: Option<&SurfaceSpec>,
face: Option<&Shape>,
range: Option<(f64, f64)>,
) -> Result<Shape, GeomError> {
let mut coordinates = Vec::with_capacity(poles.len() * 2);
for (u, v) in poles {
coordinates.extend_from_slice(&[*u, *v]);
}
let owned_face = surface_face(face)?;
let null_face = ffi::topo_ds::TopoDS_Face_new();
let face_shape: &TopoDS_Shape = match &owned_face {
Some(shape) => shape,
None => ffi::topo_ds::cast_face_to_shape(&null_face),
};
let (first, last) = range.unwrap_or((0.0, 0.0));
let edge = crate::curve::bspline2d_edge(
&coordinates,
weights,
knots,
multiplicities,
degree,
periodic,
surface,
face_shape,
first,
last,
range.is_some(),
);
match edge.as_ref() {
Some(edge) => Ok(erase(edge)),
None => Err(OcctError::NotDone {
operation: "make_bspline2d_edge",
}
.into()),
}
}
pub fn curve2d_on_surface_edge(
&self,
planar_edge: &Shape,
surface: Option<&SurfaceSpec>,
face: Option<&Shape>,
) -> Result<Shape, GeomError> {
let owned_face = surface_face(face)?;
let null_face = ffi::topo_ds::TopoDS_Face_new();
let face_shape: &TopoDS_Shape = match &owned_face {
Some(shape) => shape,
None => ffi::topo_ds::cast_face_to_shape(&null_face),
};
let edge = downcast(planar_edge)?;
let guard = edge.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null edge" })?;
let lifted = crate::curve::curve2d_on_surface(inner, surface, face_shape);
match lifted.as_ref() {
Some(shape) => Ok(erase(shape)),
None => Err(OcctError::NotDone {
operation: "curve2d_on_surface_edge",
}
.into()),
}
}
pub fn tessellate_points(
&self,
shape: &Shape,
options: &TessellationOptions,
) -> Result<(Vec<[f64; 3]>, Vec<u32>), GeomError> {
crate::topology::tessellate_points(shape, options)
}
fn assemble_shell(&self, faces: &[Shape]) -> Result<Shape, GeomError> {
if faces.is_empty() {
return Err(OcctError::InvalidInput {
what: "a shell needs at least one face",
}
.into());
}
let mut shell = ffi::topo_ds::TopoDS_Shell_new();
let builder = ffi::b_rep::BRep_Builder_new();
let builder = ffi::b_rep::BRep_Builder_upcast_to_topods_builder(&builder);
builder.MakeShell(shell.pin_mut());
let mut shell = ffi::topo_ds::TopoDS_Shell_as_shape(shell);
for face in faces {
let occt = downcast(face)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null face" })?;
if !is_face(inner) {
return Err(OcctError::InvalidInput {
what: "a shell is made of faces",
}
.into());
}
builder.Add(shell.pin_mut(), inner);
}
Ok(erase(&shell))
}
}
fn surface_face(face: Option<&Shape>) -> Result<Option<UniquePtr<TopoDS_Shape>>, GeomError> {
match face {
Some(face) => {
let occt = downcast(face)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null face" })?;
Ok(Some(ffi::topo_ds::TopoDS_Shape_to_owned(inner)))
}
None => Ok(None),
}
}
fn three(values: &[f64]) -> Option<Vector3> {
(values.len() >= 3).then(|| Vector3::new(values[0], values[1], values[2]))
}
fn is_edge(shape: &TopoDS_Shape) -> bool {
!shape.IsNull() && shape.ShapeType() == TopAbs_ShapeEnum::TopAbs_EDGE
}
fn is_wire(shape: &TopoDS_Shape) -> bool {
!shape.IsNull() && shape.ShapeType() == TopAbs_ShapeEnum::TopAbs_WIRE
}
fn is_vertex(shape: &TopoDS_Shape) -> bool {
!shape.IsNull() && shape.ShapeType() == TopAbs_ShapeEnum::TopAbs_VERTEX
}
fn is_face(shape: &TopoDS_Shape) -> bool {
!shape.IsNull() && shape.ShapeType() == TopAbs_ShapeEnum::TopAbs_FACE
}
fn is_shell(shape: &TopoDS_Shape) -> bool {
!shape.IsNull() && shape.ShapeType() == TopAbs_ShapeEnum::TopAbs_SHELL
}
impl GeometryBackend for OcctBackend {
fn make_box(&self, length: f64, width: f64, height: f64) -> Result<Shape, GeomError> {
let origin = ffi::gp::new_point(0.0, 0.0, 0.0);
let mut make = ffi::b_rep_prim_api::BRepPrimAPI_MakeBox_new(&origin, length, width, height);
let shape = erase(make.pin_mut().Shape());
if !make.IsDone() {
return Err(OcctError::NotDone {
operation: "make_box",
}
.into());
}
Ok(shape)
}
fn make_cylinder(
&self,
radius: f64,
height: f64,
base: Vector3,
direction: Vector3,
) -> Result<Shape, GeomError> {
let axis = axis_from(base, direction)?;
let mut make = ffi::b_rep_prim_api::BRepPrimAPI_MakeCylinder_new(&axis, radius, height);
let shape = erase(make.pin_mut().Shape());
if !make.IsDone() {
return Err(OcctError::NotDone {
operation: "make_cylinder",
}
.into());
}
Ok(shape)
}
fn make_sphere(&self, radius: f64, center: Vector3) -> Result<Shape, GeomError> {
let origin = point(center);
let direction = ffi::gp::gp_Dir_new(0.0, 0.0, 1.0);
let axis = ffi::gp::gp_Ax2_new(&origin, &direction);
let mut make =
ffi::b_rep_prim_api::BRepPrimAPI_MakeSphere_new(&axis, radius, std::f64::consts::TAU);
let shape = erase(make.pin_mut().Shape());
if !make.IsDone() {
return Err(OcctError::NotDone {
operation: "make_sphere",
}
.into());
}
Ok(shape)
}
fn make_cone(
&self,
radius1: f64,
radius2: f64,
height: f64,
base: Vector3,
direction: Vector3,
) -> Result<Shape, GeomError> {
let axis = axis_from(base, direction)?;
let mut make = ffi::b_rep_prim_api::BRepPrimAPI_MakeCone_new(
&axis,
radius1,
radius2,
height,
std::f64::consts::TAU,
);
let shape = erase(make.pin_mut().Shape());
if !make.IsDone() {
return Err(OcctError::NotDone {
operation: "make_cone",
}
.into());
}
Ok(shape)
}
fn make_edge(&self, curve: &EdgeCurve) -> Result<Shape, GeomError> {
match curve {
EdgeCurve::LineSegment(segment) => {
let start = point(segment.start());
let end = point(segment.end());
let mut make =
ffi::b_rep_builder_api::BRepBuilderAPI_MakeEdge_gp_Pnt_gp_Pnt(&start, &end);
if !make.IsDone() {
return Err(OcctError::NotDone {
operation: "make_edge",
}
.into());
}
Ok(erase(ffi::topo_ds::cast_edge_to_shape(
make.pin_mut().Edge(),
)))
}
EdgeCurve::Circle(circle) => edge_from_circle(circle),
EdgeCurve::Arc(arc) => {
if arc.is_closed() {
return edge_from_circle(&arc.circle());
}
let start = point(arc.start());
let middle = point(arc.point_at(arc.first() + arc.sweep() / 2.0));
let end = point(arc.end());
let arc_maker =
ffi::gc::GC_MakeArcOfCircle_point_point_point(&start, &middle, &end);
let trimmed = ffi::gc::GC_MakeArcOfCircle_Value(&*arc_maker);
if trimmed.is_null() {
return Err(OcctError::NotDone {
operation: "make_edge (arc)",
}
.into());
}
let curve = ffi::geom::new_HandleGeomCurve_from_HandleGeom_TrimmedCurve(&*trimmed);
let mut make =
ffi::b_rep_builder_api::BRepBuilderAPI_MakeEdge_HandleGeomCurve(&*curve);
if !make.IsDone() {
return Err(OcctError::NotDone {
operation: "make_edge (arc)",
}
.into());
}
Ok(erase(ffi::topo_ds::cast_edge_to_shape(
make.pin_mut().Edge(),
)))
}
EdgeCurve::Line(_) => Err(unsupported("make_edge for an infinite line")),
EdgeCurve::Ellipse(ellipse) => edge_from_ellipse(ellipse),
EdgeCurve::EllipticalArc(arc) => {
let ellipse = arc.ellipse();
edge_from_conic(
3,
&ellipse,
arc.first(),
arc.last(),
"make_edge (elliptical arc)",
)
}
EdgeCurve::Hyperbola(_) => Err(unsupported("make_edge for an unbounded hyperbola")),
EdgeCurve::ArcOfHyperbola(arc) => {
let hyperbola = arc.hyperbola();
edge_from_conic(
4,
&hyperbola,
arc.first(),
arc.last(),
"make_edge (arc of hyperbola)",
)
}
EdgeCurve::Parabola(_) => Err(unsupported("make_edge for an unbounded parabola")),
EdgeCurve::ArcOfParabola(arc) => {
let parabola = arc.parabola();
edge_from_conic(
5,
¶bola,
arc.first(),
arc.last(),
"make_edge (arc of parabola)",
)
}
EdgeCurve::BezierCurve(curve) => edge_from_bezier(curve),
EdgeCurve::BSplineCurve(curve) => edge_from_nurbs(curve),
EdgeCurve::OffsetCurve(curve) => {
let basis = self.make_edge(curve.basis())?;
let basis_occt = downcast(&basis)?;
let basis_guard = basis_occt.borrow();
let basis_inner = basis_guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null basis edge" })?;
let direction = curve.direction();
let edge = (|| {
if !is_edge(basis_inner) {
return None;
}
let mut bf = 0.0;
let mut bl = 0.0;
let base = ffi::b_rep::BRep_Tool_Curve(
ffi::topo_ds::TopoDS::Edge(basis_inner),
&mut bf,
&mut bl,
);
if base.IsNull() {
return None;
}
let dir = ffi::gp::gp_Dir_new(direction.x, direction.y, direction.z);
let offset = ffi::geom::Geom_OffsetCurve_new(&base, curve.offset(), &dir).ok()?;
let offset = ffi::geom::new_HandleGeomCurve_from_HandleGeom_OffsetCurve(&offset);
let mut make = ffi::b_rep_builder_api::BRepBuilderAPI_MakeEdge_CurveRange(
&offset,
curve.first(),
curve.last(),
)
.ok()?;
if !make.IsDone() {
return None;
}
Some(ffi::topo_ds::TopoDS_Shape_to_owned(
ffi::topo_ds::cast_edge_to_shape(make.pin_mut().Edge()),
))
})();
let Some(edge) = edge else {
return Err(OcctError::NotDone {
operation: "make_edge (offset curve)",
}
.into());
};
Ok(erase(&edge))
}
}
}
fn make_wire(&self, edges: &[Shape]) -> Result<Shape, GeomError> {
let mut make = ffi::b_rep_builder_api::BRepBuilderAPI_MakeWire_new();
for edge in edges {
let occt = downcast(edge)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null edge" })?;
if !is_edge(inner) {
return Err(OcctError::InvalidInput {
what: "make_wire expects edges",
}
.into());
}
make.pin_mut().add_edge(ffi::topo_ds::TopoDS::Edge(inner));
}
if !make.IsDone() {
return Err(OcctError::NotDone {
operation: "make_wire",
}
.into());
}
Ok(erase(ffi::topo_ds::cast_wire_to_shape(
make.pin_mut().Wire(),
)))
}
fn make_vertex(&self, at: Vector3) -> Result<Shape, GeomError> {
let pnt = point(at);
let mut make = ffi::b_rep_builder_api::BRepBuilderAPI_MakeVertex_gp_Pnt(&pnt);
Ok(erase(ffi::topo_ds::cast_vertex_to_shape(
make.pin_mut().Vertex(),
)))
}
fn vertex_point(&self, shape: &Shape) -> Option<Vector3> {
let occt = downcast(shape).ok()?;
let guard = occt.borrow();
let inner = guard.as_ref()?;
if !is_vertex(inner) {
return None;
}
let pnt = ffi::b_rep::BRep_Tool_Pnt(ffi::topo_ds::TopoDS::Vertex(inner));
Some(Vector3::new(pnt.X(), pnt.Y(), pnt.Z()))
}
fn make_bspline_edge(&self, points: &[Vector3], periodic: bool) -> Result<Shape, GeomError> {
if points.len() < 2 {
return Err(OcctError::InvalidInput {
what: "a B-spline needs at least two points",
}
.into());
}
let mut array = ffi::t_col_gp::TColgp_HArray1OfPnt_new(1, points.len() as i32);
for (index, value) in points.iter().enumerate() {
let value = point(*value);
array.pin_mut().SetValue(index as i32 + 1, &value);
}
let array = ffi::t_col_gp::new_HandleTColgpHArray1OfPnt_from_TColgpHArray1OfPnt(array);
let mut interpolate = ffi::geom_api::GeomAPI_Interpolate_new(&array, periodic, 1e-7);
interpolate.pin_mut().Perform();
let curve = ffi::geom_api::GeomAPI_Interpolate_Curve(&interpolate);
let curve = ffi::geom::new_HandleGeomCurve_from_HandleGeom_BSplineCurve(&curve);
let mut make = ffi::b_rep_builder_api::BRepBuilderAPI_MakeEdge_HandleGeomCurve(&curve);
let shape = erase(ffi::topo_ds::cast_edge_to_shape(make.pin_mut().Edge()));
if !make.IsDone() {
return Err(OcctError::NotDone {
operation: "make_bspline_edge",
}
.into());
}
Ok(shape)
}
fn make_bspline_poles(
&self,
poles: &[Vector3],
degree: i32,
periodic: bool,
) -> Result<Shape, GeomError> {
if poles.len() < 2 {
return Err(OcctError::InvalidInput {
what: "a B-spline needs at least two poles",
}
.into());
}
let mut coords = Vec::with_capacity(poles.len() * 3);
for pole in poles {
coords.extend_from_slice(&[pole.x, pole.y, pole.z]);
}
let curve = crate::curve::bspline_from_poles(&coords, degree, periodic);
let Some(curve) = curve else {
return Err(OcctError::NotDone {
operation: "make_bspline_poles",
}
.into());
};
let curve = ffi::geom::new_HandleGeomCurve_from_HandleGeom_BSplineCurve(&curve);
let mut make = ffi::b_rep_builder_api::BRepBuilderAPI_MakeEdge_HandleGeomCurve(&curve);
let shape = erase(ffi::topo_ds::cast_edge_to_shape(make.pin_mut().Edge()));
if !make.IsDone() {
return Err(OcctError::NotDone {
operation: "make_bspline_poles",
}
.into());
}
Ok(shape)
}
fn add_wire_to_face(&self, face: &Shape, wire: &Shape) -> Result<Shape, GeomError> {
let face_occt = downcast(face)?;
let face_guard = face_occt.borrow();
let face_inner = face_guard.as_ref().ok_or(OcctError::InvalidInput {
what: "null face",
})?;
let wire_occt = downcast(wire)?;
let wire_guard = wire_occt.borrow();
let wire_inner = wire_guard.as_ref().ok_or(OcctError::InvalidInput {
what: "null wire",
})?;
let added = crate::policy::face_add_wire(face_inner, wire_inner).map_err(GeomError::from)?;
Ok(erase(&added))
}
fn make_face(&self, wires: &[Shape]) -> Result<Shape, GeomError> {
let (first, rest) = wires.split_first().ok_or(OcctError::InvalidInput {
what: "a face needs a wire",
})?;
let first_occt = downcast(first)?;
let first_guard = first_occt.borrow();
let first_inner = first_guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null wire" })?;
if !is_wire(first_inner) {
return Err(OcctError::InvalidInput {
what: "make_face expects wires",
}
.into());
}
let outer = crate::policy::face_from_wire(first_inner).map_err(GeomError::from)?;
if outer.is_null() {
return Err(OcctError::NotDone {
operation: "make_face",
}
.into());
}
let mut face = outer;
for wire in rest {
let occt = downcast(wire)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null wire" })?;
if !is_wire(inner) {
return Err(OcctError::InvalidInput {
what: "make_face expects wires",
}
.into());
}
let reversed = ffi::topo_ds::Reversed(inner);
let Some(reversed) = reversed.as_ref() else {
return Err(OcctError::InvalidInput { what: "null wire" }.into());
};
let Some(source) = face.as_ref() else {
return Err(OcctError::InvalidInput { what: "null face" }.into());
};
let next = crate::policy::face_add_wire(source, reversed).map_err(GeomError::from)?;
if next.is_null() {
return Err(OcctError::NotDone {
operation: "make_face",
}
.into());
}
face = next;
}
Ok(erase(&face))
}
fn make_faces(&self, wires: &[Shape]) -> Result<Shape, GeomError> {
let mut faces = Vec::with_capacity(wires.len());
let mut splitters = Vec::new();
let mut all_planar = true;
for wire in wires {
let occt = downcast(wire)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null wire" })?;
if !is_wire(inner) {
return Err(OcctError::InvalidInput {
what: "make_faces expects wires",
}
.into());
}
let split = crate::shape_ops::split_wire_into_faces(inner);
if let Some(split) = split.as_ref() {
let map = sub_shape_map(split, TopAbs_ShapeEnum::TopAbs_FACE);
if map.Extent() > 1 {
for index in 1..=map.Extent() {
faces.push(erase(map.FindKey(index)));
}
continue;
}
}
let make = ffi::b_rep_builder_api::BRepBuilderAPI_MakeFace_wire(
ffi::topo_ds::TopoDS::Wire(inner),
true,
);
if make.IsDone() {
faces.push(erase(ffi::topo_ds::cast_face_to_shape(make.Face())));
continue;
}
let make_any = ffi::b_rep_builder_api::BRepBuilderAPI_MakeFace_wire(
ffi::topo_ds::TopoDS::Wire(inner),
false,
);
if make_any.IsDone() {
faces.push(erase(ffi::topo_ds::cast_face_to_shape(make_any.Face())));
continue;
}
let mut list = ffi::top_tools::new_list_of_shape();
let _ = list.pin_mut().Append(inner);
let filled = crate::shape_ops::fill_wires(&list);
let Some(filled) = filled.as_ref() else {
splitters.push(wire.clone());
continue;
};
let filled = erase(filled);
let filled_area = self
.mass_properties(&filled)
.map(|mass| mass.area)
.unwrap_or(0.0);
if filled_area <= 1e-9 {
splitters.push(wire.clone());
continue;
}
all_planar = false;
faces.push(filled);
}
if !splitters.is_empty() {
if faces.is_empty() {
return Err(OcctError::InvalidInput {
what: "an open wire cannot form a face",
}
.into());
}
let mut list = ffi::top_tools::new_list_of_shape();
for shape in faces.iter().chain(splitters.iter()) {
let occt = downcast(shape)?;
let guard = occt.borrow();
if let Some(inner) = guard.as_ref() {
let _ = list.pin_mut().Append(inner);
}
}
let fused = crate::shape_ops::general_fuse(&list, 0.0);
if let Some(fused) = fused.as_ref() {
let map = sub_shape_map(fused, TopAbs_ShapeEnum::TopAbs_FACE);
let mut regions = Vec::with_capacity(map.Extent() as usize);
for index in 1..=map.Extent() {
let region = erase(map.FindKey(index));
let area = self
.mass_properties(®ion)
.map(|mass| mass.area)
.unwrap_or(0.0);
if area <= 1e-9 {
continue;
}
regions.push(self.without_dangling_wires(®ion));
}
if !regions.is_empty() {
return if regions.len() == 1 {
Ok(regions.remove(0))
} else {
self.make_compound(®ions)
};
}
}
return Err(OcctError::NotDone {
operation: "make_faces",
}
.into());
}
if all_planar && faces.len() > 1 {
let area = |shape: &Shape| {
self.mass_properties(shape)
.map(|mass| mass.area)
.unwrap_or(0.0)
};
let contains = |outer: &Shape, inner: &Shape| {
let inner_area = area(inner);
if inner_area <= 0.0 {
return false;
}
match self.common(outer, inner, 0.0) {
Ok(result) => {
let overlap = area(&result.shape);
(overlap - inner_area).abs() <= 1e-6 * inner_area.max(1.0)
}
Err(_) => false,
}
};
let count = faces.len();
let mut parent: Vec<Option<usize>> = vec![None; count];
for inner in 0..count {
for outer in 0..count {
if inner == outer || !contains(&faces[outer], &faces[inner]) {
continue;
}
let smaller = parent[inner]
.map(|current| area(&faces[outer]) < area(&faces[current]))
.unwrap_or(true);
if smaller {
parent[inner] = Some(outer);
}
}
}
if parent.iter().any(Option::is_some) {
let depth = |mut index: usize| {
let mut depth = 0;
while let Some(up) = parent[index] {
depth += 1;
index = up;
if depth > count {
break;
}
}
depth
};
let even: Vec<usize> = (0..count).filter(|index| depth(*index) % 2 == 0).collect();
let odd: Vec<usize> = (0..count).filter(|index| depth(*index) % 2 == 1).collect();
let intersection_area = |a: &Shape, b: &Shape| match self.common(a, b, 0.0) {
Ok(result) => area(&result.shape),
Err(_) => 0.0,
};
let mut partial_overlap = false;
'pairs: for (position, &a) in even.iter().enumerate() {
for &b in &even[position + 1..] {
let overlap = intersection_area(&faces[a], &faces[b]);
let smaller = area(&faces[a]).min(area(&faces[b]));
if overlap > 1e-9 && smaller - overlap > 1e-9 {
partial_overlap = true;
break 'pairs;
}
}
}
if !odd.is_empty() && partial_overlap {
let mut list = ffi::top_tools::new_list_of_shape();
for face in &faces {
let occt = downcast(face)?;
let guard = occt.borrow();
if let Some(inner) = guard.as_ref() {
let _ = list.pin_mut().Append(inner);
}
}
let fused = crate::shape_ops::general_fuse(&list, 0.0);
if let Some(fused) = fused.as_ref() {
let map = sub_shape_map(fused, TopAbs_ShapeEnum::TopAbs_FACE);
let mut kept = Vec::new();
for index in 1..=map.Extent() {
let region = erase(map.FindKey(index));
let inside_hole =
odd.iter().any(|&hole| contains(&faces[hole], ®ion));
if !inside_hole {
kept.push(region);
}
}
if !kept.is_empty() {
return if kept.len() == 1 {
Ok(kept.remove(0))
} else {
self.make_compound(&kept)
};
}
}
}
let mut built = Vec::new();
for node in 0..count {
if depth(node) % 2 != 0 {
continue;
}
let mut boundaries = vec![wires[node].clone()];
let mut holes: Vec<(f64, Shape)> = (0..count)
.filter(|&child| parent[child] == Some(node))
.map(|child| (area(&faces[child]), wires[child].clone()))
.collect();
holes
.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
boundaries.extend(holes.into_iter().map(|(_, wire)| wire));
if let Ok(face) = self.make_face(&boundaries) {
built.push(face);
}
}
if !built.is_empty() {
return if built.len() == 1 {
Ok(built.remove(0))
} else {
self.make_compound(&built)
};
}
}
let mut list = ffi::top_tools::new_list_of_shape();
for face in &faces {
let occt = downcast(face)?;
let guard = occt.borrow();
if let Some(inner) = guard.as_ref() {
let _ = list.pin_mut().Append(inner);
}
}
let fused = crate::shape_ops::general_fuse(&list, 0.0);
if let Some(fused) = fused.as_ref() {
let map = sub_shape_map(fused, TopAbs_ShapeEnum::TopAbs_FACE);
let mut regions = Vec::with_capacity(map.Extent() as usize);
for index in 1..=map.Extent() {
regions.push(erase(map.FindKey(index)));
}
if regions.len() > 1 {
return self.make_compound(®ions);
}
}
}
match faces.len() {
0 => Err(OcctError::InvalidInput {
what: "a face needs a wire",
}
.into()),
1 => Ok(faces.remove(0)),
_ => self.make_compound(&faces),
}
}
fn make_face_on_surface(
&self,
surface: &SurfaceSpec,
wires: &[Shape],
) -> Result<Shape, GeomError> {
if wires.is_empty() {
return Err(OcctError::InvalidInput {
what: "a face needs a wire",
}
.into());
}
let mut list = ffi::top_tools::new_list_of_shape();
for wire in wires {
let occt = downcast(wire)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null wire" })?;
if !is_wire(inner) {
return Err(OcctError::InvalidInput {
what: "make_face_on_surface expects wires",
}
.into());
}
let _ = list.pin_mut().Append(inner);
}
let face = crate::policy::make_face_on_surface(surface, &list).map_err(GeomError::from)?;
match face.as_ref() {
Some(face) => Ok(erase(face)),
None => Err(OcctError::NotDone {
operation: "make_face_on_surface",
}
.into()),
}
}
fn make_face_on_band(
&self,
surface: &SurfaceSpec,
u1: f64,
u2: f64,
v1: f64,
v2: f64,
) -> Result<Shape, GeomError> {
let face = crate::policy::face_on_surface_band(surface, u1, u2, v1, v2)
.map_err(GeomError::from)?;
Ok(erase(&face))
}
fn surface_type(&self, shape: &Shape) -> Option<String> {
let occt = downcast(shape).ok()?;
let guard = occt.borrow();
let inner = guard.as_ref()?;
if !is_face(inner) {
return None;
}
let surface = ffi::b_rep::BRep_Tool_Surface(ffi::topo_ds::TopoDS::Face(inner));
let name = ffi::standard::type_name(ffi::geom::DynamicType(surface.as_ref()?));
Some(
match name.as_str() {
"Geom_Plane" => "Part::GeomPlane",
"Geom_CylindricalSurface" => "Part::GeomCylinder",
"Geom_ConicalSurface" => "Part::GeomCone",
"Geom_SphericalSurface" => "Part::GeomSphere",
"Geom_ToroidalSurface" => "Part::GeomToroid",
"Geom_BSplineSurface" => "Part::GeomBSplineSurface",
_ => "Part::GeomSurface",
}
.to_string(),
)
}
fn surface_data(&self, shape: &Shape) -> Option<SurfaceData> {
let occt = downcast(shape).ok()?;
let guard = occt.borrow();
let inner = guard.as_ref()?;
if !is_face(inner) {
return None;
}
match crate::surface_frame::of(ffi::topo_ds::TopoDS::Face(inner)) {
Some(frame) => Some(frame.into_surface_data()),
None => self
.surface_type(shape)
.map(|type_id| SurfaceData::Other { type_id }),
}
}
fn sew(&self, shape: &Shape, tolerance: f64) -> Result<Shape, GeomError> {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let sewn = crate::part_ops::sew_shape(inner, tolerance).map_err(GeomError::from)?;
match sewn.as_ref() {
Some(sewn) => Ok(erase(sewn)),
None => Err(OcctError::NotDone { operation: "sew" }.into()),
}
}
fn connect_edges_to_wires(
&self,
shape: &Shape,
shared: bool,
tolerance: f64,
) -> Result<Shape, GeomError> {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let wires = crate::policy::connect_edges_to_wires(inner, shared, tolerance)?;
Ok(erase(&wires))
}
fn to_nurbs(&self, shape: &Shape) -> Result<Shape, GeomError> {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let converted = crate::part_ops::to_nurbs(inner).map_err(GeomError::from)?;
match converted.as_ref() {
Some(converted) => Ok(erase(converted)),
None => Err(OcctError::NotDone {
operation: "to_nurbs",
}
.into()),
}
}
fn sub_shapes_of_type(&self, shape: &Shape, kind: &str) -> Vec<Shape> {
let Ok(occt) = downcast(shape) else {
return Vec::new();
};
let guard = occt.borrow();
let Some(inner) = guard.as_ref() else {
return Vec::new();
};
let shape_type = match kind {
"Compound" => TopAbs_ShapeEnum::TopAbs_COMPOUND,
"CompSolid" => TopAbs_ShapeEnum::TopAbs_COMPSOLID,
_ => return Vec::new(),
};
let Some(compound) = crate::part_ops::shape_sub_shapes_of_type(inner, shape_type)
.as_ref()
.map(erase)
else {
return Vec::new();
};
let compound_occt = match downcast(&compound) {
Ok(occt) => occt,
Err(_) => return Vec::new(),
};
let compound_guard = compound_occt.borrow();
let Some(compound_inner) = compound_guard.as_ref() else {
return Vec::new();
};
history::children(compound_inner)
.iter()
.filter_map(|child| child.as_ref().map(erase))
.collect()
}
fn children(&self, shape: &Shape) -> Vec<Shape> {
let Ok(occt) = downcast(shape) else {
return Vec::new();
};
let guard = occt.borrow();
let Some(inner) = guard.as_ref() else {
return Vec::new();
};
history::children(inner)
.iter()
.filter_map(|child| child.as_ref().map(erase))
.collect()
}
fn outer_wire(&self, shape: &Shape) -> Option<Shape> {
let occt = downcast(shape).ok()?;
let guard = occt.borrow();
let inner = guard.as_ref()?;
if !is_face(inner) {
return None;
}
let wire = ffi::b_rep_tools::outer_wire(ffi::topo_ds::TopoDS::Face(inner));
Some(erase(ffi::topo_ds::cast_wire_to_shape(wire.as_ref()?)))
}
fn curve_of(&self, shape: &Shape) -> Result<EdgeCurve, GeomError> {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
crate::curve::edge_curve(inner)
}
fn fuse(&self, a: &Shape, b: &Shape, tolerance: f64) -> Result<OpResult, GeomError> {
boolean(a, b, CutOperation::Fuse, tolerance)
}
fn cut(&self, a: &Shape, b: &Shape, tolerance: f64) -> Result<OpResult, GeomError> {
boolean(a, b, CutOperation::Cut, tolerance)
}
fn fillet(
&self,
shape: &Shape,
edges: &[ElementRef],
radius: f64,
) -> Result<OpResult, GeomError> {
topology::fillet(shape, edges, radius)
}
fn common(&self, a: &Shape, b: &Shape, tolerance: f64) -> Result<OpResult, GeomError> {
boolean(a, b, CutOperation::Common, tolerance)
}
fn make_compound(&self, shapes: &[Shape]) -> Result<Shape, GeomError> {
if shapes.is_empty() {
return Err(OcctError::InvalidInput {
what: "a compound needs at least one shape",
}
.into());
}
let mut compound = ffi::topo_ds::TopoDS_Compound_new();
let builder = ffi::b_rep::BRep_Builder_new();
let builder = ffi::b_rep::BRep_Builder_upcast_to_topods_builder(&builder);
builder.MakeCompound(compound.pin_mut());
let mut compound = ffi::topo_ds::TopoDS_Compound_as_shape(compound);
for shape in shapes {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
builder.Add(compound.pin_mut(), inner);
}
Ok(erase(&compound))
}
fn make_comp_solid(&self, solids: &[Shape]) -> Result<Shape, GeomError> {
if solids.is_empty() {
return Err(OcctError::InvalidInput {
what: "a comp-solid needs at least one solid",
}
.into());
}
let mut list = ffi::top_tools::new_list_of_shape();
for solid in solids {
let occt = downcast(solid)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null solid" })?;
let _ = list.pin_mut().Append(inner);
}
let composed = crate::shape_ops::comp_solid(&list);
let Some(composed) = composed.as_ref() else {
return Err(OcctError::NotDone {
operation: "make_comp_solid",
}
.into());
};
Ok(erase(composed))
}
fn make_solid(&self, shell: &Shape) -> Result<Shape, GeomError> {
let occt = downcast(shell)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shell" })?;
if !is_shell(inner) {
return Err(OcctError::InvalidInput {
what: "make_solid expects a shell",
}
.into());
}
let mut make =
ffi::b_rep_builder_api::BRepBuilderAPI_MakeSolid_new(ffi::topo_ds::TopoDS::Shell(inner));
if !make.IsDone() {
return Err(OcctError::NotDone {
operation: "make_solid",
}
.into());
}
let mut solid = ffi::topo_ds::TopoDS_Solid_to_owned(make.pin_mut().Solid());
ffi::b_rep_lib::BRepLib::OrientClosedSolid(solid.pin_mut());
Ok(erase(ffi::topo_ds::cast_solid_to_shape(&solid)))
}
fn make_shell(&self, faces: &[Shape]) -> Result<Shape, GeomError> {
let shell = self.assemble_shell(faces)?;
if self.is_valid(&shell) {
return Ok(shell);
}
let occt = downcast(&shell)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shell" })?;
match crate::part_ops::sew_shell(inner).ok().as_ref() {
Some(sewn) => Ok(erase(sewn)),
None => Ok(shell),
}
}
fn make_shell_from_wires(&self, wires: &[Shape]) -> Result<Shape, GeomError> {
if wires.is_empty() {
return Err(OcctError::InvalidInput {
what: "a shell needs at least one wire",
}
.into());
}
let mut faces = Vec::with_capacity(wires.len());
for wire in wires {
faces.push(self.make_face(std::slice::from_ref(wire))?);
}
self.assemble_shell(&faces)
}
fn make_loft(&self, wires: &[Shape], solid: bool) -> Result<Shape, GeomError> {
if wires.len() < 2 {
return Err(OcctError::InvalidInput {
what: "a loft needs at least two sections",
}
.into());
}
let mut make = ffi::b_rep_offset_api::BRepOffsetAPI_ThruSections_new(solid);
for wire in wires {
let occt = downcast(wire)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null wire" })?;
if !is_wire(inner) {
return Err(OcctError::InvalidInput {
what: "make_loft expects wires",
}
.into());
}
make.pin_mut().AddWire(ffi::topo_ds::TopoDS::Wire(inner));
}
make.pin_mut().CheckCompatibility(false);
let progress = ffi::message::Message_ProgressRange_new();
make.pin_mut().Build(&progress);
if !make.IsDone() {
return Err(OcctError::NotDone {
operation: "make_loft",
}
.into());
}
Ok(erase(make.pin_mut().Shape()))
}
fn make_ruled_surface(&self, first: &Shape, second: &Shape) -> Result<Shape, GeomError> {
let first_occt = downcast(first)?;
let second_occt = downcast(second)?;
let first_guard = first_occt.borrow();
let second_guard = second_occt.borrow();
let a = first_guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null edge" })?;
let b = second_guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null edge" })?;
let face = crate::shape_ops::ruled_surface(a, b);
let Some(face) = face.as_ref() else {
return Err(OcctError::NotDone {
operation: "make_ruled_surface",
}
.into());
};
Ok(erase(face))
}
fn make_pipe(
&self,
spine: &Shape,
profile: &Shape,
tolerance: f64,
) -> Result<Shape, GeomError> {
let spine_occt = downcast(spine)?;
let spine_guard = spine_occt.borrow();
let spine_inner = spine_guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null spine" })?;
let profile_occt = downcast(profile)?;
let profile_guard = profile_occt.borrow();
let profile_inner = profile_guard.as_ref().ok_or(OcctError::InvalidInput {
what: "null profile",
})?;
let piped = crate::shape_ops::pipe(spine_inner, profile_inner, tolerance);
let Some(piped) = piped.as_ref() else {
return Err(OcctError::NotDone {
operation: "make_pipe",
}
.into());
};
Ok(erase(piped))
}
fn intrinsic_lineage(&self, shape: &Shape) -> Result<Lineage, GeomError> {
let history = self
.intrinsic_history(shape)
.unwrap_or_else(|| self.name_every_element(shape));
Ok(Lineage::from_history(&history, MapVersion::default()))
}
fn make_filled_face(&self, edges: &[Shape]) -> Result<Shape, GeomError> {
let wire = self.make_wire(edges)?;
let mut list = ffi::top_tools::new_list_of_shape();
{
let occt = downcast(&wire)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null wire" })?;
list.pin_mut().Append(inner);
}
let face = crate::shape_ops::fill_wires(&list);
let Some(face) = face.as_ref() else {
return Err(OcctError::NotDone {
operation: "make_filled_face",
}
.into());
};
Ok(erase(face))
}
fn extrude(&self, shape: &Shape, vector: Vector3) -> Result<Shape, GeomError> {
if vector.length() <= 0.0 || !vector.length().is_finite() {
return Err(OcctError::InvalidInput {
what: "extrusion needs a non-zero vector",
}
.into());
}
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let direction = ffi::gp::new_vec(vector.x, vector.y, vector.z);
let mut make =
ffi::b_rep_prim_api::BRepPrimAPI_MakePrism_new(inner, &direction, true, true);
if !make.IsDone() {
return Err(OcctError::NotDone {
operation: "extrude",
}
.into());
}
Ok(erase(make.pin_mut().Shape()))
}
fn line_direction(&self, edge: &Shape) -> Option<Vector3> {
surface_ops::edge_line_direction(edge).ok()
}
fn planar_normal(&self, shape: &Shape) -> Option<Vector3> {
surface_ops::shape_plane_normal(shape).ok()
}
fn revolve(
&self,
shape: &Shape,
center: Vector3,
axis: Vector3,
angle: f64,
) -> Result<Shape, GeomError> {
if axis.length() <= 0.0 || !axis.length().is_finite() {
return Err(OcctError::InvalidInput {
what: "revolving needs a non-zero axis",
}
.into());
}
if !angle.is_finite() {
return Err(OcctError::InvalidInput {
what: "revolving needs a finite angle",
}
.into());
}
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let origin = point(center);
let direction = ffi::gp::gp_Dir_new(axis.x, axis.y, axis.z);
let axis = ffi::gp::gp_Ax1_new(&origin, &direction);
let mut make = ffi::b_rep_prim_api::BRepPrimAPI_MakeRevol_new(inner, &axis, angle, true);
if !make.IsDone() {
return Err(OcctError::NotDone {
operation: "revolve",
}
.into());
}
Ok(erase(make.pin_mut().Shape()))
}
fn bounds(&self, shape: &Shape) -> Option<(Vector3, Vector3)> {
let occt = downcast(shape).ok()?;
let guard = occt.borrow();
let inner = guard.as_ref()?;
let mut bnd = ffi::bnd::Bnd_Box_new();
ffi::b_rep_bnd_lib::BRepBndLib::Add(inner, bnd.pin_mut(), false);
if bnd.IsVoid() {
return None;
}
bnd.pin_mut().SetGap(0.0);
let (mut xmin, mut ymin, mut zmin) = (0.0, 0.0, 0.0);
let (mut xmax, mut ymax, mut zmax) = (0.0, 0.0, 0.0);
bnd.Get(
&mut xmin, &mut ymin, &mut zmin, &mut xmax, &mut ymax, &mut zmax,
);
Some((
Vector3::new(xmin, ymin, zmin),
Vector3::new(xmax, ymax, zmax),
))
}
fn mass_properties(&self, shape: &Shape) -> Option<MassProperties> {
let occt = downcast(shape).ok()?;
let guard = occt.borrow();
let inner = guard.as_ref()?;
let mut linear = ffi::g_prop::GProps_new();
ffi::b_rep_g_prop::BRepGProp::LinearProperties(inner, linear.pin_mut(), false, false);
let length = linear.Mass();
let mut surface = ffi::g_prop::GProps_new();
ffi::b_rep_g_prop::BRepGProp::SurfaceProperties(inner, surface.pin_mut(), false, false);
let area = surface.Mass();
let mut volume = ffi::g_prop::GProps_new();
ffi::b_rep_g_prop::BRepGProp::VolumeProperties(
inner,
volume.pin_mut(),
false,
false,
false,
);
let centre = ffi::g_prop::GProp_GProps_CentreOfMass(&volume);
Some(MassProperties {
length,
area,
volume: volume.Mass(),
center_of_mass: Vector3::new(centre.X(), centre.Y(), centre.Z()),
})
}
fn center_of_mass(&self, shape: &Shape) -> Option<Vector3> {
let occt = downcast(shape).ok()?;
let guard = occt.borrow();
let inner = guard.as_ref()?;
crate::shape_ops::center_of_mass(inner)
}
fn is_valid(&self, shape: &Shape) -> bool {
let Ok(occt) = downcast(shape) else {
return false;
};
let guard = occt.borrow();
match guard.as_ref() {
Some(inner) => crate::shape_ops::is_valid(inner),
None => false,
}
}
fn inertia_matrix(&self, shape: &Shape) -> Option<Matrix4> {
let occt = downcast(shape).ok()?;
let guard = occt.borrow();
let inner = guard.as_ref()?;
let values = crate::shape_ops::inertia_matrix(inner)?;
let mut matrix = Matrix4::identity();
for row in 0..3 {
for column in 0..3 {
matrix.m[row * 4 + column] = values[row * 3 + column];
}
}
Some(matrix)
}
fn principal_properties(&self, shape: &Shape) -> Option<PrincipalProperties> {
let occt = downcast(shape).ok()?;
let guard = occt.borrow();
let inner = guard.as_ref()?;
let values = crate::shape_ops::principal_properties(inner)?;
Some(PrincipalProperties {
symmetry_axis: values.symmetry_axis,
symmetry_point: values.symmetry_point,
moments: (values.moments[0], values.moments[1], values.moments[2]),
axes: (values.axes[0], values.axes[1], values.axes[2]),
radius_of_gyration: (
values.radius_of_gyration[0],
values.radius_of_gyration[1],
values.radius_of_gyration[2],
),
})
}
fn clean(&self, shape: &Shape) -> Option<Shape> {
let occt = downcast(shape).ok()?;
let guard = occt.borrow();
let inner = guard.as_ref()?;
let mut op = ffi::shape_upgrade::UnifySameDomain_new(inner, true, true, false);
op.pin_mut().build();
Some(erase(op.shape()))
}
fn refine(&self, shape: &Shape) -> Option<OpResult> {
let cleaned = self.clean(shape)?;
let before = downcast(shape).ok()?.borrow();
let after = downcast(&cleaned).ok()?.borrow();
let history = refine_history(before.as_ref()?, after.as_ref()?);
Some(OpResult::new(cleaned, history))
}
fn shape_type(&self, shape: &Shape) -> Option<&'static str> {
crate::part_ops::shape_kind(shape)
}
fn project(&self, shape: &Shape, tools: &[Shape]) -> Result<Shape, GeomError> {
if tools.is_empty() {
return Err(OcctError::InvalidInput {
what: "project needs at least one tool shape",
}
.into());
}
let target = downcast(shape)?;
let guard = target.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let mut list = ffi::top_tools::new_list_of_shape();
for tool in tools {
let occt = downcast(tool)?;
let tool_guard = occt.borrow();
let piece = tool_guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
list.pin_mut().Append(piece);
}
let projected = crate::part_ops::project_normal(inner, &list).map_err(GeomError::from)?;
match projected.as_ref() {
Some(projected) => Ok(erase(projected)),
None => Err(OcctError::NotDone {
operation: "project",
}
.into()),
}
}
fn make_offset(&self, shape: &Shape, distance: f64, join: i32) -> Result<Shape, GeomError> {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let offset = crate::shape_ops::offset(inner, distance, join);
let Some(offset) = offset.as_ref() else {
return Err(OcctError::NotDone {
operation: "make_offset",
}
.into());
};
Ok(erase(offset))
}
fn make_thickness(
&self,
shape: &Shape,
closing_faces: &[Shape],
thickness: f64,
tolerance: f64,
) -> Result<Shape, GeomError> {
if !thickness.is_finite() || thickness == 0.0 {
return Err(OcctError::InvalidInput {
what: "make_thickness needs a non-zero thickness",
}
.into());
}
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let mut list = ffi::top_tools::new_list_of_shape();
for face in closing_faces {
let face_occt = downcast(face)?;
let face_guard = face_occt.borrow();
let face_inner = face_guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null face" })?;
let _ = list.pin_mut().Append(face_inner);
}
let thickened = crate::shape_ops::thick_solid(inner, &list, thickness, tolerance);
let Some(thickened) = thickened.as_ref() else {
return Err(OcctError::NotDone {
operation: "make_thickness",
}
.into());
};
Ok(erase(thickened))
}
fn section(&self, a: &Shape, b: &Shape) -> Result<Shape, GeomError> {
let a_occt = downcast(a)?;
let b_occt = downcast(b)?;
let a_guard = a_occt.borrow();
let b_guard = b_occt.borrow();
let sa = a_guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let sb = b_guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let section = crate::shape_ops::section(sa, sb);
let Some(section) = section.as_ref() else {
return Err(OcctError::NotDone {
operation: "section",
}
.into());
};
Ok(erase(section))
}
fn slice(
&self,
shape: &Shape,
direction: Vector3,
distance: f64,
) -> Result<Vec<Shape>, GeomError> {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let sliced = crate::shape_ops::slice(inner, direction.x, direction.y, direction.z, distance);
let Some(sliced) = sliced.as_ref() else {
return Err(OcctError::NotDone { operation: "slice" }.into());
};
let wires = sub_shape_map(sliced, TopAbs_ShapeEnum::TopAbs_WIRE);
Ok((1..=wires.Extent())
.map(|index| erase(wires.FindKey(index)))
.collect())
}
fn general_fuse(
&self,
shapes: &[Shape],
tolerance: f64,
) -> Result<(Shape, Vec<Vec<Shape>>), GeomError> {
if shapes.is_empty() {
return Err(OcctError::InvalidInput {
what: "general fuse needs at least one shape",
}
.into());
}
let tolerance = if tolerance.is_finite() && tolerance > 0.0 {
tolerance
} else {
0.0
};
let mut list = ffi::top_tools::new_list_of_shape();
for shape in shapes {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let _ = list.pin_mut().Append(inner);
}
let Some((fused, parts)) = crate::shape_ops::general_fuse_parts(&list, tolerance) else {
return Err(OcctError::NotDone {
operation: "general_fuse",
}
.into());
};
let Some(fused) = fused.as_ref() else {
return Err(OcctError::NotDone {
operation: "general_fuse",
}
.into());
};
let split = parts
.iter()
.map(|part| {
part.as_ref()
.and_then(|part| part.as_ref())
.map(top_level_parts)
.unwrap_or_default()
})
.collect();
Ok((erase(fused), split))
}
fn split_shape(
&self,
shape: &Shape,
tools: &[(Shape, Shape)],
check_interior: bool,
) -> Result<(Vec<Shape>, Vec<Shape>), GeomError> {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let mut cutters = ffi::top_tools::new_list_of_shape();
let mut faces = ffi::top_tools::new_list_of_shape();
for (cutter, face) in tools {
let cutter_occt = downcast(cutter)?;
let cutter_guard = cutter_occt.borrow();
let cutter_inner = cutter_guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null tool" })?;
let face_occt = downcast(face)?;
let face_guard = face_occt.borrow();
let face_inner = face_guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null face" })?;
let _ = cutters.pin_mut().Append(cutter_inner);
let _ = faces.pin_mut().Append(face_inner);
}
let mut direct = ffi::top_tools::new_list_of_shape();
let mut left = ffi::top_tools::new_list_of_shape();
if !crate::shape_ops::split_shape(
inner,
&cutters,
&faces,
check_interior,
direct.pin_mut(),
left.pin_mut(),
) {
return Err(OcctError::NotDone {
operation: "split_shape",
}
.into());
}
Ok((collect_list(&direct), collect_list(&left)))
}
fn optimal_bounds(
&self,
shape: &Shape,
use_triangulation: bool,
use_tolerance: bool,
) -> Option<(Vector3, Vector3)> {
let occt = downcast(shape).ok()?;
let guard = occt.borrow();
let inner = guard.as_ref()?;
crate::shape_ops::optimal_box(inner, use_triangulation, use_tolerance)
}
fn same_shape(&self, a: &Shape, b: &Shape) -> bool {
let (Ok(a_occt), Ok(b_occt)) = (downcast(a), downcast(b)) else {
return a.is_same(b);
};
let a_guard = a_occt.borrow();
let b_guard = b_occt.borrow();
match (a_guard.as_ref(), b_guard.as_ref()) {
(Some(a_inner), Some(b_inner)) => a_inner.IsSame(b_inner),
_ => a.is_same(b),
}
}
fn element_kind(&self, shape: &Shape) -> Option<ElementKind> {
match crate::part_ops::shape_kind(shape)? {
"Solid" => Some(ElementKind::Solid),
"Shell" => Some(ElementKind::Shell),
"Face" => Some(ElementKind::Face),
"Wire" => Some(ElementKind::Wire),
"Edge" => Some(ElementKind::Edge),
"Vertex" => Some(ElementKind::Vertex),
_ => None,
}
}
fn count_sub_shapes(&self, shape: &Shape, kind: &str) -> Result<usize, GeomError> {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
if inner.IsNull() {
return Ok(0);
}
if kind == "SubShape" {
let mut count = 0;
let mut iterator = ffi::topo_ds::TopoDS_Iterator_new(inner);
while iterator.More() {
count += 1;
iterator.pin_mut().Next();
}
return Ok(count.max(0) as usize);
}
let Some(occt_kind) = count_kind(kind) else {
return Ok(0);
};
Ok(sub_shape_map(inner, occt_kind).Extent() as usize)
}
fn is_degenerate(&self, edge: &Shape) -> Result<bool, GeomError> {
let occt = downcast(edge)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null edge" })?;
if !is_edge(inner) {
return Err(OcctError::InvalidInput {
what: "not an edge",
}
.into());
}
Ok(ffi::b_rep::BRep_Tool::Degenerated(TopoDS::Edge(inner)))
}
fn is_seam(&self, edge: &Shape, face: &Shape) -> Result<bool, GeomError> {
let edge_occt = downcast(edge)?;
let face_occt = downcast(face)?;
let edge_guard = edge_occt.borrow();
let face_guard = face_occt.borrow();
let edge_inner = edge_guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null edge" })?;
let face_inner = face_guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null face" })?;
if !is_edge(edge_inner) {
return Err(OcctError::InvalidInput {
what: "not an edge",
}
.into());
}
if !is_face(face_inner) {
return Err(OcctError::InvalidInput { what: "not a face" }.into());
}
Ok(ffi::b_rep::BRep_Tool_IsClosed_edge_face(
TopoDS::Edge(edge_inner),
TopoDS::Face(face_inner),
))
}
fn edge_parameter_range(&self, edge: &Shape) -> Result<(f64, f64), GeomError> {
let occt = downcast(edge)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null edge" })?;
if !is_edge(inner) {
return Err(OcctError::InvalidInput {
what: "not an edge",
}
.into());
}
let (mut first, mut last) = (0.0, 0.0);
ffi::b_rep::BRep_Tool::Range(TopoDS::Edge(inner), &mut first, &mut last);
Ok((first, last))
}
fn face_parameter_range(&self, face: &Shape) -> Result<(f64, f64, f64, f64), GeomError> {
let occt = downcast(face)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null face" })?;
if !is_face(inner) {
return Err(OcctError::InvalidInput { what: "not a face" }.into());
}
let (mut u0, mut u1, mut v0, mut v1) = (0.0, 0.0, 0.0, 0.0);
ffi::b_rep_tools::BRepTools::UVBounds(
TopoDS::Face(inner),
&mut u0,
&mut u1,
&mut v0,
&mut v1,
);
Ok((u0, u1, v0, v1))
}
fn dist_to_shape(&self, first: &Shape, second: &Shape) -> Result<ShapeDistance, GeomError> {
let first_occt = downcast(first)?;
let second_occt = downcast(second)?;
let first_guard = first_occt.borrow();
let second_guard = second_occt.borrow();
let first_inner = first_guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let second_inner = second_guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let dist = ffi::b_rep_extrema::BRepExtrema_DistShapeShape_new(first_inner, second_inner);
if !dist.IsDone() || dist.NbSolution() < 1 {
return Err(OcctError::NotDone {
operation: "dist_to_shape",
}
.into());
}
let p1 = ffi::b_rep_extrema::BRepExtrema_DistShapeShape_point_on_shape1(&dist, 1);
let p2 = ffi::b_rep_extrema::BRepExtrema_DistShapeShape_point_on_shape2(&dist, 1);
Ok(ShapeDistance {
distance: dist.Value(),
first: Vector3::new(p1.X(), p1.Y(), p1.Z()),
second: Vector3::new(p2.X(), p2.Y(), p2.Z()),
})
}
fn is_closed(&self, shape: &Shape) -> Result<bool, GeomError> {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
Ok(policy::is_closed(inner))
}
fn shape_tolerance(&self, shape: &Shape) -> Result<f64, GeomError> {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
Ok(policy::shape_tolerance(inner))
}
fn is_inside(
&self,
shape: &Shape,
point: Vector3,
tolerance: f64,
check_face: bool,
) -> Result<bool, GeomError> {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
policy::is_inside(inner, point, tolerance, check_face).map_err(GeomError::from)
}
fn is_partner(&self, first: &Shape, second: &Shape) -> Result<bool, GeomError> {
let first_occt = downcast(first)?;
let second_occt = downcast(second)?;
let first_guard = first_occt.borrow();
let second_guard = second_occt.borrow();
match (first_guard.as_ref(), second_guard.as_ref()) {
(Some(a), Some(b)) => Ok(a.IsPartner(b)),
_ => Ok(false),
}
}
fn complement(&self, shape: &Shape) -> Result<Shape, GeomError> {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let complemented = policy::complement(inner)?;
Ok(erase(&complemented))
}
fn transform_geometry(
&self,
shape: &Shape,
matrix: &Matrix4,
copy: bool,
) -> Result<Shape, GeomError> {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let m = &matrix.m;
if m[12].abs() > 1e-12
|| m[13].abs() > 1e-12
|| m[14].abs() > 1e-12
|| (m[15] - 1.0).abs() > 1e-12
{
return Err(OcctError::InvalidInput {
what: "matrix is not affine",
}
.into());
}
let result = policy::transform_geometry(inner, m, copy)?;
Ok(erase(&result))
}
fn global_tolerance(&self, shape: &Shape, mode: i32) -> Result<f64, GeomError> {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
policy::global_tolerance(inner, mode).map_err(GeomError::from)
}
fn fix_tolerance(
&self,
shape: &Shape,
value: f64,
kind: ToleranceKind,
) -> Result<(), GeomError> {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
policy::fix_tolerance(inner, value, tolerance_shape_type(kind)).map_err(GeomError::from)
}
fn limit_tolerance(
&self,
shape: &Shape,
minimum: f64,
maximum: f64,
kind: ToleranceKind,
) -> Result<bool, GeomError> {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
policy::limit_tolerance(inner, minimum, maximum, tolerance_shape_type(kind))
.map_err(GeomError::from)
}
fn tolerance_in(
&self,
shape: &Shape,
minimum: f64,
maximum: f64,
kind: ToleranceKind,
) -> Result<Vec<Shape>, GeomError> {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let list = policy::tolerance_in(inner, minimum, maximum, tolerance_shape_type(kind))?;
Ok(list_shapes(&list))
}
fn tolerance_over(
&self,
shape: &Shape,
value: f64,
kind: ToleranceKind,
) -> Result<Vec<Shape>, GeomError> {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let list = policy::tolerance_over(inner, value, tolerance_shape_type(kind))?;
Ok(list_shapes(&list))
}
fn make_wires(
&self,
shape: &Shape,
_op: &str,
tolerance: f64,
) -> Result<Shape, GeomError> {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let wires = policy::make_wires(inner, tolerance)?;
Ok(erase(&wires))
}
fn remove_internal_wires(
&self,
shape: &Shape,
minimum_area: f64,
) -> Result<(Shape, bool), GeomError> {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let (result, performed) = policy::remove_internal_wires(inner, minimum_area)?;
Ok((erase(&result), performed))
}
fn stl_bytes(&self, shape: &Shape, deflection: f64) -> Result<Vec<u8>, GeomError> {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
if !deflection.is_finite() || deflection <= 0.0 {
return Err(OcctError::InvalidInput {
what: "the deflection is a positive number",
}
.into());
}
let bytes = crate::stl::mesh(inner, deflection)?.encode_binary();
if bytes.is_empty() {
return Err(OcctError::NotDone {
operation: "stl_bytes",
}
.into());
}
Ok(bytes)
}
fn edge_value_at(&self, edge: &Shape, t: f64) -> Result<Vector3, GeomError> {
let occt = downcast(edge)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null edge" })?;
if !is_edge(inner) {
return Err(OcctError::InvalidInput {
what: "not an edge",
}
.into());
}
let curve = ffi::b_rep_adaptor::BRepAdaptor_Curve_new(TopoDS::Edge(inner));
let point = ffi::b_rep_adaptor::BRepAdaptor_Curve_value(&curve, t);
Ok(Vector3::new(point.X(), point.Y(), point.Z()))
}
fn face_value_at(&self, face: &Shape, u: f64, v: f64) -> Result<Vector3, GeomError> {
let occt = downcast(face)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null face" })?;
if !is_face(inner) {
return Err(OcctError::InvalidInput { what: "not a face" }.into());
}
let surface = ffi::b_rep_adaptor::BRepAdaptor_Surface_new(TopoDS::Face(inner));
let point = ffi::b_rep_adaptor::BRepAdaptor_Surface_value(&surface, u, v);
Ok(Vector3::new(point.X(), point.Y(), point.Z()))
}
fn edge_discretize(
&self,
edge: &Shape,
mode: i32,
value: f64,
curvature: f64,
minimum: i32,
first: f64,
last: f64,
) -> Result<Vec<Vector3>, GeomError> {
let occt = downcast(edge)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null edge" })?;
if !is_edge(inner) {
return Err(OcctError::InvalidInput {
what: "not an edge",
}
.into());
}
let points = crate::part_ops::edge_discretize(inner, mode, value, curvature, minimum, first, last);
if points.is_empty() {
return Err(OcctError::NotDone {
operation: "edge_discretize",
}
.into());
}
Ok(points)
}
fn edge_parameter_by_length(
&self,
edge: &Shape,
length: f64,
tolerance: f64,
) -> Result<f64, GeomError> {
let occt = downcast(edge)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null edge" })?;
if !is_edge(inner) {
return Err(OcctError::InvalidInput {
what: "not an edge",
}
.into());
}
let parameter = crate::part_ops::edge_parameter_by_length(inner, length, tolerance);
if !parameter.is_finite() {
return Err(OcctError::InvalidInput {
what: "value out of range",
}
.into());
}
Ok(parameter)
}
fn shell_free_edges(&self, shell: &Shape) -> Result<Shape, GeomError> {
let occt = downcast(shell)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shell" })?;
let free = crate::part_ops::shell_free_edges(inner).map_err(GeomError::from)?;
match free.as_ref() {
Some(free) => Ok(erase(free)),
None => Err(OcctError::NotDone {
operation: "shell_free_edges",
}
.into()),
}
}
fn bspline_surface_interpolate(
&self,
rows: &[Vec<Vector3>],
) -> Result<BsplineSurfaceData, GeomError> {
crate::part_ops::bspline_surface_interpolate(rows)
}
fn bspline_surface_face(&self, rows: &[Vec<Vector3>]) -> Result<Shape, GeomError> {
let face = crate::part_ops::bspline_surface_face_from_points(rows)?;
let Some(face) = face.as_ref() else {
return Err(OcctError::NotDone {
operation: "bspline_surface_face",
}
.into());
};
Ok(erase(face))
}
fn is_equal(&self, a: &Shape, b: &Shape) -> Result<bool, GeomError> {
let a_occt = downcast(a)?;
let b_occt = downcast(b)?;
let a_guard = a_occt.borrow();
let b_guard = b_occt.borrow();
match (a_guard.as_ref(), b_guard.as_ref()) {
(Some(a_inner), Some(b_inner)) => Ok(a_inner.IsEqual(b_inner)),
_ => Ok(false),
}
}
fn copy_shape(&self, shape: &Shape) -> Result<Shape, GeomError> {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
if inner.IsNull() {
return Err(OcctError::InvalidInput { what: "null shape" }.into());
}
let mut copier = ffi::b_rep_builder_api::BRepBuilderAPI_Copy_new(inner, true, false);
if !copier.IsDone() {
return Err(OcctError::NotDone {
operation: "copy_shape",
}
.into());
}
Ok(erase(copier.pin_mut().Shape()))
}
fn shape_hash(&self, shape: &Shape) -> Result<u64, GeomError> {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
if inner.IsNull() {
return Ok(0);
}
let ptr = ffi::topo_ds::TopoDS_Shape_t_shape_ptr(inner);
let mut hasher = DefaultHasher::new();
ptr.hash(&mut hasher);
let mut hash = hasher.finish();
let location = inner.Location().HashCode() as u64;
hash ^= location
.wrapping_add(0x9e3779b97f4a7c15u64)
.wrapping_add(hash.wrapping_shl(6))
.wrapping_add(hash.wrapping_shr(2));
Ok(hash)
}
fn orientation(&self, shape: &Shape) -> Option<&'static str> {
let occt = downcast(shape).ok()?;
let guard = occt.borrow();
let inner = guard.as_ref()?;
Some(match inner.Orientation() {
TopAbs_Orientation::TopAbs_REVERSED => "Reversed",
TopAbs_Orientation::TopAbs_INTERNAL => "Internal",
TopAbs_Orientation::TopAbs_EXTERNAL => "External",
TopAbs_Orientation::TopAbs_FORWARD => "Forward",
_ => "Forward",
})
}
fn reversed(&self, shape: &Shape) -> Result<Shape, GeomError> {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let reversed = ffi::topo_ds::Reversed(inner);
let Some(reversed) = reversed.as_ref() else {
return Err(OcctError::NotDone {
operation: "reversed",
}
.into());
};
Ok(erase(reversed))
}
fn with_orientation(&self, shape: &Shape, orientation: &str) -> Result<Shape, GeomError> {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let value = match orientation {
"Forward" => 0,
"Reversed" => 1,
"Internal" => 2,
"External" => 3,
_ => {
return Err(OcctError::InvalidInput {
what: "an orientation is Forward, Reversed, Internal or External",
}
.into());
}
};
let oriented = crate::part_ops::with_orientation(inner, value);
let Some(oriented) = oriented.as_ref() else {
return Err(OcctError::NotDone {
operation: "with_orientation",
}
.into());
};
Ok(erase(oriented))
}
fn remove_shapes(&self, shape: &Shape, shapes: &[Shape]) -> Result<Shape, GeomError> {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let mut list = ffi::top_tools::new_list_of_shape();
for removal in shapes {
let removal_occt = downcast(removal)?;
let removal_guard = removal_occt.borrow();
let removal_inner = removal_guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let _ = list.pin_mut().Append(removal_inner);
}
let result = crate::shape_ops::reshape_remove(inner, &list);
let Some(result) = result.as_ref() else {
return Err(OcctError::NotDone {
operation: "remove_shapes",
}
.into());
};
Ok(erase(result))
}
fn split_edge(&self, edge: &Shape, parameters: &[f64]) -> Result<Shape, GeomError> {
let occt = downcast(edge)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null edge" })?;
if !is_edge(inner) {
return Err(OcctError::InvalidInput {
what: "split_edge needs an edge",
}
.into());
}
let split = crate::shape_ops::split_edge(inner, parameters);
let Some(split) = split.as_ref() else {
return Err(OcctError::NotDone {
operation: "split_edge",
}
.into());
};
Ok(erase(split))
}
fn replace_shapes(
&self,
shape: &Shape,
replacements: &[(Shape, Shape)],
) -> Result<Shape, GeomError> {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let mut from = ffi::top_tools::new_list_of_shape();
let mut to = ffi::top_tools::new_list_of_shape();
for (old, new) in replacements {
let old_occt = downcast(old)?;
let old_guard = old_occt.borrow();
let old_inner = old_guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let new_occt = downcast(new)?;
let new_guard = new_occt.borrow();
let new_inner = new_guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let _ = from.pin_mut().Append(old_inner);
let _ = to.pin_mut().Append(new_inner);
}
let result = crate::shape_ops::reshape_replace(inner, &from, &to);
let Some(result) = result.as_ref() else {
return Err(OcctError::NotDone {
operation: "replace_shapes",
}
.into());
};
Ok(erase(result))
}
fn static_moments(&self, shape: &Shape) -> Option<[f64; 3]> {
let occt = downcast(shape).ok()?;
let guard = occt.borrow();
let inner = guard.as_ref()?;
let mut props = ffi::g_prop::GProps_new();
ffi::b_rep_g_prop::BRepGProp::VolumeProperties(inner, props.pin_mut(), false, false, false);
let (mut lx, mut ly, mut lz) = (0.0, 0.0, 0.0);
props.StaticMoments(&mut lx, &mut ly, &mut lz);
Some([lx, ly, lz])
}
fn place(&self, shape: &Shape, placement: &Placement) -> Result<Shape, GeomError> {
let shape_occt = downcast(shape)?;
let shape_guard = shape_occt.borrow();
let s = shape_guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let trsf = transform_from(placement);
let mut op = ffi::b_rep_builder_api::BRepBuilderAPI_Transform_new(s, &trsf, true);
let out = erase(op.pin_mut().Shape());
if !op.IsDone() {
return Err(OcctError::NotDone { operation: "place" }.into());
}
Ok(out)
}
fn moved(&self, shape: &Shape, placement: &Placement) -> Result<Shape, GeomError> {
let shape_occt = downcast(shape)?;
let shape_guard = shape_occt.borrow();
let s = shape_guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let trsf = transform_from(placement);
let mut op = ffi::b_rep_builder_api::BRepBuilderAPI_Transform_new(s, &trsf, false);
let out = erase(op.pin_mut().Shape());
if !op.IsDone() {
return Err(OcctError::NotDone { operation: "moved" }.into());
}
Ok(out)
}
fn relocate(&self, shape: &Shape, placement: &Placement) -> Result<Shape, GeomError> {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
if !inner.Location().IsIdentity() {
return self.transform(shape, &placement.to_matrix());
}
let trsf = transform_from(placement);
let location = ffi::top_loc::Location_from_transform(&trsf);
let mut moved = ffi::topo_ds::TopoDS_Shape_to_owned(inner);
moved.pin_mut().set_location(&location, false);
Ok(erase(&moved))
}
fn transform(&self, shape: &Shape, matrix: &Matrix4) -> Result<Shape, GeomError> {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let mut trsf = ffi::gp::new_transform();
let m = &matrix.m;
if m.len() < 16 {
return Err(OcctError::InvalidInput {
what: "matrix is not an affine transform",
}
.into());
}
ffi::gp::gp_Trsf_SetValues(
trsf.pin_mut(),
m[0], m[1], m[2], m[3],
m[4], m[5], m[6], m[7],
m[8], m[9], m[10], m[11],
)
.map_err(|_| GeomError::from(OcctError::InvalidInput {
what: "matrix is not an affine transform",
}))?;
let mut op = ffi::b_rep_builder_api::BRepBuilderAPI_Transform_new(inner, &trsf, true);
let out = erase(op.pin_mut().Shape());
if !op.IsDone() {
return Err(OcctError::NotDone {
operation: "transform",
}
.into());
}
Ok(out)
}
fn general_transform(&self, shape: &Shape, matrix: &Matrix4) -> Result<Shape, GeomError> {
let occt = downcast(shape)?;
let guard = occt.borrow();
let inner = guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let m = &matrix.m;
if m[12].abs() > 1e-12
|| m[13].abs() > 1e-12
|| m[14].abs() > 1e-12
|| (m[15] - 1.0).abs() > 1e-12
{
return Err(OcctError::InvalidInput {
what: "matrix is not affine",
}
.into());
}
let mut transform = ffi::gp::new_gp_GTrsf();
for row in 1..=3 {
for column in 1..=4 {
let value = m[((row - 1) * 4 + (column - 1)) as usize];
transform.pin_mut().SetValue(row, column, value);
}
}
let mut op = ffi::b_rep_builder_api::BRepBuilderAPI_GTransform_new(
inner,
transform.as_ref().unwrap(),
true,
);
if !op.IsDone() {
return Err(OcctError::NotDone {
operation: "general_transform",
}
.into());
}
let result = op.pin_mut().Shape();
if result.IsNull() {
return Err(OcctError::NotDone {
operation: "general_transform",
}
.into());
}
Ok(erase(result))
}
fn resolve(&self, shape: &Shape, name: &str) -> Option<Shape> {
let shape_occt = downcast(shape).ok()?;
let shape_guard = shape_occt.borrow();
let s = shape_guard.as_ref()?;
let (kind, index) = parse_sub_name(name)?;
let map = sub_shape_map(s, kind);
if index >= 1 && index <= map.Extent() {
Some(erase(map.FindKey(index)))
} else {
None
}
}
fn save_shape(&self, shape: &Shape) -> Vec<u8> {
crate::shape::write_brep(shape).unwrap_or_default()
}
fn load_shape(&self, bytes: &[u8]) -> Option<Shape> {
crate::shape::read_brep(bytes)
}
fn capabilities(&self) -> Capabilities {
Capabilities::BOOLEANS
| Capabilities::FILLET
| Capabilities::CHAMFER
| Capabilities::TESSELLATION
| Capabilities::TOPOLOGY
}
fn tessellate(
&self,
shape: &Shape,
options: &TessellationOptions,
) -> Result<Tessellation, GeomError> {
topology::tessellate(shape, options)
}
fn elements(&self, shape: &Shape, kind: ElementKind) -> Vec<ElementRef> {
topology::elements(shape, kind)
}
fn ancestors(&self, shape: &Shape, element: &ElementRef, kind: ElementKind) -> Vec<ElementRef> {
topology::ancestors(shape, element, kind)
}
fn continuity(&self, shape: &Shape, a: &ElementRef, b: &ElementRef) -> Option<Continuity> {
topology::continuity(shape, a, b)
}
fn chamfer(
&self,
shape: &Shape,
edges: &[ElementRef],
d1: f64,
d2: Option<f64>,
) -> Result<OpResult, GeomError> {
topology::chamfer(shape, edges, d1, d2)
}
fn classify(&self, error: &GeomError) -> FailureKind {
crate::error::classify(error)
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum CutOperation {
Cut,
Fuse,
Common,
}
impl CutOperation {
fn code(self) -> ffi::bop_algo::BOPAlgo_Operation {
match self {
CutOperation::Cut => ffi::bop_algo::BOPAlgo_Operation::BOPAlgo_CUT,
CutOperation::Fuse => ffi::bop_algo::BOPAlgo_Operation::BOPAlgo_FUSE,
CutOperation::Common => ffi::bop_algo::BOPAlgo_Operation::BOPAlgo_COMMON,
}
}
fn label(self) -> &'static str {
match self {
CutOperation::Cut => "cut",
CutOperation::Fuse => "fuse",
CutOperation::Common => "common",
}
}
}
fn tolerance_shape_type(kind: ToleranceKind) -> TopAbs_ShapeEnum {
match kind {
ToleranceKind::All => TopAbs_ShapeEnum::TopAbs_SHAPE,
ToleranceKind::Solid => TopAbs_ShapeEnum::TopAbs_SOLID,
ToleranceKind::Shell => TopAbs_ShapeEnum::TopAbs_SHELL,
ToleranceKind::Face => TopAbs_ShapeEnum::TopAbs_FACE,
ToleranceKind::Wire => TopAbs_ShapeEnum::TopAbs_WIRE,
ToleranceKind::Edge => TopAbs_ShapeEnum::TopAbs_EDGE,
ToleranceKind::Vertex => TopAbs_ShapeEnum::TopAbs_VERTEX,
}
}
fn list_shapes(list: &TopTools_ListOfShape) -> Vec<Shape> {
ffi::topo_ds::shape_list_to_vector(list)
.iter()
.map(erase)
.collect()
}
fn owned(shape: &TopoDS_Shape) -> UniquePtr<TopoDS_Shape> {
ffi::topo_ds::TopoDS_Shape_to_owned(shape)
}
fn refs(shapes: &[UniquePtr<TopoDS_Shape>]) -> Vec<&TopoDS_Shape> {
shapes.iter().filter_map(|shape| shape.as_ref()).collect()
}
fn direct_children(shape: &TopoDS_Shape) -> Vec<UniquePtr<TopoDS_Shape>> {
history::children(shape)
}
fn flatten_compound(shape: &TopoDS_Shape) -> Vec<UniquePtr<TopoDS_Shape>> {
let mut out = Vec::new();
flatten_compound_into(shape, &mut out);
out
}
fn flatten_compound_into(shape: &TopoDS_Shape, out: &mut Vec<UniquePtr<TopoDS_Shape>>) {
if shape.ShapeType() == TopAbs_ShapeEnum::TopAbs_COMPOUND {
for child in direct_children(shape) {
if let Some(child) = child.as_ref() {
flatten_compound_into(child, out);
}
}
} else {
out.push(owned(shape));
}
}
fn shape_list(shapes: &[&TopoDS_Shape]) -> UniquePtr<TopTools_ListOfShape> {
let mut list = ffi::top_tools::new_list_of_shape();
for shape in shapes {
let _ = list.pin_mut().Append(shape);
}
list
}
fn compound_of(shapes: &[&TopoDS_Shape]) -> UniquePtr<TopoDS_Shape> {
let mut compound = ffi::topo_ds::TopoDS_Compound_new();
let builder = ffi::b_rep::BRep_Builder_new();
let builder = ffi::b_rep::BRep_Builder_upcast_to_topods_builder(&builder);
builder.MakeCompound(compound.pin_mut());
let mut compound = ffi::topo_ds::TopoDS_Compound_as_shape(compound);
for shape in shapes {
builder.Add(compound.pin_mut(), shape);
}
compound
}
fn build_cut_policy(
op: &mut UniquePtr<ffi::b_rep_algo_api::BRepAlgoAPI_Cut>,
arguments: &[&TopoDS_Shape],
tools: &[&TopoDS_Shape],
operation: CutOperation,
) -> Option<UniquePtr<TopoDS_Shape>> {
if operation == CutOperation::Cut
&& arguments.len() == 1
&& tools.len() == 1
&& tools[0].ShapeType() == TopAbs_ShapeEnum::TopAbs_COMPOUND
{
let mut pieces = flatten_compound(tools[0]);
if pieces.len() >= 2 {
let first = pieces.remove(0);
let rest = refs(&pieces);
let fuse_arguments = [first.as_ref().expect("a tool piece")];
let argument_list = shape_list(&fuse_arguments);
let tool_list = shape_list(&rest);
history::set_operation(op.pin_mut(), true);
history::configure_cut(op.pin_mut(), &argument_list, &tool_list);
history::build_cut(op.pin_mut());
history::set_operation(op.pin_mut(), false);
if !op.IsDone() {
return None;
}
let fused = owned(op.pin_mut().Shape());
pieces = flatten_compound(fused.as_ref().expect("the fused tool"));
}
let tool_refs = refs(&pieces);
let argument_list = shape_list(arguments);
let tool_list = shape_list(&tool_refs);
history::set_operation(op.pin_mut(), false);
history::configure_cut(op.pin_mut(), &argument_list, &tool_list);
history::build_cut(op.pin_mut());
return op.IsDone().then(|| owned(op.pin_mut().Shape()));
}
if operation == CutOperation::Cut
&& arguments.len() == 1
&& arguments[0].ShapeType() == TopAbs_ShapeEnum::TopAbs_COMPOUND
{
let mut results = Vec::new();
for child in direct_children(arguments[0]) {
let child = child.as_ref().expect("a compound child");
let child_arguments = [child];
let out = build_cut_policy(op, &child_arguments, tools, CutOperation::Cut)?;
results.push(out);
}
let result_refs = refs(&results);
return Some(compound_of(&result_refs));
}
let argument_list = shape_list(arguments);
let tool_list = shape_list(tools);
history::set_boolean_operation(op.pin_mut(), operation.code());
history::configure_cut(op.pin_mut(), &argument_list, &tool_list);
history::build_cut(op.pin_mut());
op.IsDone().then(|| owned(op.pin_mut().Shape()))
}
fn boolean(
a: &Shape,
b: &Shape,
operation: CutOperation,
tolerance: f64,
) -> Result<OpResult, GeomError> {
let a_occt = downcast(a)?;
let b_occt = downcast(b)?;
let a_guard = a_occt.borrow();
let b_guard = b_occt.borrow();
let sa = a_guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let sb = b_guard
.as_ref()
.ok_or(OcctError::InvalidInput { what: "null shape" })?;
let mut op = ffi::b_rep_algo_api::BRepAlgoAPI_Cut_new_default();
let initial_arguments = shape_list(&[sa]);
let initial_tools = shape_list(&[sb]);
history::configure_cut(op.pin_mut(), &initial_arguments, &initial_tools);
policy::cut_prepare(op.pin_mut());
policy::apply_boolean_fuzzy(op.pin_mut(), tolerance);
let result = match operation {
CutOperation::Cut => build_cut_policy(&mut op, &[sa], &[sb], CutOperation::Cut),
_ => {
history::set_boolean_operation(op.pin_mut(), operation.code());
history::build_cut(op.pin_mut());
op.IsDone().then(|| owned(op.pin_mut().Shape()))
}
};
let Some(result) = result else {
return Err(OcctError::NotDone {
operation: operation.label(),
}
.into());
};
let result = result.as_ref().expect("the boolean result");
let out_maps = sub_shape_maps(result);
let history = build_history(
[(OperandId::A, sa), (OperandId::B, sb)],
&out_maps,
|sub, mods, gens| {
history::collect(op.pin_mut().Modified(sub), mods);
history::collect(op.pin_mut().Generated(sub), gens);
op.pin_mut().IsDeleted(sub)
},
);
Ok(OpResult::new(erase(result), history))
}
const HISTORY_KINDS: [(ElementKind, TopAbs_ShapeEnum); 3] = [
(ElementKind::Face, TopAbs_ShapeEnum::TopAbs_FACE),
(ElementKind::Edge, TopAbs_ShapeEnum::TopAbs_EDGE),
(ElementKind::Vertex, TopAbs_ShapeEnum::TopAbs_VERTEX),
];
fn count_kind(kind: &str) -> Option<TopAbs_ShapeEnum> {
const KINDS: [(&str, TopAbs_ShapeEnum); 8] = [
("Vertex", TopAbs_ShapeEnum::TopAbs_VERTEX),
("Edge", TopAbs_ShapeEnum::TopAbs_EDGE),
("Face", TopAbs_ShapeEnum::TopAbs_FACE),
("Wire", TopAbs_ShapeEnum::TopAbs_WIRE),
("Shell", TopAbs_ShapeEnum::TopAbs_SHELL),
("Solid", TopAbs_ShapeEnum::TopAbs_SOLID),
("Compound", TopAbs_ShapeEnum::TopAbs_COMPOUND),
("CompSolid", TopAbs_ShapeEnum::TopAbs_COMPSOLID),
];
KINDS
.iter()
.find(|(name, _)| kind.starts_with(name))
.map(|(_, occt)| *occt)
}
fn sub_shape_maps(shape: &TopoDS_Shape) -> [(ElementKind, UniquePtr<Map>); 3] {
HISTORY_KINDS.map(|(kind, occt)| (kind, sub_shape_map(shape, occt)))
}
fn build_history<F>(
operands: [(OperandId, &TopoDS_Shape); 2],
out_maps: &[(ElementKind, UniquePtr<Map>); 3],
mut probe: F,
) -> History
where
F: FnMut(&TopoDS_Shape, &mut UniquePtr<Map>, &mut UniquePtr<Map>) -> bool,
{
let mut history = History::default();
for (operand, in_shape) in operands {
for (kind_index, (kind, occt_kind)) in HISTORY_KINDS.into_iter().enumerate() {
let in_map = sub_shape_map(in_shape, occt_kind);
let out_map = &out_maps[kind_index].1;
for ordinal in 1..=in_map.Extent() {
let element = in_map.FindKey(ordinal);
let mut mods = new_map();
let mut gens = new_map();
let deleted = probe(element, &mut mods, &mut gens);
let input_id = ElementId::new(operand, kind.prefix(), ordinal as usize);
let mut mapped = false;
for entry in 1..=mods.Extent() {
let out = mods.FindKey(entry);
let index = out_map.FindIndex(out);
if index > 0 {
history.push_modified(
element_ref(kind, ordinal, element),
input_id.clone(),
element_ref(kind, index, out),
);
mapped = true;
}
}
for entry in 1..=gens.Extent() {
let out = gens.FindKey(entry);
let index = out_map.FindIndex(out);
if index > 0 {
history.push_generated(
element_ref(kind, ordinal, element),
input_id.clone(),
element_ref(kind, index, out),
);
mapped = true;
}
}
if !mapped && deleted {
history.push_deleted(element_ref(kind, ordinal, element), input_id);
}
}
}
}
add_identity_relations(&mut history, operands, out_maps);
add_derived_names(&mut history, out_maps);
history.provenance.sort();
history
}
fn element_key(name: &str) -> Option<(ElementKind, i32)> {
for kind in [ElementKind::Face, ElementKind::Edge, ElementKind::Vertex] {
if let Some(rest) = name.strip_prefix(kind.prefix()) {
if let Ok(ordinal) = rest.parse::<i32>() {
return Some((kind, ordinal));
}
}
}
None
}
fn refine_history(before: &TopoDS_Shape, after: &TopoDS_Shape) -> History {
let mut history = History::default();
for (kind, occt_kind) in HISTORY_KINDS {
let in_map = sub_shape_map(before, occt_kind);
let out_map = sub_shape_map(after, occt_kind);
let out_keys: Vec<Option<(f64, Vector3)>> = (1..=out_map.Extent())
.map(|index| sub_shape_key(kind, &out_map.FindKey(index)))
.collect();
for ordinal in 1..=in_map.Extent() {
let element = in_map.FindKey(ordinal);
let matched = sub_shape_key(kind, &element).and_then(|key| {
let mut hits = out_keys
.iter()
.enumerate()
.filter(|(_, other)| other.as_ref().is_some_and(|other| same_key(&key, other)))
.map(|(index, _)| index as i32 + 1);
let first = hits.next()?;
if hits.next().is_some() {
return None;
}
Some(first)
});
match matched {
Some(index) => history.push_identity(
element_ref(kind, ordinal, &element),
element_ref(kind, index, &out_map.FindKey(index)),
),
None => history.push_deleted(
element_ref(kind, ordinal, &element),
ElementId::new(OperandId::A, kind.prefix(), ordinal as usize),
),
}
}
}
history.provenance.sort();
history
}
fn sub_shape_key(kind: ElementKind, shape: &TopoDS_Shape) -> Option<(f64, Vector3)> {
if kind == ElementKind::Vertex {
let point = ffi::b_rep::BRep_Tool_Pnt(ffi::topo_ds::TopoDS::Vertex(shape));
return Some((0.0, Vector3::new(point.X(), point.Y(), point.Z())));
}
crate::shape_ops::measure_key(shape)
}
fn same_key(a: &(f64, Vector3), b: &(f64, Vector3)) -> bool {
let scale = a.0.abs().max(b.0.abs()).max(1.0);
(a.0 - b.0).abs() <= 1e-7 * scale && a.1.sub(&b.1).length() <= 1e-7
}
fn add_identity_relations(
history: &mut History,
operands: [(OperandId, &TopoDS_Shape); 2],
out_maps: &[(ElementKind, UniquePtr<Map>); 3],
) {
for (_operand, in_shape) in operands {
for (kind_index, (kind, occt_kind)) in HISTORY_KINDS.into_iter().enumerate() {
let in_map = sub_shape_map(in_shape, occt_kind);
let out_map = &out_maps[kind_index].1;
for ordinal in 1..=in_map.Extent() {
let element = in_map.FindKey(ordinal);
let index = out_map.FindIndex(element);
if index > 0 {
history.push_identity(
element_ref(kind, ordinal, element),
element_ref(kind, index, out_map.FindKey(index)),
);
}
}
}
}
}
fn add_derived_names(history: &mut History, out_maps: &[(ElementKind, UniquePtr<Map>); 3]) {
let face_map = &out_maps[0].1;
let edge_map = &out_maps[1].1;
let vertex_map = &out_maps[2].1;
let mut named: BTreeSet<(ElementKind, i32)> = BTreeSet::new();
for (_, output) in history.modified.iter().chain(&history.generated) {
if let Some(key) = element_key(&output.name) {
named.insert(key);
}
}
for (_, output) in &history.identity {
if let Some(key) = element_key(&output.name) {
named.insert(key);
}
}
for (upper_kind, upper_map, lower_kind, lower_occt) in [
(
ElementKind::Face,
face_map,
ElementKind::Edge,
TopAbs_ShapeEnum::TopAbs_EDGE,
),
(
ElementKind::Edge,
edge_map,
ElementKind::Vertex,
TopAbs_ShapeEnum::TopAbs_VERTEX,
),
] {
let lower_map = if lower_kind == ElementKind::Edge {
edge_map
} else {
vertex_map
};
for index in 1..=upper_map.Extent() {
if !named.contains(&(upper_kind, index)) {
continue;
}
let upper = upper_map.FindKey(index);
let sub = sub_shape_map(upper, lower_occt);
for sub_index in 1..=sub.Extent() {
let lower_shape = sub.FindKey(sub_index);
let lower_index = lower_map.FindIndex(lower_shape);
if lower_index <= 0 || named.contains(&(lower_kind, lower_index)) {
continue;
}
history.push_derived(
element_ref(upper_kind, index, upper),
element_ref(lower_kind, lower_index, lower_map.FindKey(lower_index)),
);
named.insert((lower_kind, lower_index));
}
}
}
for index in 1..=edge_map.Extent() {
if named.contains(&(ElementKind::Edge, index)) {
continue;
}
let edge = edge_map.FindKey(index);
let Some(lower) =
complete_lower(&edge, TopAbs_ShapeEnum::TopAbs_VERTEX, vertex_map, &named)
else {
continue;
};
for ordinal in lower {
history.push_derived(
element_ref(ElementKind::Vertex, ordinal, vertex_map.FindKey(ordinal)),
element_ref(ElementKind::Edge, index, edge),
);
}
named.insert((ElementKind::Edge, index));
}
for index in 1..=face_map.Extent() {
if named.contains(&(ElementKind::Face, index)) {
continue;
}
let face = face_map.FindKey(index);
let wire = ffi::b_rep_tools::outer_wire(ffi::topo_ds::TopoDS::Face(face));
let Some(wire) = wire.as_ref() else {
continue;
};
let wire = ffi::topo_ds::cast_wire_to_shape(wire);
let Some(lower) = complete_lower(wire, TopAbs_ShapeEnum::TopAbs_EDGE, edge_map, &named)
else {
continue;
};
for ordinal in lower {
history.push_derived(
element_ref(ElementKind::Edge, ordinal, edge_map.FindKey(ordinal)),
element_ref(ElementKind::Face, index, face),
);
}
named.insert((ElementKind::Face, index));
}
}
fn complete_lower(
shape: &TopoDS_Shape,
kind: TopAbs_ShapeEnum,
map: &UniquePtr<Map>,
named: &BTreeSet<(ElementKind, i32)>,
) -> Option<Vec<i32>> {
let element_kind = if kind == TopAbs_ShapeEnum::TopAbs_EDGE {
ElementKind::Edge
} else {
ElementKind::Vertex
};
let sub = sub_shape_map(shape, kind);
let mut ordinals: Vec<i32> = Vec::new();
for index in 1..=sub.Extent() {
let index = map.FindIndex(sub.FindKey(index));
if index <= 0 || !named.contains(&(element_kind, index)) {
return None;
}
if !ordinals.contains(&index) {
ordinals.push(index);
}
}
(!ordinals.is_empty()).then_some(ordinals)
}
fn element_ref(kind: ElementKind, index: i32, shape: &TopoDS_Shape) -> ElementRef {
ElementRef {
shape: erase(shape),
name: format!("{}{index}", kind.prefix()),
}
}
fn top_level_parts(shape: &TopoDS_Shape) -> Vec<Shape> {
for kind in [
TopAbs_ShapeEnum::TopAbs_SOLID,
TopAbs_ShapeEnum::TopAbs_SHELL,
TopAbs_ShapeEnum::TopAbs_FACE,
TopAbs_ShapeEnum::TopAbs_EDGE,
TopAbs_ShapeEnum::TopAbs_WIRE,
TopAbs_ShapeEnum::TopAbs_VERTEX,
] {
let map = sub_shape_map(shape, kind);
if map.Extent() > 0 {
return (1..=map.Extent())
.map(|index| erase(map.FindKey(index)))
.collect();
}
}
Vec::new()
}
fn collect_list(list: &UniquePtr<TopTools_ListOfShape>) -> Vec<Shape> {
let Some(list) = list.as_ref() else {
return Vec::new();
};
ffi::topo_ds::shape_list_to_vector(list)
.iter()
.map(erase)
.collect()
}
fn transform_from(placement: &Placement) -> UniquePtr<ffi::gp::gp_Trsf> {
let mut trsf = ffi::gp::new_transform();
let angle = placement.rotation.angle();
if angle.abs() > 1e-12 {
let axis = placement.rotation.axis();
let dir = ffi::gp::gp_Dir_new(axis.x, axis.y, axis.z);
let origin = ffi::gp::new_point(0.0, 0.0, 0.0);
let ax1 = ffi::gp::gp_Ax1_new(&origin, &dir);
trsf.pin_mut().SetRotation(&ax1, angle);
}
let translation = ffi::gp::new_vec(placement.base.x, placement.base.y, placement.base.z);
trsf.pin_mut().set_translation_vec(&translation);
trsf
}
fn parse_sub_name(name: &str) -> Option<(TopAbs_ShapeEnum, i32)> {
for (prefix, kind) in [
("Solid", TopAbs_ShapeEnum::TopAbs_SOLID),
("Shell", TopAbs_ShapeEnum::TopAbs_SHELL),
("Face", TopAbs_ShapeEnum::TopAbs_FACE),
("Wire", TopAbs_ShapeEnum::TopAbs_WIRE),
("Edge", TopAbs_ShapeEnum::TopAbs_EDGE),
("Vertex", TopAbs_ShapeEnum::TopAbs_VERTEX),
] {
if let Some(rest) = name.strip_prefix(prefix) {
if let Ok(index) = rest.parse::<i32>() {
return Some((kind, index));
}
}
}
None
}
fn axis_from(base: Vector3, direction: Vector3) -> Result<UniquePtr<ffi::gp::gp_Ax2>, GeomError> {
if direction.x == 0.0 && direction.y == 0.0 && direction.z == 0.0 {
return Err(OcctError::InvalidInput {
what: "a primitive needs a non-zero direction",
}
.into());
}
let origin = point(base);
let direction = ffi::gp::gp_Dir_new(direction.x, direction.y, direction.z);
Ok(ffi::gp::gp_Ax2_new(&origin, &direction))
}
fn point(vector: Vector3) -> UniquePtr<ffi::gp::gp_Pnt> {
ffi::gp::new_point(vector.x, vector.y, vector.z)
}
fn flatten(points: &[Vector3]) -> Vec<f64> {
let mut coords = Vec::with_capacity(points.len() * 3);
for point in points {
coords.extend_from_slice(&[point.x, point.y, point.z]);
}
coords
}
trait ConicFrame {
fn conic_frame(&self) -> (Vector3, Vector3, Vector3, f64, f64);
}
impl ConicFrame for Ellipse {
fn conic_frame(&self) -> (Vector3, Vector3, Vector3, f64, f64) {
(
self.center(),
self.normal(),
self.x_axis(),
self.major_radius(),
self.minor_radius(),
)
}
}
impl ConicFrame for Hyperbola {
fn conic_frame(&self) -> (Vector3, Vector3, Vector3, f64, f64) {
(
self.center(),
self.normal(),
self.x_axis(),
self.major_radius(),
self.minor_radius(),
)
}
}
impl ConicFrame for Parabola {
fn conic_frame(&self) -> (Vector3, Vector3, Vector3, f64, f64) {
(
self.vertex(),
self.normal(),
self.x_axis(),
self.focal(),
0.0,
)
}
}
fn parse_edge_curve(data: &[f64]) -> Result<EdgeCurve, GeomError> {
if data.len() < 14 {
return Err(unsupported("curve_of: the bridge returned no curve data"));
}
let origin = Vector3::new(data[1], data[2], data[3]);
let direction = Vector3::new(data[4], data[5], data[6]);
let x_axis = Vector3::new(data[7], data[8], data[9]);
let (first, last) = (data[10], data[11]);
let (major, minor) = (data[12], data[13]);
let tail = &data[14..];
match data[0] as i32 {
1 => Ok(EdgeCurve::Line(Line::new(origin, direction)?)),
2 => {
let circle = Circle::with_axis(origin, direction, x_axis, major)?;
if (last - first).abs() >= std::f64::consts::TAU - 1e-9 {
Ok(EdgeCurve::Circle(circle))
} else {
Ok(EdgeCurve::Arc(Arc::new(circle, first, last)?))
}
}
3 => {
let ellipse = Ellipse::with_axis(origin, direction, x_axis, major, minor)?;
if (last - first).abs() >= std::f64::consts::TAU - 1e-9 {
Ok(EdgeCurve::Ellipse(ellipse))
} else {
Ok(EdgeCurve::EllipticalArc(EllipticalArc::new(
ellipse, first, last,
)?))
}
}
4 => {
let hyperbola = Hyperbola::with_axis(origin, direction, x_axis, major, minor)?;
Ok(EdgeCurve::ArcOfHyperbola(ArcOfHyperbola::new(
hyperbola, first, last,
)?))
}
5 => {
let parabola = Parabola::with_axis(origin, direction, x_axis, major)?;
Ok(EdgeCurve::ArcOfParabola(ArcOfParabola::new(
parabola, first, last,
)?))
}
6 => parse_bezier(tail, first, last),
7 => parse_bspline(tail),
8 => parse_offset(tail, direction, major, first, last),
_ => Err(unsupported("curve_of: unsupported curve type")),
}
}
fn parse_points(values: &[f64], count: usize) -> Result<Vec<Vector3>, GeomError> {
let count3 = count.checked_mul(3).ok_or_else(|| unsupported("curve_of: truncated poles"))?;
let coordinates = values
.get(..count3)
.ok_or_else(|| unsupported("curve_of: truncated poles"))?;
Ok(coordinates
.chunks_exact(3)
.map(|triple| Vector3::new(triple[0], triple[1], triple[2]))
.collect())
}
fn parse_bezier(tail: &[f64], first: f64, last: f64) -> Result<EdgeCurve, GeomError> {
let count = tail
.first()
.map(|value| *value as usize)
.ok_or_else(|| unsupported("curve_of: truncated Bezier"))?;
let poles = parse_points(&tail[1..], count)?;
let weight_start = 1 + count * 3;
let weights = tail
.get(weight_start..weight_start + count)
.ok_or_else(|| unsupported("curve_of: truncated Bezier weights"))?
.to_vec();
let base = BezierCurve::new(poles, weights)?;
let curve = if (first - 0.0).abs() <= 1e-12 && (last - 1.0).abs() <= 1e-12 {
base
} else {
base.trim(first, last).unwrap_or(base)
};
Ok(EdgeCurve::BezierCurve(curve))
}
fn parse_bspline(tail: &[f64]) -> Result<EdgeCurve, GeomError> {
let header = tail
.get(..5)
.ok_or_else(|| unsupported("curve_of: truncated B-spline"))?;
let degree = header[0] as i32;
let pole_count = header[1] as usize;
let knot_count = header[2] as usize;
let mult_count = header[3] as usize;
let periodic = header[4] != 0.0;
let mut at = 5;
let poles = parse_points(
tail.get(at..).ok_or_else(|| unsupported("curve_of: truncated B-spline"))?,
pole_count,
)?;
at += pole_count * 3;
let weights = tail
.get(at..at + pole_count)
.ok_or_else(|| unsupported("curve_of: truncated B-spline weights"))?
.to_vec();
at += pole_count;
let knots = tail
.get(at..at + knot_count)
.ok_or_else(|| unsupported("curve_of: truncated B-spline knots"))?
.to_vec();
at += knot_count;
let mults = tail
.get(at..at + mult_count)
.ok_or_else(|| unsupported("curve_of: truncated B-spline multiplicities"))?
.iter()
.map(|value| *value as i32)
.collect();
let curve = if periodic {
NurbsCurve::new_periodic(degree, knots, mults, poles, weights)?
} else {
NurbsCurve::new(degree, knots, mults, poles, weights)?
};
Ok(EdgeCurve::BSplineCurve(curve))
}
fn parse_offset(
tail: &[f64],
direction: Vector3,
offset: f64,
first: f64,
last: f64,
) -> Result<EdgeCurve, GeomError> {
let length = tail
.first()
.map(|value| *value as usize)
.ok_or_else(|| unsupported("curve_of: truncated offset curve"))?;
let basis_data = tail
.get(1..1 + length)
.ok_or_else(|| unsupported("curve_of: truncated offset basis"))?;
let basis = parse_edge_curve(basis_data)?;
Ok(EdgeCurve::OffsetCurve(OffsetCurve::new(
basis, offset, direction, first, last,
)?))
}
fn edge_from_conic<T: ConicFrame>(
kind: i32,
curve: &T,
first: f64,
last: f64,
what: &'static str,
) -> Result<Shape, GeomError> {
let (center, normal, x_axis, major, minor) = curve.conic_frame();
let edge = crate::curve::conic_edge(
kind,
center,
normal,
x_axis,
major,
minor,
first,
last,
);
let Some(edge) = edge else {
return Err(OcctError::NotDone { operation: what }.into());
};
Ok(erase(&edge))
}
fn edge_from_bezier(curve: &BezierCurve) -> Result<Shape, GeomError> {
let edge = crate::curve::bezier_edge(&flatten(curve.poles()), curve.weights());
let Some(edge) = edge else {
return Err(OcctError::NotDone {
operation: "make_edge (Bezier)",
}
.into());
};
Ok(erase(&edge))
}
fn edge_from_nurbs(curve: &NurbsCurve) -> Result<Shape, GeomError> {
let edge = crate::curve::bspline_edge_range(
&flatten(curve.poles()),
curve.weights(),
curve.knots(),
curve.mults(),
curve.degree(),
curve.is_periodic(),
curve.first(),
curve.last(),
);
let Some(edge) = edge else {
return Err(OcctError::NotDone {
operation: "make_edge (B-spline)",
}
.into());
};
Ok(erase(&edge))
}
fn edge_from_circle(circle: &Circle) -> Result<Shape, GeomError> {
let center = point(circle.center());
let normal = ffi::gp::gp_Dir_new(circle.normal().x, circle.normal().y, circle.normal().z);
let x_axis = circle.x_axis();
let x_dir = ffi::gp::gp_Dir_new(x_axis.x, x_axis.y, x_axis.z);
let axis = match ffi::gp::gp_Ax2_new3(¢er, &normal, &x_dir) {
Ok(axis) => axis,
Err(_) => {
return Err(OcctError::NotDone {
operation: "make_edge (circle)",
}
.into())
}
};
let circ = ffi::gp::gp_Circ_new(&axis, circle.radius());
let mut make = ffi::b_rep_builder_api::BRepBuilderAPI_MakeEdge_circle(&circ);
if !make.IsDone() {
return Err(OcctError::NotDone {
operation: "make_edge (circle)",
}
.into());
}
Ok(erase(ffi::topo_ds::cast_edge_to_shape(
make.pin_mut().Edge(),
)))
}
fn edge_from_ellipse(ellipse: &Ellipse) -> Result<Shape, GeomError> {
let edge = crate::curve::ellipse_edge(
ellipse.center(),
ellipse.normal(),
ellipse.x_axis(),
ellipse.major_radius(),
ellipse.minor_radius(),
);
let Some(edge) = edge else {
return Err(OcctError::NotDone {
operation: "make_edge (ellipse)",
}
.into());
};
Ok(erase(&edge))
}
#[cfg(test)]
mod provenance_tests {
use std::collections::{BTreeMap, BTreeSet};
use ferrocad_geom::{ElementKind, GeometryBackend, History, OperandId, Relation};
use ferrocad_types::Rotation;
use super::*;
fn overlapping_boxes(backend: &OcctBackend) -> (Shape, Shape) {
let a = backend.make_box(10.0, 10.0, 10.0).unwrap();
let b = backend
.place(
&backend.make_box(10.0, 10.0, 10.0).unwrap(),
&Placement {
base: Vector3::new(5.0, 5.0, 5.0),
rotation: Rotation::identity(),
},
)
.unwrap();
(a, b)
}
fn counts(history: &History) -> BTreeMap<(OperandId, String, Relation), usize> {
let mut counts = BTreeMap::new();
for entry in &history.provenance {
*counts
.entry((
entry.input.operand(),
entry.input.kind().to_string(),
entry.relation,
))
.or_insert(0) += 1;
}
counts
}
fn expected(
entries: &[(OperandId, &str, Relation, usize)],
) -> BTreeMap<(OperandId, String, Relation), usize> {
entries
.iter()
.map(|(operand, kind, relation, count)| {
((*operand, kind.to_string(), *relation), *count)
})
.collect()
}
fn split_name(name: &str) -> (String, usize) {
for prefix in ["Face", "Edge", "Vertex"] {
if let Some(rest) = name.strip_prefix(prefix) {
let ordinal = rest.parse().expect("a positional ordinal");
return (prefix.to_string(), ordinal);
}
}
panic!("not a positional sub-element name: {name}");
}
fn relation_projection(history: &History) -> Vec<(String, usize, Relation, Option<String>)> {
let mut entries = Vec::new();
for (input, output) in &history.modified {
let (kind, ordinal) = split_name(&input.name);
entries.push((kind, ordinal, Relation::Modified, Some(output.name.clone())));
}
for (input, output) in &history.generated {
let (kind, ordinal) = split_name(&input.name);
entries.push((
kind,
ordinal,
Relation::Generated,
Some(output.name.clone()),
));
}
for input in &history.deleted {
let (kind, ordinal) = split_name(&input.name);
entries.push((kind, ordinal, Relation::Deleted, None));
}
entries.sort();
entries
}
fn provenance_projection(history: &History) -> Vec<(String, usize, Relation, Option<String>)> {
let mut entries: Vec<_> = history
.provenance
.iter()
.map(|entry| {
(
entry.input.kind().to_string(),
entry.input.ordinal(),
entry.relation,
entry.output.clone(),
)
})
.collect();
entries.sort();
entries
}
fn relation_names(
history: &History,
) -> (Vec<(String, String)>, Vec<(String, String)>, Vec<String>) {
(
history
.modified
.iter()
.map(|(input, output)| (input.name.clone(), output.name.clone()))
.collect(),
history
.generated
.iter()
.map(|(input, output)| (input.name.clone(), output.name.clone()))
.collect(),
history
.deleted
.iter()
.map(|input| input.name.clone())
.collect(),
)
}
fn assert_histories_are_coherent(
backend: &OcctBackend,
operands: [(&Shape, OperandId); 2],
result: &Shape,
history: &History,
) {
let kinds = [ElementKind::Face, ElementKind::Edge, ElementKind::Vertex];
let total = |shape: &Shape, kind: ElementKind| backend.elements(shape, kind).len();
let mut outputs = BTreeMap::new();
for kind in kinds {
outputs.insert(kind.prefix(), total(result, kind));
}
for entry in &history.provenance {
let operand = operands
.iter()
.find(|(_, id)| *id == entry.input.operand())
.map(|(shape, _)| *shape)
.expect("a known operand");
let kind = kinds
.iter()
.find(|kind| kind.prefix() == entry.input.kind())
.copied()
.expect("Face, Edge or Vertex");
let input_total = total(operand, kind);
assert!(
(1..=input_total).contains(&entry.input.ordinal()),
"{} {}#{} is outside the operand's {input_total} elements",
entry.input.kind(),
entry.input.operand().position(),
entry.input.ordinal(),
);
if let Some(output) = &entry.output {
let (output_kind, ordinal) = split_name(output);
assert_eq!(
output_kind,
entry.input.kind(),
"an input keeps its kind in the result"
);
let output_total = outputs[output_kind.as_str()];
assert!(
ordinal >= 1 && ordinal <= output_total,
"output {output} is outside the result's {output_total} {output_kind}s",
);
}
}
assert_eq!(
provenance_projection(history),
relation_projection(history),
"every relation has exactly one identity entry",
);
let operand_ids: BTreeSet<_> = history
.provenance
.iter()
.map(|entry| entry.input.operand())
.collect();
assert_eq!(
operand_ids,
BTreeSet::from([OperandId::A, OperandId::B]),
"both operands are reported",
);
}
#[test]
fn a_boolean_honours_the_fuzzy_tolerance() {
let backend = OcctBackend::new();
let a = backend.make_box(10.0, 10.0, 10.0).unwrap();
let b = backend
.place(
&backend.make_box(10.0, 10.0, 10.0).unwrap(),
&Placement {
base: Vector3::new(10.0 + 1e-4, 0.0, 0.0),
rotation: Rotation::identity(),
},
)
.unwrap();
let exact = backend.fuse(&a, &b, 0.0).unwrap();
assert_eq!(
backend.elements(&exact.shape, ElementKind::Solid).len(),
2,
"a 1e-4 gap is wider than the confusion tolerance"
);
let fuzzy = backend.fuse(&a, &b, 1e-2).unwrap();
assert_eq!(
backend.elements(&fuzzy.shape, ElementKind::Solid).len(),
1,
"a fuzzy value wider than the gap bridges it"
);
let auto = backend.fuse(&a, &b, ferrocad_geom::AUTO_FUZZY).unwrap();
assert_eq!(
backend.elements(&auto.shape, ElementKind::Solid).len(),
2,
"the automatic value is measured from the bounds"
);
}
#[test]
fn a_general_fuse_reports_images_of_its_own_result() {
let backend = OcctBackend::new();
let a = backend.make_box(10.0, 10.0, 10.0).unwrap();
let b = backend
.place(
&backend.make_box(10.0, 10.0, 10.0).unwrap(),
&Placement {
base: Vector3::new(5.0, 0.0, 0.0),
rotation: Rotation::identity(),
},
)
.unwrap();
let edge = backend.elements(&a, ElementKind::Edge)[0].shape.clone();
let (result, split) = backend
.general_fuse(&[a.clone(), b, edge], 0.0)
.unwrap();
assert_eq!(split.len(), 3, "one group per input");
let mut reported = 0;
for pieces in &split {
for piece in pieces {
reported += 1;
let kind = backend.shape_type(piece).expect("a kind");
let element_kind = ElementKind::ALL
.into_iter()
.find(|candidate| candidate.prefix() == kind)
.expect("a known element kind");
let same_kind = backend.elements(&result, element_kind);
assert!(
same_kind
.iter()
.any(|element| backend.same_shape(&element.shape, piece)),
"a reported {kind} belongs to the returned result"
);
}
}
assert!(reported > 0, "the overlap splits an input");
}
#[test]
fn a_container_names_its_own_elements() {
use ferrocad_geom::{Lineage, MapVersion};
let backend = OcctBackend::new();
let a = backend.make_box(1.0, 2.0, 2.0).unwrap();
let b = backend.make_box(2.0, 1.0, 2.0).unwrap();
assert!(backend.intrinsic_history(&a).is_none());
let fused = backend.fuse(&a, &b, 0.0).unwrap();
let lineage = Lineage::from_history(&fused.history, MapVersion::default());
assert_eq!(lineage.reverse().len(), 58, "the boolean's own history");
let compound = backend.make_compound(&[a.clone(), b.clone()]).unwrap();
let history = backend
.intrinsic_history(&compound)
.expect("a compound of bodies names itself");
assert_eq!(history.identity.len(), 52);
assert!(history.modified.is_empty());
assert!(history.generated.is_empty());
assert!(history.deleted.is_empty());
let lineage = Lineage::from_history(&history, MapVersion::default());
assert_eq!(lineage.reverse().len(), 52);
let faces: Vec<Shape> = backend
.elements(&a, ElementKind::Face)
.into_iter()
.map(|element| element.shape)
.collect();
let lower = backend.make_compound(&faces).unwrap();
assert!(backend.intrinsic_history(&lower).is_none());
let (result, _split) = backend
.general_fuse(&[a.clone(), b.clone()], 0.0)
.unwrap();
let history = backend
.intrinsic_history(&result)
.expect("the result names itself");
assert_eq!(history.identity.len(), 60);
use ferrocad_curves::{Circle, LineSegment};
let profile = backend
.make_edge(&ferrocad_curves::EdgeCurve::Circle(
Circle::new(Vector3::zero(), Vector3::new(0.0, 0.0, 1.0), 5.0).unwrap(),
))
.unwrap();
let spine = backend
.make_edge(&ferrocad_curves::EdgeCurve::LineSegment(
LineSegment::new(Vector3::zero(), Vector3::new(0.0, 0.0, 10.0)).unwrap(),
))
.unwrap();
let sweep = backend.make_pipe(&spine, &profile, 0.001).unwrap();
assert_eq!(backend.name_every_element(&sweep).identity.len(), 6);
}
#[test]
fn a_refine_keeps_every_name_it_does_not_merge() {
let backend = OcctBackend::new();
let (a, b) = overlapping_boxes(&backend);
let fused = backend.fuse(&a, &b, 0.0).unwrap();
let refined = backend.refine(&fused.shape).expect("the backend refines");
assert!(
!refined.shape.is_same(&fused.shape),
"the unifier rebuilds the shape even when it merges nothing"
);
assert!(
refined.history.modified.is_empty() && refined.history.generated.is_empty(),
"a refine is nothing but identity and deletion"
);
assert!(
refined.history.deleted.is_empty(),
"no two faces of this fuse are coplanar, so nothing is merged"
);
assert_eq!(
refined.history.identity.len(),
["Face", "Edge", "Vertex"]
.into_iter()
.map(|kind| backend.count_sub_shapes(&fused.shape, kind).unwrap())
.sum::<usize>(),
"every face, edge and vertex keeps its name"
);
assert!(
!refined.history.identity.is_empty(),
"matching is geometric, so a rebuilt face still keeps its name"
);
}
#[test]
fn fuse_reports_both_operands_and_all_three_kinds() {
let backend = OcctBackend::new();
let (a, b) = overlapping_boxes(&backend);
let out = backend.fuse(&a, &b, 0.0).unwrap();
assert_eq!(
counts(&out.history),
expected(&[
(OperandId::A, "Face", Relation::Modified, 3),
(OperandId::A, "Edge", Relation::Modified, 3),
(OperandId::A, "Vertex", Relation::Deleted, 1),
(OperandId::B, "Face", Relation::Modified, 3),
(OperandId::B, "Edge", Relation::Modified, 3),
(OperandId::B, "Vertex", Relation::Deleted, 1),
]),
);
assert!(
out.history.generated.is_empty(),
"fuse generates no new elements"
);
assert_histories_are_coherent(
&backend,
[(&a, OperandId::A), (&b, OperandId::B)],
&out.shape,
&out.history,
);
let mut sorted = out.history.provenance.clone();
sorted.sort();
assert_eq!(sorted, out.history.provenance);
}
#[test]
fn cut_reports_both_operands_and_all_three_kinds() {
let backend = OcctBackend::new();
let (a, b) = overlapping_boxes(&backend);
let out = backend.cut(&a, &b, 0.0).unwrap();
assert_eq!(
counts(&out.history),
expected(&[
(OperandId::A, "Face", Relation::Modified, 3),
(OperandId::A, "Edge", Relation::Modified, 3),
(OperandId::A, "Vertex", Relation::Deleted, 1),
(OperandId::B, "Face", Relation::Modified, 3),
(OperandId::B, "Face", Relation::Deleted, 3),
(OperandId::B, "Edge", Relation::Modified, 3),
(OperandId::B, "Edge", Relation::Deleted, 9),
(OperandId::B, "Vertex", Relation::Deleted, 7),
]),
);
assert!(
out.history.generated.is_empty(),
"cut generates no new elements"
);
assert_histories_are_coherent(
&backend,
[(&a, OperandId::A), (&b, OperandId::B)],
&out.shape,
&out.history,
);
}
#[test]
fn the_same_boolean_twice_yields_the_same_history() {
let backend = OcctBackend::new();
let (a, b) = overlapping_boxes(&backend);
for (first, second) in [
(backend.fuse(&a, &b, 0.0).unwrap(), backend.fuse(&a, &b, 0.0).unwrap()),
(backend.cut(&a, &b, 0.0).unwrap(), backend.cut(&a, &b, 0.0).unwrap()),
] {
assert_eq!(
first.history.provenance, second.history.provenance,
"identity is deterministic",
);
assert_eq!(
relation_names(&first.history),
relation_names(&second.history),
"the relation lists are deterministic",
);
}
}
}
#[cfg(test)]
mod curve_bridge_tests {
use ferrocad_curves::{EdgeCurve, Ellipse, Vector3};
use ferrocad_geom::GeometryBackend;
use super::*;
const DEGREE: usize = 0;
const NB_POLES: usize = 2;
const NB_KNOTS: usize = 3;
const PERIODIC: usize = 4;
const FIRST_PARAMETER: usize = 12;
const LAST_PARAMETER: usize = 13;
const CONTINUITY: usize = 16;
#[test]
fn an_ellipse_round_trips_through_an_edge() {
let backend = OcctBackend::new();
let ellipse = Ellipse::with_axis(
Vector3::new(1.0, 2.0, 3.0),
Vector3::new(0.0, 0.0, 1.0),
Vector3::new(1.0, 0.0, 0.0),
5.0,
3.0,
)
.unwrap();
let edge = backend
.make_edge(&EdgeCurve::Ellipse(ellipse))
.expect("an ellipse has an OCCT edge");
let EdgeCurve::Ellipse(back) = backend.curve_of(&edge).unwrap() else {
panic!("the ellipse edge's basis curve is an ellipse");
};
assert!((back.center().sub(&ellipse.center())).length() < 1e-9);
assert!((back.major_radius() - 5.0).abs() < 1e-9);
assert!((back.minor_radius() - 3.0).abs() < 1e-9);
assert!((back.normal().sub(&ellipse.normal())).length() < 1e-9);
assert!((back.x_axis().sub(&ellipse.x_axis())).length() < 1e-9);
}
fn upstream_nurbs_poles() -> [Vector3; 4] {
[
Vector3::new(0.0, 0.0, 0.0),
Vector3::new(1.0, 1.0, 0.0),
Vector3::new(2.0, 0.0, 0.0),
Vector3::new(1.0, -1.0, 0.0),
]
}
#[test]
fn an_explicit_knot_vector_reads_back_from_occt() {
let backend = OcctBackend::new();
let poles = upstream_nurbs_poles();
let state = backend
.bspline_state(
&poles,
&[1.0; 4],
&[0.0, 0.5, 1.0],
&[3, 1, 3],
2,
false,
true,
)
.expect("the upstream NURBS builds");
assert_eq!(state.degree, 2);
assert_eq!(state.poles.len(), 4);
assert_eq!(state.knots.len(), 3);
assert!(!state.periodic);
assert_eq!(state.first_parameter, 0.0);
assert_eq!(state.last_parameter, 1.0);
assert_eq!(state.continuity, 2, "C1 at the inner knot (mult 1, degree 2)");
let edge = backend
.make_bspline_poles_mults_knots(
&poles,
&[1.0; 4],
&[0.0, 0.5, 1.0],
&[3, 1, 3],
2,
false,
true,
)
.expect("the explicit B-spline has an edge");
assert!(
matches!(backend.curve_of(&edge), Ok(EdgeCurve::BSplineCurve(_))),
"a B-spline now reports its poles, weights and knots"
);
assert_eq!(backend.elements(&edge, ElementKind::Edge).len(), 1);
}
#[test]
fn the_periodic_conversion_restructures_the_curve() {
let backend = OcctBackend::new();
let poles = [
Vector3::new(0.0, 0.0, 0.0),
Vector3::new(1.0, 1.0, 0.0),
Vector3::new(2.0, 0.0, 0.0),
];
let state = backend
.bspline_state(&poles, &[1.0; 3], &[0.0, 1.0], &[3, 3], 2, false, true)
.expect("the clamped quadratic builds");
assert!(!state.periodic);
assert_eq!(state.poles.len(), 3);
let periodic = backend
.bspline_periodic_state(
&poles,
&[1.0; 3],
&[0.0, 1.0],
&[3, 3],
2,
false,
true,
true,
)
.expect("SetPeriodic succeeds");
assert!(periodic.periodic);
assert_eq!(periodic.poles.len(), 2);
}
#[test]
fn a_periodic_bspline_round_trips_through_an_edge() {
use std::f64::consts::TAU;
let backend = OcctBackend::new();
let step = TAU / 3.0;
let poles = [
Vector3::new(5.0, 0.0, 10.0),
Vector3::new(5.0, 8.660_254_037_844_387, 10.0),
Vector3::new(-2.5, 4.330_127_018_922_193, 10.0),
Vector3::new(-10.0, 0.0, 10.0),
Vector3::new(-2.5, -4.330_127_018_922_193, 10.0),
Vector3::new(5.0, -8.660_254_037_844_387, 10.0),
];
let weights = [1.0, 0.5, 1.0, 0.5, 1.0, 0.5];
let knots = [0.0, step, 2.0 * step, TAU];
let mults = [2, 2, 2, 2];
let edge = backend
.make_bspline_poles_mults_knots(&poles, &weights, &knots, &mults, 2, true, true)
.expect("a periodic spline has an edge");
let EdgeCurve::BSplineCurve(curve) = backend.curve_of(&edge).unwrap() else {
panic!("a periodic spline reports its B-spline form");
};
assert!(curve.is_periodic());
assert_eq!(curve.degree(), 2);
assert_eq!(curve.poles().len(), 6);
assert_eq!(curve.weights(), &weights[..]);
assert_eq!(curve.knots(), &knots[..]);
assert_eq!(curve.mults(), &mults[..]);
assert!((curve.first() - 0.0).abs() < 1e-12);
assert!((curve.last() - TAU).abs() < 1e-12);
let start = curve.point_at(0.0).unwrap();
assert!((start.sub(&Vector3::new(5.0, 0.0, 10.0))).length() < 1e-9);
assert!((curve.point_at(TAU).unwrap().sub(&start)).length() < 1e-9);
let rebuilt = backend
.make_edge(&EdgeCurve::BSplineCurve(curve.clone()))
.expect("the periodic curve has an edge");
let EdgeCurve::BSplineCurve(back) = backend.curve_of(&rebuilt).unwrap() else {
panic!("the rebuilt edge still reports a B-spline");
};
assert!(back.is_periodic());
assert_eq!(back.poles().len(), 6);
for parameter in [0.0, 0.4, 1.7, 4.2, TAU - 0.1] {
let point = back.point_at(parameter).unwrap();
assert!(
point.sub(&curve.point_at(parameter).unwrap()).length() < 1e-9,
"the rebuilt curve moved at {parameter}"
);
let radius = (point.x * point.x + point.y * point.y).sqrt();
assert!((radius - 5.0).abs() < 1e-9);
}
}
#[test]
fn the_resolution_is_reported_by_occt() {
let backend = OcctBackend::new();
let poles = upstream_nurbs_poles();
let resolution = backend
.bspline_resolution(
&poles,
&[1.0; 4],
&[0.0, 0.5, 1.0],
&[3, 1, 3],
2,
false,
true,
0.5,
)
.expect("the resolution is finite");
assert!(resolution > 0.0);
}
}
#[cfg(test)]
mod shape_query_tests {
use std::f64::consts::TAU;
use ferrocad_geom::{ElementKind, GeometryBackend};
use super::*;
fn box_shape() -> Shape {
OcctBackend::new().make_box(2.0, 3.0, 4.0).expect("a box")
}
#[test]
fn count_element_counts_a_boxes_topology() {
let backend = OcctBackend::new();
let shape = box_shape();
assert_eq!(backend.count_sub_shapes(&shape, "Face").unwrap(), 6);
assert_eq!(backend.count_sub_shapes(&shape, "Edge").unwrap(), 12);
assert_eq!(backend.count_sub_shapes(&shape, "Vertex").unwrap(), 8);
assert_eq!(backend.count_sub_shapes(&shape, "Solid").unwrap(), 1);
assert_eq!(backend.count_sub_shapes(&shape, "Shell").unwrap(), 1);
assert_eq!(backend.count_sub_shapes(&shape, "Compound").unwrap(), 0);
assert_eq!(backend.count_sub_shapes(&shape, "CompSolid").unwrap(), 0);
assert_eq!(backend.count_sub_shapes(&shape, "Faces").unwrap(), 6);
assert_eq!(backend.count_sub_shapes(&shape, "SubShape").unwrap(), 1);
assert_eq!(backend.count_sub_shapes(&shape, "Bogus").unwrap(), 0);
}
#[test]
fn a_cone_apex_has_a_degenerate_edge() {
let backend = OcctBackend::new();
let cone = backend
.make_cone(5.0, 0.0, 10.0, Vector3::zero(), Vector3::new(0.0, 0.0, 1.0))
.expect("a cone with an apex");
let edges = backend.elements(&cone, ElementKind::Edge);
assert!(
edges
.iter()
.any(|edge| backend.is_degenerate(&edge.shape).unwrap()),
"the apex edge collapses to a point"
);
let box_shape = box_shape();
assert!(
backend
.elements(&box_shape, ElementKind::Edge)
.iter()
.all(|edge| !backend.is_degenerate(&edge.shape).unwrap()),
"a box has no degenerate edge"
);
}
#[test]
fn a_cylinder_seam_is_closed_on_its_face() {
let backend = OcctBackend::new();
let cylinder = backend
.make_cylinder(5.0, 10.0, Vector3::zero(), Vector3::new(0.0, 0.0, 1.0))
.expect("a cylinder");
let edges = backend.elements(&cylinder, ElementKind::Edge);
let faces = backend.elements(&cylinder, ElementKind::Face);
assert!(
edges.iter().any(|edge| faces
.iter()
.any(|face| backend.is_seam(&edge.shape, &face.shape).unwrap())),
"a full cylinder has a seam edge"
);
let box_shape = box_shape();
let box_edges = backend.elements(&box_shape, ElementKind::Edge);
let box_faces = backend.elements(&box_shape, ElementKind::Face);
assert!(
box_edges.iter().all(|edge| box_faces
.iter()
.all(|face| !backend.is_seam(&edge.shape, &face.shape).unwrap())),
"a box has no seam edge"
);
}
#[test]
fn parameter_ranges_match_the_face_and_edge_geometry() {
let backend = OcctBackend::new();
let cylinder = backend
.make_cylinder(5.0, 10.0, Vector3::zero(), Vector3::new(0.0, 0.0, 1.0))
.expect("a cylinder");
let face = backend.elements(&cylinder, ElementKind::Face)[0]
.shape
.clone();
let (u0, u1, v0, v1) = backend.face_parameter_range(&face).unwrap();
assert!((u1 - u0 - TAU).abs() < 1e-6, "a full turn in U");
assert!((v1 - v0 - 10.0).abs() < 1e-6, "the cylinder's height in V");
let box_shape = box_shape();
let edge = backend.elements(&box_shape, ElementKind::Edge)[0]
.shape
.clone();
let (first, last) = backend.edge_parameter_range(&edge).unwrap();
assert!(first.is_finite() && last.is_finite());
assert!(
[2.0, 3.0, 4.0]
.iter()
.any(|length| ((last - first) - length).abs() < 1e-9),
"a box edge spans one of the box's dimensions: {first}..{last}"
);
}
#[test]
fn is_equal_requires_the_same_orientation() {
let backend = OcctBackend::new();
let box_shape = box_shape();
let same = {
let occt = downcast(&box_shape).unwrap();
let guard = occt.borrow();
erase(guard.as_ref().unwrap())
};
assert!(backend.is_equal(&box_shape, &same).unwrap());
let reversed = backend.reversed(&box_shape).unwrap();
assert!(
backend.same_shape(&box_shape, &reversed),
"reversing changes orientation only"
);
assert!(
!backend.is_equal(&box_shape, &reversed).unwrap(),
"isEqual sees the orientation difference"
);
}
#[test]
fn a_copy_has_a_new_tshape_and_the_same_geometry() {
let backend = OcctBackend::new();
let box_shape = box_shape();
let copy = backend.copy_shape(&box_shape).expect("a deep copy");
assert!(!backend.same_shape(&box_shape, ©), "a new TShape");
assert!(!backend.is_equal(&box_shape, ©).unwrap());
let original = backend.mass_properties(&box_shape).expect("box mass");
let copied = backend.mass_properties(©).expect("copy mass");
assert!(
(original.volume - copied.volume).abs() < 1e-9,
"the copy has the same volume"
);
assert!(
(original.area - copied.area).abs() < 1e-9,
"the copy has the same area"
);
}
#[test]
fn the_shape_hash_follows_is_same_not_orientation() {
let backend = OcctBackend::new();
let box_shape = box_shape();
let hash = backend.shape_hash(&box_shape).unwrap();
let same = {
let occt = downcast(&box_shape).unwrap();
let guard = occt.borrow();
erase(guard.as_ref().unwrap())
};
assert_eq!(backend.shape_hash(&same).unwrap(), hash);
let reversed = backend.reversed(&box_shape).unwrap();
assert_eq!(backend.shape_hash(&reversed).unwrap(), hash);
let copy = backend.copy_shape(&box_shape).unwrap();
assert_ne!(backend.shape_hash(©).unwrap(), hash);
}
}
#[cfg(test)]
mod geometry_query_tests {
use std::f64::consts::{FRAC_PI_2, PI};
use ferrocad_curves::LineSegment;
use ferrocad_geom::{ElementKind, GeometryBackend};
use ferrocad_types::{Placement, Rotation};
use super::*;
fn placed_box(offset: Vector3) -> Shape {
let backend = OcctBackend::new();
backend
.place(
&backend.make_box(2.0, 2.0, 2.0).expect("a box"),
&Placement {
base: offset,
rotation: Rotation::identity(),
},
)
.expect("a placed box")
}
fn box_shape() -> Shape {
OcctBackend::new().make_box(2.0, 3.0, 4.0).expect("a box")
}
fn rectangle_face(width: f64, height: f64) -> Shape {
let backend = OcctBackend::new();
let corners = [
Vector3::new(0.0, 0.0, 0.0),
Vector3::new(width, 0.0, 0.0),
Vector3::new(width, height, 0.0),
Vector3::new(0.0, height, 0.0),
];
let mut edges = Vec::with_capacity(4);
for i in 0..4 {
let segment =
LineSegment::new(corners[i], corners[(i + 1) % 4]).expect("a rectangle side");
edges.push(
backend
.make_edge(&EdgeCurve::LineSegment(segment))
.expect("an edge"),
);
}
let wire = backend.make_wire(&edges).expect("a wire");
backend.make_face(&[wire]).expect("a face")
}
fn close(a: Vector3, b: Vector3) -> bool {
a.distance(&b) < 1e-7
}
#[test]
fn two_boxes_five_apart_report_the_gap_and_its_endpoints() {
let backend = OcctBackend::new();
let first = placed_box(Vector3::zero());
let second = placed_box(Vector3::new(7.0, 0.0, 0.0));
let result = backend.dist_to_shape(&first, &second).unwrap();
assert!((result.distance - 5.0).abs() < 1e-9, "{}", result.distance);
assert!(close(
result.first,
Vector3::new(2.0, result.first.y, result.first.z)
));
assert!(close(
result.second,
Vector3::new(7.0, result.first.y, result.first.z)
));
assert!((result.first.distance(&result.second) - 5.0).abs() < 1e-9);
}
#[test]
fn intersecting_boxes_are_zero_apart() {
let backend = OcctBackend::new();
let first = placed_box(Vector3::zero());
let second = placed_box(Vector3::new(1.0, 1.0, 1.0));
let result = backend.dist_to_shape(&first, &second).unwrap();
assert!(result.distance.abs() < 1e-9, "{}", result.distance);
assert!(close(result.first, result.second));
}
#[test]
fn a_vertex_and_a_face_report_both_closest_points() {
let backend = OcctBackend::new();
let face = rectangle_face(2.0, 3.0);
let vertex = backend
.make_vertex(Vector3::new(1.0, 1.5, 5.0))
.expect("a vertex");
let result = backend.dist_to_shape(&vertex, &face).unwrap();
assert!((result.distance - 5.0).abs() < 1e-9, "{}", result.distance);
assert!(
close(result.first, Vector3::new(1.0, 1.5, 5.0)),
"{:?}",
result.first
);
assert!(
close(result.second, Vector3::new(1.0, 1.5, 0.0)),
"{:?}",
result.second
);
let swapped = backend.dist_to_shape(&face, &vertex).unwrap();
assert!(close(swapped.first, result.second));
assert!(close(swapped.second, result.first));
assert!((swapped.distance - result.distance).abs() < 1e-9);
}
#[test]
fn a_box_solid_is_closed() {
let backend = OcctBackend::new();
assert!(backend.is_closed(&box_shape()).unwrap());
}
#[test]
fn an_open_shell_and_a_bare_face_are_not_closed() {
let backend = OcctBackend::new();
let box_shape = box_shape();
let face = backend.elements(&box_shape, ElementKind::Face)[0]
.shape
.clone();
assert!(!backend.is_closed(&face).unwrap(), "a bare face is open");
let open_shell = backend
.make_shell(std::slice::from_ref(&face))
.expect("a one-face shell");
assert!(
!backend.is_closed(&open_shell).unwrap(),
"one face leaves free boundaries"
);
}
#[test]
fn a_wire_and_an_edge_are_closed_when_they_have_no_free_ends() {
let backend = OcctBackend::new();
let circle =
Circle::new(Vector3::zero(), Vector3::new(0.0, 0.0, 1.0), 2.0).expect("a circle");
let circle_edge = backend
.make_edge(&EdgeCurve::Circle(circle))
.expect("a circle edge");
assert!(
backend.is_closed(&circle_edge).unwrap(),
"a circle edge closes on itself"
);
let closed_wire = backend
.make_wire(std::slice::from_ref(&circle_edge))
.expect("a circle wire");
assert!(backend.is_closed(&closed_wire).unwrap());
let segment =
LineSegment::new(Vector3::zero(), Vector3::new(1.0, 0.0, 0.0)).expect("a segment");
let segment_edge = backend
.make_edge(&EdgeCurve::LineSegment(segment))
.expect("a segment edge");
assert!(!backend.is_closed(&segment_edge).unwrap());
let open_wire = backend
.make_wire(std::slice::from_ref(&segment_edge))
.expect("a segment wire");
assert!(!backend.is_closed(&open_wire).unwrap());
}
#[test]
fn a_cylinders_shell_is_closed() {
let backend = OcctBackend::new();
let cylinder = backend
.make_cylinder(5.0, 10.0, Vector3::zero(), Vector3::new(0.0, 0.0, 1.0))
.expect("a cylinder");
let shells = backend.elements(&cylinder, ElementKind::Shell);
assert_eq!(shells.len(), 1);
assert!(backend.is_closed(&shells[0].shape).unwrap());
}
#[test]
fn a_fresh_box_reports_a_positive_kernel_tolerance() {
let backend = OcctBackend::new();
let box_shape = box_shape();
let tolerance = backend.shape_tolerance(&box_shape).unwrap();
assert!(tolerance.is_finite() && tolerance > 0.0, "{tolerance}");
for kind in [ElementKind::Vertex, ElementKind::Edge, ElementKind::Face] {
let element = &backend.elements(&box_shape, kind)[0].shape;
let tolerance = backend.shape_tolerance(element).unwrap();
assert!(
tolerance.is_finite() && tolerance > 0.0,
"{kind:?}: {tolerance}"
);
}
}
#[test]
fn a_box_edge_maps_its_parameter_endpoints_to_vertices() {
let backend = OcctBackend::new();
let unit = backend.make_box(1.0, 1.0, 1.0).expect("a unit box");
let edge = backend.elements(&unit, ElementKind::Edge)[0].shape.clone();
let (first, last) = backend.edge_parameter_range(&edge).unwrap();
let start = backend.edge_value_at(&edge, first).unwrap();
let end = backend.edge_value_at(&edge, last).unwrap();
let vertices: Vec<Vector3> = backend
.elements(&unit, ElementKind::Vertex)
.iter()
.map(|vertex| backend.vertex_point(&vertex.shape).expect("a vertex point"))
.collect();
assert!(
vertices.iter().any(|vertex| close(*vertex, start)),
"{start:?}"
);
assert!(vertices.iter().any(|vertex| close(*vertex, end)), "{end:?}");
assert!((start.distance(&end) - 1.0).abs() < 1e-9);
let middle = backend.edge_value_at(&edge, 0.5 * (first + last)).unwrap();
let expected = start.add(&end).scale(0.5);
assert!(close(middle, expected), "{middle:?} != {expected:?}");
}
#[test]
fn a_plane_face_evaluates_the_expected_point() {
let backend = OcctBackend::new();
let face = rectangle_face(2.0, 3.0);
let (u0, u1, v0, v1) = backend.face_parameter_range(&face).unwrap();
let center = backend
.face_value_at(&face, 0.5 * (u0 + u1), 0.5 * (v0 + v1))
.unwrap();
assert!(close(center, Vector3::new(1.0, 1.5, 0.0)), "{center:?}");
let corners = [
Vector3::new(0.0, 0.0, 0.0),
Vector3::new(2.0, 0.0, 0.0),
Vector3::new(2.0, 3.0, 0.0),
Vector3::new(0.0, 3.0, 0.0),
];
for (u, v) in [(u0, v0), (u1, v0), (u1, v1), (u0, v1)] {
let point = backend.face_value_at(&face, u, v).unwrap();
assert!(
corners.iter().any(|corner| close(*corner, point)),
"{point:?} is not a rectangle corner"
);
}
}
#[test]
fn a_sphere_face_evaluates_its_parameters_and_poles() {
let backend = OcctBackend::new();
let radius = 2.0;
let sphere = backend
.make_sphere(radius, Vector3::zero())
.expect("a sphere");
let face = backend.elements(&sphere, ElementKind::Face)[0]
.shape
.clone();
let (u0, u1, v0, v1) = backend.face_parameter_range(&face).unwrap();
assert!((u0 - 0.0).abs() < 1e-9, "u0 = {u0}");
assert!((u1 - 2.0 * PI).abs() < 1e-9, "u1 = {u1}");
assert!((v0 + FRAC_PI_2).abs() < 1e-9, "v0 = {v0}");
assert!((v1 - FRAC_PI_2).abs() < 1e-9, "v1 = {v1}");
let equator = backend.face_value_at(&face, 0.0, 0.0).unwrap();
assert!(
close(equator, Vector3::new(radius, 0.0, 0.0)),
"{equator:?}"
);
let north = backend.face_value_at(&face, 0.0, v1).unwrap();
assert!(close(north, Vector3::new(0.0, 0.0, radius)), "{north:?}");
let south = backend.face_value_at(&face, PI, v0).unwrap();
assert!(close(south, Vector3::new(0.0, 0.0, -radius)), "{south:?}");
}
#[test]
fn value_at_rejects_the_wrong_shape_type() {
let backend = OcctBackend::new();
let box_shape = box_shape();
let face = backend.elements(&box_shape, ElementKind::Face)[0]
.shape
.clone();
let edge = backend.elements(&box_shape, ElementKind::Edge)[0]
.shape
.clone();
let error = backend.edge_value_at(&face, 0.0).unwrap_err();
assert!(matches!(
error.downcast_ref::<OcctError>(),
Some(OcctError::InvalidInput { .. })
));
let error = backend.face_value_at(&edge, 0.0, 0.0).unwrap_err();
assert!(matches!(
error.downcast_ref::<OcctError>(),
Some(OcctError::InvalidInput { .. })
));
}
fn parameters(surface: &SurfaceData, point: Vector3) -> (f64, f64) {
match surface {
SurfaceData::Plane {
origin,
x_dir,
y_dir,
..
} => {
let offset = point.sub(origin);
(offset.dot(x_dir), offset.dot(y_dir))
}
SurfaceData::Cylinder {
origin,
axis,
x_dir,
direct,
..
} => {
let offset = point.sub(origin);
let mut y_dir = axis.cross(x_dir);
if !direct {
y_dir = y_dir.neg();
}
let mut u = offset.dot(&y_dir).atan2(offset.dot(x_dir));
if u < 0.0 {
u += std::f64::consts::TAU;
}
(u, offset.dot(axis))
}
SurfaceData::Sphere {
center,
axis,
x_dir,
radius,
direct,
} => {
let offset = point.sub(center);
let mut y_dir = axis.cross(x_dir);
if !direct {
y_dir = y_dir.neg();
}
let mut u = offset.dot(&y_dir).atan2(offset.dot(x_dir));
if u < 0.0 {
u += std::f64::consts::TAU;
}
let v = (offset.dot(axis) / radius).clamp(-1.0, 1.0).asin();
(u, v)
}
SurfaceData::Cone {
origin,
axis,
x_dir,
semi_angle,
direct,
..
} => {
let offset = point.sub(origin);
let mut y_dir = axis.cross(x_dir);
if !direct {
y_dir = y_dir.neg();
}
let axial = offset.dot(axis);
let radial = offset.sub(&axis.scale(axial));
let mut u = radial.dot(&y_dir).atan2(radial.dot(x_dir));
if u < 0.0 {
u += std::f64::consts::TAU;
}
(u, axial / semi_angle.cos())
}
SurfaceData::Torus {
center,
axis,
x_dir,
major_radius,
direct,
minor_radius: _,
} => {
let offset = point.sub(center);
let mut y_dir = axis.cross(x_dir);
if !direct {
y_dir = y_dir.neg();
}
let height = offset.dot(axis);
let radial = offset.sub(&axis.scale(height));
let mut u = radial.dot(&y_dir).atan2(radial.dot(x_dir));
if u < 0.0 {
u += std::f64::consts::TAU;
}
let v = height.atan2(radial.length() - major_radius);
(u, v)
}
SurfaceData::Other { .. } => panic!("a classified surface was expected"),
}
}
#[test]
fn a_box_face_is_a_plane_and_parameter_round_trips_exactly() {
let backend = OcctBackend::new();
let shape = box_shape();
let face = backend.elements(&shape, ElementKind::Face)[0]
.shape
.clone();
let surface = backend.surface_data(&face).expect("a box face has a surface");
let SurfaceData::Plane {
origin,
x_dir,
y_dir,
normal,
} = &surface
else {
panic!("a box face is planar, got {surface:?}");
};
assert!((x_dir.length() - 1.0).abs() < 1e-12);
assert!((y_dir.length() - 1.0).abs() < 1e-12);
assert!((normal.length() - 1.0).abs() < 1e-12);
assert!(x_dir.dot(y_dir).abs() < 1e-12);
assert!(normal.sub(&x_dir.cross(y_dir)).length() < 1e-12);
let (u, v) = (0.3, 0.7);
let point = backend.face_value_at(&face, u, v).unwrap();
let expected = origin.add(&x_dir.scale(u)).add(&y_dir.scale(v));
assert!(close(point, expected), "{point:?} != {expected:?}");
let (u2, v2) = parameters(&surface, point);
assert!((u2 - u).abs() < 1e-12, "u = {u2}");
assert!((v2 - v).abs() < 1e-12, "v = {v2}");
assert!(close(backend.face_value_at(&face, u2, v2).unwrap(), point));
}
#[test]
fn a_cylinder_face_is_classified_and_parameter_round_trips() {
let backend = OcctBackend::new();
let shape = backend
.make_cylinder(2.0, 5.0, Vector3::zero(), Vector3::new(0.0, 0.0, 1.0))
.expect("a cylinder");
let faces = backend.elements(&shape, ElementKind::Face);
let (face, surface) = faces
.iter()
.find_map(|face| match backend.surface_data(&face.shape) {
Some(surface @ SurfaceData::Cylinder { .. }) => {
Some((face.shape.clone(), surface))
}
_ => None,
})
.expect("a cylindrical lateral face");
let SurfaceData::Cylinder {
origin,
axis,
x_dir,
radius,
..
} = &surface
else {
unreachable!();
};
assert!((radius - 2.0).abs() < 1e-12);
assert!(axis.sub(&Vector3::new(0.0, 0.0, 1.0)).length() < 1e-12);
assert!((origin.length()).abs() < 1e-12);
assert!(x_dir.dot(axis).abs() < 1e-12);
for (u, v) in [(0.0, 0.5), (0.7, 2.0), (5.5, 4.0)] {
let point = backend.face_value_at(&face, u, v).unwrap();
let (u2, v2) = parameters(&surface, point);
assert!((u2 - u).abs() < 1e-9, "u {u} -> {u2}");
assert!((v2 - v).abs() < 1e-9, "v {v} -> {v2}");
let back = backend.face_value_at(&face, u2, v2).unwrap();
assert!(close(back, point), "{back:?} != {point:?}");
}
}
#[test]
fn a_sphere_face_is_classified_and_parameter_round_trips() {
let backend = OcctBackend::new();
let shape = backend
.make_sphere(2.0, Vector3::new(1.0, 2.0, 3.0))
.expect("a sphere");
let face = backend.elements(&shape, ElementKind::Face)[0]
.shape
.clone();
let surface = backend.surface_data(&face).expect("a sphere face has a surface");
let SurfaceData::Sphere {
center,
axis,
x_dir,
radius,
..
} = &surface
else {
panic!("a sphere face is spherical, got {surface:?}");
};
assert!((radius - 2.0).abs() < 1e-12);
assert!(center.sub(&Vector3::new(1.0, 2.0, 3.0)).length() < 1e-12);
assert!(axis.sub(&Vector3::new(0.0, 0.0, 1.0)).length() < 1e-12);
assert!(x_dir.dot(axis).abs() < 1e-12);
for (u, v) in [(0.0, 0.0), (0.8, 0.4), (4.0, -1.2)] {
let point = backend.face_value_at(&face, u, v).unwrap();
let (u2, v2) = parameters(&surface, point);
assert!((u2 - u).abs() < 1e-9, "u {u} -> {u2}");
assert!((v2 - v).abs() < 1e-9, "v {v} -> {v2}");
let back = backend.face_value_at(&face, u2, v2).unwrap();
assert!(close(back, point), "{back:?} != {point:?}");
}
}
#[test]
fn cone_and_torus_faces_are_classified_and_parameter_round_trips() {
let backend = OcctBackend::new();
let cone = backend
.make_cone(
2.0,
1.0,
4.0,
Vector3::zero(),
Vector3::new(0.0, 0.0, 1.0),
)
.expect("a cone");
let faces = backend.elements(&cone, ElementKind::Face);
let (face, surface) = faces
.iter()
.find_map(|face| match backend.surface_data(&face.shape) {
Some(surface @ SurfaceData::Cone { .. }) => Some((face.shape.clone(), surface)),
_ => None,
})
.expect("a conical face");
let SurfaceData::Cone {
origin,
axis,
x_dir,
radius,
semi_angle,
..
} = &surface
else {
unreachable!();
};
assert!((radius - 2.0).abs() < 1e-9);
assert!(semi_angle.is_finite() && semi_angle.abs() > 0.0);
assert!(x_dir.dot(axis).abs() < 1e-12);
let _ = origin;
for (u, v) in [(0.0, 0.0), (0.8, 1.5), (4.0, 3.0)] {
let point = backend.face_value_at(&face, u, v).unwrap();
let (u2, v2) = parameters(&surface, point);
assert!((u2 - u).abs() < 1e-9, "u {u} -> {u2}");
assert!((v2 - v).abs() < 1e-9, "v {v} -> {v2}");
let back = backend.face_value_at(&face, u2, v2).unwrap();
assert!(close(back, point), "{back:?} != {point:?}");
}
let edge = backend.elements(&cone, ElementKind::Edge)[0].shape.clone();
assert!(backend.surface_data(&edge).is_none());
}
}
#[cfg(test)]
mod tessellation_tests {
use ferrocad_geom::TessellationOptions;
use super::*;
fn sphere() -> Shape {
OcctBackend::new()
.make_sphere(10.0, Vector3::new(0.0, 0.0, 0.0))
.expect("a sphere")
}
fn triangle_count(linear: f64, angular: f64) -> usize {
OcctBackend::new()
.tessellate(
&sphere(),
&TessellationOptions {
linear_deflection: Some(linear),
angular_deflection: angular,
relative: false,
},
)
.expect("a tessellation")
.triangles
.len()
/ 3
}
#[test]
fn angular_deflection_changes_the_triangle_count() {
let coarse = triangle_count(2.0, 2.0);
assert!(coarse < 100, "a coarse sphere must be small, got {coarse}");
assert!(
triangle_count(2.0, 1.0) > coarse,
"a smaller angular deflection must refine the mesh"
);
assert!(
triangle_count(0.5, 0.2) > triangle_count(2.0, 1.0),
"a tighter linear deflection must refine the mesh"
);
}
#[test]
fn a_non_positive_angular_deflection_is_rejected() {
let shape = sphere();
for angular in [0.0, -0.5, f64::NAN, std::f64::consts::PI] {
let result = OcctBackend::new().tessellate(
&shape,
&TessellationOptions {
linear_deflection: Some(1.0),
angular_deflection: angular,
relative: false,
},
);
assert!(result.is_err(), "angular {angular} must be rejected");
}
}
}