Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions developer.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,50 @@ Contributor-facing notes. For end-user docs see [README.md](./README.md) and
- `main/opengeometry-three/` — Three.js wrapper (the published TypeScript SDK)
- `main/dist/` — generated npm bundle (do not edit)

## Building a B-rep from Rust

`brep::Builder` builds a body face by face for Rust crates that depend on `opengeometry`.
Edge uses are made with `boundary(edge, from, to, sense, pcurve)` (the pcurve from `uv_line`
or `uv_conic`) or `plane_boundary`, and passed to `face` or `face_with_holes`.

- An unknown edge, vertex or face id is a `MissingReference`. An edge used by a third loop
is `InvalidTopology`. A rejected face leaves the builder unchanged, so the corrected face
can be added next.
- `finish_solid` checks topology with `validate()`, **not orientation**. The caller owns
each face's sense (`set_face_sense`, read back with `face_sense`): a solid whose faces
point inward is accepted as built. To check one, take a point just off each face along
`face_normal_at`; `query::classify_point` should call it `Outside`.

## The general boolean

`operations/modifying/boolean/general` is one boolean for analytic solids, by the classic
pipeline rather than by operand family. It is the last attempt in `generic_boolean`: the
family handlers go first, and a refusal of the general boolean reports the original
coverage gap. Planes and cylinders, meeting in lines, circles and ellipses.

1. `intersect_breps` intersects every face pair whose boxes meet: closed-form curves where
the surfaces have them, traced intersection curves where not, each clipped to where it
lies on both faces.
2. `pieces`: each piece cuts the face it runs across, and its ends split the edges they lie
on. A cut over a cylinder's seam is split there on every face it crosses, and so is the
seam.
3. `flat` unrolls a face into flat (u, v): u scaled by the radius on a cylinder so lengths are
lengths, and on a periodic axis a window one period wide holding the whole face.
`arrangement` traces the face's regions there, loops with the face on their left (at every
node the first use clockwise from the way back), outer loops and the holes inside them.
4. `mod.rs` locates each region against the other solid at a point well inside it. A region
no cut crosses with a corner outside the other solid's box is outside without a probe.
5. `sew` builds the regions the operation keeps (the second solid's reversed in a
subtraction) into one body by their edges' geometry: vertices where the curves through
them meet, one edge per pair of uses with the same ends and middle, intersection pcurves
lifted by whole periods to where each face has them. A result that fails `validate()` is
an `UnresolvedIntersection`, never an invalid body.

Faces of both solids on one surface (`imprint`) cut each other where their edges lie on the
other face; a region on the other solid's boundary is kept by whether the two faces point the
same way (a union keeps the first solid's, a subtraction the opposite-facing). A region
narrower than the snap (100 x the geometric accuracy) is refused.

## Local build

```bash
Expand Down
73 changes: 54 additions & 19 deletions main/opengeometry/src/brep/builder/boundary.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use super::brep_builder::{Builder, Use};
use crate::brep::error::GeometryError;
use crate::brep::error::{missing, GeometryError};
use crate::brep::frame::Frame3;
use crate::brep::geometry::CurveGeometry;
use crate::brep::pcurve::PcurveGeometry;
Expand All @@ -15,16 +15,27 @@ pub(crate) fn dimensions(values: &[f64]) -> Result<(), GeometryError> {
Ok(())
}

pub(crate) fn plane_boundary(
pub fn plane_boundary(
builder: &Builder,
frame: Frame3,
edge: u32,
from: u32,
to: u32,
sense: Orientation,
) -> Result<Use, GeometryError> {
let curve = match builder.brep.topology.edges[edge as usize].geometry {
EdgeGeometry::Curve { curve, .. } => &builder.brep.geometry.curves[curve as usize],
let brep = &builder.brep;
let geometry = &brep
.topology
.edges
.get(edge as usize)
.ok_or_else(|| missing("edge", edge))?
.geometry;
let curve = match *geometry {
EdgeGeometry::Curve { curve, .. } => brep
.geometry
.curves
.get(curve as usize)
.ok_or_else(|| missing("curve", curve))?,
_ => {
return Err(GeometryError::InvalidGeometry(
"collapsed planar boundary".into(),
Expand All @@ -36,20 +47,20 @@ pub(crate) fn plane_boundary(
CurveGeometry::Line { origin, direction } => {
uv_line(local(sub(*origin, frame.origin)), local(*direction))
}
CurveGeometry::Circle { frame: c, radius } => PcurveGeometry::Conic2 {
origin: local(sub(c.origin, frame.origin)),
axis_a: local(scale(c.x, *radius)),
axis_b: local(scale(c.y, *radius)),
},
CurveGeometry::Circle { frame: c, radius } => uv_conic(
local(sub(c.origin, frame.origin)),
local(scale(c.x, *radius)),
local(scale(c.y, *radius)),
),
CurveGeometry::Ellipse {
frame: c,
major_radius,
minor_radius,
} => PcurveGeometry::Conic2 {
origin: local(sub(c.origin, frame.origin)),
axis_a: local(scale(c.x, *major_radius)),
axis_b: local(scale(c.y, *minor_radius)),
},
} => uv_conic(
local(sub(c.origin, frame.origin)),
local(scale(c.x, *major_radius)),
local(scale(c.y, *minor_radius)),
),
_ => {
return Err(GeometryError::UnsupportedGeometry(
"planar primitive boundary".into(),
Expand All @@ -59,22 +70,46 @@ pub(crate) fn plane_boundary(
Ok(boundary(edge, from, to, sense, pcurve))
}

pub(crate) fn uv_line(origin: [f64; 2], direction: [f64; 2]) -> PcurveGeometry {
PcurveGeometry::Line2 { origin, direction }
#[derive(Clone, Debug, PartialEq)]
pub struct UvCurve(PcurveGeometry);

impl From<PcurveGeometry> for UvCurve {
fn from(pcurve: PcurveGeometry) -> Self {
Self(pcurve)
}
}

impl From<UvCurve> for PcurveGeometry {
fn from(curve: UvCurve) -> Self {
curve.0
}
}
pub(crate) fn boundary(

pub fn uv_line(origin: [f64; 2], direction: [f64; 2]) -> UvCurve {
UvCurve(PcurveGeometry::Line2 { origin, direction })
}

pub fn uv_conic(origin: [f64; 2], axis_a: [f64; 2], axis_b: [f64; 2]) -> UvCurve {
UvCurve(PcurveGeometry::Conic2 {
origin,
axis_a,
axis_b,
})
}

pub fn boundary(
edge: u32,
from: u32,
to: u32,
sense: Orientation,
pcurve: PcurveGeometry,
pcurve: impl Into<UvCurve>,
) -> Use {
Use {
edge,
from,
to,
sense,
pcurve,
pcurve: pcurve.into().0,
}
}

Expand Down
126 changes: 87 additions & 39 deletions main/opengeometry/src/brep/builder/brep_builder.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,35 @@
use crate::brep::accuracy::Accuracy;
use crate::brep::error::GeometryError;
use crate::brep::error::{missing, GeometryError};
use crate::brep::geometry::{CurveGeometry, SurfaceGeometry};
use crate::brep::pcurve::PcurveGeometry;
use crate::brep::topology::{
BrepEnvelope, Edge, EdgeGeometry, Face, FaceProvenance, FaceRole, FaceSource, HalfEdge,
HalfEdgeGeometryUse, Loop, Orientation, Shell, SolidRegion, TrimRegion, Vertex,
};
use crate::math::{Interval, Point3};
use std::collections::BTreeMap;

pub(crate) struct Use {
pub struct Use {
pub(super) edge: u32,
pub(super) from: u32,
pub(super) to: u32,
pub(super) sense: Orientation,
pub(super) pcurve: PcurveGeometry,
}

pub(crate) struct Builder {
pub struct Builder {
pub(crate) brep: BrepEnvelope,
}
impl Builder {
pub(crate) fn new(id: String, accuracy: Accuracy) -> Result<Self, GeometryError> {
pub fn new(id: String, accuracy: Accuracy) -> Result<Self, GeometryError> {
Ok(Self {
brep: BrepEnvelope::new(id, accuracy)?,
})
}
pub(crate) fn vertex(&mut self, p: Point3) -> u32 {
pub fn brep(&self) -> &BrepEnvelope {
&self.brep
}
pub fn vertex(&mut self, p: Point3) -> u32 {
let id = self.brep.topology.vertices.len() as u32;
self.brep.topology.vertices.push(Vertex {
id,
Expand All @@ -35,7 +39,7 @@ impl Builder {
});
id
}
pub(crate) fn edge(&mut self, curve: CurveGeometry, range: Interval, seam: bool) -> u32 {
pub fn edge(&mut self, curve: CurveGeometry, range: Interval, seam: bool) -> u32 {
let curve_id = self.brep.geometry.curves.len() as u32;
self.brep.geometry.curves.push(curve);
self.edge_geometry(
Expand Down Expand Up @@ -64,35 +68,59 @@ impl Builder {
is_hole: bool,
uses: Vec<Use>,
) -> Result<u32, GeometryError> {
self.check_loops([&uses])?;
Ok(self.write_loop(face, is_hole, uses))
}
fn check_loops<'a>(
&self,
loops: impl IntoIterator<Item = &'a Vec<Use>>,
) -> Result<(), GeometryError> {
let topology = &self.brep.topology;
let mut uses_of_edge = BTreeMap::new();
for uses in loops {
if uses.is_empty() {
return Err(GeometryError::InvalidTopology(
"empty primitive face".into(),
));
}
for u in uses {
let edge = topology
.edges
.get(u.edge as usize)
.ok_or_else(|| missing("edge", u.edge))?;
if let Some(&vertex) = [u.from, u.to]
.iter()
.find(|&&vertex| vertex as usize >= topology.vertices.len())
{
return Err(missing("vertex", vertex));
}
let uses = uses_of_edge.entry(u.edge).or_insert(
usize::from(edge.halfedge != u32::MAX)
+ usize::from(edge.twin_halfedge.is_some()),
);
*uses += 1;
if *uses > 2 {
return Err(GeometryError::InvalidTopology(
"nonmanifold primitive edge".into(),
));
}
}
}
Ok(())
}
fn write_loop(&mut self, face: u32, is_hole: bool, uses: Vec<Use>) -> u32 {
let loop_id = self.brep.topology.loops.len() as u32;
let start = self.brep.topology.halfedges.len() as u32;
let count = uses.len() as u32;
if count == 0 {
return Err(GeometryError::InvalidTopology(
"empty primitive face".into(),
));
}
for (i, u) in uses.into_iter().enumerate() {
let id = start + i as u32;
let pcurve = self.brep.geometry.pcurves.len() as u32;
self.brep.geometry.pcurves.push(u.pcurve);
let e = self
.brep
.topology
.edges
.get_mut(u.edge as usize)
.ok_or_else(|| {
GeometryError::InvalidTopology("builder references missing edge".into())
})?;
let e = &mut self.brep.topology.edges[u.edge as usize];
let twin = if e.halfedge == u32::MAX {
e.halfedge = id;
None
} else {
if e.twin_halfedge.is_some() {
return Err(GeometryError::InvalidTopology(
"nonmanifold primitive edge".into(),
));
}
e.twin_halfedge = Some(id);
self.brep.topology.halfedges[e.halfedge as usize].twin = Some(id);
Some(e.halfedge)
Expand Down Expand Up @@ -127,44 +155,46 @@ impl Builder {
face_ref: face,
is_hole,
});
Ok(loop_id)
loop_id
}
pub(crate) fn face(
pub fn face(
&mut self,
key: &str,
surface: SurfaceGeometry,
bounds: [[f64; 2]; 2],
uses: Vec<Use>,
) -> Result<(), GeometryError> {
) -> Result<u32, GeometryError> {
self.face_with_holes(key, surface, bounds, uses, Vec::new())
}
pub(crate) fn face_with_holes(
pub fn face_with_holes(
&mut self,
key: &str,
surface: SurfaceGeometry,
bounds: [[f64; 2]; 2],
outer_uses: Vec<Use>,
hole_uses: Vec<Vec<Use>>,
) -> Result<(), GeometryError> {
) -> Result<u32, GeometryError> {
let uv_bounds = [
Interval::new(bounds[0][0], bounds[0][1])?,
Interval::new(bounds[1][0], bounds[1][1])?,
];
self.check_loops(std::iter::once(&outer_uses).chain(&hole_uses))?;
let surface_id = self.brep.geometry.surfaces.len() as u32;
self.brep.geometry.surfaces.push(surface);
let face = self.brep.topology.faces.len() as u32;
let outer = self.face_loop(face, false, outer_uses)?;
let mut holes = Vec::with_capacity(hole_uses.len());
for uses in hole_uses {
holes.push(self.face_loop(face, true, uses)?);
}
let outer = self.write_loop(face, false, outer_uses);
let holes = hole_uses
.into_iter()
.map(|uses| self.write_loop(face, true, uses))
.collect();
self.brep.topology.faces.push(Face {
id: face,
key: key.into(),
surface: surface_id,
sense: Orientation::Forward,
trim: TrimRegion {
chart: 0,
uv_bounds: [
Interval::new(bounds[0][0], bounds[0][1])?,
Interval::new(bounds[1][0], bounds[1][1])?,
],
uv_bounds,
outer,
holes,
},
Expand All @@ -180,9 +210,26 @@ impl Builder {
reversed: false,
},
});
Ok(face)
}
pub fn face_sense(&self, face: u32) -> Result<Orientation, GeometryError> {
self.brep
.topology
.faces
.get(face as usize)
.map(|face| face.sense)
.ok_or_else(|| missing("face", face))
}
pub fn set_face_sense(&mut self, face: u32, sense: Orientation) -> Result<(), GeometryError> {
self.brep
.topology
.faces
.get_mut(face as usize)
.ok_or_else(|| missing("face", face))?
.sense = sense;
Ok(())
}
pub(crate) fn finish_solid(mut self) -> Result<BrepEnvelope, GeometryError> {
pub fn finish_solid(mut self) -> Result<BrepEnvelope, GeometryError> {
let faces = (0..self.brep.topology.faces.len() as u32).collect();
self.brep.topology.shells.push(Shell {
id: 0,
Expand All @@ -193,6 +240,7 @@ impl Builder {
outer_shell: 0,
cavity_shells: Vec::new(),
});
self.brep.orient_loops()?;
self.brep.validate()?;
Ok(self.brep)
}
Expand Down
Loading
Loading