From 6b37953be4d6b1374db82697ffabaceab4a131af Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Sun, 22 Nov 2026 17:30:24 -0500 Subject: [PATCH] feat(cad-converter): find and show a part number label box Add LabelBoxFinder (Core): erodes the cut material by an etch clearance, cuts bands out around bend lines and breakoff scrap, then centers a label-sized box in the roomiest empty rectangle over a few orientations (axes, bend and edge directions). Placement is stored on Drawing.LabelBox in the source frame, persisted in the .nest file and carried through BuildDrawing/ApplyEdit; it never affects the program. The CAD Converter gets a Label Box... button that finds the best spot, draws it as a dashed rectangle, lets the user drag and resize it, and warns when nothing fits. Etching the text is a later step. Co-Authored-By: Claude Sonnet 5.5 --- AGENTS.md | 1 + OpenNest.Core/Drawing.cs | 6 + OpenNest.Core/Labels/LabelBox.cs | 82 +++++++ OpenNest.Core/Labels/LabelBoxFinder.cs | 230 ++++++++++++++++++ OpenNest.IO/CadImporter.cs | 7 +- OpenNest.IO/NestFormat.cs | 16 ++ OpenNest.IO/NestReader.cs | 17 ++ OpenNest.IO/NestWriter.cs | 10 + OpenNest.Tests/Labels/LabelBoxFinderTests.cs | 223 +++++++++++++++++ .../Labels/LabelBoxPersistenceTests.cs | 116 +++++++++ .../Forms/CadConverterLabelBoxTests.cs | 154 ++++++++++++ OpenNest/Controls/EntityView.Breakoffs.cs | 8 +- OpenNest/Controls/EntityView.LabelBox.cs | 108 ++++++++ OpenNest/Controls/EntityView.cs | 1 + OpenNest/Controls/FileListControl.cs | 3 + OpenNest/Forms/CadConverterForm.Designer.cs | 16 ++ OpenNest/Forms/CadConverterForm.LabelBox.cs | 96 ++++++++ OpenNest/Forms/CadConverterForm.cs | 7 +- docs/label-box.md | 53 ++++ docs/nest-file-format.md | 14 +- 20 files changed, 1163 insertions(+), 5 deletions(-) create mode 100644 OpenNest.Core/Labels/LabelBox.cs create mode 100644 OpenNest.Core/Labels/LabelBoxFinder.cs create mode 100644 OpenNest.Tests/Labels/LabelBoxFinderTests.cs create mode 100644 OpenNest.Tests/Labels/LabelBoxPersistenceTests.cs create mode 100644 OpenNest.WinForms.Tests/Forms/CadConverterLabelBoxTests.cs create mode 100644 OpenNest/Controls/EntityView.LabelBox.cs create mode 100644 OpenNest/Forms/CadConverterForm.LabelBox.cs create mode 100644 docs/label-box.md diff --git a/AGENTS.md b/AGENTS.md index 2292f15a..00c5fe42 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -73,6 +73,7 @@ Read the relevant contract before changing its behavior: - [Lead-in placement](docs/geometry/lead-in-placement.md) (including the planner's eroded pierce for cutouts too small for their lead-in and the stop at a feature's center line) and [pierce zones](docs/geometry/pierce-zone.md): opt-in `PierceDiameter` clearance, the hole pole fallback and the planner's perimeter scrap fallback - [Breakoffs](docs/breakoffs.md): tabbed scrap; `Break`-layer open cuts that are cut but are not material - [Tabbed cutouts](docs/tabbed-cutouts.md): holes cut in pieces around `Tab`-layer spans that are material but never cut; nesting reads material through `NestingMaterial.ForNesting`, so nothing nests in them +- [Label box](docs/label-box.md): CAD Converter placement for the etched part number, found by eroding the material clear of edges, holes, bend lines and breakoff scrap; placement only, never affects the program - [Dimensions](docs/dimensions.md): CAD Converter annotations that store placement only, are measured from the cut geometry when shown and never affect the program - [Common-line cutting](docs/common-line-cutting.md): parts one kerf apart in `Plate.CommonLines` share an edge; spans are derived, never stored, and spacing checks hold group members to the kerf. Plan Cutting cuts each shared span once (the owner, cut first, starts its compensated outside on the common line; partners cut only their remainders) unless the plate is set to cut them twice; only posts implementing `ICommonLinePostProcessor` (CI Fiber) may write it, others refuse. Machine trial pending. Auto Nest and Fill Area pair `AllowCommonLine` drawings at the nest's `CommonLineUsage` (Off by default, byte-identical to no common lines); `NestLayoutCheck` exempts only explicit result groups - [Support tabs](docs/support-tabs.md): the nest's support grid, the center-of-gravity check, Plan Cutting's tab placement for parts the grid cannot hold level, and its opt-in slicing of slugs the grid cannot hold level diff --git a/OpenNest.Core/Drawing.cs b/OpenNest.Core/Drawing.cs index d8379ab8..45b7ca79 100644 --- a/OpenNest.Core/Drawing.cs +++ b/OpenNest.Core/Drawing.cs @@ -151,6 +151,12 @@ namespace OpenNest /// public List Dimensions { get; set; } = new List(); + /// + /// Where the part number label would be etched, in the source frame, or null when none is + /// set. Placement only: it never affects , nesting or posts. + /// + public Labels.LabelBox LabelBox { get; set; } + /// /// Complete set of source entities with stable GUIDs. /// Null when the drawing was created from G-code or an older nest file. diff --git a/OpenNest.Core/Labels/LabelBox.cs b/OpenNest.Core/Labels/LabelBox.cs new file mode 100644 index 00000000..2ea9e2ef --- /dev/null +++ b/OpenNest.Core/Labels/LabelBox.cs @@ -0,0 +1,82 @@ +using OpenNest.Geometry; +using OpenNest.Math; + +namespace OpenNest.Labels +{ + /// + /// Where a part's number label would be etched: a rectangle on the flat face, in the drawing's + /// source frame. Only the placement is stored. It is an annotation, like a dimension: it never + /// affects the program, nesting geometry or posts. + /// + public sealed class LabelBox + { + public LabelBox() + { + } + + public LabelBox(Vector center, double width, double height, double rotation) + { + Center = center; + Width = width; + Height = height; + Rotation = rotation; + } + + public Vector Center { get; set; } + + /// The side along the text, before . + public double Width { get; set; } + + /// The side across the text, before . + public double Height { get; set; } + + /// Counterclockwise turn about , in radians. + public double Rotation { get; set; } + + /// True when the center, both sides and the rotation are finite and both sides are positive. + public bool IsValid => + double.IsFinite(Center.X) && double.IsFinite(Center.Y) + && double.IsFinite(Width) && Width > 0 + && double.IsFinite(Height) && Height > 0 + && double.IsFinite(Rotation); + + public LabelBox Clone() => new(Center, Width, Height, Rotation); + + /// The corners counterclockwise from the text's lower left. + public Vector[] Corners() + { + var cos = PortableMath.Cos(Rotation); + var sin = PortableMath.Sin(Rotation); + var hw = Width / 2; + var hh = Height / 2; + Vector Corner(double x, double y) => new(Center.X + x * cos - y * sin, Center.Y + x * sin + y * cos); + return new[] { Corner(-hw, -hh), Corner(hw, -hh), Corner(hw, hh), Corner(-hw, hh) }; + } + + /// A point in the box's own frame (x along the text, y across it), origin at the center. + public Vector ToLocal(Vector point) + { + var cos = PortableMath.Cos(Rotation); + var sin = PortableMath.Sin(Rotation); + var dx = point.X - Center.X; + var dy = point.Y - Center.Y; + return new Vector(dx * cos + dy * sin, -dx * sin + dy * cos); + } + + /// The point at in the box's own frame. + public Vector ToWorld(Vector local) + { + var cos = PortableMath.Cos(Rotation); + var sin = PortableMath.Sin(Rotation); + return new Vector( + Center.X + local.X * cos - local.Y * sin, + Center.Y + local.X * sin + local.Y * cos); + } + + public bool Contains(Vector point) + { + var local = ToLocal(point); + return System.Math.Abs(local.X) <= Width / 2 && System.Math.Abs(local.Y) <= Height / 2; + } + } +} diff --git a/OpenNest.Core/Labels/LabelBoxFinder.cs b/OpenNest.Core/Labels/LabelBoxFinder.cs new file mode 100644 index 00000000..dff67c03 --- /dev/null +++ b/OpenNest.Core/Labels/LabelBoxFinder.cs @@ -0,0 +1,230 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Clipper2Lib; +using OpenNest.Bending; +using OpenNest.Converters; +using OpenNest.Geometry; +using OpenNest.Math; + +namespace OpenNest.Labels +{ + /// What must fit, in the drawing's units. + public sealed class LabelBoxOptions + { + /// Characters in the longest label: a part number and a few bend group letters ("1234-AB"). + public const int DefaultCharacters = 7; + + /// Etch stroke advance as a share of the character height. + public const double CharacterAdvance = 0.75; + + /// The label's length along the text. + public double Width { get; set; } + + /// The label's height across the text. + public double Height { get; set; } + + /// The clearance kept from the part's edges, holes and cutouts. + public double Clearance { get; set; } + + /// The clearance kept from each side of a bend line; when null. + public double? BendClearance { get; set; } + + /// A label of characters in a stroke font of height . + public static LabelBoxOptions ForText(int characters, double characterHeight, double clearance) => + new() + { + Width = characters * characterHeight * CharacterAdvance, + Height = characterHeight, + Clearance = clearance, + }; + + /// A quarter inch (6 mm) label of characters, an eighth inch (3 mm) from anything else. + public static LabelBoxOptions Default(Units units) => units == Units.Millimeters + ? ForText(DefaultCharacters, 6, 3) + : ForText(DefaultCharacters, 0.25, 0.125); + } + + /// + /// Finds where a part number label can be etched: a rectangle of the label's size on the part's + /// flat material, clear of its edges, holes, cutouts and bend lines. + /// + /// + /// The material is eroded by the etch clearance (the same Clipper inward offset the pierce + /// search uses on a cutout), and a band either side of each bend line is cut out of what is + /// left. For each orientation tried, the largest empty rectangles of the rotated region are + /// searched () and the one with the most room around the label + /// wins; the label-sized box is centered in it. Orientations are the axes and the direction of + /// each bend and of the longest straight edge, plus the quarter turn of each, with text turned + /// at most a quarter so it never reads upside down. Earlier orientations win unless a later + /// one has a clearly roomier rectangle, so the result is deterministic and favors the + /// horizontal. Rectangles are staircased against slanted and curved edges, so they never cross + /// the clearance. + /// + public static class LabelBoxFinder + { + // A later orientation must have this much more room than the best so far to replace it. + private const double ImprovementFactor = 1.05; + + private const int Divisions = 128; + private const int RectanglesPerOrientation = 8; + private static readonly double AngleMerge = Angle.ToRadians(0.5); + + /// + /// A box for the label, or null when nothing fits. are the part as + /// it will be cut; marks and rapids are not material, and a tabbed cutout's slug counts as + /// part (). + /// + /// The part as it will be cut. + /// Bend lines to keep clear of. + /// The label size and clearances. + /// Closed outlines inside the part's material that must stay clear, each + /// grown by the clearance: a breakoff's scrap, which is snapped off after forming. + public static LabelBox Find(IEnumerable entities, IEnumerable bends, LabelBoxOptions options, + IEnumerable> keepOut = null) + { + ArgumentNullException.ThrowIfNull(entities); + ArgumentNullException.ThrowIfNull(options); + if (!(options.Width > 0) || !(options.Height > 0) || !double.IsFinite(options.Width) + || !double.IsFinite(options.Height) || !(options.Clearance >= 0) || !double.IsFinite(options.Clearance)) + throw new ArgumentException("The label size and clearance must be finite and positive.", nameof(options)); + + var material = entities.Where(e => !ScribeLayerRepair.IsMarkLayer(e.Layer)).ForNesting(); + var shapes = ShapeBuilder.GetShapes(material).Where(s => s.IsClosed()).ToList(); + if (shapes.Count == 0) + return null; + + var bendList = (bends ?? Enumerable.Empty()) + .Where(b => b.Length > Tolerance.Epsilon) + .ToList(); + + var clearance = options.Clearance; + var bendClearance = options.BendClearance ?? clearance; + var tolerance = System.Math.Max(System.Math.Min(clearance, bendClearance) / 20, + System.Math.Pow(10, -ClipperBridge.Precision)); + + // The perimeter is flattened inside the true curve and cutouts outside it, so the + // region never reaches past the real material. + var region = ClipperBridge.ToRegion(ShapeProfile.FromShapes(shapes), tolerance, circumscribe: false); + var free = clearance > 0 + ? Clipper.InflatePaths(region, -(clearance + tolerance), JoinType.Round, EndType.Polygon, 2.0, + ClipperBridge.Precision, tolerance) + : region; + + var bands = new PathsD(); + foreach (var bend in bendList) + { + bands.AddRange(Clipper.InflatePaths( + new PathsD { new PathD { new PointD(bend.StartPoint.X, bend.StartPoint.Y), new PointD(bend.EndPoint.X, bend.EndPoint.Y) } }, + bendClearance + tolerance, JoinType.Round, EndType.Round, 2.0, ClipperBridge.Precision, tolerance)); + } + + // A kept-out outline is flattened outside its curve so it never under-covers. + foreach (var outline in keepOut ?? Enumerable.Empty>()) + { + foreach (var shape in ShapeBuilder.GetShapes(outline.ToList()).Where(s => s.IsClosed())) + { + var path = new PathsD { ClipperBridge.ToPath(ClipperBridge.Flatten(shape, tolerance, circumscribe: true), positive: true) }; + bands.AddRange(Clipper.InflatePaths(path, clearance + tolerance, JoinType.Round, EndType.Polygon, 2.0, + ClipperBridge.Precision, tolerance)); + } + } + + if (bands.Count > 0) + free = Clipper.Difference(free, bands, FillRule.NonZero, ClipperBridge.Precision); + + if (free.Count == 0) + return null; + + LabelBox best = null; + var bestRoom = 0.0; + foreach (var angle in Orientations(bendList, shapes)) + { + var room = Best(Rotate(free, -angle), options, out var center); + if (room < 1 - Tolerance.Epsilon || !(room > bestRoom * ImprovementFactor)) + continue; + + bestRoom = room; + best = new LabelBox(Turn(center, angle), options.Width, options.Height, angle); + } + return best; + } + + // The most room any large rectangle has around the label: how many times the label fits in + // its tighter side. Under 1 means the label does not fit. + private static double Best(PathsD region, LabelBoxOptions options, out Vector center) + { + center = default; + var best = 0.0; + foreach (var rect in MaximalRectangles.InRegion(region, 0, Divisions, RectanglesPerOrientation)) + { + // A Box's Length runs along X and its Width along Y. + var room = System.Math.Min(rect.Length / options.Width, rect.Width / options.Height); + if (room > best) + { + best = room; + center = rect.Center; + } + } + return best; + } + + // Axes first (text horizontal reads best on the sheet), then the longest bend, the other + // bends, and the longest straight edge, each with its quarter turn. Text is never turned + // past a quarter: angles are taken in (-π/2, π/2]. + private static List Orientations(List bends, List shapes) + { + var raw = new List { 0, System.Math.PI / 2 }; + foreach (var bend in bends.OrderByDescending(b => b.Length)) + raw.Add(bend.LineAngle); + + var edge = shapes.SelectMany(s => s.Entities).OfType() + .OrderByDescending(l => l.Length) + .FirstOrDefault(); + if (edge != null) + raw.Add(edge.StartPoint.AngleTo(edge.EndPoint)); + + var angles = new List(); + foreach (var value in raw) + { + foreach (var turn in new[] { 0.0, System.Math.PI / 2 }) + { + var angle = Quarter(value + turn); + if (!angles.Any(a => System.Math.Abs(a - angle) < AngleMerge)) + angles.Add(angle); + } + } + return angles; + } + + // The equivalent angle in (-π/2, π/2]: a half turn only flips the text. + private static double Quarter(double angle) + { + var half = System.Math.PI; + angle -= System.Math.Floor(angle / half) * half; // [0, π) + return angle > half / 2 ? angle - half : angle; + } + + private static PathsD Rotate(PathsD paths, double angle) + { + var cos = PortableMath.Cos(angle); + var sin = PortableMath.Sin(angle); + var result = new PathsD(paths.Count); + foreach (var path in paths) + { + var rotated = new PathD(path.Count); + foreach (var point in path) + rotated.Add(new PointD(point.x * cos - point.y * sin, point.x * sin + point.y * cos)); + result.Add(rotated); + } + return result; + } + + private static Vector Turn(Vector point, double angle) + { + var cos = PortableMath.Cos(angle); + var sin = PortableMath.Sin(angle); + return new Vector(point.X * cos - point.Y * sin, point.X * sin + point.Y * cos); + } + } +} diff --git a/OpenNest.IO/CadImporter.cs b/OpenNest.IO/CadImporter.cs index 02bd2ea2..1701f77c 100644 --- a/OpenNest.IO/CadImporter.cs +++ b/OpenNest.IO/CadImporter.cs @@ -10,6 +10,7 @@ using OpenNest.Converters; using OpenNest.Dimensions; using OpenNest.Geometry; using OpenNest.IO.Bending; +using OpenNest.Labels; using OpenNest.Math; using OpenNest.TabbedCutouts; @@ -187,6 +188,7 @@ namespace OpenNest.IO /// on the drawing; display-only entities stay out of the program. /// /// Dimensions to keep on the drawing; they never affect the program. + /// The part number label box to keep on the drawing; it never affects the program. public static Drawing BuildDrawing( CadImportResult result, IEnumerable entities, @@ -197,7 +199,8 @@ namespace OpenNest.IO IReadOnlyList breakoffs = null, IReadOnlyList tabbedCutouts = null, IReadOnlyDictionary entityRoles = null, - IReadOnlyList dimensions = null + IReadOnlyList dimensions = null, + LabelBox labelBox = null ) { var visible = entityRoles is { Count: > 0 } @@ -237,6 +240,7 @@ namespace OpenNest.IO drawing.Breakoffs = breakoffs?.Select(b => b.Clone()).ToList() ?? new List(); drawing.TabbedCutouts = tabbedCutouts?.Select(c => c.Clone()).ToList() ?? new List(); drawing.Dimensions = dimensions?.Select(d => d.Clone()).ToList() ?? new List(); + drawing.LabelBox = labelBox?.Clone(); drawing.Program = editedProgram ?? pgm; var bendSources = new HashSet( @@ -314,6 +318,7 @@ namespace OpenNest.IO existing.Breakoffs = edited.Breakoffs; existing.TabbedCutouts = edited.TabbedCutouts; existing.Dimensions = edited.Dimensions; + existing.LabelBox = edited.LabelBox; } private static bool IsRepairMark(Entity e) => diff --git a/OpenNest.IO/NestFormat.cs b/OpenNest.IO/NestFormat.cs index da59ef04..1e5b82fa 100644 --- a/OpenNest.IO/NestFormat.cs +++ b/OpenNest.IO/NestFormat.cs @@ -505,6 +505,22 @@ namespace OpenNest.IO /// Dimension placements; values are measured when shown. Omitted when there are none. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public List Dimensions { get; init; } + + /// Where the part number label is etched, in the source frame. Omitted when none is set. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public LabelBoxDto LabelBox { get; init; } + } + + public record LabelBoxDto + { + public double X { get; init; } + public double Y { get; init; } + public double Width { get; init; } + public double Height { get; init; } + + /// Counterclockwise turn about the center in radians. Omitted when zero. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] + public double Rotation { get; init; } } public record DimensionDto diff --git a/OpenNest.IO/NestReader.cs b/OpenNest.IO/NestReader.cs index 9bedacb5..b0d97b76 100644 --- a/OpenNest.IO/NestReader.cs +++ b/OpenNest.IO/NestReader.cs @@ -17,6 +17,7 @@ using OpenNest.Converters; using OpenNest.CutOffs; using OpenNest.Dimensions; using OpenNest.Geometry; +using OpenNest.Labels; using OpenNest.Support; using OpenNest.TabbedCutouts; using static OpenNest.IO.NestFormat; @@ -366,6 +367,7 @@ namespace OpenNest.IO drawing.Breakoffs = ReadBreakoffs(d); drawing.TabbedCutouts = ReadTabbedCutouts(d); drawing.Dimensions = ReadDimensions(d); + drawing.LabelBox = ReadLabelBox(d); map[d.Id] = drawing; } return map; @@ -513,6 +515,21 @@ namespace OpenNest.IO return dimensions; } + // The label box is an annotation: one that cannot be read is dropped, never what is cut. + private LabelBox ReadLabelBox(DrawingDto d) + { + if (d.LabelBox == null) + return null; + + var box = new LabelBox(new Vector(d.LabelBox.X, d.LabelBox.Y), d.LabelBox.Width, d.LabelBox.Height, + d.LabelBox.Rotation); + if (box.IsValid) + return box; + + warnings.Add($"Drawing '{d.Name}': its label box could not be read; skipped it."); + return null; + } + private bool ReadPinsOff(PartDto dto, int plateId, int partIndex, Part part) { if (dto.DrawingPinsOff is bool pinsOff) diff --git a/OpenNest.IO/NestWriter.cs b/OpenNest.IO/NestWriter.cs index 87e136bb..d0c56902 100644 --- a/OpenNest.IO/NestWriter.cs +++ b/OpenNest.IO/NestWriter.cs @@ -304,6 +304,16 @@ namespace OpenNest.IO Angle = m.IsRadial ? m.Angle : null, }).ToList() : null, + LabelBox = d.LabelBox is { IsValid: true } box + ? new LabelBoxDto + { + X = box.Center.X, + Y = box.Center.Y, + Width = box.Width, + Height = box.Height, + Rotation = box.Rotation, + } + : null, } ); } diff --git a/OpenNest.Tests/Labels/LabelBoxFinderTests.cs b/OpenNest.Tests/Labels/LabelBoxFinderTests.cs new file mode 100644 index 00000000..e59ff384 --- /dev/null +++ b/OpenNest.Tests/Labels/LabelBoxFinderTests.cs @@ -0,0 +1,223 @@ +using OpenNest.Bending; +using OpenNest.Geometry; +using OpenNest.Labels; + +namespace OpenNest.Tests.Labels; + +public class LabelBoxFinderTests +{ + private static List Rectangle(double left, double bottom, double right, double top) => + [ + new Line(left, bottom, right, bottom), new Line(right, bottom, right, top), + new Line(right, top, left, top), new Line(left, top, left, bottom), + ]; + + // A width x height rectangle turned about the origin and moved to (cx, cy). + private static List Turned(double width, double height, double degrees, double cx, double cy) + { + var angle = degrees * System.Math.PI / 180; + Vector P(double x, double y) => new( + cx + x * System.Math.Cos(angle) - y * System.Math.Sin(angle), + cy + x * System.Math.Sin(angle) + y * System.Math.Cos(angle)); + var corners = new[] { P(-width / 2, -height / 2), P(width / 2, -height / 2), P(width / 2, height / 2), P(-width / 2, height / 2) }; + return corners.Select((c, i) => (Entity)new Line(c, corners[(i + 1) % 4])).ToList(); + } + + private static LabelBoxOptions Options(double width = 2, double height = 0.5, double clearance = 0.25) => + new() { Width = width, Height = height, Clearance = clearance }; + + [Fact] + public void FlatPart_GetsAnAxisAlignedBoxInsideTheClearance() + { + var box = LabelBoxFinder.Find(Rectangle(0, 0, 10, 5), [], Options()); + + Assert.NotNull(box); + Assert.Equal(0, box.Rotation, 9); + Assert.Equal(2, box.Width, 9); + Assert.Equal(0.5, box.Height, 9); + foreach (var corner in box.Corners()) + { + Assert.InRange(corner.X, 0.25 - 1e-6, 9.75 + 1e-6); + Assert.InRange(corner.Y, 0.25 - 1e-6, 4.75 + 1e-6); + } + } + + [Fact] + public void Hole_IsAvoided() + { + var entities = Rectangle(0, 0, 10, 5); + entities.Add(new Circle(5, 2.5, 2)); + + var box = LabelBoxFinder.Find(entities, [], Options()); + + Assert.NotNull(box); + foreach (var corner in box.Corners()) + Assert.True(corner.DistanceTo(new Vector(5, 2.5)) >= 2.25 - 1e-3, $"{corner} is too close to the hole"); + Assert.False(box.Contains(new Vector(5, 2.5))); + } + + [Fact] + public void BendLine_IsKeptClearOnBothSides() + { + var bend = new Bend { StartPoint = new Vector(5, 0), EndPoint = new Vector(5, 5) }; + + var box = LabelBoxFinder.Find(Rectangle(0, 0, 10, 5), [bend], Options()); + + Assert.NotNull(box); + var xs = box.Corners().Select(c => c.X).ToList(); + Assert.True(xs.Max() <= 5 - 0.25 + 1e-3 || xs.Min() >= 5 + 0.25 - 1e-3, + $"The box spans the bend: x from {xs.Min()} to {xs.Max()}"); + } + + [Fact] + public void BendClearance_CanDifferFromTheEdgeClearance() + { + var bend = new Bend { StartPoint = new Vector(5, 0), EndPoint = new Vector(5, 5) }; + var options = Options(clearance: 0.25); + options.BendClearance = 1; + + var box = LabelBoxFinder.Find(Rectangle(0, 0, 10, 5), [bend], options); + + Assert.NotNull(box); + var xs = box.Corners().Select(c => c.X).ToList(); + Assert.True(xs.Max() <= 4 + 1e-3 || xs.Min() >= 6 - 1e-3); + } + + [Fact] + public void KeepOutOutline_IsAvoided_WithTheClearance() + { + // The left half is breakoff scrap: the box must stay in the right half, clear of the joint. + var scrap = Rectangle(0, 0, 5, 5); + + var box = LabelBoxFinder.Find(Rectangle(0, 0, 10, 5), [], Options(), [scrap]); + + Assert.NotNull(box); + Assert.True(box.Corners().All(c => c.X >= 5 + 0.25 - 1e-3), "The box reaches into the scrap or its clearance"); + } + + [Fact] + public void KeepOutThatLeavesNoRoom_GivesNoBox() + { + Assert.Null(LabelBoxFinder.Find(Rectangle(0, 0, 10, 5), [], Options(), [Rectangle(0, 0, 9, 5)])); + } + + [Fact] + public void PartTooSmall_GivesNoBox() + { + Assert.Null(LabelBoxFinder.Find(Rectangle(0, 0, 3, 1), [], Options(clearance: 0.5))); + Assert.Null(LabelBoxFinder.Find(Rectangle(0, 0, 10, 5), [], Options(width: 20))); + } + + [Fact] + public void BendsThatLeaveNoRoom_GiveNoBox() + { + var bends = Enumerable.Range(1, 9) + .Select(i => new Bend { StartPoint = new Vector(i, 0), EndPoint = new Vector(i, 5) }) + .ToList(); + + Assert.Null(LabelBoxFinder.Find(Rectangle(0, 0, 10, 5), bends, Options())); + } + + [Fact] + public void NarrowDiagonalPart_GetsABoxAlongItsLength() + { + var part = Turned(20, 1.5, 30, 10, 10); + + var box = LabelBoxFinder.Find(part, [], Options(width: 3, height: 0.5, clearance: 0.2)); + + Assert.NotNull(box); + Assert.Equal(30 * System.Math.PI / 180, box.Rotation, 2); + foreach (var corner in box.Corners()) + { + // The part's own frame: x along its length, y across it. + var dx = corner.X - 10; + var dy = corner.Y - 10; + var along = dx * System.Math.Cos(30 * System.Math.PI / 180) + dy * System.Math.Sin(30 * System.Math.PI / 180); + var across = -dx * System.Math.Sin(30 * System.Math.PI / 180) + dy * System.Math.Cos(30 * System.Math.PI / 180); + Assert.True(System.Math.Abs(along) <= 10 - 0.2 + 1e-2); + Assert.True(System.Math.Abs(across) <= 0.75 - 0.2 + 1e-2, $"{corner} is outside the part's clearance"); + } + } + + [Fact] + public void BendDirection_IsTriedAndText_NeverReadsUpsideDown() + { + var part = Turned(20, 1.5, 120, 0, 0); + var bend = new Bend { StartPoint = new Vector(0, 0), EndPoint = new Vector(System.Math.Cos(120 * System.Math.PI / 180), System.Math.Sin(120 * System.Math.PI / 180)) }; + + var box = LabelBoxFinder.Find(part, [bend], Options(width: 3, height: 0.5, clearance: 0.2)); + + Assert.NotNull(box); + Assert.InRange(box.Rotation, -System.Math.PI / 2 - 1e-9, System.Math.PI / 2 + 1e-9); + } + + [Fact] + public void Marks_AreNotMaterialAndDoNotBlockTheBox() + { + var entities = Rectangle(0, 0, 10, 5); + var plain = LabelBoxFinder.Find(entities, [], Options()); + entities.Add(new Line(0, 2.5, 10, 2.5) { Layer = SpecialLayers.Scribe }); + + var marked = LabelBoxFinder.Find(entities, [], Options()); + + Assert.NotNull(marked); + Assert.Equal(plain.Center, marked.Center); + } + + [Fact] + public void Result_IsDeterministic() + { + var entities = Rectangle(0, 0, 10, 5); + entities.Add(new Circle(3, 2.5, 1)); + var bends = new List { new() { StartPoint = new Vector(7, 0), EndPoint = new Vector(7, 5) } }; + + var a = LabelBoxFinder.Find(entities, bends, Options()); + var b = LabelBoxFinder.Find(entities, bends, Options()); + + Assert.NotNull(a); + Assert.Equal(a.Center, b.Center); + Assert.Equal(a.Rotation, b.Rotation); + } + + [Fact] + public void NoClosedGeometry_GivesNoBox() + { + Assert.Null(LabelBoxFinder.Find([new Line(0, 0, 10, 0)], [], Options())); + Assert.Null(LabelBoxFinder.Find([], [], Options())); + } + + [Fact] + public void BadOptions_Throw() + { + Assert.Throws(() => LabelBoxFinder.Find(Rectangle(0, 0, 10, 5), [], Options(width: 0))); + Assert.Throws(() => LabelBoxFinder.Find(Rectangle(0, 0, 10, 5), [], Options(clearance: -1))); + } + + [Fact] + public void ForText_SizesTheBoxFromTheCharacters() + { + var options = LabelBoxOptions.ForText(7, 0.25, 0.125); + + Assert.Equal(7 * 0.25 * LabelBoxOptions.CharacterAdvance, options.Width, 9); + Assert.Equal(0.25, options.Height, 9); + Assert.Equal(0.125, options.Clearance, 9); + Assert.True(LabelBoxOptions.Default(Units.Millimeters).Height > LabelBoxOptions.Default(Units.Inches).Height); + } + + [Fact] + public void LabelBox_ConvertsBetweenItsOwnFrameAndTheDrawingFrame() + { + var box = new LabelBox(new Vector(10, 20), 4, 2, System.Math.PI / 2); + + Assert.Equal(new Vector(10, 22), box.ToWorld(new Vector(2, 0)).Round()); + Assert.Equal(2, box.ToLocal(new Vector(10, 22)).X, 9); + Assert.True(box.Contains(new Vector(10, 21.5))); + Assert.False(box.Contains(new Vector(12, 20))); + Assert.Equal(4, box.Corners().Length); + } +} + +file static class VectorExtensions +{ + public static Vector Round(this Vector v) => new(System.Math.Round(v.X, 6), System.Math.Round(v.Y, 6)); +} diff --git a/OpenNest.Tests/Labels/LabelBoxPersistenceTests.cs b/OpenNest.Tests/Labels/LabelBoxPersistenceTests.cs new file mode 100644 index 00000000..6793f768 --- /dev/null +++ b/OpenNest.Tests/Labels/LabelBoxPersistenceTests.cs @@ -0,0 +1,116 @@ +using OpenNest.Bending; +using OpenNest.Geometry; +using OpenNest.IO; +using OpenNest.Labels; + +namespace OpenNest.Tests.Labels; + +public class LabelBoxPersistenceTests +{ + private static List Rectangle() => + [ + new Line(1, 2, 11, 2), new Line(11, 2, 11, 7), new Line(11, 7, 1, 7), new Line(1, 7, 1, 2), + ]; + + private static Nest RoundTrip(Drawing drawing) + { + var nest = new Nest(); + nest.Drawings.Add(drawing); + var plate = new Plate(60, 120); + plate.Parts.Add(new Part(drawing, new Vector(0, 0))); + nest.Plates.Add(plate); + + using var ms = new MemoryStream(); + new NestWriter(nest).Write(ms); + ms.Position = 0; + return new NestReader(ms).Read(); + } + + [Fact] + public void LabelBox_SurvivesNestRoundTrip() + { + var drawing = TestHelpers.MakeSquareDrawing(); + drawing.LabelBox = new LabelBox(new Vector(3.5, 4.25), 1.75, 0.25, 0.3); + + var loaded = RoundTrip(drawing).Drawings.Single(); + + Assert.NotNull(loaded.LabelBox); + Assert.Equal(3.5, loaded.LabelBox.Center.X, 9); + Assert.Equal(4.25, loaded.LabelBox.Center.Y, 9); + Assert.Equal(1.75, loaded.LabelBox.Width, 9); + Assert.Equal(0.25, loaded.LabelBox.Height, 9); + Assert.Equal(0.3, loaded.LabelBox.Rotation, 9); + } + + [Fact] + public void NoLabelBox_StaysNullAndIsOmittedFromTheFile() + { + var drawing = TestHelpers.MakeSquareDrawing(); + Assert.Null(RoundTrip(drawing).Drawings.Single().LabelBox); + + var nest = new Nest(); + nest.Drawings.Add(drawing); + using var ms = new MemoryStream(); + new NestWriter(nest).Write(ms); + ms.Position = 0; + using var zip = new System.IO.Compression.ZipArchive(ms); + foreach (var entry in zip.Entries.Where(e => e.FullName.EndsWith(".json", StringComparison.OrdinalIgnoreCase))) + { + using var reader = new StreamReader(entry.Open()); + Assert.DoesNotContain("labelBox", reader.ReadToEnd(), StringComparison.OrdinalIgnoreCase); + } + } + + [Fact] + public void InvalidLabelBox_IsNotWritten() + { + var drawing = TestHelpers.MakeSquareDrawing(); + drawing.LabelBox = new LabelBox(new Vector(1, 1), 0, 0.25, 0); + + Assert.Null(RoundTrip(drawing).Drawings.Single().LabelBox); + } + + [Fact] + public void LabelBox_LeavesTheProgramUnchanged() + { + var entities = Rectangle(); + var result = new CadImportResult { Entities = entities, Name = "part" }; + var plain = CadImporter.BuildDrawing(result, entities, new List(), 1, null, null); + var labeled = CadImporter.BuildDrawing(result, entities, new List(), 1, null, null, + labelBox: new LabelBox(new Vector(6, 4.5), 1.75, 0.25, 0)); + + Assert.NotNull(labeled.LabelBox); + Assert.Equal(plain.Program.Codes.Select(c => c.ToString()), labeled.Program.Codes.Select(c => c.ToString())); + Assert.Equal(plain.Source.Offset, labeled.Source.Offset); + } + + [Fact] + public void BuildDrawing_KeepsACopy() + { + var entities = Rectangle(); + var result = new CadImportResult { Entities = entities, Name = "part" }; + var box = new LabelBox(new Vector(6, 4.5), 1.75, 0.25, 0); + + var drawing = CadImporter.BuildDrawing(result, entities, new List(), 1, null, null, labelBox: box); + box.Center = new Vector(0, 0); + + Assert.Equal(new Vector(6, 4.5), drawing.LabelBox.Center); + } + + [Fact] + public void ApplyEdit_TakesTheEditedLabelBox() + { + var entities = Rectangle(); + var result = new CadImportResult { Entities = entities, Name = "part" }; + var drawing = CadImporter.BuildDrawing(result, entities, new List(), 1, null, null, + labelBox: new LabelBox(new Vector(2, 2), 1, 0.25, 0)); + var edited = CadImporter.BuildDrawing(result, entities, new List(), 1, null, null, + labelBox: new LabelBox(new Vector(6, 4.5), 1.75, 0.25, 0)); + + CadImporter.ApplyEdit(drawing, edited); + Assert.Equal(new Vector(6, 4.5), drawing.LabelBox.Center); + + CadImporter.ApplyEdit(drawing, CadImporter.BuildDrawing(result, entities, new List(), 1, null, null)); + Assert.Null(drawing.LabelBox); + } +} diff --git a/OpenNest.WinForms.Tests/Forms/CadConverterLabelBoxTests.cs b/OpenNest.WinForms.Tests/Forms/CadConverterLabelBoxTests.cs new file mode 100644 index 00000000..7e7e6a3e --- /dev/null +++ b/OpenNest.WinForms.Tests/Forms/CadConverterLabelBoxTests.cs @@ -0,0 +1,154 @@ +using System.Reflection; +using OpenNest.Bending; +using OpenNest.Controls; +using OpenNest.Forms; +using OpenNest.Geometry; +using OpenNest.IO; +using OpenNest.Labels; +using static OpenNest.WinForms.Tests.FormTesting; + +namespace OpenNest.WinForms.Tests.Forms; + +/// Drives the CAD Converter's part number label box through its real mouse handling. +public class CadConverterLabelBoxTests +{ + [Fact] + public void Finding_PlacesTheBox_DraggingMovesIt_ItComesBackOnTheDrawing() => ArchUnitsTests.RunSta(() => + { + using var form = new LabelTestForm(); + Show(form); + form.LoadDrawings([Part(10, 6)]); + var view = Field(form, "entityView1"); + var item = Field(form, "fileList").SelectedItem!; + Assert.Null(item.LabelBox); + Assert.Null(view.LabelBox); + + Invoke(form, "OnLabelBoxClick", null, EventArgs.Empty); + + Assert.NotNull(item.LabelBox); + Assert.NotNull(view.LabelBox); + var placed = item.LabelBox!.Center; + Assert.InRange(placed.X, 0, 10); + Assert.InRange(placed.Y, 0, 6); + + // Drag the body one unit right and half a unit up. + var press = view.PointWorldToControl(placed); + var release = view.PointWorldToControl(new Vector(placed.X + 1, placed.Y + 0.5)); + Mouse(view, "OnMouseDown", press); + Mouse(view, "OnMouseMove", release); + Mouse(view, "OnMouseUp", release); + + Assert.InRange(item.LabelBox!.Center.X, placed.X + 0.9, placed.X + 1.1); + Assert.InRange(item.LabelBox.Center.Y, placed.Y + 0.4, placed.Y + 0.6); + + var drawing = Assert.Single(form.GetDrawings()); + Assert.Equal(item.LabelBox.Center, drawing.LabelBox!.Center); + form.Close(); + }); + + [Fact] + public void DraggingACorner_ResizesAndKeepsTheOppositeCornerFixed() => ArchUnitsTests.RunSta(() => + { + using var form = new LabelTestForm(); + Show(form); + form.LoadDrawings([Part(10, 6)]); + var view = Field(form, "entityView1"); + var item = Field(form, "fileList").SelectedItem!; + Invoke(form, "OnLabelBoxClick", null, EventArgs.Empty); + var before = item.LabelBox!.Clone(); + var corners = before.Corners(); + + var press = view.PointWorldToControl(corners[2]); + var release = view.PointWorldToControl(new Vector(corners[2].X + 1, corners[2].Y + 1)); + Mouse(view, "OnMouseDown", press); + Mouse(view, "OnMouseMove", release); + Mouse(view, "OnMouseUp", release); + + var after = item.LabelBox!; + Assert.InRange(after.Width, before.Width + 0.9, before.Width + 1.1); + Assert.InRange(after.Height, before.Height + 0.9, before.Height + 1.1); + Assert.InRange(after.Corners()[0].X, corners[0].X - 0.01, corners[0].X + 0.01); + Assert.InRange(after.Corners()[0].Y, corners[0].Y - 0.01, corners[0].Y + 0.01); + form.Close(); + }); + + [Fact] + public void NoRoom_ExplainsAndLeavesNoBox() => ArchUnitsTests.RunSta(() => + { + using var form = new LabelTestForm(); + Show(form); + form.LoadDrawings([Part(1, 0.5)]); + var item = Field(form, "fileList").SelectedItem!; + + Invoke(form, "OnLabelBoxClick", null, EventArgs.Empty); + + Assert.Null(item.LabelBox); + Assert.Single(form.Messages); + form.Close(); + }); + + [Fact] + public void ABendLine_IsKeptClear() => ArchUnitsTests.RunSta(() => + { + using var form = new LabelTestForm(); + Show(form); + form.LoadDrawings([Part(10, 6, [new Bend { StartPoint = new Vector(5, 0), EndPoint = new Vector(5, 6) }])]); + var item = Field(form, "fileList").SelectedItem!; + + Invoke(form, "OnLabelBoxClick", null, EventArgs.Empty); + + var xs = item.LabelBox!.Corners().Select(c => c.X).ToList(); + Assert.True(xs.Max() <= 5 - 0.125 + 1e-3 || xs.Min() >= 5 + 0.125 - 1e-3); + form.Close(); + }); + + [Fact] + public void Remove_DropsTheBox_AndSelectingAgainShowsIt() => ArchUnitsTests.RunSta(() => + { + using var form = new LabelTestForm(); + Show(form); + form.LoadDrawings([Part(10, 6)]); + var view = Field(form, "entityView1"); + var item = Field(form, "fileList").SelectedItem!; + Invoke(form, "OnLabelBoxClick", null, EventArgs.Empty); + Assert.NotNull(view.LabelBox); + + form.FindLabelBox(item); + Assert.NotNull(item.LabelBox); + Invoke(form, "RefreshLabelBox", item); + Assert.NotNull(view.LabelBox); + + item.LabelBox = null; + Invoke(form, "RefreshLabelBox", item); + Assert.Null(view.LabelBox); + Assert.Null(Assert.Single(form.GetDrawings()).LabelBox); + form.Close(); + }); + + private static Drawing Part(double width, double height, List? bends = null) + { + var entities = new List + { + new Line(0, 0, width, 0), new Line(width, 0, width, height), + new Line(width, height, 0, height), new Line(0, height, 0, 0), + }; + var layer = new Layer("0") { IsVisible = true }; + foreach (var e in entities) + e.Layer = layer; + return CadImporter.BuildDrawing(new CadImportResult { Entities = entities, Name = "labelled" }, entities, + bends ?? new List(), 1, null, null); + } + + private static T Field(object owner, string name) => + TestReflection.Field(owner.GetType().BaseType!, owner, name); + + private static void Invoke(CadConverterForm form, string name, params object?[] args) => + typeof(CadConverterForm).GetMethod(name, BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(form, args); + + private sealed class LabelTestForm : CadConverterForm + { + public List Messages { get; } = new(); + + internal override void ShowLabelBoxMessage(string message) => Messages.Add(message); + } +} diff --git a/OpenNest/Controls/EntityView.Breakoffs.cs b/OpenNest/Controls/EntityView.Breakoffs.cs index 5af9e36e..34f97579 100644 --- a/OpenNest/Controls/EntityView.Breakoffs.cs +++ b/OpenNest/Controls/EntityView.Breakoffs.cs @@ -66,7 +66,8 @@ namespace OpenNest.Controls if (draggedTab == null) draggedCutoutTab = HitTestCutoutTab(e.Location); var dimension = draggedTab == null && draggedCutoutTab == null && BeginDimensionDrag(e.Location); - if (draggedTab == null && draggedCutoutTab == null && !dimension) + var label = draggedTab == null && draggedCutoutTab == null && !dimension && BeginLabelBoxDrag(e.Location); + if (draggedTab == null && draggedCutoutTab == null && !dimension && !label) BeginWindowSelect(e); else suppressNextClick = true; // A tab press or drag does not change the selection. @@ -79,6 +80,7 @@ namespace OpenNest.Controls return; EndWindowSelect(e); EndDimensionDrag(); + EndLabelBoxDrag(); if (draggedCutoutTab is { } cutoutTab) { draggedCutoutTab = null; @@ -98,12 +100,16 @@ namespace OpenNest.Controls RaiseCutoutTabDragged(cutoutTab, e.Location, finished: false); else if (draggedDimension is { } dimension) RaiseDimensionDragged(dimension, e.Location); + else if (draggedLabelBoxPart != null) + RaiseLabelBoxDragged(e.Location); else if (e.Button == MouseButtons.None && !IsPicking) { if (HitTestTab(e.Location) != null || HitTestCutoutTab(e.Location) != null) Cursor = Cursors.SizeAll; else if (HitTestDimension(e.Location) is { } hover) Cursor = DimensionCursor(hover); + else if (HitTestLabelBox(e.Location) is { } labelPart) + Cursor = LabelBoxCursor(labelPart); else Cursor = Cursors.Cross; } diff --git a/OpenNest/Controls/EntityView.LabelBox.cs b/OpenNest/Controls/EntityView.LabelBox.cs new file mode 100644 index 00000000..a3b4b40d --- /dev/null +++ b/OpenNest/Controls/EntityView.LabelBox.cs @@ -0,0 +1,108 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Linq; +using System.Windows.Forms; +using OpenNest.Geometry; + +namespace OpenNest.Controls +{ + public partial class EntityView + { + private const int LabelBoxHandlePixels = 4; + private const int LabelBoxMinimumPixels = 6; + private static readonly Color LabelBoxColor = Color.FromArgb(230, 90, 200); + + // The grabbed corner (0-3, as Labels.LabelBox.Corners orders them), or -1 for the body; + // null when nothing is being dragged. + private int? draggedLabelBoxPart; + private Vector labelBoxGrab; + private Labels.LabelBox labelBoxAtPress; + + /// + /// Where the part number label would be etched, in world coordinates, drawn as a dashed + /// rectangle the user can move and resize; null draws nothing. + /// + public Labels.LabelBox LabelBox { get; set; } + + /// The label box was moved or resized; the argument is its new placement. + public event EventHandler LabelBoxChanged; + + private bool BeginLabelBoxDrag(Point location) + { + draggedLabelBoxPart = HitTestLabelBox(location); + if (draggedLabelBoxPart is not { } part || LabelBox == null) + return false; + + labelBoxAtPress = LabelBox.Clone(); + labelBoxGrab = labelBoxAtPress.Center - PointControlToWorld(location); + return true; + } + + private void EndLabelBoxDrag() => draggedLabelBoxPart = null; + + // A corner handle first, then anywhere inside the box. + private int? HitTestLabelBox(Point location) + { + if (LabelBox is not { IsValid: true } box) + return null; + + var corners = box.Corners(); + for (var i = 0; i < corners.Length; i++) + { + var at = PointWorldToControl(corners[i]); + var reach = LabelBoxHandlePixels + 3; + if (System.Math.Abs(at.X - location.X) <= reach && System.Math.Abs(at.Y - location.Y) <= reach) + return i; + } + return box.Contains(PointControlToWorld(location)) ? -1 : null; + } + + private void RaiseLabelBoxDragged(Point location) + { + if (draggedLabelBoxPart is not { } part || labelBoxAtPress == null) + return; + + var point = PointControlToWorld(location); + if (part < 0) + { + LabelBoxChanged?.Invoke(this, new Labels.LabelBox(point + labelBoxGrab, labelBoxAtPress.Width, + labelBoxAtPress.Height, labelBoxAtPress.Rotation)); + return; + } + + // The corner follows the pointer and the opposite corner stays put, in the box's own frame. + var corners = labelBoxAtPress.Corners(); + var anchor = labelBoxAtPress.ToLocal(corners[(part + 2) % 4]); + var moved = labelBoxAtPress.ToLocal(point); + var minimum = LengthGuiToWorld(LabelBoxMinimumPixels); + var width = System.Math.Max(System.Math.Abs(moved.X - anchor.X), minimum); + var height = System.Math.Max(System.Math.Abs(moved.Y - anchor.Y), minimum); + var centerX = anchor.X + System.Math.Sign(moved.X - anchor.X == 0 ? 1 : moved.X - anchor.X) * width / 2; + var centerY = anchor.Y + System.Math.Sign(moved.Y - anchor.Y == 0 ? 1 : moved.Y - anchor.Y) * height / 2; + LabelBoxChanged?.Invoke(this, new Labels.LabelBox(labelBoxAtPress.ToWorld(new Vector(centerX, centerY)), + width, height, labelBoxAtPress.Rotation)); + } + + private Cursor LabelBoxCursor(int part) => part < 0 ? Cursors.SizeAll : Cursors.SizeNWSE; + + private void DrawLabelBox(Graphics g) + { + if (LabelBox is not { IsValid: true } box) + return; + + var points = box.Corners().Select(PointWorldToGraph).ToArray(); + using var pen = new Pen(LabelBoxColor) { DashStyle = DashStyle.Dash }; + using var brush = new SolidBrush(Color.FromArgb(30, LabelBoxColor)); + g.FillPolygon(brush, points); + g.DrawPolygon(pen, points); + + using var handleBrush = new SolidBrush(LabelBoxColor); + foreach (var point in points) + { + g.FillRectangle(handleBrush, point.X - LabelBoxHandlePixels, point.Y - LabelBoxHandlePixels, + LabelBoxHandlePixels * 2, LabelBoxHandlePixels * 2); + } + } + } +} diff --git a/OpenNest/Controls/EntityView.cs b/OpenNest/Controls/EntityView.cs index b1bd6a48..1f9c7134 100644 --- a/OpenNest/Controls/EntityView.cs +++ b/OpenNest/Controls/EntityView.cs @@ -162,6 +162,7 @@ namespace OpenNest.Controls DrawSelection(e.Graphics); DrawTexts(e.Graphics); DrawDimensions(e.Graphics); + DrawLabelBox(e.Graphics); if (ShowEntityLabels) DrawEntityLabels(e.Graphics); diff --git a/OpenNest/Controls/FileListControl.cs b/OpenNest/Controls/FileListControl.cs index 6f9ceeda..c0038809 100644 --- a/OpenNest/Controls/FileListControl.cs +++ b/OpenNest/Controls/FileListControl.cs @@ -31,6 +31,9 @@ namespace OpenNest.Controls public List Breakoffs { get; set; } = new(); public List TabbedCutouts { get; set; } = new(); public List Dimensions { get; set; } = new(); + + /// Where the part number label would be etched, in the entities' frame; null when none is set. + public Labels.LabelBox LabelBox { get; set; } public HashSet SuppressedEntityIds { get; set; } /// Entities the user excluded one by one; they stay excluded whatever the filters show. diff --git a/OpenNest/Forms/CadConverterForm.Designer.cs b/OpenNest/Forms/CadConverterForm.Designer.cs index edd24cd1..4008ac9e 100644 --- a/OpenNest/Forms/CadConverterForm.Designer.cs +++ b/OpenNest/Forms/CadConverterForm.Designer.cs @@ -34,6 +34,7 @@ namespace OpenNest.Forms btnSeparate = new System.Windows.Forms.Button(); btnExport = new System.Windows.Forms.Button(); btnHoleTable = new System.Windows.Forms.Button(); + btnLabelBox = new System.Windows.Forms.Button(); chkShowOriginal = new System.Windows.Forms.CheckBox(); chkLabels = new System.Windows.Forms.CheckBox(); lblDetect = new System.Windows.Forms.Label(); @@ -175,6 +176,7 @@ namespace OpenNest.Forms detailBar.Controls.Add(btnSimplify); detailBar.Controls.Add(btnExport); detailBar.Controls.Add(btnHoleTable); + detailBar.Controls.Add(btnLabelBox); detailBar.Controls.Add(chkShowOriginal); detailBar.Controls.Add(chkLabels); detailBar.Controls.Add(lblDetect); @@ -318,6 +320,19 @@ namespace OpenNest.Forms btnHoleTable.Text = "Holes..."; btnHoleTable.Click += OnHoleTableClick; // + // btnLabelBox + // + btnLabelBox.AutoSize = true; + btnLabelBox.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + btnLabelBox.Font = new System.Drawing.Font("Segoe UI", 9F); + btnLabelBox.Location = new System.Drawing.Point(600, 6); + btnLabelBox.Margin = new System.Windows.Forms.Padding(0, 0, 10, 0); + btnLabelBox.Name = "btnLabelBox"; + btnLabelBox.Size = new System.Drawing.Size(86, 27); + btnLabelBox.TabIndex = 8; + btnLabelBox.Text = "Label Box..."; + btnLabelBox.Click += OnLabelBoxClick; + // // chkShowOriginal // chkShowOriginal.AutoSize = true; @@ -465,6 +480,7 @@ namespace OpenNest.Forms private System.Windows.Forms.Button btnSimplify; private System.Windows.Forms.Button btnExport; private System.Windows.Forms.Button btnHoleTable; + private System.Windows.Forms.Button btnLabelBox; private System.Windows.Forms.CheckBox chkShowOriginal; private System.Windows.Forms.CheckBox chkLabels; private System.Windows.Forms.ComboBox cboBendDetector; diff --git a/OpenNest/Forms/CadConverterForm.LabelBox.cs b/OpenNest/Forms/CadConverterForm.LabelBox.cs new file mode 100644 index 00000000..47ec3e94 --- /dev/null +++ b/OpenNest/Forms/CadConverterForm.LabelBox.cs @@ -0,0 +1,96 @@ +using System; +using System.Linq; +using System.Windows.Forms; +using OpenNest.Breakoffs; +using OpenNest.Controls; +using OpenNest.Labels; + +namespace OpenNest.Forms +{ + // The part number label box: where the part number would be etched, found on the flat material + // clear of edges, holes and bend lines, and adjustable by dragging. It stores placement only. + public partial class CadConverterForm + { + private ContextMenuStrip labelBoxMenu; + + private void OnLabelBoxClick(object sender, EventArgs e) + { + var item = CurrentItem; + if (item == null) + return; + + if (item.LabelBox == null) + { + FindLabelBox(item); + return; + } + + labelBoxMenu ??= BuildLabelBoxMenu(); + labelBoxMenu.Show(btnLabelBox, new System.Drawing.Point(0, btnLabelBox.Height)); + } + + private ContextMenuStrip BuildLabelBoxMenu() + { + var menu = new ContextMenuStrip(); + menu.Items.Add("Find Best Location", null, (_, _) => + { + if (CurrentItem is { } item) + FindLabelBox(item); + }); + menu.Items.Add("Remove", null, (_, _) => + { + if (CurrentItem is not { } item) + return; + item.LabelBox = null; + RefreshLabelBox(item); + }); + return menu; + } + + /// + /// Places the label box on the best flat area of the part as it will be cut. A part with no + /// room keeps its current box (if any) and is told so. + /// + internal void FindLabelBox(FileListItem item) + { + var visible = VisibleEntities(item); + var allEdges = item.Breakoffs.SelectMany(b => b.EdgeIds).ToList(); + var scrap = item.Breakoffs + .Select(b => BreakoffBuilder.Layout(visible, b, allEdges)) + .Where(l => l.IsValid) + .Select(l => (System.Collections.Generic.IEnumerable)l.Scrap) + .ToList(); + + var box = LabelBoxFinder.Find(DimensionedEntities(item), item.Bends, LabelBoxOptions.Default(DrawingUnits), scrap); + if (box == null) + { + ShowLabelBoxMessage("No flat area of this part is big enough for the part number label, " + + "clear of its edges, holes and bend lines. Place the box by hand or leave it off."); + return; + } + + item.LabelBox = box; + RefreshLabelBox(item); + } + + private void RefreshLabelBox(FileListItem item) + { + entityView1.LabelBox = item?.LabelBox?.Clone(); + entityView1.Invalidate(); + } + + private void OnLabelBoxChanged(object sender, LabelBox box) + { + var item = CurrentItem; + if (item == null) + return; + + item.LabelBox = box; + entityView1.LabelBox = box; + entityView1.Invalidate(); + } + + internal virtual void ShowLabelBoxMessage(string message) => + MessageBox.Show(this, message, "Label Box", MessageBoxButtons.OK, MessageBoxIcon.Information); + } +} diff --git a/OpenNest/Forms/CadConverterForm.cs b/OpenNest/Forms/CadConverterForm.cs index ef7749ab..0e112485 100644 --- a/OpenNest/Forms/CadConverterForm.cs +++ b/OpenNest/Forms/CadConverterForm.cs @@ -71,6 +71,7 @@ namespace OpenNest.Forms filterPanel.DimensionSelected += OnDimensionSelected; filterPanel.DimensionRemoved += OnDimensionRemoved; entityView1.DimensionDragged += OnDimensionDragged; + entityView1.LabelBoxChanged += OnLabelBoxChanged; entityView1.TextConvertRequested += OnTextConvertRequested; entityView1.EntityActionRequested += OnEntityActionRequested; btnSplit.Click += OnSplitClicked; @@ -254,6 +255,7 @@ namespace OpenNest.Forms filterPanel.LoadItem(item.Entities, item.Bends); RefreshBreakoffs(item); RefreshTabbedCutouts(item); + RefreshLabelBox(item); numQuantity.Value = item.Quantity; txtCustomer.Text = item.Customer ?? ""; @@ -325,6 +327,7 @@ namespace OpenNest.Forms lblEntityCount.Text = ""; entityView1.Entities.Clear(); entityView1.DimensionLayouts = Array.Empty(); + RefreshLabelBox(null); entityView1.Invalidate(); RefreshHoleTable(); RefreshSeparable(null); @@ -1440,6 +1443,7 @@ namespace OpenNest.Forms Breakoffs = drawing.Breakoffs?.Select(b => b.Clone()).ToList() ?? new List(), TabbedCutouts = drawing.TabbedCutouts?.Select(c => c.Clone()).ToList() ?? new List(), Dimensions = drawing.Dimensions?.Select(d => d.Clone()).ToList() ?? new List(), + LabelBox = drawing.LabelBox?.Clone(), SuppressedEntityIds = drawing.SuppressedEntityIds.Count > 0 ? new HashSet(drawing.SuppressedEntityIds) @@ -1495,7 +1499,8 @@ namespace OpenNest.Forms item.Breakoffs, item.TabbedCutouts, item.EntityRoles, - item.Dimensions + item.Dimensions, + item.LabelBox ); drawings.Add(drawing); diff --git a/docs/label-box.md b/docs/label-box.md new file mode 100644 index 00000000..e1cbf8aa --- /dev/null +++ b/docs/label-box.md @@ -0,0 +1,53 @@ +# Part number label box + +A drawing can carry a label box: the rectangle where its part number will be etched, found +on flat material clear of everything else. This stage stores and shows the placement only; +nothing is etched yet. + +In the CAD Converter, **Label Box...** (bottom bar) finds the best spot for the shown part. +The box is drawn as a dashed rectangle. Drag its body to move it and a corner to resize it +(the opposite corner stays put); the box keeps its angle. Once a box exists the button +offers **Find Best Location** again and **Remove**. When nothing fits, the button says so and +leaves any existing box alone. + +## Contract + +The box is an annotation, like a [dimension](dimensions.md): it never affects the program, +nesting geometry, cut time or posts, and it does not appear in DXF, DWG or SVG export. + +- `Drawing.LabelBox` stores the center, the sides (`Width` along the text, `Height` across + it) and the counterclockwise `Rotation` in radians, in the source frame, the frame of the + converter's entities. Null when none is set. +- `LabelBoxFinder` (`OpenNest.Core/Labels`) is a pure, deterministic function of the part as + it will be cut (visible, roles, breakoffs and tabbed cutouts applied, as the Dimensions + code reads it), its bends and a `LabelBoxOptions`. The converter uses + `LabelBoxOptions.Default(units)`: seven characters (a part number and a few bend group + letters such as `1234-AB`) of a quarter inch (6 mm) stroke font, an eighth inch (3 mm) + clear of anything else. +- Material is what nesting reads (`NestingMaterial.ForNesting`, marks excluded), so a tabbed + cutout's slug counts as part and etch, scribe and break cuts do not. The material is + eroded by the clearance with the same Clipper inward offset the pierce search uses, a band + of the clearance is cut out either side of each bend line, and a breakoff's scrap is cut + out grown by the clearance, because it is snapped off after forming. +- For each orientation tried, the largest empty rectangles of the rotated region + (`MaximalRectangles`) are searched and the label-sized box is centered in the one with the + most room around it. Orientations are the axes, each bend's direction and the longest + straight edge's, plus the quarter turn of each; text is never turned past a quarter so it + never reads upside down. A later orientation replaces an earlier one only with 5% more + room, which favors horizontal text. Rectangles are staircased against slanted and curved + edges, so they stay inside the clearance and may fall a little short of the true best. +- No box when no orientation fits. The finder throws for a non-positive size or a negative + clearance. +- Split pieces start with no label box, like dimensions, breakoffs and tabbed cutouts. + +Out of scope for now: etching the text, the bend group letters, and an automatic placement +on import; the box is placed when asked. + +File format: see [drawing label box](nest-file-format.md#drawing-label-box). + +## Regression checks + +```sh +dotnet test OpenNest.Tests/OpenNest.Tests.csproj -c Release --filter "FullyQualifiedName~Labels" +scripts/Test-Hidden.ps1 OpenNest.WinForms.Tests/OpenNest.WinForms.Tests.csproj --filter FullyQualifiedName~CadConverterLabelBoxTests +``` diff --git a/docs/nest-file-format.md b/docs/nest-file-format.md index 22319ac5..2895a663 100644 --- a/docs/nest-file-format.md +++ b/docs/nest-file-format.md @@ -346,8 +346,8 @@ fixed archive timestamps and dates, and no best-fit entries, so equal content ha equal bytes and SHA-256. The server stores each distinct package once by that hash. A package holds geometry and geometry-bound data only: program, source entities and -offset, suppressed entity IDs, entity roles, bends, cut pins, breakoffs, tabbed cutouts, dimensions -and material density. Fields +offset, suppressed entity IDs, entity roles, bends, cut pins, breakoffs, tabbed cutouts, dimensions, +label box and material density. Fields the server's library record owns are written as their defaults, so editing them never changes the hash: @@ -454,6 +454,16 @@ offset that is zero or not finite, or a radius or diameter without a non-empty ` a finite `angle` is dropped with a reader warning; the drawing and its program are unaffected. Versions without radius and diameter support drop those entries the same way. +## Drawing label box + +A drawing may carry a `labelBox` object, omitted when none is set: where its part number +label would be etched, in the source frame. `x` and `y` are the center, `width` is the side +along the text and `height` the side across it (both positive), and `rotation` is the +counterclockwise turn about the center in radians, omitted when zero. It is placement only +and never affects the program. A box that is not finite or has a non-positive side is +dropped with a reader warning; versions without label box support ignore it. See +[label box](label-box.md). + ## Drawing entity roles `entities/entities-N` holds drawing N's source entities, the IDs of suppressed