Skip to content
Merged
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: 11 additions & 3 deletions crates/doc/src/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1208,9 +1208,10 @@ pub enum FeatureKind {
body: Option<BodyName>,
},
/// A perforation field (#732): round holes of `diameter` on a staggered (60°) or square grid of `pitch` over the
/// whole flat sheet, kept `margin` (default: the diameter) clear of its edges, cut-outs and bend zones. Stored like
/// a cosmetic thread: the holes go to the flat pattern, the DXF and the measured volume, not into the B-rep, so a
/// panel can carry tens of thousands of them.
/// whole flat sheet, or inside the closed profiles of `sketch` when it is given, kept `margin` (default: the
/// diameter) clear of its edges, cut-outs, bend zones and the outline. Stored like a cosmetic thread: the holes go
/// to the flat pattern, the DXF and the measured volume, not into the B-rep, so a panel can carry tens of thousands
/// of them.
SheetPerforate {
#[walk(length = "Diameter")]
diameter: Expr,
Expand All @@ -1223,6 +1224,13 @@ pub enum FeatureKind {
pattern: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
body: Option<BodyName>,
/// The field's outline: a sketch on a face of the sheet. None: the whole sheet.
#[serde(default, skip_serializing_if = "Option::is_none")]
sketch: Option<SketchId>,
/// Which of the outline sketch's profiles bound the field. None: all of them.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[walk(profiles_of = sketch)]
profiles: Option<ProfileSel>,
},
/// Fold a sheet along a line on its base face: a sketch line (followed when the sketch
/// changes), else the points `a`, `b`.
Expand Down
14 changes: 12 additions & 2 deletions crates/doc/src/eval_more.rs
Original file line number Diff line number Diff line change
Expand Up @@ -684,7 +684,7 @@ pub(super) fn sheet_eval(
tag_flanges(sh, n0, f.id);
rebuild_sheet(st, i)
}
FeatureKind::SheetPerforate { diameter, pitch, margin, pattern, body } => {
FeatureKind::SheetPerforate { diameter, pitch, margin, pattern, body, sketch, profiles } => {
// Without a body name the field goes on the newest sheet, as the command's own body lookup does.
let i = match body {
Some(_) => sheet_for(st, body, None)?,
Expand All @@ -706,8 +706,18 @@ pub(super) fn sheet_eval(
"perforation needs diameter > 0, pitch > diameter and margin >= 0 (diameter {d}, pitch {pitch}, margin {margin})"
)));
}
// The outline sketch's profiles, where they lie on the sheet now.
let outline = match sketch {
Some(sk) => {
let ss = st.sketch(sk.0).ok_or_else(|| DocError::Unknown(format!("sketch {sk}")))?;
let regions = select_profiles(ss, profiles.as_ref().unwrap_or(&ProfileSel::All))?;
let sh = st.sheets.get(i).ok_or_else(|| DocError::Invalid("sheet".into()))?;
Some(sh.perforation_outline(&ss.plane, &regions)?)
}
None => None,
};
let sh = st.sheets.get_mut(i).ok_or_else(|| DocError::Invalid("sheet".into()))?;
sh.perforations.push(crate::sheet::SheetPerforation { feature: f.id, diameter: d, pitch, margin, square, from_right: false });
sh.perforations.push(crate::sheet::SheetPerforation { feature: f.id, diameter: d, pitch, margin, square, from_right: false, outline });
Ok(())
}
FeatureKind::SheetHem { edges, length, gap, flip, body } => {
Expand Down
5 changes: 4 additions & 1 deletion crates/doc/src/feature_walk_tests/fixtures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,10 @@ pub(super) fn fixtures() -> Vec<(&'static str, Value)> {
("sheet_hem", json!({"type": "sheet_hem", "edges": [o], "length": "hem.length", "gap": "hem.gap"})),
(
"sheet_perforate",
json!({"type": "sheet_perforate", "diameter": "perforate.diameter", "pitch": "perforate.pitch", "margin": "perforate.margin"}),
json!({
"type": "sheet_perforate", "diameter": "perforate.diameter", "pitch": "perforate.pitch", "margin": "perforate.margin",
"sketch": 1, "profiles": {"type": "all"}
}),
),
(
"sheet_fold",
Expand Down
1 change: 1 addition & 0 deletions crates/doc/src/feature_walk_tests/golden_geometry.txt
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ sheet_flange
sheet_hem
moves: edges[0][0], edges[0][1], edges[0][2]
sheet_perforate
profiles: 1 all
sheet_fold
moves: a[0], a[1], a[2], b[1], b[2], fixed[0], fixed[1], fixed[2]
sheet_path
Expand Down
2 changes: 2 additions & 0 deletions crates/doc/src/feature_walk_tests/golden_refs.txt
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,8 @@ sheet_flange
sheet_hem
remap_bodies: body
sheet_perforate
sketches: [1]
remap_refs: sketch
remap_bodies: body
sheet_fold
sketches: [7]
Expand Down
4 changes: 4 additions & 0 deletions crates/doc/src/format/pending/sheet-perforation-outline.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
//! A perforation field can be bounded by a sketch: a `sheet_perforate` feature saves an optional `sketch` and
//! `profiles` (its outline), and a sheet's perforation the outline in flat coordinates (`outline`). Holes go only
//! inside the outline. Older designs need no transformation: a field without an outline covers the whole sheet as
//! before. The last release refuses a design saved with this (the newer format number).
69 changes: 64 additions & 5 deletions crates/doc/src/sheet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -688,6 +688,10 @@ pub struct SheetPerforation {
/// copy, whose holes are the mirror image of its source's.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub from_right: bool,
/// The field's outline in flat coordinates (see [`SheetBody::perforation_outline`]): holes only inside these
/// regions, margin clear of their edges, on a grid that starts from their bounding box. None: the whole flat.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub outline: Option<Vec<Region2>>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
Expand Down Expand Up @@ -2104,9 +2108,45 @@ impl SheetBody {
self.flanges.iter().map(|f| self.zone(f)).collect()
}

/// A perforation field's outline (#732) in flat coordinates: closed regions of a sketch in `plane` (world). An
/// unfolded sheet takes them as drawn on the flat; a folded one through each panel whose material the plane lies
/// in, clipped to that panel, so an outline on one face never reaches a flange in the flat. Refused when the
/// plane lies in no panel.
pub fn perforation_outline(&self, plane: &Plane, regions: &[Region2]) -> Result<Vec<Region2>> {
let on = |pi: Option<usize>| {
let w = self.world(pi);
let n = apply_vector(&w, Vec3::Z);
let z = (plane.origin - apply_point(&w, Vec3::ZERO)).dot(n);
n.cross(plane.normal()).len() < 1e-6 && (-LINEAR_TOL..=self.t + LINEAR_TOL).contains(&z)
};
if self.flat {
if !on(None) {
return Err(DocError::Invalid("the perforation's outline sketch must lie on the flat sheet".into()));
}
return regions.iter().map(|r| self.region_to_flat(None, plane, r)).collect();
}
let mut work = FlatWork::new();
let mut out = Vec::new();
let mut found = false;
for (pi, panel) in self.parallel_panels(plane) {
if !on(pi) {
continue;
}
found = true;
let mapped = regions.iter().map(|r| self.region_to_flat(pi, plane, r)).collect::<Result<Vec<_>>>()?;
out.extend(material_boolean(std::slice::from_ref(&panel), &mapped, kernel::BoolOp::Intersect, &mut work)?);
}
if !found {
return Err(DocError::Invalid("the perforation's outline sketch must lie on a face of the sheet".into()));
}
Ok(out)
}

/// Hole centres of a perforation field (#732), flat coordinates: a staggered (60°, odd rows shifted half a pitch)
/// or square grid from the flat bounding box's lower-left corner plus margin + radius; a hole is kept where it is
/// at least margin clear of the material's edges and cut-outs and of every bend zone.
/// at least margin clear of the material's edges and cut-outs and of every bend zone. A field with an outline
/// keeps its holes inside the outline and margin clear of its edges too, on a grid from the lower-left corner of
/// the outline's bounding box (within the flat's).
pub fn perforation_holes(&self, p: &SheetPerforation) -> Result<Vec<Vec2>> {
let regions = self.flat_regions()?;
let zones = self.bend_zones();
Expand All @@ -2127,6 +2167,20 @@ impl SheetBody {
if !(lo.x <= hi.x) || !(p.pitch > 0.0) {
return Ok(Vec::new());
}
// The rows and columns span the flat, or the outline's part of it; the bucket grid below stays the flat's.
let mut field = Aabb2 { min: lo, max: hi };
if let Some(outline) = &p.outline {
let n = segs.len();
for r in outline {
for l in std::iter::once(&r.outer).chain(&r.holes) {
segs.extend(l.polyline(1e-3).edges().map(|(&a, &b)| (a, b)));
}
}
field = field.intersection(&segs.get(n..).unwrap_or(&[]).iter().map(|(a, _)| *a).collect::<Aabb2>());
if !(field.min.x <= field.max.x && field.min.y <= field.max.y) {
return Ok(Vec::new());
}
}
// Segments bucketed in a grid, so each hole only checks the edges near it.
let cell = (2.0 * clear).max(p.pitch).max(1.0);
let (nx, ny) = (((hi.x - lo.x) / cell) as usize + 1, ((hi.y - lo.y) / cell) as usize + 1);
Expand All @@ -2153,20 +2207,22 @@ impl SheetBody {
let dy = if p.square { p.pitch } else { p.pitch * 3f64.sqrt() / 2.0 };
let mut out = Vec::new();
let mut row = 0usize;
let Aabb2 { min: flo, max: fhi } = field;
loop {
let y = lo.y + clear + row as f64 * dy;
if y > hi.y - clear + 1e-9 {
let y = flo.y + clear + row as f64 * dy;
if y > fhi.y - clear + 1e-9 {
break;
}
let shift = if !p.square && row % 2 == 1 { p.pitch / 2.0 } else { 0.0 };
// Steps across the row from its first hole; a mirrored field counts from the right.
let mut step = 0.0;
while lo.x + clear + shift + step <= hi.x - clear + 1e-9 {
let x = if p.from_right { hi.x - clear - shift - step } else { lo.x + clear + shift + step };
while flo.x + clear + shift + step <= fhi.x - clear + 1e-9 {
let x = if p.from_right { fhi.x - clear - shift - step } else { flo.x + clear + shift + step };
let c = Vec2::new(x, y);
let (i, j) = idx(x, y);
let near = grid.get(j * nx + i).map(Vec::as_slice).unwrap_or(&[]);
if regions.iter().any(|r| r.contains(c))
&& p.outline.as_ref().is_none_or(|o| o.iter().any(|r| r.contains(c)))
&& !zones.iter().any(|z| z.contains(c))
&& near.iter().all(|&k| segs.get(k).is_none_or(|&s| dist(c, s) >= clear - 1e-9))
{
Expand Down Expand Up @@ -4733,6 +4789,9 @@ impl SheetBody {
}
for p in &mut self.perforations {
p.from_right = !p.from_right;
for r in p.outline.iter_mut().flatten() {
*r = flip_x_region(r);
}
}
for (_, a, b) in &mut self.base_curves {
(*a, *b) = (flip_x(*b), flip_x(*a));
Expand Down
9 changes: 9 additions & 0 deletions crates/engine/src/cmd/edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1748,6 +1748,15 @@ fn redefine(s: &mut Session, p: &Value) -> Result<Value> {
{
*after = before.clone();
}
// A perforation keeps its outline through an edit that names no sketch (the Perforate dialog has no outline).
if let (FeatureKind::SheetPerforate { sketch: Some(before), profiles: picked, .. }, FeatureKind::SheetPerforate { sketch, profiles, .. }) =
(&old.kind, &mut new.kind)
&& sketch.is_none()
&& params.get("sketch").is_none()
{
*sketch = Some(*before);
*profiles = picked.clone();
}
// A boundary surface's loop of sketch curves and its curve network are one command's two
// forms: an edit may turn one into the other.
let boundary = |k: &FeatureKind| matches!(k, FeatureKind::SurfaceBoundary { .. } | FeatureKind::SurfaceNetwork { .. });
Expand Down
11 changes: 9 additions & 2 deletions crates/engine/src/cmd/sheet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ pub static COMMANDS: &[CommandSpec] = &[
.contract(&PERFORATE_CONTRACT)
.output(output_schema_for::<FeatureResult>)
.params(
"diameter, pitch: expr; margin?: expr (clear of edges, cut-outs and bends; default: the diameter); pattern?: staggered (60°, default) | square; body? - a perforation field over the whole flat sheet: holes in the flat pattern (perforations), the DXF (layer PERFORATION) and the measured volume, not cut into the B-rep (#732)",
"diameter, pitch: expr; margin?: expr (clear of edges, cut-outs, bends and the outline; default: the diameter); pattern?: staggered (60°, default) | square; body?; sketch? + profiles? (the outline: closed profiles of a sketch on a face of the sheet; holes only inside them, out of their inner loops) - a perforation field over the whole flat sheet or inside the outline: holes in the flat pattern (perforations), the DXF (layer PERFORATION) and the measured volume, not cut into the B-rep (#732)",
),
CommandSpec::new("sheet.hem", "Hem", crate::checked!("sheet.hem", hem))
.at("SHEET METAL", "CREATE")
Expand Down Expand Up @@ -472,7 +472,14 @@ fn perforate(s: &mut Session, p: &Value) -> Result<Value> {
check_expr(s, m, Kind::Length, cmd, "margin")?;
}
let pattern = str_(p, "pattern").map(|t| perforation_pattern(t).map(str::to_string).map_err(|why| bad(cmd, why))).transpose()?;
add_feature(s, p, FeatureKind::SheetPerforate { diameter, pitch, margin, pattern, body: str_(p, "body").map(BodyName::from) })
// The outline: only a sketch named here, never the active one.
let sketch = match p.get("sketch") {
Some(_) => Some(SketchId(feature_sketch(s, p, cmd)?)),
None if p.get("profiles").is_some() => return Err(bad(cmd, "`profiles` picks the outline's profiles: it needs `sketch`")),
None => None,
};
let profiles = p.get("profiles").map(|_| profiles(p, cmd)).transpose()?;
add_feature(s, p, FeatureKind::SheetPerforate { diameter, pitch, margin, pattern, body: str_(p, "body").map(BodyName::from), sketch, profiles })
}

fn hem(s: &mut Session, p: &Value) -> Result<Value> {
Expand Down
Loading
Loading