From 919f54a23e360794b3ed42e145511a0a01ca6414 Mon Sep 17 00:00:00 2001 From: Ahmad Khan Date: Sun, 25 Oct 2026 05:11:13 +0000 Subject: [PATCH] Sheet metal: bend angles as the included (press-brake) angle, set per rule (#4968) (#6040) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * claim: #4968 * Sheet metal rules: bend angles as the included angle (#4968) A sheet metal rule's angle_display (bend, the default, or included) sets how the DXF bend notes read each bend: a 58° bend is B1 UP 122° R1 under an included rule. The bend table always gives included_angle_deg beside angle_deg (CSV and JSON). Set in sheet.manage_rules and the Sheet Metal Rules dialog, listed by sheet.rules; the flange angle stays the bend angle. * Bend table: the included angle as the CSV's last column, so the columns before it keep their places (#4968) A test also covers a body whose base flange names its rule, which keeps that rule's notes whichever rule is active, and a bend down. * Sheet Metal Rules: Angle Display reads Bend or Included, so the choice fits its box (#4968) The rule editor's row contract lists the new row and the key the dialog sends. --------- Co-authored-by: begsaquib --- assets/locales/en.json | 3 + assets/locales/ja.json | 3 + assets/locales/zh.json | 3 + .../pending/sheet-rule-angle-display.rs | 6 + crates/doc/src/sheet.rs | 117 ++++++++++++++++++ crates/engine/src/cmd/sheet.rs | 46 ++++--- crates/engine/src/cmd/sheet_dxf_tests.rs | 40 ++++++ crates/engine/src/cmd/sheet_tests.rs | 106 +++++++++++++++- crates/ui-egui/src/dialogs_sheet.rs | 15 ++- crates/ui-egui/src/dialogs_sheet_tests.rs | 45 +++++++ crates/ui-egui/src/rule_editor_tests.rs | 3 +- docs/book/src/guide/sheet-metal.md | 23 +++- 12 files changed, 389 insertions(+), 21 deletions(-) create mode 100644 crates/doc/src/format/pending/sheet-rule-angle-display.rs diff --git a/assets/locales/en.json b/assets/locales/en.json index 1602d0488..d8d58e629 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -36,6 +36,7 @@ "Also deletes": "Also deletes", "Anchor": "Anchor", "Angle 2": "Angle 2", + "Angle Display": "Angle Display", "Animate": "Animate", "App/system information and command settings are included. Review private details before sharing.": "App/system information and command settings are included. Review private details before sharing.", "Appearance name": "Appearance name", @@ -53,6 +54,7 @@ "BOUNDARY SURFACE": "BOUNDARY SURFACE", "BROWSER": "BROWSER", "Bar": "Bar", + "Bend": "Bend", "Bend Edges": "Bend Edges", "Bend Line Position": "Bend Line Position", "Bend Position": "Bend Position", @@ -249,6 +251,7 @@ "In This Design": "In This Design", "In place (surfaces)": "In place (surfaces)", "In plane": "In plane", + "Included": "Included", "Inside": "Inside", "Instant": "Instant", "Interface font": "Interface font", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 82b1ca132..fcd6770d3 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -36,6 +36,7 @@ "Also deletes": "同時に削除される要素:", "Anchor": "基準点", "Angle 2": "角度 2", + "Angle Display": "角度の表示", "Animate": "アニメーション", "App/system information and command settings are included. Review private details before sharing.": "アプリ・システム情報とコマンド設定が含まれます。共有前に非公開の情報を確認してください。", "Appearance name": "外観名", @@ -53,6 +54,7 @@ "BOUNDARY SURFACE": "境界サーフェス", "BROWSER": "ブラウザ", "Bar": "平鋼", + "Bend": "曲げ角度", "Bend Edges": "曲げエッジ", "Bend Line Position": "曲げ線位置", "Bend Position": "曲げ位置", @@ -249,6 +251,7 @@ "In This Design": "このデザイン内", "In place (surfaces)": "その場で(サーフェス)", "In plane": "平面内", + "Included": "挟角", "Inside": "内側", "Instant": "即時", "Interface font": "インターフェースフォント", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 63a5bcda5..27f76b63b 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -36,6 +36,7 @@ "Also deletes": "同时删除", "Anchor": "基准点", "Angle 2": "角度 2", + "Angle Display": "角度显示", "Animate": "动画", "App/system information and command settings are included. Review private details before sharing.": "报告包含应用和系统信息以及命令设置。共享前请检查私人信息。", "Appearance name": "外观名称", @@ -53,6 +54,7 @@ "BOUNDARY SURFACE": "边界曲面", "BROWSER": "浏览器", "Bar": "扁钢", + "Bend": "折弯角度", "Bend Edges": "折弯边", "Bend Line Position": "弯折线位置", "Bend Position": "折弯位置", @@ -249,6 +251,7 @@ "In This Design": "在此设计中", "In place (surfaces)": "原位(曲面)", "In plane": "在平面内", + "Included": "夹角", "Inside": "内侧", "Instant": "即时", "Interface font": "界面字体", diff --git a/crates/doc/src/format/pending/sheet-rule-angle-display.rs b/crates/doc/src/format/pending/sheet-rule-angle-display.rs new file mode 100644 index 000000000..4d35f3c30 --- /dev/null +++ b/crates/doc/src/format/pending/sheet-rule-angle-display.rs @@ -0,0 +1,6 @@ +//! A sheet metal rule can say how the bend angles of its parts read in the DXF bend notes +//! (`angle_display`: `bend`, the default, or `included`, the angle left between a bend's two +//! sides, 180° less the bend angle, as a press brake is set; #4968). It is saved only when it is +//! `included`, in the rule and in the sheet bodies of the design's saved model. Older designs +//! need no step: a rule or body without it reads its bends as bend angles, as before. The last +//! release refuses a design saved with this (the newer format number). diff --git a/crates/doc/src/sheet.rs b/crates/doc/src/sheet.rs index 9a6e00181..0c78b2649 100644 --- a/crates/doc/src/sheet.rs +++ b/crates/doc/src/sheet.rs @@ -259,6 +259,11 @@ pub struct SheetRule { /// Gap between flanges that meet at a corner. #[serde(default = "rule_gap")] pub gap: String, + /// How the bend angles of its parts read in the DXF bend notes: `bend` (how far the sheet + /// turns from flat) or `included` (the angle left between the bend's two sides, as a press + /// brake is set). A choice, not an expression; saved only when it isn't `bend`. + #[serde(default = "rule_angle_display", skip_serializing_if = "is_bend_display")] + pub angle_display: String, } impl SheetRule { @@ -311,6 +316,14 @@ fn rule_corner_relief_shape() -> String { fn rule_hem_gap() -> String { "0.01 mm".into() } +fn rule_angle_display() -> String { + AngleDisplay::Bend.name().into() +} +/// A rule that reads bend angles as bend angles leaves the setting out of the design, which +/// then saves as it did before the setting existed. +fn is_bend_display(s: &str) -> bool { + AngleDisplay::parse(s) == Some(AngleDisplay::Bend) +} impl SheetRule { /// Default: Steel (mm), 2.5 mm, K 0.44, bend radius = Thickness. @@ -326,6 +339,7 @@ impl SheetRule { corner_relief_shape: rule_corner_relief_shape(), hem_gap: rule_hem_gap(), gap: rule_gap(), + angle_display: rule_angle_display(), } } } @@ -384,6 +398,48 @@ impl ReliefShape { } } +/// How a rule's bend angles read in the DXF bend notes (a rule's `angle_display`). The bend +/// table gives both angles, and a flange's `angle` is always the bend angle. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum AngleDisplay { + /// How far the sheet turns from flat: a flange at 58° reads 58°. + #[default] + Bend, + /// The angle left between the bend's two sides, 180° less the bend angle: a 58° bend reads + /// 122°, a 90° bend 90°. + Included, +} + +impl AngleDisplay { + pub fn parse(s: &str) -> Option { + match s.trim().to_ascii_lowercase().as_str() { + "bend" => Some(AngleDisplay::Bend), + "included" => Some(AngleDisplay::Included), + _ => None, + } + } + + pub fn name(self) -> &'static str { + match self { + AngleDisplay::Bend => "bend", + AngleDisplay::Included => "included", + } + } + + pub fn is_bend(&self) -> bool { + *self == AngleDisplay::Bend + } + + /// A bend of `bend_deg` degrees as this display reads it. + pub fn of(self, bend_deg: f64) -> f64 { + match self { + AngleDisplay::Bend => bend_deg, + AngleDisplay::Included => 180.0 - bend_deg, + } + } +} + /// The corner relief an edge flange feature asks for in place of the rule's. A value left out /// follows the rule. #[derive(Clone, Copy, Debug, Default, PartialEq)] @@ -405,6 +461,7 @@ pub struct RuleValues { pub corner_relief_shape: ReliefShape, pub hem_gap: f64, pub gap: f64, + pub angle_display: AngleDisplay, } impl Document { @@ -440,6 +497,8 @@ impl Document { })?, hem_gap: with_t(&r.hem_gap, Kind::Length)?, gap: with_t(&r.gap, Kind::Length)?, + angle_display: AngleDisplay::parse(&r.angle_display) + .ok_or_else(|| DocError::Invalid(format!("unknown bend angle display `{}` (bend or included)", r.angle_display)))?, }; if !(0.0..=1.0).contains(&v.k_factor) || v.bend_radius < 0.0 { return Err(DocError::Invalid("the K-factor must be 0…1 and the bend radius positive".into())); @@ -541,6 +600,9 @@ pub struct SheetBody { /// The rule's bend relief (`relief_width`, `relief_depth`), cut into the base where a /// flange's bend ends beside more of the base. pub bend_relief: (f64, f64), + /// How the DXF bend notes read its bend angles (the rule's `angle_display`). + #[serde(default, skip_serializing_if = "AngleDisplay::is_bend")] + pub angle_display: AngleDisplay, /// The base sketch's lines (id, ends in flat coordinates), naming the base panel's edges. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub base_curves: Vec<(String, Vec2, Vec2)>, @@ -685,6 +747,13 @@ pub struct BendInfo { pub end: Vec2, } +impl BendInfo { + /// The angle left between the bend's two sides (degrees): 180° less `angle_deg`. + pub fn included_angle_deg(&self) -> f64 { + AngleDisplay::Included.of(self.angle_deg) + } +} + fn rot_about(o: Vec3, k: Vec3, a: f64) -> Mat { crate::rigid(Vec3::ZERO, o, k, a) } @@ -4515,6 +4584,7 @@ pub fn base_flange(body: &str, rule: &str, rv: &RuleValues, plane: Plane, region relief: rv.corner_relief_shape, relief_size: rv.corner_relief, bend_relief: (rv.relief_width, rv.relief_depth), + angle_display: rv.angle_display, base_curves: Vec::new(), altered_by: None, } @@ -4574,6 +4644,7 @@ pub fn contour_flange(body: &str, rule: &str, rv: &RuleValues, plane: &Plane, pt relief: rv.corner_relief_shape, relief_size: rv.corner_relief, bend_relief: (rv.relief_width, rv.relief_depth), + angle_display: rv.angle_display, base_curves: Vec::new(), altered_by: None, }; @@ -4699,6 +4770,7 @@ mod tests { corner_relief_shape: ReliefShape::Notch, hem_gap: 0.01, gap: 2.5, + angle_display: AngleDisplay::Bend, } } @@ -5251,6 +5323,7 @@ mod tests { corner_relief_shape: ReliefShape::Notch, hem_gap: 0.01, gap: 2.0, + angle_display: AngleDisplay::Bend, }; let r = rect(Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0), Vec2::new(100.0, 80.0), Vec2::new(0.0, 80.0)); let mut s = base_flange("Body1", "AL2", &rule, Plane::XY, r); @@ -5346,6 +5419,7 @@ mod tests { corner_relief_shape: ReliefShape::Notch, hem_gap: 0.01, gap: 0.5, + angle_display: AngleDisplay::Bend, } } @@ -5593,6 +5667,49 @@ mod tests { } } + #[test] + fn the_rule_names_how_its_bend_angles_read() { + // A rule saved before the setting existed reads bend angles, and saves as it did. + let old: SheetRule = serde_json::from_str(r#"{"name":"Old","thickness":"2 mm","k_factor":"0.5","bend_radius":"1 mm"}"#).unwrap(); + assert_eq!(old.angle_display, "bend"); + assert_eq!(SheetRule::steel().angle_display, "bend"); + assert!(serde_json::to_value(&old).unwrap().get("angle_display").is_none()); + let (doc, vals) = (Document::default(), std::collections::BTreeMap::new()); + assert_eq!(doc.rule_values(&vals, &old).unwrap().angle_display, AngleDisplay::Bend); + for (text, display) in [("included", AngleDisplay::Included), (" Included ", AngleDisplay::Included), ("BEND", AngleDisplay::Bend)] { + let rule = SheetRule { angle_display: text.into(), ..old.clone() }; + assert_eq!(doc.rule_values(&vals, &rule).unwrap().angle_display, display); + assert_eq!(AngleDisplay::parse(display.name()), Some(display)); + } + // An included rule is saved with the setting and read back the same. + let included = SheetRule { angle_display: "included".into(), ..old.clone() }; + let saved = serde_json::to_value(&included).unwrap(); + assert_eq!(saved["angle_display"], "included"); + assert_eq!(serde_json::from_value::(saved).unwrap(), included); + // No other word is a display. + for text in ["deflection", "inside", ""] { + let err = doc.rule_values(&vals, &SheetRule { angle_display: text.into(), ..old.clone() }).unwrap_err().to_string(); + assert!(err.contains(&format!("unknown bend angle display `{text}` (bend or included)")), "{err}"); + } + } + + /// The included angle is what a bend leaves between its sides: 180° less the bend angle, so a + /// 90° bend reads the same both ways. A body keeps its rule's display. + #[test] + fn the_included_angle_is_180_less_the_bend_angle() { + for (deg, included) in [(58.0, 122.0), (90.0, 90.0), (120.0, 60.0)] { + let bends = flanged(f64::to_radians(deg)).bends(); + assert_eq!(bends.len(), 1); + assert!((bends[0].angle_deg - deg).abs() < 1e-9 && (bends[0].included_angle_deg() - included).abs() < 1e-9, "{bends:?}"); + assert!((AngleDisplay::Bend.of(bends[0].angle_deg) - deg).abs() < 1e-9); + assert!((AngleDisplay::Included.of(bends[0].angle_deg) - included).abs() < 1e-9); + } + let r = rect(Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0), Vec2::new(100.0, 80.0), Vec2::new(0.0, 80.0)); + assert_eq!(base_flange("Body1", "Steel", &steel(), Plane::XY, r.clone()).angle_display, AngleDisplay::Bend); + let shop = RuleValues { angle_display: AngleDisplay::Included, ..steel() }; + assert_eq!(base_flange("Body1", "Shop", &shop, Plane::XY, r).angle_display, AngleDisplay::Included); + } + #[test] fn corner_reliefs_cut_the_base_corner_and_stop_the_bends() { use std::f64::consts::{FRAC_PI_2, FRAC_PI_4}; diff --git a/crates/engine/src/cmd/sheet.rs b/crates/engine/src/cmd/sheet.rs index 1388eddee..59e81a554 100644 --- a/crates/engine/src/cmd/sheet.rs +++ b/crates/engine/src/cmd/sheet.rs @@ -57,6 +57,8 @@ pub static COMMANDS: &[CommandSpec] = &[ gap: between flanges that meet at a corner, whose ends are closed toward each other at any angle); \ corner_relief_shape?: notch|round|rectangular|tear (what is cut where two bends meet at a corner of the base: round and rectangular a relief \ `corner_relief` across; tear none, each bend's end is cut straight from the corner to its flange's end; default notch); \ + angle_display?: bend|included (how the DXF bend notes read the bend angles: the bend angle, default, or the included angle \ + left between the bend's sides, 180° less it; the bend table gives both, and a flange's `angle` is always the bend angle); \ active?: bool; delete?: bool", ), CommandSpec::new("sheet.rules", "List Sheet Metal Rules", list_rules).icon("sheet_rules").noundo().doc_only().params("→ rules with their expressions and values, and the active one"), @@ -72,7 +74,8 @@ pub static COMMANDS: &[CommandSpec] = &[ .params( "body?, path?, curves?: exact|arcs (default exact: an ellipse as ELLIPSE, splines, text outlines and other Béziers as SPLINE; arcs: tangent arcs and lines within 0.001 mm, for machines that read only those), \ text?: cut|etch (default cut: letters that text cut through the sheet are cut contours on layer TEXT; etch: single contours on layer ETCH and the sheet keeps its material there; text machined to a depth is always on ETCH), \ - bend_notes?: bool (default false: a note beside each bend line on layer BEND_NOTES, `B1 UP 90%%d R1`), note_height?: mm (default 3), \ + bend_notes?: bool (default false: a note beside each bend line on layer BEND_NOTES, `B1 UP 90%%d R1`, its angle the included angle \ + when the body's rule has angle_display: included), note_height?: mm (default 3), \ bend_lines?: bool (default true; false leaves BEND_UP and BEND_DOWN out, for a cutter that would cut them), \ layers?: roles|single (default roles, the layers below; single: every entity on layer 0), \ per_body?: bool (a file for every sheet body, `-.dxf`, or their DXF texts without a path → files: [{body, path | dxf, bends}]; not with `body`) \ @@ -81,7 +84,7 @@ pub static COMMANDS: &[CommandSpec] = &[ ), CommandSpec::new("sheet.export_bend_table", "Export Bend Table", export_bend_table).icon("bendtable") .noundo() - .params("body?, format?: csv|json (default csv), path? → bend table in mm and degrees, including rule and flat centre-line coordinates; a bend that cut-outs split has a row for each piece"), + .params("body?, format?: csv|json (default csv), path? → bend table in mm and degrees, including rule and flat centre-line coordinates; angle_deg is the bend angle and included_angle_deg the angle left between the bend's sides (180° less it); a bend that cut-outs split has a row for each piece"), ]; fn points(p: &Value, k: &str, cmd: &str) -> Result> { @@ -416,6 +419,10 @@ fn rules(s: &mut Session, p: &Value) -> Result { let shape = shape.as_str().and_then(solidcraft_doc::sheet::ReliefShape::parse); rule.corner_relief_shape = shape.ok_or_else(|| bad(cmd, "`corner_relief_shape` must be notch, round, rectangular or tear"))?.name().into(); } + if let Some(display) = p.get("angle_display").filter(|v| !v.is_null()) { + let display = display.as_str().and_then(sheet::AngleDisplay::parse); + rule.angle_display = display.ok_or_else(|| bad(cmd, "`angle_display` must be bend or included"))?.name().into(); + } let (vals, _) = s.doc.param_values(); let values = s.doc.rule_values(&vals, &rule).map_err(|e| bad(cmd, e.to_string()))?; let doc = s.doc_mut(); @@ -433,7 +440,17 @@ fn rules(s: &mut Session, p: &Value) -> Result { } s.refresh(); let errors: Vec = s.model.results.iter().filter_map(|r| r.error.as_ref().map(|e| json!({"feature": r.name, "error": e}))).collect(); - Ok(json!({"rule": rule, "values": values, "errors": errors})) + Ok(json!({"rule": rule_json(&rule), "values": values, "errors": errors})) +} + +/// A rule as the rule commands list it: as saved, and with its `angle_display` also while it is +/// the `bend` a design leaves out. +fn rule_json(r: &SheetRule) -> Value { + let mut v = json!(r); + if let Value::Object(m) = &mut v { + m.insert("angle_display".into(), json!(r.angle_display)); + } + v } fn list_rules(s: &mut Session, _p: &Value) -> Result { @@ -442,7 +459,7 @@ fn list_rules(s: &mut Session, _p: &Value) -> Result { if all.is_empty() { all.push(SheetRule::steel()); } - let rules: Vec = all.iter().map(|r| json!({"rule": r, "values": s.doc.rule_values(&vals, r).ok()})).collect(); + let rules: Vec = all.iter().map(|r| json!({"rule": rule_json(r), "values": s.doc.rule_values(&vals, r).ok()})).collect(); let active = s.doc.sheet_rule(None).name; Ok(json!({"rules": rules, "active": active})) } @@ -508,7 +525,7 @@ fn flat_json(sh: &SheetBody) -> Result { .bends() .iter() .map(|b| { - json!({"bend": b.index, "angle_deg": b.angle_deg, "radius": b.radius, "direction": if b.up { "up" } else { "down" }, + json!({"bend": b.index, "angle_deg": b.angle_deg, "included_angle_deg": b.included_angle_deg(), "radius": b.radius, "direction": if b.up { "up" } else { "down" }, "allowance": b.allowance, "length": b.length, "start": pt(&b.start), "end": pt(&b.end)}) }) .collect(); @@ -622,10 +639,10 @@ fn compact(v: f64) -> String { if t.is_empty() || t == "-0" { "0".into() } else { t.into() } } -/// The note beside a bend line, `B1 UP 90%%d R2.5` (number, direction, angle, inner radius): as -/// high as `height`, centred half a height beside the middle of the line, parallel to it and -/// readable from below or from the right. (`%%d` is AutoCAD's degree sign.) -fn bend_note(b: &solidcraft_doc::sheet::BendInfo, height: f64) -> solidcraft_io::DxfShape { +/// The note beside a bend line, `B1 UP 90%%d R2.5` (number, direction, angle as `display` reads +/// it, inner radius): as high as `height`, centred half a height beside the middle of the line, +/// parallel to it and readable from below or from the right. (`%%d` is AutoCAD's degree sign.) +fn bend_note(b: &solidcraft_doc::sheet::BendInfo, height: f64, display: sheet::AngleDisplay) -> solidcraft_io::DxfShape { let along = (b.end - b.start).normalized().unwrap_or(Vec2::X); let mut angle = along.angle().to_degrees(); if angle > 90.0 + 1e-9 { @@ -638,7 +655,7 @@ fn bend_note(b: &solidcraft_doc::sheet::BendInfo, height: f64) -> solidcraft_io: at: (b.start + b.end) * 0.5 + beside * (height * 0.5), height, angle_deg: angle, - text: format!("B{} {} {}%%d R{}", b.index, if b.up { "UP" } else { "DOWN" }, compact(b.angle_deg), compact(b.radius)), + text: format!("B{} {} {}%%d R{}", b.index, if b.up { "UP" } else { "DOWN" }, compact(display.of(b.angle_deg)), compact(b.radius)), } } @@ -742,7 +759,7 @@ pub fn flat_dxf(sh: &SheetBody, o: &DxfOptions) -> Result { entities.push(DxfEntity { layer: if b.up { "BEND_UP" } else { "BEND_DOWN" }.into(), shape: DxfShape::Line(b.start, b.end) }); } if let Some(height) = o.bend_notes { - entities.push(DxfEntity { layer: "BEND_NOTES".into(), shape: bend_note(&b, height) }); + entities.push(DxfEntity { layer: "BEND_NOTES".into(), shape: bend_note(&b, height, sh.angle_display) }); } } for (c, r) in perforation { @@ -893,11 +910,11 @@ fn export_bend_table(s: &mut Session, p: &Value) -> Result { // Always quote text fields: body/rule names may include commas, quotes or newlines. let quote = |s: &str| format!("\"{}\"", s.replace('"', "\"\"")); let mut csv = - "body,rule,thickness_mm,k_factor,bend,angle_deg,direction,radius_mm,allowance_mm,length_mm,start_x_mm,start_y_mm,end_x_mm,end_y_mm\r\n" + "body,rule,thickness_mm,k_factor,bend,angle_deg,direction,radius_mm,allowance_mm,length_mm,start_x_mm,start_y_mm,end_x_mm,end_y_mm,included_angle_deg\r\n" .to_string(); for b in sh.bends() { csv.push_str(&format!( - "{},{},{:.9},{:.9},{},{:.9},{},{:.9},{:.9},{:.9},{:.9},{:.9},{:.9},{:.9}\r\n", + "{},{},{:.9},{:.9},{},{:.9},{},{:.9},{:.9},{:.9},{:.9},{:.9},{:.9},{:.9},{:.9}\r\n", quote(&sh.body), quote(&sh.rule), sh.t, @@ -911,7 +928,8 @@ fn export_bend_table(s: &mut Session, p: &Value) -> Result { b.start.x, b.start.y, b.end.x, - b.end.y + b.end.y, + b.included_angle_deg() )); } csv diff --git a/crates/engine/src/cmd/sheet_dxf_tests.rs b/crates/engine/src/cmd/sheet_dxf_tests.rs index 3fa2455fb..8a99ce6eb 100644 --- a/crates/engine/src/cmd/sheet_dxf_tests.rs +++ b/crates/engine/src/cmd/sheet_dxf_tests.rs @@ -471,6 +471,46 @@ fn a_bend_note_sits_beside_each_bend_line_when_asked_for() { assert!(note.is_some_and(|e| values(e, 40) == [5.0])); } +#[test] +fn a_bend_note_gives_the_included_angle_when_the_rule_reads_it_so() { + // The included angle is 180° less the bend angle: 122° for a 58° bend, 90° for a 90° one. + for (deg, included) in [(58.0, 122.0), (90.0, 90.0)] { + let mut plain = Vec::new(); + for display in ["bend", "included"] { + let mut s = sheet_of_2mm(); + run(&mut s, "sheet.manage_rules", json!({"name": "Sheet2", "angle_display": display})); + let mut s = plate_in(s, &[]); + run(&mut s, "sheet.flange", json!({"edges": [[50, 0, 2]], "height": 20, "angle": format!("{deg} deg")})); + let dxf = export(&mut s, json!({"bend_notes": true})); + let notes: Vec = entities(&dxf).iter().filter(|e| e.0 == "TEXT").map(|e| string(e, 1)).collect(); + let shown = if display == "included" { included } else { deg }; + assert_eq!(notes, [format!("B1 UP {shown}%%d R1")], "{deg}° under {display}"); + plain.push(export(&mut s, json!({}))); + } + // Without notes the setting changes nothing in the file. + assert_eq!(plain.first(), plain.get(1), "{deg}°"); + } +} + +/// A body whose base flange names its rule keeps that rule's notes whichever rule is active when +/// the DXF is written, and a bend down reads its included angle the same way. +#[test] +fn a_bend_note_follows_the_bodys_own_rule_and_bends_down_too() { + let mut s = sheet_of_2mm(); + run(&mut s, "sheet.manage_rules", json!({"name": "Sheet2", "angle_display": "included"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Base"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [100, 60]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "sheet.flange", json!({"sketch": "Base", "rule": "Sheet2"})); + run(&mut s, "sheet.flange", json!({"edges": [[50, 0, 2]], "height": 20, "angle": "58 deg", "flip": true})); + let notes = |s: &mut Session| -> Vec { + entities(&export(s, json!({"bend_notes": true}))).iter().filter(|e| e.0 == "TEXT").map(|e| string(e, 1)).collect() + }; + assert_eq!(notes(&mut s), ["B1 DOWN 122%%d R1"]); + run(&mut s, "sheet.manage_rules", json!({"name": "Other", "thickness": "2 mm", "angle_display": "bend", "active": true})); + assert_eq!(notes(&mut s), ["B1 DOWN 122%%d R1"], "another active rule does not change this body's notes"); +} + /// Two sheet bodies: a lid and, 200 mm away, a side wall with one bend. fn lid_and_wall() -> Session { let mut s = Session::default(); diff --git a/crates/engine/src/cmd/sheet_tests.rs b/crates/engine/src/cmd/sheet_tests.rs index 8e862439f..a4af61367 100644 --- a/crates/engine/src/cmd/sheet_tests.rs +++ b/crates/engine/src/cmd/sheet_tests.rs @@ -1296,7 +1296,12 @@ fn the_bend_table_and_the_dxf_follow_what_flat_cuts_leave_of_a_bend() { let csv = run(&mut s, "sheet.export_bend_table", json!({})); let text = csv["text"].as_str().unwrap_or_default(); assert_eq!((text.lines().count(), csv["bends"].as_u64()), (2, Some(1)), "{text}"); - assert!(text.lines().nth(1).is_some_and(|l| l.contains(",1,90.000000000,up,1.000000000,3.141592654,100.000000000,100.000000000,")), "{text}"); + assert!( + text.lines() + .nth(1) + .is_some_and(|l| l.contains(",1,90.000000000,up,1.000000000,3.141592654,100.000000000,100.000000000,") && l.ends_with(",90.000000000")), + "{text}" + ); // A slot across what is left splits the bend: a row and a line for each piece, both bend 1. run(&mut s, "sheet.unfold", json!({})); rectangle_tool(&mut s, "Slot", [140.0, -20.0], [160.0, 10.0]); @@ -1598,6 +1603,8 @@ fn bend_table_exports_shop_dimensions_and_tracks_parameter_changes() { let csv = run(&mut s, "sheet.export_bend_table", json!({})); let text = csv["text"].as_str().unwrap(); assert!(text.starts_with("body,rule,thickness_mm,k_factor,bend,angle_deg,direction,")); + // The included angle comes last, so a reader that takes the columns by position is unaffected. + assert!(text.lines().next().is_some_and(|h| h.ends_with(",end_y_mm,included_angle_deg")), "{text}"); assert!(text.contains("\"Shop, \"\"steel\"\"\""), "{text}"); assert_eq!(text.lines().count(), 2); assert_eq!(csv["bends"], 1); @@ -1617,6 +1624,103 @@ fn bend_table_exports_shop_dimensions_and_tracks_parameter_changes() { assert!(empty.execute("sheet.export_bend_table", &json!({})).is_err()); } +/// A 100 x 60 base of the 2 mm rule `Shop` (R 1, K 0.5, its `angle_display` as given; none leaves +/// it out) with a 20 mm edge flange at `deg` on its y = 0 edge. +fn shop_bend(deg: f64, display: Option<&str>) -> Session { + let mut s = Session::default(); + let mut rule = json!({"name": "Shop", "thickness": "2 mm", "k_factor": 0.5, "bend_radius": "1 mm", "active": true}); + if let Some(d) = display { + rule["angle_display"] = json!(d); + } + run(&mut s, "sheet.manage_rules", rule); + base(&mut s, 100.0, 60.0); + run(&mut s, "sheet.flange", json!({"edges": [[50, 0, 2]], "height": 20, "angle": format!("{deg} deg")})); + s +} + +/// The DXF bend notes of the last sheet body. +fn bend_notes(s: &mut Session) -> Vec { + let dxf = run(s, "sheet.export_dxf", json!({"bend_notes": true}))["dxf"].as_str().unwrap_or_default().to_string(); + dxf.lines().map(str::trim).filter(|l| l.starts_with('B') && l.contains("%%d")).map(str::to_string).collect() +} + +#[test] +fn the_bend_table_gives_the_included_angle_beside_the_bend_angle() { + // 180° less the bend angle whatever the rule shows: a 58° bend leaves 122°, a 90° one 90°. + for (deg, included) in [(58.0, 122.0), (90.0, 90.0)] { + for display in [None, Some("bend"), Some("included")] { + let mut s = shop_bend(deg, display); + let csv = run(&mut s, "sheet.export_bend_table", json!({})); + let text = csv["text"].as_str().unwrap_or_default(); + let mut lines = text.lines(); + let header: Vec<&str> = lines.next().unwrap_or_default().split(',').collect(); + let row: Vec<&str> = lines.next().unwrap_or_default().split(',').collect(); + let column = |name: &str| header.iter().position(|h| *h == name); + assert_eq!((column("angle_deg"), column("included_angle_deg")), (Some(5), Some(14)), "{text}"); + let (angle, inside) = (format!("{deg:.9}"), format!("{included:.9}")); + assert_eq!((row.get(5).copied(), row.get(14).copied()), (Some(angle.as_str()), Some(inside.as_str())), "{display:?}: {text}"); + for format in ["json", "flat"] { + let table = if format == "json" { + let text = run(&mut s, "sheet.export_bend_table", json!({"format": "json"}))["text"].as_str().unwrap_or_default().to_string(); + serde_json::from_str(&text).unwrap_or_default() + } else { + flat(&mut s) + }; + let b = &table["bends"][0]; + let near = |k: &str, want: f64| (b[k].as_f64().unwrap_or(f64::NAN) - want).abs() < 1e-9; + assert!(near("angle_deg", deg) && near("included_angle_deg", included), "{format} {display:?}: {b}"); + } + } + } +} + +#[test] +fn the_angle_display_is_a_rule_setting_checked_saved_and_undone() { + let mut s = shop_bend(58.0, None); + let display = |s: &mut Session| { + let r = run(s, "sheet.rules", json!({})); + (r["rules"][0]["rule"]["angle_display"].clone(), r["rules"][0]["values"]["angle_display"].clone()) + }; + assert_eq!(display(&mut s), (json!("bend"), json!("bend"))); + assert_eq!(bend_notes(&mut s), ["B1 UP 58%%d R1"]); + // A design whose rules read bend angles saves as it did before the setting. + let before = s.doc.to_json(); + assert!(!before.contains("angle_display"), "{before}"); + // Only the two words are displays; a refused one changes nothing and makes no rule. + for wrong in [json!("deflection"), json!("press brake"), json!(""), json!(122), json!(true)] { + for name in ["Shop", "Other"] { + let e = s.execute("sheet.manage_rules", &json!({"name": name, "angle_display": wrong})).map(|_| ()).unwrap_err().to_string(); + assert!(e.contains("`angle_display` must be bend or included"), "{e}"); + assert_eq!(s.doc.to_json(), before, "{name}: {wrong}"); + } + } + let undo = s.undo.len(); + let r = run(&mut s, "sheet.manage_rules", json!({"name": "Shop", "angle_display": " Included "})); + assert_eq!((&r["rule"]["angle_display"], &r["values"]["angle_display"]), (&json!("included"), &json!("included"))); + assert_eq!(bend_notes(&mut s), ["B1 UP 122%%d R1"]); + // Other settings leave it alone, and so does null. + run(&mut s, "sheet.manage_rules", json!({"name": "Shop", "hem_gap": "0.02 mm", "angle_display": null})); + assert_eq!(display(&mut s), (json!("included"), json!("included"))); + // Saved with the design and read back; a design saved without it reads bend angles. + let mut saved: Value = serde_json::from_str(&s.doc.to_json()).unwrap(); + assert_eq!(saved["sheet"]["rules"][0]["angle_display"], "included"); + let mut reopened = Session::new(solidcraft_doc::Document::from_json(&saved.to_string()).unwrap()); + assert_eq!(display(&mut reopened).0, "included"); + assert_eq!(bend_notes(&mut reopened), ["B1 UP 122%%d R1"]); + if let Some(rule) = saved["sheet"]["rules"][0].as_object_mut() { + rule.remove("angle_display"); + } + let mut older = Session::new(solidcraft_doc::Document::from_json(&saved.to_string()).unwrap()); + assert_eq!(display(&mut older), (json!("bend"), json!("bend"))); + assert_eq!(bend_notes(&mut older), ["B1 UP 58%%d R1"]); + // Undone like the rule's other changes. + assert_eq!(s.undo.len(), undo + 2); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert_eq!(display(&mut s).0, "bend"); + assert_eq!(bend_notes(&mut s), ["B1 UP 58%%d R1"]); +} + #[test] fn malformed_fold_points_are_rejected_atomically() { let mut s = Session::default(); diff --git a/crates/ui-egui/src/dialogs_sheet.rs b/crates/ui-egui/src/dialogs_sheet.rs index 560b10ca6..dfe47d6cf 100644 --- a/crates/ui-egui/src/dialogs_sheet.rs +++ b/crates/ui-egui/src/dialogs_sheet.rs @@ -37,6 +37,10 @@ const RULE_FIELDS: [(&str, &str); 8] = [ /// The corner relief shapes the manager offers (the rule's `corner_relief_shape`) and their labels. const RELIEF_SHAPES: [&str; 4] = ["notch", "round", "rectangular", "tear"]; const RELIEF_SHAPE_LABELS: [&str; 4] = ["Notch", "Round", "Rectangular", "Tear"]; +/// How the manager's rule reads bend angles in the DXF bend notes (the rule's `angle_display`) +/// and their labels. +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. const FLANGE_RELIEF_LABELS: [&str; 5] = ["Rule", "Notch", "Round", "Rectangular", "Tear"]; @@ -90,6 +94,8 @@ crate::dialog_descriptor::dialog_descriptors! { values: Vec, /// The corner relief shape (index into `RELIEF_SHAPES`). relief: usize, + /// How bend angles read (index into `ANGLE_DISPLAYS`). + angles: usize, active: bool, loaded: Option, }, @@ -165,7 +171,7 @@ pub fn start(app: &SolveApp, id: &str) -> Option<(Kind, Vec)> { let active = app.session.doc.sheet.active.clone(); let rules = rule_list(app); let pick = active.and_then(|a| rules.iter().position(|r| r.name == a)).unwrap_or(0); - (Sm::Rules { pick, name: String::new(), values: Vec::new(), relief: 0, active: true, loaded: None }, vec![]) + (Sm::Rules { pick, name: String::new(), values: Vec::new(), relief: 0, angles: 0, active: true, loaded: None }, vec![]) } "sheet.flat_pattern" => (Sm::FlatPattern { data: None, key: None, status: None }, vec![SelInput::new("Body (last if none)", BODIES, false)]), _ => Sm::simple_start(id)?, @@ -286,7 +292,7 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Sm, inputs: &mut [Sel } Sm::Unfold { .. } => {} Sm::Convert { rule } => rule_combo(app, ui, "sm_conv_rule", rule), - Sm::Rules { pick, name, values, relief, active, loaded } => { + Sm::Rules { pick, name, values, relief, angles, active, loaded } => { let rules = rule_list(app); crate::rule_editor::rule_editor! { ui, "sm_rules", rules, pick, name, active, loaded; @@ -305,6 +311,7 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Sm, inputs: &mut [Sel base.gap.clone(), ]; *relief = RELIEF_SHAPES.iter().position(|s| s.eq_ignore_ascii_case(base.corner_relief_shape.trim())).unwrap_or(0); + *angles = ANGLE_DISPLAYS.iter().position(|d| d.eq_ignore_ascii_case(base.angle_display.trim())).unwrap_or(0); *active = app.session.doc.sheet_rule(None).name == base.name || *pick >= rules.len(); }, fields: { @@ -315,6 +322,7 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Sm, inputs: &mut [Sel } enter |= expr_row(ui, label, v); } + choice_row(ui, "Angle Display", "sm_angle_display", angles, &ANGLE_DISPLAY_LABELS); } } if *pick < rules.len() @@ -569,11 +577,12 @@ pub fn commands(app: &SolveApp, k: &Sm, inputs: &[SelInput], extra: &Map { + Sm::Rules { pick, name, values, relief, angles, active, .. } => { let rules = rule_list(app); let fields = RULE_FIELDS.iter().map(|(key, _)| *key).zip(values); let mut p = crate::rule_editor::params(rules.get(*pick).map(|r| r.name.as_str()), name, *active, fields)?; p["corner_relief_shape"] = json!(RELIEF_SHAPES.get(*relief).copied().unwrap_or("notch")); + p["angle_display"] = json!(ANGLE_DISPLAYS.get(*angles).copied().unwrap_or("bend")); ("sheet.manage_rules", p) } Sm::FlatPattern { .. } => return Ok(Vec::new()), diff --git a/crates/ui-egui/src/dialogs_sheet_tests.rs b/crates/ui-egui/src/dialogs_sheet_tests.rs index eef150156..3371d278b 100644 --- a/crates/ui-egui/src/dialogs_sheet_tests.rs +++ b/crates/ui-egui/src/dialogs_sheet_tests.rs @@ -391,6 +391,51 @@ fn rules_dialog_picks_the_corner_relief_shape() { } } +/// The rule manager's angle display: picked in the dialog, it reaches the rule and the bend notes +/// of the part made with it, and the dialog shows it the next time. +#[test] +fn rules_dialog_sets_how_bend_angles_read() { + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = crate::scenario::Harness::new(); + h.call("ui.set", json!({"layout":mode})); + h.app.run("sheet.manage_rules", json!({"name": "AL2", "thickness": "2 mm", "bend_radius": "1 mm", "active": true})).unwrap(); + 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": [[50, 0, 2]], "height": 20, "angle": "58 deg"})).unwrap(); + let shown = |app: &SolveApp| match app.dialog.as_ref().map(|d| &d.kind) { + Some(Kind::Sheet(Sm::Rules { angles, .. })) => Some(*angles), + _ => None, + }; + let note = |app: &mut SolveApp| { + let dxf = app.session.execute("sheet.export_dxf", &json!({"bend_notes": true})).unwrap(); + dxf["dxf"].as_str().unwrap_or_default().lines().map(str::trim).find(|l| l.starts_with("B1 ")).map(str::to_string) + }; + assert_eq!(note(&mut h.app).as_deref(), Some("B1 UP 58%%d R1")); + h.step(&json!({"start": "sheet.manage_rules"})).unwrap(); + h.frames(3); + assert_eq!(shown(&h.app), Some(0), "a rule starts with bend angles"); + h.step(&json!({"click": {"handle": "dialog:Angle Display"}})).unwrap(); + h.step(&json!({"click": {"handle": "dialog:Angle Display:Included"}})).unwrap(); + assert_eq!(shown(&h.app), Some(1)); + h.step(&json!({"widget": "OK"})).unwrap(); + assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog); + assert_eq!(h.app.session.doc.sheet_rule(None).angle_display, "included"); + assert_eq!(note(&mut h.app).as_deref(), Some("B1 UP 122%%d R1")); + h.step(&json!({"start": "sheet.manage_rules"})).unwrap(); + h.frames(3); + assert_eq!(shown(&h.app), Some(1), "the dialog shows the rule's display"); + // Back to bend angles; the rule's other values are as they were. + h.step(&json!({"click": {"handle": "dialog:Angle Display"}})).unwrap(); + h.step(&json!({"click": {"handle": "dialog:Angle Display:Bend"}})).unwrap(); + h.step(&json!({"widget": "OK"})).unwrap(); + let rule = h.app.session.doc.sheet_rule(None); + assert_eq!((rule.angle_display.as_str(), rule.thickness.as_str()), ("bend", "2 mm")); + assert_eq!(note(&mut h.app).as_deref(), Some("B1 UP 58%%d R1")); + } +} + /// The rule manager's rectangular relief, on a base whose corners are not square: the shape and /// the size the dialog shows reach the part, the bends and the flat pattern. #[test] diff --git a/crates/ui-egui/src/rule_editor_tests.rs b/crates/ui-egui/src/rule_editor_tests.rs index 712dc5e7a..b7aaf15ad 100644 --- a/crates/ui-egui/src/rule_editor_tests.rs +++ b/crates/ui-egui/src/rule_editor_tests.rs @@ -13,6 +13,7 @@ const SHEET_ROWS: &[&str] = &[ "Corner Relief", "Hem Gap", "Flange Gap", + "Angle Display", "Active rule", ]; const PLASTIC_ROWS: &[&str] = &[ @@ -65,7 +66,7 @@ fn sheet_rule_editor_contract() { let (mut kind, _) = crate::dialogs_sheet::start(&app, "sheet.manage_rules").unwrap(); frame(&mut app, &ctx, &mut kind, SHEET_ROWS); let mut expected = json!({"name":"Steel (mm)","active":true,"corner_relief_shape":"notch","thickness":"2.5 mm","k_factor":"0.44", - "bend_radius":"Thickness","relief_width":"Thickness","relief_depth":"Thickness * 0.5","corner_relief":"Thickness * 4.0","hem_gap":"0.01 mm","gap":"Thickness"}); + "bend_radius":"Thickness","relief_width":"Thickness","relief_depth":"Thickness * 0.5","corner_relief":"Thickness * 4.0","hem_gap":"0.01 mm","gap":"Thickness","angle_display":"bend"}); assert_eq!(commands(&app, &kind), vec![("sheet.manage_rules".into(), expected.clone())]); let Kind::Sheet(Sm::Rules { pick, values, relief, .. }) = &mut kind else { panic!() }; *pick = 1; diff --git a/docs/book/src/guide/sheet-metal.md b/docs/book/src/guide/sheet-metal.md index 5f7ede6ee..da9bdce92 100644 --- a/docs/book/src/guide/sheet-metal.md +++ b/docs/book/src/guide/sheet-metal.md @@ -210,8 +210,10 @@ computing a point on a face with holes or a curved outline: `model.faces` gives For a shop drawing or spreadsheet, `sheet.export_bend_table` returns CSV by default; choose `format: "json"` for structured data. It includes the sheet rule, thickness, bend angles, -radii, allowances and flat centre-line coordinates. Lengths use millimetres and angles use -degrees. A bend is listed where its centre line has material: one that a cut-out has shortened +radii, allowances and flat centre-line coordinates. Each bend has its bend angle (`angle_deg`) +and its included angle (`included_angle_deg`, below; the CSV's last column, so the columns before +it keep their places). Lengths use millimetres and +angles use degrees. A bend is listed where its centre line has material: one that a cut-out has shortened gives the length and ends it has left, and one that cut-outs split gives a row for every piece, all with the bend's number (the flat pattern and the DXF draw the same pieces as bend lines). Supply `path` to save it, or omit `path` to receive the content through the command @@ -268,6 +270,23 @@ For a program that cuts every line it is given, `"bend_lines": false` leaves the (`BEND_UP` and `BEND_DOWN` are then empty), and `"layers": "single"` writes every entity on layer `0` instead of a layer for each role. +A bend's angle is how far the sheet turns from flat. Many press brakes are set by the +**included angle** instead: the angle left between the bend's two sides, 180° less the bend +angle. A 90° bend is 90° either way, but a 58° bend is set as 122°. The rule's `angle_display` +(Angle Display in Sheet Metal Rules) says which one the DXF's bend notes give: `bend` (Bend, +the default) or `included` (Included). Under an `included` rule the note of a 58° +bend reads `B1 UP 122° R1`. The bend table gives both angles whatever the rule says, in columns +of their own (`angle_deg` and `included_angle_deg`), so neither is taken for the other. The +setting does not change the flange angle yet: `angle` in `sheet.flange` and in the Flange dialog +is always the bend angle, so a 122° included angle is a flange at `180 deg - 122 deg`. A design +keeps the setting in its rule, so templates made from it read their bends the same way. + +```json +{"command":"sheet.manage_rules","params":{"name":"Sheet 2 mm","angle_display":"included"}} +{"command":"sheet.flange","params":{"edges":[[50,0,2]],"height":20,"angle":"180 deg - 122 deg"}} +{"command":"sheet.export_dxf","params":{"path":"bracket-flat.dxf","bend_notes":true}} +``` + A design with several sheet bodies exports one file for each with `"per_body": true`: the files are `-.dxf` (characters a file name cannot hold become `_`; two bodies that would share a name get `_2`, `_3`…), and the reply lists them in `files`. Without a `path` it lists