Sheet metal: Path Flange, a chain of bends on an existing sheet edge (#4094) (#4096)

* claim: #4094

* Sheet metal: Path Flange, a chain of bends on an existing sheet edge (#4094)

Path Flange (`sheet.path_flange`): sketch an open chain of lines across a sheet edge, pick the
edge and one line; each line becomes a flange as long as the line and each corner a bend, one
feature and one body. The edge flange takes further bends (`then`), each on the far edge of the
one before, and the Flange dialog shows them as rows with a bin each.
This commit is contained in:
Ahmad Khan
2026-10-25 11:33:42 +00:00
committed by GitHub
parent 4e2270517a
commit 5a5a98ee80
22 changed files with 900 additions and 12 deletions
@@ -148,6 +148,7 @@ origin false
pan false
params false
paste false
path_flange false
pattern_circ false
pattern_path false
pattern_rect false
@@ -0,0 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<title>Path Flange</title>
<path d="M9.5 44L23.5 44A6 6 0 0 0 29.5 38L29.5 26A6 6 0 0 1 35.5 20L43.5 20A6 6 0 0 1 47.74 21.76L54.81 28.83" fill="none" stroke="#34465b" stroke-width="11.4" stroke-linejoin="round" stroke-linecap="round"/>
<path d="M9.5 44L23.5 44" fill="none" stroke="#b8c3cf" stroke-width="6.3" stroke-linejoin="round" stroke-linecap="round"/>
<path d="M23.5 44A6 6 0 0 0 29.5 38L29.5 26A6 6 0 0 1 35.5 20L43.5 20A6 6 0 0 1 47.74 21.76L54.81 28.83" fill="none" stroke="#328bd3" stroke-width="6.3" stroke-linejoin="round" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 638 B

@@ -0,0 +1,38 @@
{
"en": {
"Add bend": "Add bend",
"Another bend on the far edge of the last flange": "Another bend on the far edge of the last flange",
"Flanges": "Flanges",
"Further Bends": "Further Bends",
"Other way": "Other way",
"Remove this bend": "Remove this bend",
"Same way": "Same way",
"cmd.sheet_path_flange": "Path Flange",
"pick the path": "pick the path",
"set by the sketch's lines": "set by the sketch's lines"
},
"ja": {
"Add bend": "曲げを追加",
"Another bend on the far edge of the last flange": "最後のフランジの先端にさらに曲げを追加",
"Flanges": "フランジ",
"Further Bends": "追加の曲げ",
"Other way": "反対方向",
"Remove this bend": "この曲げを削除",
"Same way": "同じ方向",
"cmd.sheet_path_flange": "パスフランジ",
"pick the path": "パスを選択",
"set by the sketch's lines": "スケッチの線で決まります"
},
"zh": {
"Add bend": "添加折弯",
"Another bend on the far edge of the last flange": "在最后一个法兰的远端边上再加一道折弯",
"Flanges": "法兰",
"Further Bends": "更多折弯",
"Other way": "反方向",
"Remove this bend": "移除此折弯",
"Same way": "同方向",
"cmd.sheet_path_flange": "路径法兰",
"pick the path": "选择路径",
"set by the sketch's lines": "由草图的线条决定"
}
}
+1
View File
@@ -0,0 +1 @@
| assets/icons/ui/design/svg/model/path_flange.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 |
+16
View File
@@ -1157,6 +1157,19 @@ pub enum FeatureKind {
#[serde(default, skip_serializing_if = "Option::is_none")]
body: Option<BodyName>,
},
/// Path flange: a chain of edge flanges on the sheet edge at `edge` that follows an open
/// chain of sketch lines drawn across that edge: each line one flange as long as the line,
/// each corner one bend.
SheetPath {
edge: Position,
sketch: SketchId,
curves: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[walk(length = "Bend radius")]
radius: Option<Expr>,
#[serde(default, skip_serializing_if = "Option::is_none")]
body: Option<BodyName>,
},
/// Unfold a sheet body flat (all bends), or refold it.
SheetUnfold {
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -2202,6 +2215,7 @@ impl FeatureKind {
| FeatureKind::SheetHem { .. }
| FeatureKind::SheetPerforate { .. }
| FeatureKind::SheetFold { .. }
| FeatureKind::SheetPath { .. }
| FeatureKind::SheetUnfold { .. }
| FeatureKind::SheetConvert { .. }
)
@@ -2257,6 +2271,7 @@ impl FeatureKind {
FeatureKind::SheetHem { .. } => "HemFeature",
FeatureKind::SheetPerforate { .. } => "PerforateFeature",
FeatureKind::SheetFold { .. } => "FoldFeature",
FeatureKind::SheetPath { .. } => "PathFlangeFeature",
FeatureKind::SheetUnfold { refold: false, .. } => "UnfoldFeature",
FeatureKind::SheetUnfold { .. } => "RefoldFeature",
FeatureKind::SheetConvert { .. } => "ConvertToSheetMetalFeature",
@@ -2338,6 +2353,7 @@ impl FeatureKind {
FeatureKind::SheetHem { .. } => "Hem",
FeatureKind::SheetPerforate { .. } => "Perforate",
FeatureKind::SheetFold { .. } => "Fold",
FeatureKind::SheetPath { .. } => "PathFlange",
FeatureKind::SheetUnfold { refold: false, .. } => "Unfold",
FeatureKind::SheetUnfold { .. } => "Refold",
FeatureKind::SheetConvert { .. } => "ConvertToSheetMetal",
+32
View File
@@ -1034,6 +1034,37 @@ impl Clone for KeptSlot {
}
impl SolvedSketch {
/// The curves `ids` in order along the open chain they make, from one free end to the other,
/// whatever order they were given in. Refused unless they join end to end into one open chain.
pub fn chain_order(&self, ids: &[String]) -> Result<Vec<String>> {
let tol = 1e-5;
let mut ends = Vec::with_capacity(ids.len());
for id in ids {
let ci = self.sketch.curve_index(id).ok_or_else(|| DocError::Unknown(format!("curve `{id}`")))?;
let segs = self.sketch.segs(ci);
let (Some(first), Some(last)) = (segs.first(), segs.last()) else { return Err(DocError::Invalid(format!("curve `{id}` has no length"))) };
ends.push((id.clone(), first.start(), last.end()));
}
let joined = |p: Vec2, skip: usize| ends.iter().enumerate().any(|(k, e)| k != skip && (e.1.dist(p) < tol || e.2.dist(p) < tol));
// Start at a curve with a free end, walking away from it.
let Some((start, at)) = ends.iter().enumerate().find_map(|(k, e)| match (joined(e.1, k), joined(e.2, k)) {
(false, _) => Some((k, e.2)),
(_, false) => Some((k, e.1)),
_ => None,
}) else {
return Err(DocError::Invalid("the curves close into a loop: an open chain is needed".into()));
};
let (mut order, mut at) = (vec![start], at);
while order.len() < ends.len() {
let Some((k, e)) = ends.iter().enumerate().find(|(k, e)| !order.contains(k) && (e.1.dist(at) < tol || e.2.dist(at) < tol)) else {
return Err(DocError::Invalid("the curves are not joined end to end into one chain".into()));
};
at = if e.1.dist(at) < tol { e.2 } else { e.1 };
order.push(k);
}
Ok(order.iter().filter_map(|k| ends.get(*k).map(|e| e.0.clone())).collect())
}
/// Rough heap footprint (see [`ModelState::retained_bytes`]).
pub fn retained_bytes(&self) -> usize {
let entities = self.sketch.points.len() + self.sketch.curves.len() + self.sketch.constraints.len() + self.sketch.links.len();
@@ -6652,6 +6683,7 @@ fn eval_feature(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature, st:
| FeatureKind::SheetHem { .. }
| FeatureKind::SheetPerforate { .. }
| FeatureKind::SheetFold { .. }
| FeatureKind::SheetPath { .. }
| FeatureKind::SheetUnfold { .. }
| FeatureKind::SheetConvert { .. } => more::sheet_eval(doc, vals, f, st, warning),
FeatureKind::Boss { .. } | FeatureKind::Lip { .. } | FeatureKind::SnapFit { .. } | FeatureKind::Rest { .. } => {
+37
View File
@@ -620,6 +620,43 @@ pub(super) fn sheet_eval(
tag_flanges(sh, n0, f.id);
rebuild_sheet(st, i)
}
FeatureKind::SheetPath { edge, sketch, curves, radius, body } => {
let ss = st.sketch(sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {sketch}")))?.clone();
if curves.is_empty() || curves.len() > sheet::MAX_PATH_LINES {
return Err(DocError::Invalid(format!("a path flange's path must have 1…{} lines", sheet::MAX_PATH_LINES)));
}
for id in curves {
let ci = ss.sketch.curve_index(id).ok_or_else(|| DocError::Unknown(format!("curve `{id}`")))?;
if !ss.sketch.segs(ci).iter().all(|s| matches!(s, Seg2::Line { .. })) {
return Err(DocError::Invalid("not supported yet: arcs in a path flange's path (use lines; the bends are made for you)".into()));
}
}
let path: Vec<Vec3> = chain_points(&ss, &ss.chain_order(curves)?)?.into_iter().map(|p| ss.plane.to_world(p)).collect();
let i = sheet_for(st, body, Some(edge.0))?;
let rr = match radius {
Some(e) => val(vals, e, Kind::Length)?,
None => {
let rule = st.sheets.get(i).map(|s| s.rule.clone()).unwrap_or_default();
doc.rule_values(vals, &doc.sheet_rule(Some(&rule)))?.bend_radius
}
};
let sh = st.sheets.get_mut(i).ok_or_else(|| DocError::Invalid("sheet".into()))?;
if sh.flat {
return Err(DocError::Invalid("refold the sheet before adding flanges".into()));
}
let pick = sheet_picks(sh, f, &[edge.0], warning).first().copied().unwrap_or(edge.0);
let n0 = sh.flanges.len();
let (_, notes) = sh.add_path_flange(pick, &path, rr, sheet::ReliefOverride::default())?;
if !notes.is_empty() {
let notes = notes.join("; ");
*warning = Some(match warning.take() {
Some(w) => format!("{w}; {notes}"),
None => notes,
});
}
tag_flanges(sh, n0, f.id);
rebuild_sheet(st, i)
}
FeatureKind::SheetPerforate { diameter, pitch, margin, pattern, body } => {
// Without a body name the field goes on the newest sheet, as the command's own body lookup does.
let i = match body {
@@ -145,6 +145,7 @@ pub(super) fn fixtures() -> Vec<(&'static str, Value)> {
"sheet_fold",
json!({"type": "sheet_fold", "a": o, "b": [1, 0, 0], "angle": "fold.angle", "radius": "fold.radius", "position": "centerline"}),
),
("sheet_path", json!({"type": "sheet_path", "edge": o, "sketch": 1, "curves": ["l1"], "radius": "path.radius"})),
("sheet_unfold", json!({"type": "sheet_unfold"})),
("sheet_convert", json!({"type": "sheet_convert", "body": "B", "face": o})),
(
@@ -238,8 +239,8 @@ pub(super) fn with_refs(name: &str, mut v: Value) -> Value {
let extra = match name {
"extrude" | "extrude_thin" | "revolve" | "sweep" | "sweep_options" | "pipe" | "coil" | "thicken" => json!({"targets": ["B"]}),
"fillet_constant" | "fillet_chord" | "fillet_curvature" | "fillet_variable" | "fillet_spline" | "chamfer" | "shell" | "draft"
| "offset_face" | "delete_face" | "replace_face" | "sheet_flange" | "sheet_hem" | "sheet_perforate" | "sheet_unfold" | "boss" | "lip"
| "snap_fit" | "rest" | "surface_offset" => {
| "offset_face" | "delete_face" | "replace_face" | "sheet_flange" | "sheet_hem" | "sheet_perforate" | "sheet_path" | "sheet_unfold"
| "boss" | "lip" | "snap_fit" | "rest" | "surface_offset" => {
json!({"body": "B"})
}
"combine" => json!({"target": "B", "tools": ["B"]}),
@@ -286,6 +286,10 @@ sheet_fold
Angle = fold.angle (Angle)
Bend radius = fold.radius (Length)
expressions: fold.angle, fold.radius
sheet_path
inputs:
Bend radius = path.radius (Length)
expressions: path.radius
sheet_unfold
sheet_convert
boss
@@ -129,6 +129,8 @@ sheet_hem
sheet_perforate
sheet_fold
moves: a[0], a[1], a[2], b[1], b[2], fixed[0], fixed[1], fixed[2]
sheet_path
moves: edge[0], edge[1], edge[2]
sheet_unfold
sheet_convert
moves: bends[0][0], bends[0][1], bends[0][2], face[0], face[1], face[2]
@@ -146,6 +146,10 @@ sheet_fold
sketches: [7]
remap_refs: sketch
remap_bodies: body
sheet_path
sketches: [1]
remap_refs: sketch
remap_bodies: body
sheet_unfold
remap_bodies: body
sheet_convert
@@ -0,0 +1,4 @@
//! A design can hold a path flange (`sheet_path`): a chain of edge flanges on a sheet edge
//! that follows an open chain of sketch lines drawn across it. Older designs need no
//! transformation: they have none. The last release refuses a design saved with one (the newer
//! format number).
+111
View File
@@ -558,6 +558,9 @@ pub struct EdgeFlange {
pub angle: f64,
}
/// The most lines a path flange's path may have (each one flange and its bend).
pub const MAX_PATH_LINES: usize = 64;
/// A sheet metal body (see the module docs).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SheetBody {
@@ -1111,6 +1114,18 @@ impl SheetBody {
mat_mul(&self.frame_mat(), &f)
}
/// A world point on flange `i`'s far edge, nearer the top face than the bottom one: where to
/// pick that edge for a flange that stands on it (a chain of bends, one flange after another).
/// The side is not left to a tie in the middle of the thickness: it decides which way the
/// flange bends, and `flip` turns it the other way.
pub fn far_edge_pick(&self, i: usize) -> Option<Vec3> {
let f = self.flanges.get(i)?;
let (u0, u1) = self.far_edge(f);
let mid = f.p + f.n * (self.allowance(f) + f.leg) + f.d * ((u0 + u1) / 2.0);
let at = apply_point(&self.world(Some(i)), v3(mid) + Vec3::Z * (self.t * 0.75));
(at.x.is_finite() && at.y.is_finite() && at.z.is_finite()).then_some(at)
}
/// Where a flat point of a piece lands (folded), at height `z` in the sheet.
fn map3(&self, piece: Piece, q: Vec2, z: f64) -> Vec3 {
match piece {
@@ -2373,6 +2388,102 @@ impl SheetBody {
self.add_flanges_each(&each, radius, position, flip, ReliefOverride::default())
}
/// A path flange: a chain of edge flanges on the edge nearest `pick` that follows `path`, an
/// open chain of world points drawn on a plane across that edge, from the end nearer the edge.
/// Each line of the path is one flange, its length the flange's height (to the outer face from
/// the virtual sharp, as for an edge flange), and each corner one bend: the first line's angle
/// to the sheet makes the first bend, the turn between two lines the next. Which way the path
/// turns says which way each bend goes. Returns the flanges made, in order, and the notes of
/// the first one's corners.
pub fn add_path_flange(&mut self, pick: Vec3, path: &[Vec3], radius: f64, relief: ReliefOverride) -> Result<(Vec<usize>, Vec<String>)> {
if path.len() < 2 || path.len() > MAX_PATH_LINES + 1 {
return Err(DocError::Invalid(format!("a path flange's path must have 1…{MAX_PATH_LINES} lines")));
}
if !path.iter().all(|p| p.x.is_finite() && p.y.is_finite() && p.z.is_finite()) {
return Err(DocError::Invalid("the path flange's path is not finite".into()));
}
let (panel, a, b, top, dist) = self.edge_at(pick).ok_or_else(|| DocError::Invalid("no sheet edge there".into()))?;
if dist > self.t * 2.0 + 1e-3 {
return Err(DocError::Invalid("pick an edge of the sheet's top or bottom face".into()));
}
let d = (b - a).normalized().ok_or_else(|| DocError::Invalid("edge".into()))?;
// The edge's frame in the world: along it, out of the sheet past it, and the top face's normal.
let w = self.world(panel);
let at = apply_point(&w, v3(a));
let dir = |v: Vec3| apply_point(&w, v3(a) + v) - at;
let (along, out, up) = (dir(v3(d)), dir(v3(Vec2::new(d.y, -d.x))), dir(Vec3::Z));
// From the end nearer the edge.
let off = |p: Vec3| {
let q = p - at;
(q - along * q.dot(along)).len()
};
let path: Vec<Vec3> = match (path.first(), path.last()) {
(Some(&f), Some(&l)) if off(l) < off(f) => path.iter().rev().copied().collect(),
_ => path.to_vec(),
};
// Each line's length and its direction in the plane across the edge (out, up).
let mut lines: Vec<(f64, f64)> = Vec::with_capacity(path.len() - 1);
for (k, pair) in path.windows(2).enumerate() {
let [p, q] = pair else { continue };
let v = *q - *p;
let len = v.len();
if !(len > 1e-6) {
return Err(DocError::Invalid(format!("line {} of the path flange's path has no length", k + 1)));
}
if v.dot(along).abs() > len * 1e-4 {
return Err(DocError::Invalid("draw the path flange's path on a plane across the edge (square to it)".into()));
}
let heading = v.dot(up).atan2(v.dot(out));
// A line straight on from the one before lengthens it.
match lines.last_mut() {
Some((l, h)) if (heading - *h).abs() < 1e-9 => *l += len,
_ => lines.push((len, heading)),
}
}
// Each bend's turn: the first from the sheet, the others from the line before. A turn
// toward the panel's top face is positive.
let mut turns = Vec::with_capacity(lines.len());
let mut before = 0.0;
for (k, &(len, heading)) in lines.iter().enumerate() {
let mut turn = heading - before;
while turn > std::f64::consts::PI {
turn -= std::f64::consts::TAU;
}
while turn <= -std::f64::consts::PI {
turn += std::f64::consts::TAU;
}
if !(turn.abs() > 1e-6 && turn.abs() < std::f64::consts::PI - 1e-6) {
let what = if k == 0 { "the sheet" } else { "the line before it" };
return Err(DocError::Invalid(format!(
"line {} of the path flange's path runs straight on from {what} or back over it: each line must turn",
k + 1
)));
}
turns.push((len, turn));
before = heading;
}
let mut made = Vec::with_capacity(turns.len());
let mut notes = Vec::new();
for (k, &(height, turn)) in turns.iter().enumerate() {
let line = |e: DocError| match e {
DocError::Invalid(m) => DocError::Invalid(format!("line {}: {m}", k + 1)),
e => e,
};
// The first bend on the picked face's side; each after it on the last flange's far
// edge, picked nearer its top face, so `flip` turns it toward the bottom one.
let (at, flip) = match made.last() {
None => (pick, top == (turn < 0.0)),
Some(&i) => (self.far_edge_pick(i).ok_or_else(|| DocError::Invalid("the flange has no far edge to bend again".into()))?, turn < 0.0),
};
let each = [EdgeFlange { pick: at, height, angle: turn.abs() }];
let own = if k == 0 { relief } else { ReliefOverride::default() };
let (new, more) = self.add_flanges_each(&each, radius, "inside", flip, own).map_err(line)?;
made.extend(new);
notes.extend(more);
}
Ok((made, notes))
}
/// Edge flanges that each have their own height and angle, in one go: every edge is trimmed
/// back by its own setback first, then the flanges are added and the corners between them
/// are closed. The closing works from the two flanges it joins (each one's own fold and
+1
View File
@@ -1332,6 +1332,7 @@ fn redefine(s: &mut Session, p: &Value) -> Result<Value> {
| "sheet.hem"
| "sheet.perforate"
| "sheet.fold"
| "sheet.path_flange"
| "sheet.unfold"
| "sheet.refold"
| "sheet.convert"
+110 -7
View File
@@ -1,4 +1,4 @@
//! Sheet metal: rules, Flange (base, edge, contour), Hem, Unfold/Refold, Convert to Sheet Metal,
//! Sheet metal: rules, Flange (base, edge, contour), Path Flange, Hem, Unfold/Refold, Convert to Sheet Metal,
//! the flat pattern (outline, bend lines, bend table) and its DXF export.
use serde_json::{Value, json};
@@ -21,10 +21,16 @@ pub static COMMANDS: &[CommandSpec] = &[
height (to the outer face), angle? (default 90 deg), radius? (default: rule), \
position?: inside|outside|middle, flip?, body?, corner_relief_shape?: notch|round|rectangular|tear and corner_relief? (size across): \
the relief at the corners these flanges make (default: the rule's); \
then?: [{angle?, height, flip?}] further bends (at most 16), each a flange on the far edge of the one before, flip: true turns that bend the other way (edge only); \
type?: base|edge|contour (default from the inputs); name?, body_name? (the new body). \
Thickness, K-factor and bend radius come from the rule (sheet.manage_rules); passing them here is refused, \
and so is the corner relief on a base or contour flange",
),
CommandSpec::new("sheet.path_flange", "Path Flange", path_flange).at("SHEET METAL", "CREATE").icon("path_flange").params(
"edge: [x,y,z] on a top or bottom edge of the sheet; sketch + curves: an open chain of sketch lines drawn on a plane across \
that edge, from the edge out (each line one flange as long as the line, to the outer face from the virtual sharp; each \
corner one bend, turning the way the lines turn); radius? (default: rule); body?. One feature, one body",
),
CommandSpec::new("sheet.perforate", "Perforate", perforate).at("SHEET METAL", "CREATE").icon("perforate").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)",
),
@@ -99,6 +105,58 @@ fn points(p: &Value, k: &str, cmd: &str) -> Result<Vec<Vec3>> {
/// The `edges` of an edge flange: points `[x, y, z]` on sheet edges, or `{point, angle?, height?}`
/// for an edge with its own angle and height (expressions, checked like the feature's).
/// Most bends `then` may add after an edge flange's own.
const MAX_THEN: usize = 16;
/// One further bend of an edge flange: its angle, its height and, if it has its own, which way
/// it turns (`flip`; the flange's own otherwise).
type ThenStep = (solidcraft_doc::Expr, solidcraft_doc::Expr, Option<bool>);
/// The further bends of an edge flange (`then`): each an angle and a height, made one after
/// the other, every one on the far edge of the flange before it.
fn then_steps(s: &Session, p: &Value, cmd: &str) -> Result<Vec<ThenStep>> {
let Some(v) = p.get("then").filter(|v| !v.is_null()) else { return Ok(Vec::new()) };
let list = "`then` must list further bends {angle?, height, flip?}: each on the far edge of the flange before it";
let a = v.as_array().ok_or_else(|| bad(cmd, list))?;
if a.len() > MAX_THEN {
return Err(bad(cmd, format!("`then` may list at most {MAX_THEN} bends")));
}
let mut out = Vec::with_capacity(a.len());
for (i, step) in a.iter().enumerate() {
let o = step.as_object().ok_or_else(|| bad(cmd, format!("then[{i}]: {list}")))?;
if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "angle" | "height" | "flip")) {
return Err(bad(cmd, format!("then[{i}]: unknown key `{k}` (a bend takes angle, height and flip)")));
}
let flip = match o.get("flip").filter(|v| !v.is_null()) {
Some(v) => Some(v.as_bool().ok_or_else(|| bad(cmd, format!("then[{i}]: `flip` must be true or false")))?),
None => None,
};
let height = req_expr(cmd, step, "height").map_err(|_| bad(cmd, format!("then[{i}]: `height` is required")))?;
check_expr(s, &height, Kind::Length, cmd, &format!("then[{i}].height"))?;
let angle = expr(step, "angle").unwrap_or_else(|| "90 deg".into());
check_expr(s, &angle, Kind::Angle, cmd, &format!("then[{i}].angle"))?;
out.push((angle, height, flip));
}
Ok(out)
}
/// Where to pick the far edges of the flanges feature `id` made: a point on each, for the flanges
/// of the next bend of a chain.
fn far_edge_picks(s: &Session, id: u64, cmd: &str) -> Result<Vec<FlangeEdge>> {
let prefix = format!("F{id}.");
let st = s.model.state();
let picks: Vec<FlangeEdge> = st
.sheets
.iter()
.flat_map(|sh| sh.flanges.iter().enumerate().filter(|(_, f)| f.tag.starts_with(&prefix)).filter_map(|(i, _)| sh.far_edge_pick(i)))
.map(FlangeEdge::at)
.collect();
if picks.is_empty() {
return Err(bad(cmd, "the flange has no far edge to bend again"));
}
Ok(picks)
}
fn flange_edges(s: &Session, p: &Value, cmd: &str) -> Result<Vec<FlangeEdge>> {
const KEYS: [&str; 3] = ["point", "angle", "height"];
let list = "`edges` must list points [x, y, z] on sheet edges, or {point, angle?, height?}";
@@ -165,6 +223,9 @@ fn flange(s: &mut Session, p: &Value) -> Result<Value> {
),
));
}
if ty != "edge" && p.get("then").is_some_and(|v| !v.is_null()) {
return Err(bad(cmd, "`then` (further bends) is only for edge flanges"));
}
match ty.as_str() {
"base" => {
let sketch = feature_sketch(s, p, cmd)?;
@@ -199,6 +260,7 @@ fn flange(s: &mut Session, p: &Value) -> Result<Value> {
}
"edge" => {
let edges = flange_edges(s, p, cmd)?;
let then = then_steps(s, p, cmd)?;
let height = req_expr(cmd, p, "height")?;
check_expr(s, &height, Kind::Length, cmd, "height")?;
let angle = expr(p, "angle").unwrap_or_else(|| "90 deg".into());
@@ -229,21 +291,43 @@ fn flange(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(c) = &corner_relief {
check_expr(s, c, Kind::Length, cmd, "corner_relief")?;
}
add_feature(
let flip = bool_(p, "flip").unwrap_or(false);
let mut made = add_feature(
s,
p,
FeatureKind::SheetFlange {
edges,
height,
angle,
radius,
position,
flip: bool_(p, "flip").unwrap_or(false),
body: body.map(BodyName),
radius: radius.clone(),
position: position.clone(),
flip,
body: body.clone().map(BodyName),
corner_relief_shape,
corner_relief,
},
)
)?;
// Each further bend stands on the far edge of the flange before it.
for (angle, height, own_flip) in then {
let id = made.get("feature").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "no feature to bend again"))?;
let edges = far_edge_picks(s, id, cmd)?;
made = add_feature(
s,
&json!({}),
FeatureKind::SheetFlange {
edges,
height,
angle,
radius: radius.clone(),
position: position.clone(),
flip: own_flip.unwrap_or(flip),
body: body.clone().map(BodyName),
corner_relief_shape: None,
corner_relief: None,
},
)?;
}
Ok(made)
}
other => Err(bad(cmd, format!("unknown flange type `{other}` (base, edge or contour)"))),
}
@@ -360,6 +444,25 @@ fn fold(s: &mut Session, p: &Value) -> Result<Value> {
Ok(r)
}
fn path_flange(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sheet.path_flange";
let edge = p.get("edge").and_then(vec3).ok_or_else(|| bad(cmd, "`edge` must be a point [x, y, z] on a sheet edge"))?;
let sketch = sketch_id(s, p.get("sketch"), cmd, "sketch")?;
let curves = string_list(p, "curves");
if curves.is_empty() || curves.len() > sheet::MAX_PATH_LINES {
return Err(bad(cmd, format!("`curves` must list the path's lines (1…{})", sheet::MAX_PATH_LINES)));
}
let radius = expr(p, "radius");
if let Some(r) = &radius {
check_expr(s, r, Kind::Length, cmd, "radius")?;
}
add_feature(
s,
p,
FeatureKind::SheetPath { edge: Position(edge), sketch: SketchId(sketch), curves, radius, body: str_(p, "body").map(BodyName::from) },
)
}
fn unfold(s: &mut Session, p: &Value) -> Result<Value> {
add_feature(s, p, FeatureKind::SheetUnfold { body: str_(p, "body").map(BodyName::from), refold: false })
}
+206
View File
@@ -543,6 +543,212 @@ fn contour_flange_hem_and_tray() {
assert!(rel(v, want) < 1e-4 && rel(v, 29666.234) < 1e-4, "{v} {want}");
}
/// A 150 x 100 base on a 2 mm rule with one 40 mm wall on its left edge: the part a chained
/// flap (#4094) is made on.
fn wall_bracket(s: &mut Session) {
run(
s,
"sheet.manage_rules",
json!({"name": "Demo", "thickness": "2 mm", "bend_radius": "2 mm", "gap": "0.5 mm", "k_factor": "0.4", "active": true}),
);
base(s, 150.0, 100.0);
run(s, "sheet.flange", json!({"edges": [[0, 50, 2]], "height": 40}));
}
/// `then` bends one flange after another, each on the far edge of the one before, in one feature
/// and one undo step: the same part as picking each far edge by hand.
#[test]
fn an_edge_flange_can_carry_further_bends() {
let mut chained = Session::default();
wall_bracket(&mut chained);
let walls = chained.doc.features.len();
run(&mut chained, "sheet.flange", json!({"edges": [[1, 0, 20]], "height": 40, "angle": "45 deg", "then": [{"angle": "45 deg", "height": 80}]}));
assert_eq!(chained.model.state().bodies.len(), 1, "the flap is part of the sheet, not a second body");
assert_eq!(chained.doc.features.len(), walls + 2, "one flange per bend");
let flat_chained = flat(&mut chained);
assert_eq!(flat_chained["bends"].as_array().map(Vec::len), Some(3), "the wall's bend and the flap's two");
let directions: Vec<&str> = flat_chained["bends"].as_array().into_iter().flatten().filter_map(|b| b["direction"].as_str()).collect();
assert_eq!(directions, ["up", "up", "up"], "a further bend turns the way the one before did");
// Each 45° bend of the flap takes (pi/4) x (radius + K x thickness) = (pi/4) x (2 + 0.4 x 2) of flat length.
let allowance = PI / 4.0 * (2.0 + 0.4 * 2.0);
let quarter: Vec<f64> = flat_chained["bends"]
.as_array()
.into_iter()
.flatten()
.filter(|b| (b["angle_deg"].as_f64().unwrap_or(0.0) - 45.0).abs() < 1e-6)
.filter_map(|b| b["allowance"].as_f64())
.collect();
assert_eq!(quarter.len(), 2, "{flat_chained}");
assert!(quarter.iter().all(|a| rel(*a, allowance) < 1e-9), "{quarter:?} vs {allowance}");
let mut by_hand = Session::default();
wall_bracket(&mut by_hand);
run(&mut by_hand, "sheet.flange", json!({"edges": [[1, 0, 20]], "height": 40, "angle": "45 deg"}));
run(&mut by_hand, "sheet.flange", json!({"edges": [[30.3, -28.3, 20]], "height": 80, "angle": "45 deg"}));
assert!(rel(volume(&mut chained), volume(&mut by_hand)) < 1e-9, "{} vs {}", volume(&mut chained), volume(&mut by_hand));
assert_eq!(flat_chained["bends"], flat(&mut by_hand)["bends"]);
// One undo takes the whole chain back.
run(&mut chained, "edit.undo", json!({}));
assert_eq!(chained.doc.features.len(), walls);
}
#[test]
fn further_bends_are_checked_before_anything_is_made() {
let mut s = Session::default();
wall_bracket(&mut s);
let features = s.doc.features.len();
let edges = json!([[1, 0, 20]]);
for (what, then) in [
("not a list", json!("45 deg")),
("a bend without a height", json!([{"angle": "45 deg"}])),
("an unknown key", json!([{"height": 10, "radius": 1}])),
("too many bends", Value::Array((0..17).map(|_| json!({"angle": "10 deg", "height": 10})).collect())),
("a bad expression", json!([{"height": "10 deg"}])),
] {
let r = s.execute("sheet.flange", &json!({"edges": edges, "height": 40, "angle": "45 deg", "then": then}));
assert!(r.is_err(), "{what}: {r:?}");
assert_eq!(s.doc.features.len(), features, "{what}: nothing is left behind");
}
// `then` belongs to edge flanges.
let r = s.execute("sheet.flange", &json!({"sketch": "Base", "then": [{"height": 10}]}));
assert!(r.is_err(), "{r:?}");
}
/// A further bend with `flip` turns the other way: an offset (a jog) in one command, the same part
/// as flipping the second flange by hand.
#[test]
fn a_further_bend_can_turn_the_other_way() {
let mut chained = Session::default();
wall_bracket(&mut chained);
run(
&mut chained,
"sheet.flange",
json!({"edges": [[1, 0, 20]], "height": 40, "angle": "45 deg", "then": [{"angle": "45 deg", "height": 60, "flip": true}]}),
);
assert_eq!(chained.model.state().bodies.len(), 1);
let directions: Vec<String> =
flat(&mut chained)["bends"].as_array().into_iter().flatten().filter_map(|b| b["direction"].as_str().map(str::to_string)).collect();
assert_eq!(directions, ["up", "up", "down"], "the flap's second bend turns back");
let mut by_hand = Session::default();
wall_bracket(&mut by_hand);
run(&mut by_hand, "sheet.flange", json!({"edges": [[1, 0, 20]], "height": 40, "angle": "45 deg"}));
run(&mut by_hand, "sheet.flange", json!({"edges": [[30.3, -28.3, 20]], "height": 60, "angle": "45 deg", "flip": true}));
assert!(rel(volume(&mut chained), volume(&mut by_hand)) < 1e-9, "{} vs {}", volume(&mut chained), volume(&mut by_hand));
// `flip` must be true or false.
let r = chained.execute("sheet.flange", &json!({"edges": [[1, 0, 20]], "height": 10, "then": [{"height": 10, "flip": "yes"}]}));
assert!(r.is_err(), "{r:?}");
}
/// The wall bracket with a path sketched across the end edge of its wall, at half its height: the
/// lines through `points` (sketch coordinates, x and y as the world's).
fn path_sketch(s: &mut Session, points: Value) {
wall_bracket(s);
run(s, "sketch.create", json!({"plane": {"origin": [0, 0, 20], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}, "name": "Path"}));
let ids: Vec<String> = (1..points.as_array().map_or(0, Vec::len)).map(|k| format!("p{k}")).collect();
run(s, "sketch.line", json!({"points": points, "ids": ids}));
run(s, "sketch.finish", json!({}));
}
/// A path flange makes the flanges its path's lines draw, each line one flange as long as the
/// line and each corner one bend: the same part as the edge flange with further bends, in one
/// feature and one body.
#[test]
fn a_path_flange_follows_its_path() {
let a = 40.0 / 2f64.sqrt();
let mut made = Session::default();
path_sketch(&mut made, json!([[0, 0], [a, -a], [a + 80.0, -a]]));
let features = made.doc.features.len();
run(&mut made, "sheet.path_flange", json!({"edge": [1, 0, 20], "sketch": "Path", "curves": ["p1", "p2"]}));
assert_eq!(made.doc.features.len(), features + 1, "one feature");
assert_eq!(made.model.state().bodies.len(), 1, "the flap is part of the sheet");
let directions: Vec<String> =
flat(&mut made)["bends"].as_array().into_iter().flatten().filter_map(|b| b["direction"].as_str().map(str::to_string)).collect();
assert_eq!(directions, ["up", "up", "up"]);
let mut chained = Session::default();
wall_bracket(&mut chained);
run(&mut chained, "sheet.flange", json!({"edges": [[1, 0, 20]], "height": 40, "angle": "45 deg", "then": [{"angle": "45 deg", "height": 80}]}));
assert!(rel(volume(&mut made), volume(&mut chained)) < 1e-9, "{} vs {}", volume(&mut made), volume(&mut chained));
// Drawn from its far end, the path is the same.
let mut reversed = Session::default();
path_sketch(&mut reversed, json!([[a + 80.0, -a], [a, -a], [0, 0]]));
run(&mut reversed, "sheet.path_flange", json!({"edge": [1, 0, 20], "sketch": "Path", "curves": ["p1", "p2"]}));
assert!(rel(volume(&mut reversed), volume(&mut chained)) < 1e-9, "{} vs {}", volume(&mut reversed), volume(&mut chained));
// The lines given in any order are the same path.
let mut jumbled = Session::default();
path_sketch(&mut jumbled, json!([[0, 0], [a, -a], [a + 80.0, -a]]));
run(&mut jumbled, "sheet.path_flange", json!({"edge": [1, 0, 20], "sketch": "Path", "curves": ["p2", "p1"]}));
assert!(rel(volume(&mut jumbled), volume(&mut chained)) < 1e-9, "{} vs {}", volume(&mut jumbled), volume(&mut chained));
// One undo takes the whole flap away.
run(&mut made, "edit.undo", json!({}));
assert_eq!(made.doc.features.len(), features);
}
/// Which way the path turns says which way each bend goes: a jog turns back, and a path that
/// leaves the sheet the other way starts with a bend down.
#[test]
fn a_path_flange_turns_the_way_its_path_turns() {
let a = 40.0 / 2f64.sqrt();
let mut jog = Session::default();
path_sketch(&mut jog, json!([[0, 0], [a, -a], [a, -a - 60.0]]));
run(&mut jog, "sheet.path_flange", json!({"edge": [1, 0, 20], "sketch": "Path", "curves": ["p1", "p2"]}));
let directions: Vec<String> =
flat(&mut jog)["bends"].as_array().into_iter().flatten().filter_map(|b| b["direction"].as_str().map(str::to_string)).collect();
assert_eq!(directions, ["up", "up", "down"]);
let mut by_hand = Session::default();
wall_bracket(&mut by_hand);
run(
&mut by_hand,
"sheet.flange",
json!({"edges": [[1, 0, 20]], "height": 40, "angle": "45 deg", "then": [{"angle": "45 deg", "height": 60, "flip": true}]}),
);
assert!(rel(volume(&mut jog), volume(&mut by_hand)) < 1e-9, "{} vs {}", volume(&mut jog), volume(&mut by_hand));
let box_of = |s: &mut Session| run(s, "inspect.measure", json!({}))["total"]["bbox"].clone();
assert_eq!(box_of(&mut jog), box_of(&mut by_hand), "the same place, not only the same size");
let mut down = Session::default();
path_sketch(&mut down, json!([[0, 0], [-a, -a]]));
run(&mut down, "sheet.path_flange", json!({"edge": [1, 0, 20], "sketch": "Path", "curves": ["p1"]}));
let mut by_hand = Session::default();
wall_bracket(&mut by_hand);
run(&mut by_hand, "sheet.flange", json!({"edges": [[1, 0, 20]], "height": 40, "angle": "45 deg", "flip": true}));
assert_eq!(box_of(&mut down), box_of(&mut by_hand));
}
/// A path that cannot be bent is refused, and the design stays as it was.
#[test]
fn a_path_flange_refuses_a_path_it_cannot_bend() {
let mut s = Session::default();
// Straight on from the wall: no bend.
path_sketch(&mut s, json!([[0, 0], [0, -40]]));
let features = s.doc.features.len();
let r = s.execute("sheet.path_flange", &json!({"edge": [1, 0, 20], "sketch": "Path", "curves": ["p1"]}));
assert!(r.as_ref().is_err_and(|e| e.to_string().contains("straight on")), "{r:?}");
assert_eq!(s.doc.features.len(), features);
// Too short for its bend.
let r = s.execute("sheet.path_flange", &json!({"edge": [1, 0, 20], "sketch": "Path", "curves": ["p1"], "radius": "200 mm"}));
assert!(r.is_err(), "{r:?}");
// No curves, no edge, an unknown curve.
for p in [
json!({"edge": [1, 0, 20], "sketch": "Path", "curves": []}),
json!({"sketch": "Path", "curves": ["p1"]}),
json!({"edge": [1, 0, 20], "sketch": "Path", "curves": ["nope"]}),
] {
assert!(s.execute("sheet.path_flange", &p).is_err(), "{p}");
}
// A path along the edge instead of across it.
let mut along = Session::default();
wall_bracket(&mut along);
run(&mut along, "sketch.create", json!({"plane": {"origin": [0, 0, 0], "x_dir": [0, 1, 0], "y_dir": [0, 0, 1]}, "name": "Path"}));
run(&mut along, "sketch.line", json!({"points": [[0, 10], [-20, 30]], "ids": ["p1"]}));
run(&mut along, "sketch.finish", json!({}));
let r = along.execute("sheet.path_flange", &json!({"edge": [1, 0, 20], "sketch": "Path", "curves": ["p1"]}));
assert!(r.as_ref().is_err_and(|e| e.to_string().contains("across the edge")), "{r:?}");
}
#[test]
fn unfold_cut_refold_and_convert() {
// Oracle 74: two flanges, unfold, a slot across the bend, refold.
+1
View File
@@ -73,6 +73,7 @@ fn table(id: &str) -> &'static [(&'static str, K)] {
"sheet.convert" => &[("face", Pick), ("bends", Picks), ("body", Body)],
"sheet.flange" | "sheet.hem" => &[("edges", Picks), ("body", Body)],
"sheet.fold" => &[("points", Picks), ("fixed", Pick), ("body", Body)],
"sheet.path_flange" => &[("edge", Pick), ("body", Body)],
"sheet.perforate" => &[("body", Body)],
"sketch.create" | "sketch.redefine" => &[("plane", HerePlane)],
"canvas.decal" => &[("face", Here)],
+1
View File
@@ -353,6 +353,7 @@ form_case!(surface_trim, "surface.trim", []);
form_case!(surface_untrim, "surface.untrim", ["Holes"]);
form_case!(split_face, "solid.split_face", []);
form_case!(flange, "sheet.flange", ["Type", "Rule"]);
form_case!(path_flange, "sheet.path_flange", ["Bend Radius"]);
form_case!(hem, "sheet.hem", ["Type", "Length", "ui.sheet_gap"]);
form_case!(fold, "sheet.fold", ["Bend Line Position", "Angle", "Bend Radius"]);
form_case!(unfold, "sheet.unfold", []);
+171 -2
View File
@@ -43,6 +43,8 @@ const ANGLE_DISPLAYS: [&str; 2] = ["bend", "included"];
const ANGLE_DISPLAY_LABELS: [&str; 2] = ["Bend", "Included"];
/// The corner relief shapes an edge flange offers: the rule's (index 0, nothing of its own), then
/// the shapes of `RELIEF_SHAPES` in order.
/// Which way a further bend turns, against the bend before it.
const BEND_WAY_LABELS: [&str; 2] = ["Same way", "Other way"];
const FLANGE_RELIEF_LABELS: [&str; 5] = ["Rule", "Notch", "Round", "Rectangular", "Tear"];
crate::dialog_descriptor::dialog_descriptors! {
@@ -61,6 +63,10 @@ crate::dialog_descriptor::dialog_descriptors! {
position: usize = 0 => FOLD_POSITIONS.iter().position(|x| x == position || (*x == "mould" && position == "mold")).unwrap_or(0),
flip: bool = false => *flip,
} => json!({"angle": angle, "position": FOLD_POSITIONS.get(*position).copied().unwrap_or("centerline"), "flip": flip});
Path("sheet.path_flange", "PATH FLANGE", [("Edge", EDGES, false), ("Path", CURVES, true)],
FeatureKind::SheetPath { radius, .. }) {
radius: String = String::new() => radius.as_deref().map(str::to_string).unwrap_or_default(),
} => json!({});
; custom {
/// Base, edge or contour flange (`ty` follows the picks: profiles, edges, sketch lines).
Flange {
@@ -80,6 +86,9 @@ crate::dialog_descriptor::dialog_descriptors! {
/// 0 is the rule's) and its size (empty: the rule's).
relief: usize,
relief_size: String,
/// Edge flanges: further bends (angle, height, turns the other way), each a flange on
/// the far edge of the one before it (the command's `then`).
then: Vec<(String, String, bool)>,
},
Unfold {
refold: bool,
@@ -155,6 +164,7 @@ fn new_flange(app: &SolveApp, ty: usize) -> Sm {
own: Vec::new(),
relief: 0,
relief_size: String::new(),
then: Vec::new(),
}
}
@@ -213,7 +223,7 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Sm, inputs: &mut [Sel
let t = Tokens::get();
let mut enter = false;
match k {
Sm::Flange { ty, height, angle, radius, position, flip, distance, reverse, rule, own, relief, relief_size } => {
Sm::Flange { ty, height, angle, radius, position, flip, distance, reverse, rule, own, relief, relief_size, then } => {
*ty = flange_type(inputs);
form_row(ui, "Type", |ui| {
ui.label(FLANGE_TYPES.get(*ty).copied().unwrap_or(""));
@@ -223,6 +233,33 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Sm, inputs: &mut [Sel
enter |= expr_row(ui, "Height", height);
enter |= expr_row(ui, "Angle", angle);
choice_row(ui, "Bend Position", "sm_pos", position, &POSITION_LABELS);
// Further bends: each a flange on the far edge of the one before it.
form_row(ui, "Further Bends", |ui| {
let add = crate::ui_kit::button(ui, "Add bend", crate::ui_kit::Button::Normal)
.on_hover_text(crate::i18n::tr_label("Another bend on the far edge of the last flange"));
if add.clicked() && then.len() < 16 {
then.push(("45 deg".into(), "20 mm".into(), false));
}
});
let mut drop = None;
for (n, (a, h, other)) in then.iter_mut().enumerate() {
let bend = n + 2;
// The bend's heading: what it makes, and a bin to take it out.
form_row(ui, &format!("Bend {bend}"), |ui| {
if crate::ui_kit::bin_button(ui, crate::i18n::tr_label("Remove this bend")).clicked() {
drop = Some(n);
}
ui.label(format!("{} · {}", a.trim(), h.trim()));
});
enter |= expr_row(ui, &format!("Bend {bend} angle"), a);
enter |= expr_row(ui, &format!("Bend {bend} height"), h);
let mut way = usize::from(*other);
choice_row(ui, &format!("Bend {bend} turns"), &format!("sm_then_way_{n}"), &mut way, &BEND_WAY_LABELS);
*other = way == 1;
}
if let Some(n) = drop {
then.remove(n);
}
crate::ui_kit::section(ui, "flange_advanced", "Advanced", false, |ui| {
enter |= hint_row(ui, "Bend Radius", radius, crate::i18n::tr_label("from the rule"));
// The relief at the corners these flanges make: the rule's unless set here.
@@ -290,6 +327,21 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Sm, inputs: &mut [Sel
enter |= hint_row(ui, "Bend Radius", radius, crate::i18n::tr_label("from the rule"));
crate::ui_kit::options(ui, "sheet_options", &mut [("Flip", flip)]);
}
Sm::Path { radius } => {
path_chain(app, inputs);
// What the path makes: a flange per line, as long as the line (the sketch's lengths).
let lengths = path_lengths(app, inputs);
form_row(ui, "Flanges", |ui| {
ui.label(if lengths.is_empty() {
crate::i18n::tr_label("pick the path").to_string()
} else {
let each: Vec<String> = lengths.iter().map(|l| format!("{l:.1}")).collect();
format!("{} mm", each.join(" · "))
});
});
crate::ui_kit::caption(ui, "Flanges", crate::i18n::tr_label("set by the sketch's lines"));
enter |= hint_row(ui, "Bend Radius", radius, crate::i18n::tr_label("from the rule"));
}
Sm::Unfold { .. } => {}
Sm::Convert { rule } => rule_combo(app, ui, "sm_conv_rule", rule),
Sm::Rules { pick, name, values, relief, angles, active, loaded } => {
@@ -442,6 +494,75 @@ fn rule_value(app: &SolveApp, rule: usize) -> Option<String> {
rule.checked_sub(1).and_then(|i| rule_list(app).get(i).map(|r| r.name.clone()))
}
/// A path flange's path is a chain: a line picked into Path brings every line joined to it end
/// to end, so one click takes the whole path.
fn path_chain(app: &SolveApp, inputs: &mut [SelInput]) {
let edge = inputs.first().and_then(|i| i.items.edge_points().first().copied());
let Some(input) = inputs.get_mut(1) else { return };
let st = app.session.world_state();
let mut chained: Vec<Sel> = Vec::new();
for sel in &input.items {
let Sel::SketchCurve { id } = sel else { continue };
let ids = st
.sketches
.iter()
.rev()
.find_map(|ss| {
let ci = ss.sketch.curve_index(id)?;
Some(
ss.sketch
.chain(ci)
.into_iter()
.filter_map(|c| ss.sketch.curves.get(c))
.filter(|c| !c.construction)
.map(|c| c.id.clone())
.collect(),
)
})
.unwrap_or_else(|| vec![id.clone()]);
for id in ids {
let sel = Sel::SketchCurve { id };
if !chained.contains(&sel) {
chained.push(sel);
}
}
}
// In order along the path, so the flanges read from the edge out.
let ids: Vec<String> = chained.iter().filter_map(|sel| if let Sel::SketchCurve { id } = sel { Some(id.clone()) } else { None }).collect();
if let Some(ss) = ids.first().and_then(|first| st.sketches.iter().rev().find(|ss| ss.sketch.curve_index(first).is_some()))
&& let Ok(mut order) = ss.chain_order(&ids)
{
// From the end nearer the picked edge.
let near = |id: Option<&String>| {
let segs = id.and_then(|id| ss.sketch.curve_index(id)).map(|ci| ss.sketch.segs(ci)).unwrap_or_default();
let ends = [segs.first().map(|s| s.start()), segs.last().map(|s| s.end())];
ends.into_iter().flatten().map(|p| edge.map_or(0.0, |e| ss.plane.to_world(p).dist(e))).fold(f64::INFINITY, f64::min)
};
if near(order.last()) < near(order.first()) {
order.reverse();
}
chained = order.into_iter().map(|id| Sel::SketchCurve { id }).collect();
}
if chained != input.items {
input.items = chained;
}
}
/// The lengths of the path's lines, in the order picked (mm).
fn path_lengths(app: &SolveApp, inputs: &[SelInput]) -> Vec<f64> {
let st = app.session.world_state();
items(inputs, 1)
.iter()
.filter_map(|sel| match sel {
Sel::SketchCurve { id } => st.sketches.iter().rev().find_map(|ss| {
let ci = ss.sketch.curve_index(id)?;
Some(ss.sketch.segs(ci).iter().map(|s| s.start().dist(s.end())).sum())
}),
_ => None,
})
.collect()
}
fn edge_points(inputs: &[SelInput]) -> Vec<Value> {
items(inputs, 0).edge_points().into_iter().map(pt).collect()
}
@@ -484,7 +605,7 @@ fn flange_edges(inputs: &[SelInput], own: &[(Vec3, String, String)]) -> Vec<Valu
pub fn commands(app: &SolveApp, k: &Sm, inputs: &[SelInput], extra: &Map<String, Value>) -> Result<Vec<(String, Value)>, String> {
let s = &app.session;
let (cmd, mut p): (&str, Value) = match k {
Sm::Flange { height, angle, radius, position, flip, distance, reverse, rule, own, relief, relief_size, .. } => {
Sm::Flange { height, angle, radius, position, flip, distance, reverse, rule, own, relief, relief_size, then, .. } => {
let mut p = match flange_type(inputs) {
1 => {
let mut p = json!({"type": "edge", "edges": flange_edges(inputs, own), "height": height, "angle": angle,
@@ -494,6 +615,22 @@ pub fn commands(app: &SolveApp, k: &Sm, inputs: &[SelInput], extra: &Map<String,
p["corner_relief_shape"] = json!(shape);
}
put(&mut p, &[("corner_relief", relief_size)]);
if !then.is_empty() {
let mut bends = Vec::with_capacity(then.len());
for (n, (a, h, other)) in then.iter().enumerate() {
if h.trim().is_empty() {
return Err(format!("bend {} needs a height", n + 2));
}
let mut b = json!({"height": h});
put(&mut b, &[("angle", a)]);
// The bend's own side: the flange's, or the other one.
if *other {
b["flip"] = json!(!*flip);
}
bends.push(b);
}
p["then"] = json!(bends);
}
p
}
2 => {
@@ -555,6 +692,23 @@ pub fn commands(app: &SolveApp, k: &Sm, inputs: &[SelInput], extra: &Map<String,
}
("sheet.fold", p)
}
Sm::Path { radius } => {
let edge = edge_points(inputs).into_iter().next().ok_or("select the sheet edge first")?;
let curves: Vec<String> = items(inputs, 1)
.iter()
.filter_map(|sel| match sel {
Sel::SketchCurve { id } => Some(id.clone()),
_ => None,
})
.collect();
let first = curves.first().ok_or("select the path (sketch lines across the edge)")?;
let st = s.world_state();
let sketch =
st.sketches.iter().rev().find(|ss| ss.sketch.curve_index(first).is_some()).map(|ss| ss.feature).ok_or("the path's sketch is gone")?;
let mut p = json!({"edge": edge, "sketch": sketch, "curves": curves});
put(&mut p, &[("radius", radius)]);
("sheet.path_flange", p)
}
Sm::Unfold { refold } => {
let mut p = json!({});
if let Some(Sel::Body { name }) = items(inputs, 0).first() {
@@ -656,6 +810,7 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind) -> Option<(Kind, Vec<SelI
.and_then(|name| RELIEF_SHAPES.iter().position(|s| s.eq_ignore_ascii_case(name.trim())))
.map_or(0, |i| i + 1),
relief_size: corner_relief.as_deref().map(str::to_string).unwrap_or_default(),
then: Vec::new(),
};
(f, picked)
}
@@ -687,6 +842,20 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind) -> Option<(Kind, Vec<SelI
}
return Some((Kind::Sheet(k), ins, extra));
}
FeatureKind::SheetPath { edge, curves, body, .. } => {
if let Some(bd) = body {
extra.insert("body".into(), json!(bd));
}
let k = Sm::simple_restore(kind)?;
let (_, mut ins) = start(app, "sheet.path_flange")?;
if let Some(i) = ins.first_mut() {
i.items = edge_sel(s, edge.0).into_iter().collect();
}
if let Some(i) = ins.get_mut(1) {
i.items = curves.iter().map(|id| Sel::SketchCurve { id: id.clone() }).collect();
}
return Some((Kind::Sheet(k), ins, extra));
}
FeatureKind::SheetUnfold { body, refold } => {
(Sm::Unfold { refold: *refold }, body.iter().map(|n| Sel::Body { name: n.to_string() }).collect())
}
+116
View File
@@ -647,6 +647,80 @@ fn edge_flanges_can_have_an_angle_and_a_height_of_their_own() {
}
}
/// The Flange dialog's Further Bends make the command's `then` (#4094): a flap with two bends is
/// one flange command, one body and one undo step, and a bend with no height is refused.
#[test]
fn further_bends_in_the_flange_dialog_make_one_chained_flap() {
for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] {
let mut app = plate(mode);
app.run("sheet.flange", json!({"sketch": "Base"})).unwrap();
app.run("sheet.flange", json!({"edges": [[0, 30, 2.5]], "height": 30})).unwrap();
let features = app.session.doc.features.len();
let end = edge_sel(&app.session, Vec3::new(1.25, 0.0, 15.0)).expect("the wall's end edge");
app.session.selection = vec![end];
app.start("sheet.flange");
let mut d = app.dialog.clone().unwrap();
let Kind::Sheet(Sm::Flange { height, angle, then, .. }) = &mut d.kind else { panic!("not a flange dialog") };
*height = "30 mm".into();
*angle = "45 deg".into();
// A bend added with the button starts at 45° and 20 mm; give the first a height of its own.
then.push(("45 deg".into(), String::new(), false));
assert!(apply_commands(&app, &d).is_err(), "a bend needs a height");
let Kind::Sheet(Sm::Flange { then, .. }) = &mut d.kind else { panic!("not a flange dialog") };
then[0].1 = "50 mm".into();
let c = apply_commands(&app, &d).unwrap();
assert_eq!(c.len(), 1);
assert_eq!(c[0].1["then"], json!([{"height": "50 mm", "angle": "45 deg"}]));
// A bend that turns the other way says so, against the flange's own side.
let Kind::Sheet(Sm::Flange { then, .. }) = &mut d.kind else { panic!("not a flange dialog") };
then.push(("45 deg".into(), "30 mm".into(), true));
assert_eq!(
apply_commands(&app, &d).unwrap()[0].1["then"],
json!([{"height": "50 mm", "angle": "45 deg"}, {"height": "30 mm", "angle": "45 deg", "flip": true}])
);
let Kind::Sheet(Sm::Flange { then, .. }) = &mut d.kind else { panic!("not a flange dialog") };
then.pop();
run_all(&mut app, c);
assert_eq!(app.session.model.state().bodies.len(), 1, "the flap is part of the sheet");
assert_eq!(app.session.doc.features.len(), features + 2, "one flange per bend");
assert!(app.session.model.results.iter().all(|r| r.error.is_none()), "{:?}", app.session.model.results);
// A dialog with no further bends sends no `then`.
app.session.selection = vec![edge_sel(&app.session, Vec3::new(50.0, 0.0, 2.5)).expect("an edge")];
app.dialog = None;
app.start("sheet.flange");
let d = app.dialog.clone().unwrap();
assert!(apply_commands(&app, &d).unwrap()[0].1.get("then").is_none());
}
}
/// The Add bend button and a further bend's bin work in the real dialog.
#[test]
fn add_bend_and_remove_bend_buttons_work() {
let mut h = crate::scenario::Harness::new();
h.app.run("sketch.create", json!({"plane": "XY", "name": "Base"})).unwrap();
h.app.run("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [100, 60]})).unwrap();
h.app.run("sketch.finish", json!({})).unwrap();
h.app.run("sheet.flange", json!({"sketch": "Base"})).unwrap();
h.app.run("sheet.flange", json!({"edges": [[0, 30, 2.5]], "height": 30})).unwrap();
h.app.session.selection = vec![edge_sel(&h.app.session, Vec3::new(1.25, 0.0, 15.0)).expect("the wall's end edge")];
h.step(&json!({"start": "sheet.flange"})).unwrap();
h.frames(6);
let bends = |h: &crate::scenario::Harness| match &h.app.dialog.as_ref().unwrap().kind {
Kind::Sheet(Sm::Flange { then, .. }) => then.clone(),
_ => panic!("not a flange dialog"),
};
assert!(bends(&h).is_empty(), "no further bends to start with");
for want in 1..=2 {
h.step(&json!({"widget": "Add bend"})).unwrap();
h.frames(3);
assert_eq!(bends(&h).len(), want);
}
assert_eq!(bends(&h)[0], ("45 deg".to_string(), "20 mm".to_string(), false));
h.step(&json!({"click": {"handle": "dialog:button:Bend 2:Delete"}})).unwrap();
h.frames(3);
assert_eq!(bends(&h).len(), 1, "the bin takes one bend out");
}
/// Convert takes a fixed face and, for a solid or shelled body, its bend edges; Edit Feature
/// brings both back.
#[test]
@@ -685,6 +759,48 @@ fn convert_takes_the_fixed_face_and_the_bend_edges() {
assert!(app.session.model.results.iter().all(|r| r.error.is_none()), "{:?}", app.session.model.results);
}
/// The Path Flange dialog takes the edge and the path's sketch lines: one feature, one body,
/// and Edit Feature brings the edge and the path back.
#[test]
fn path_flange_dialog_follows_the_path() {
for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] {
let mut app = plate(mode);
app.run("sheet.flange", json!({"sketch": "Base"})).unwrap();
app.run("sheet.flange", json!({"edges": [[0, 30, 2.5]], "height": 30})).unwrap();
// A path across the wall's end edge: 30 mm out at 45°, then 30 mm on along the wall.
let a = 30.0 / 2f64.sqrt();
app.run("sketch.create", json!({"plane": {"origin": [0, 0, 15], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}, "name": "Path"})).unwrap();
app.run("sketch.line", json!({"points": [[0, 0], [a, -a], [a + 30.0, -a]], "ids": ["p1", "p2"]})).unwrap();
app.run("sketch.finish", json!({})).unwrap();
let features = app.session.doc.features.len();
app.start("sheet.path_flange");
let mut d = app.dialog.clone().unwrap();
assert!(apply_commands(&app, &d).is_err(), "no edge picked yet");
d.inputs[0].items = vec![edge_sel(&app.session, Vec3::new(1.25, 0.0, 15.0)).expect("the wall's end edge")];
assert!(apply_commands(&app, &d).is_err(), "no path picked yet");
// One line picked takes the whole path, and the dialog shows the flanges it makes.
d.inputs[1].items = vec![Sel::SketchCurve { id: "p2".into() }];
path_chain(&app, &mut d.inputs);
assert_eq!(d.inputs[1].items, vec![Sel::SketchCurve { id: "p1".into() }, Sel::SketchCurve { id: "p2".into() }], "in order along the path");
let lengths = path_lengths(&app, &d.inputs);
assert!(lengths.len() == 2 && lengths.iter().all(|l| (l - 30.0).abs() < 1e-6), "{lengths:?}");
d.inputs[1].items = vec![Sel::SketchCurve { id: "p1".into() }, Sel::SketchCurve { id: "p2".into() }];
let c = apply_commands(&app, &d).unwrap();
assert_eq!(c.len(), 1);
assert_eq!(c[0].0, "sheet.path_flange");
assert_eq!(c[0].1["curves"], json!(["p1", "p2"]));
run_all(&mut app, c);
assert!(app.session.model.results.iter().all(|r| r.error.is_none()), "{:?}", app.session.model.results);
assert_eq!(app.session.doc.features.len(), features + 1, "one feature");
assert_eq!(app.session.model.state().bodies.len(), 1, "the flap is part of the sheet");
let f = app.session.doc.features.last().cloned().unwrap();
let e = edit_dialog(&app, f.id, None).unwrap();
assert!(matches!(&e.kind, Kind::Sheet(Sm::Path { .. })));
assert_eq!((e.inputs[0].items.len(), e.inputs[1].items.len()), (1, 2));
assert!(apply_commands(&app, &e).is_ok());
}
}
// ---- flat pattern navigation ----
fn flat_app(preset: &str, mode: crate::shell::LayoutMode) -> SolveApp {
+3 -1
View File
@@ -253,7 +253,7 @@ pub const SECTIONS: &[Section] = &[
tab: "SHEET METAL",
panel: "CREATE",
promoted: 4,
ids: &["sheet.flange", "sheet.hem", "sheet.fold", "sheet.perforate", "sheet.convert"],
ids: &["sheet.flange", "sheet.path_flange", "sheet.hem", "sheet.fold", "sheet.perforate", "sheet.convert"],
},
Section { tab: "SHEET METAL", panel: "FLAT", promoted: 3, ids: &["sheet.unfold", "sheet.refold", "sheet.flat_pattern"] },
Section { tab: "SHEET METAL", panel: "OUTPUT", promoted: 2, ids: &["sheet.export_dxf", "sheet.export_bend_table"] },
@@ -374,6 +374,7 @@ pub const RIBBON_LABELS: &[(&str, &str)] = &[
("sheet.export_dxf", "Export DXF"),
("sheet.flat_pattern", "Flat Pattern"),
("sheet.manage_rules", "Sheet Rules"),
("sheet.path_flange", "Path"),
("sketch.cancel", "Cancel"),
("sketch.circle.center", "Circle"),
("sketch.constraint.coincident", "Coincident"),
@@ -488,6 +489,7 @@ pub fn feature_icon(k: &FeatureKind) -> Option<&'static str> {
FeatureKind::SheetBase { .. } | FeatureKind::SheetContour { .. } | FeatureKind::SheetFlange { .. } => "flange",
FeatureKind::SheetHem { .. } => "hem",
FeatureKind::SheetFold { .. } => "fold",
FeatureKind::SheetPath { .. } => "path_flange",
FeatureKind::SheetUnfold { refold: false, .. } => "unfold",
FeatureKind::SheetUnfold { .. } => "refold",
FeatureKind::SheetConvert { .. } => "convert_sheet",
+32
View File
@@ -119,6 +119,38 @@ per edge with an angle and a height box; an empty box takes the value above.
"height":38.6,"angle":"75 deg"}}
```
An edge flange can bend more than once: `then` lists further bends, each an `angle` and a
`height`, and each is a flange on the far edge of the one before it, made in the same command
and undone with one step. It is the way to make a flap with two or more bends that is part of
the same sheet (a Contour Flange is always a sheet of its own). The example bends the end edge of
a wall 45° outward, then 45° again, the second leg 80 mm long. Each bend is a flange feature of
its own in the timeline, so each can be edited there. In the Flange dialog, an edge flange has
**Further Bends** under Bend Position: **Add bend** adds a row with an angle and a height, and the
bin beside a row takes it out.
```json
{"command":"sheet.flange","params":{"edges":[[1,0,20]],"height":40,"angle":"45 deg",
"then":[{"angle":"45 deg","height":80}]}}
```
A further bend turns the way the one before it did. `"flip": true` on a bend turns it the other
way, which makes an offset (a jog): bend 45° out, then 45° back, and the last leg runs parallel to
the first. In the dialog each further bend has a **turns** choice, Same way or Other way.
When the shape is easier to draw than to count out, **Path Flange** (`sheet.path_flange`) makes
the same chain from a sketch. Sketch an open chain of lines on a plane across the edge (square to
it), starting at the edge, then pick the edge and the lines. Each line becomes a flange as long
as the line (measured like an edge flange's height: to the outer face from the virtual sharp),
and each corner a bend. The first line's angle to the sheet sets the first bend, and the path's
turns set which way each later bend goes, so a jog is just a path that turns back. Changing the
sketch changes the flap. It is one feature in the timeline and part of the same sheet. Lines
that run straight on from each other count as one; a line that does not turn from the sheet is
refused, and so is a line too short for its bend. Arcs are not supported yet.
```json
{"command":"sheet.path_flange","params":{"edge":[1,0,20],"sketch":"Path","curves":["p1","p2"]}}
```
A flange can also stand on the far edge of another flange: a return, such as a lip turned in
along the top of a tray's walls. It runs along that edge from end to end, so it follows the
closed end of the flange it stands on, slanted or not. Two returns of one feature whose flanges