Skip to content
Open
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
14 changes: 14 additions & 0 deletions developer.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,20 @@ 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`.

## 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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bad ids panic. plane_boundary indexes edges[edge] and face_loop indexes vertices[u.from] unchecked.

Suggestion: use .get(..).ok_or(GeometryError::MissingReference { .. }), as set_face_sense already does, and check to as well.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 1db7aa6. plane_boundary looks up the edge and its curve with .get(..) and returns MissingReference { kind: "edge" | "curve", .. }. face and face_with_holes check every use's edge and both its from and to vertices before they write anything (next thread), with MissingReference { kind: "edge" | "vertex", .. }. face_loop indexes only after that check.

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
125 changes: 86 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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A rejected face() leaves the builder half-written, so a corrected retry fails with "nonmanifold primitive edge".

Suggestion: in face_with_holes, check every use (edge exists, vertices exist, edge not already used twice) and build the two Intervals first, then write.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 1db7aa6. face_with_holes first builds the two Intervals, then checks every loop together: no empty loop, the edge and vertices exist, and no edge ends up with more than two uses, counting the uses it already has plus those in this face, so a seam used twice in one face is counted correctly. Only then does it push the surface, the loops and the face. The writing step can't fail. a_rejected_face_leaves_the_builder_unchanged builds five box faces and tries the sixth with a third use of an edge, then with an unknown vertex. Both are rejected, the builder's Debug output is unchanged, and the corrected sixth face gets id 5 and finishes as a solid.

&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> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

finish_solid accepts an inside-out solid after set_face_sense; validate() never reads a face's sense.

Suggestion: say in the docs that the builder does not check orientation and the caller owns it, add a face_sense getter, and have the tests prove it for the solids they build: for each face, a point just off the face along face_normal_at classifies as Outside.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 1db7aa6:

  • Docs: OG's zero-comments rule also covers ///, so the note is a short "Building a B-rep from Rust" section in developer.md. It says finish_solid validates topology and not orientation, that the caller owns each face's sense, and how to check it: a point just off each face along face_normal_at should classify as Outside. If you'd rather have it somewhere else, tell me where.
  • Getter: Builder::face_sense(face) -> Result<Orientation, GeometryError>, with MissingReference for an unknown id.
  • Tests: assert_faces_point_outward checks exactly that for every face of the solids the tests build (the box, the plate with a reversed bore, and the box finished after a rejected face). the_builder_leaves_orientation_to_the_caller turns every face of a box to Reverse, and finish_solid accepts it. Every off-face point then classifies as Inside, which pins the documented behaviour.

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 Down
5 changes: 3 additions & 2 deletions main/opengeometry/src/brep/builder/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ mod brep_builder;
mod tests;
mod wire;

pub(crate) use boundary::{boundary, dimensions, padded_uv_bounds, plane_boundary, uv_line};
pub(crate) use brep_builder::{Builder, Use};
pub use boundary::{boundary, plane_boundary, uv_conic, uv_line, UvCurve};
pub(crate) use boundary::{dimensions, padded_uv_bounds};
pub use brep_builder::{Builder, Use};
pub(crate) use wire::WireUse;
11 changes: 5 additions & 6 deletions main/opengeometry/src/brep/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,8 @@ mod validate;
pub use accuracy::Accuracy;
pub use body_type::BodyType;
pub use bounds::PatchBounds;
pub(super) use builder::{
boundary, dimensions, padded_uv_bounds, plane_boundary, uv_line, Builder, Use, WireUse,
};
pub use builder::{boundary, plane_boundary, uv_conic, uv_line, Builder, Use, UvCurve};
pub(super) use builder::{dimensions, padded_uv_bounds, WireUse};
pub(super) use error::coverage_gap;
pub use error::GeometryError;
pub use frame::Frame3;
Expand All @@ -39,9 +38,9 @@ pub use similarity::Similarity3;
#[cfg(test)]
pub(super) use topology::{circular_face, coarse_accuracy, fine_accuracy};
pub use topology::{
BrepEnvelope, Edge, Face, FaceProvenance, FaceRole, FaceSource, HalfEdge, Topology, Vertex,
BrepEnvelope, Edge, Face, FaceProvenance, FaceRole, FaceSource, HalfEdge, Orientation,
Topology, Vertex,
};
pub(super) use topology::{
EdgeGeometry, GeometryQuality, HalfEdgeGeometryUse, Loop, Orientation, Shell, SolidRegion,
TrimRegion, Wire,
EdgeGeometry, GeometryQuality, HalfEdgeGeometryUse, Loop, Shell, SolidRegion, TrimRegion, Wire,
};
Loading
Loading