From 68cd07039987665b84fe9ffb4dbbb5229568bef3 Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Thu, 19 Nov 2026 10:26:16 -0500 Subject: [PATCH] feat(report): leader labels for parts too thin to hold their ID A thin strip on N26-2CJ had no ID in the plate diagram, and a half ring's ID landed in the open side of its C shape, away from the material. The in-part fallback searched the whole bounding box, so concave openings counted as the part's own space. That fallback now uses only enclosed holes. A part still unlabeled after grouping gets its ID in the nearest clear space outside it, with a thin leader to a dot at its pole; the leader crosses no other part, cutoff, clamp, label or leader. Tiny parts whose ID other unlabeled parts share get no leaders, so an ungroupable cluster does not bury the sheet in them. Co-Authored-By: Claude Opus 5.5 --- OpenNest.Reporting/NestPdfWriter.cs | 10 + OpenNest.Reporting/NestReportDiagram.cs | 178 ++++++++++++++++-- .../Reporting/NestPdfLayoutTests.cs | 110 ++++++++++- docs/nest-reports.md | 18 +- 4 files changed, 300 insertions(+), 16 deletions(-) diff --git a/OpenNest.Reporting/NestPdfWriter.cs b/OpenNest.Reporting/NestPdfWriter.cs index 3782f7e4..3c77a93f 100644 --- a/OpenNest.Reporting/NestPdfWriter.cs +++ b/OpenNest.Reporting/NestPdfWriter.cs @@ -461,6 +461,16 @@ public static class NestPdfWriter var groupPen = new XPen(XColors.Black, 0.6) { DashPattern = [1, 3] }; foreach (var group in view.Groups) gfx.DrawRectangle(groupPen, group.Boundary); + // Leaders first, so each label's white box covers the end that runs to its center. + var leader = new XPen(XColors.Black, 0.5); + foreach (var label in view.Labels) + { + if (label.Anchor is not { } anchor) + continue; + gfx.DrawLine(leader, anchor, new XPoint(label.Box.X + label.Box.Width / 2, label.Box.Y + label.Box.Height / 2)); + const double dot = 1.2; + gfx.DrawEllipse(XBrushes.Black, anchor.X - dot, anchor.Y - dot, 2 * dot, 2 * dot); + } var font = NestReportDiagram.LabelFont(); foreach (var label in view.Labels.Concat(view.Groups.Select(group => group.Label))) { diff --git a/OpenNest.Reporting/NestReportDiagram.cs b/OpenNest.Reporting/NestReportDiagram.cs index b0843d93..b96008eb 100644 --- a/OpenNest.Reporting/NestReportDiagram.cs +++ b/OpenNest.Reporting/NestReportDiagram.cs @@ -4,8 +4,11 @@ using PdfSharp.Drawing; namespace OpenNest.Reporting; -/// A part ID label in canvas-local page coordinates (Y down). -internal sealed record DiagramLabel(int Part, string Id, XRect Box); +/// +/// A part ID label in canvas-local page coordinates (Y down). A label set beside a part too thin +/// to hold it has a leader on the part's material. +/// +internal sealed record DiagramLabel(int Part, string Id, XRect Box, XPoint? Anchor = null); /// A dotted group boundary and its shared ID, in canvas coordinates. internal sealed record DiagramGroup(IReadOnlyList Parts, XRect Boundary, DiagramLabel Label); @@ -108,6 +111,9 @@ internal static class NestReportDiagram var canvas = new Canvas(new XRect(0, 0, width, height), [rulers.Horizontal, rulers.Vertical]); var labels = PlaceLabels(plate, shapes, obstacles, all, fit, canvas, font, out var failed); var groups = PlaceGroups(plate, obstacles, failed, labels, fit, canvas, font); + var grouped = groups.SelectMany(group => group.Parts).ToHashSet(); + PlaceLeaders(plate, shapes, obstacles, failed.Where(index => !grouped.Contains(index)), labels, groups, + fit, canvas, font); return new DiagramView(new XSize(width, height), fit, labels, groups, rulers); } @@ -368,8 +374,9 @@ internal static class NestReportDiagram failed.Add(index); } - // A part too narrow at its pole (a ring around a large hole) may still have clear room - // elsewhere within its own extents, such as the hole itself. + // A part too narrow at its pole (a ring around a large hole) may still have clear room in + // one of its own holes. Only an enclosed hole: open space beside a concave part (inside a + // C shape's opening) reads as belonging to whatever is near it, so that part gets a leader. foreach (var index in failed.ToList()) { var id = plate.Parts[index].ReportId; @@ -377,7 +384,7 @@ internal static class NestReportDiagram var area = fit.Rect(shapes[index].Bounds); var others = obstacles.Where((_, other) => other != index).ToList(); var spot = BestSpot(Grid(area, size.Width + 2 * LabelPadding, size.Height + 2 * LabelPadding) - .Where(area.Contains), obstacles, others, fit, + .Where(area.Contains).Where(box => shapes[index].InHole(Center(fit, box))), obstacles, others, fit, padded => !canvas.Holds(padded) || OnSheetEdge(fit.Rect(plate.Bounds), padded) || placed.Any(label => label.Box.IntersectsWith(padded)), new XPoint(area.X + area.Width / 2, area.Y + area.Height / 2)); if (spot is not { } found) @@ -388,6 +395,123 @@ internal static class NestReportDiagram return placed; } + /// The model-space point under a canvas rectangle's center. + private static Vector Center(Fit fit, XRect box) + { + var center = fit.Model(new XPoint(box.X + box.Width / 2, box.Y + box.Height / 2)); + return new Vector(center.X, center.Y); + } + + /// + /// Sets the ID of each part still unlabeled (too thin for it, with no hole to hold it and no + /// same-ID neighbors to share one) in the nearest clear space outside it, with a leader to + /// its pole. Tiny parts whose ID other unlabeled parts share are skipped. The label keeps the usual clearance from every contour and other label; the + /// leader crosses no other part, cutoff, clamp, label or leader. A part with no such spot + /// within reach stays unlabeled, as before. + /// + private static void PlaceLeaders(ReportPlate plate, List shapes, List obstacles, + IEnumerable targets, List labels, List groups, Fit fit, Canvas canvas, + XFont font) + { + var sheet = fit.Rect(plate.Bounds); + var boxes = labels.Select(label => label.Box) + .Concat(groups.SelectMany(group => new[] { group.Boundary, group.Label.Box })).ToList(); + var leaders = new List<(XPoint From, XPoint To)>(); + var unlabeled = targets.ToList(); + var shared = unlabeled.GroupBy(index => plate.Parts[index].ReportId) + .Where(group => group.Count() > 1).Select(group => group.Key).ToHashSet(); + foreach (var index in unlabeled) + { + var id = plate.Parts[index].ReportId; + var size = ReportText.Size(id, font); + var width = size.Width + 2 * LabelPadding; + var height = size.Height + 2 * LabelPadding; + // Leaders are for thin parts. Tiny repeated parts that could not share a group label + // would bury the sheet in leaders, so they stay unlabeled; a lone tiny part gets one. + var extent = fit.Rect(shapes[index].Bounds); + if (shared.Contains(id) && System.Math.Max(extent.Width, extent.Height) < 2 * height) + continue; + var anchor = fit.Point(shapes[index].Pole.X, shapes[index].Pole.Y); + var others = obstacles.Where((_, other) => other != index).ToList(); + var step = System.Math.Max(1, height / 3); + XRect? found = null; + XPoint end = default; + foreach (var reach in LeaderReach) + { + var area = fit.Rect(shapes[index].Bounds); + area.Inflate(reach * height, reach * height); + var candidates = new List<(XRect Box, double Distance)>(); + for (var y = area.Top; y <= area.Bottom - height; y += step) + { + for (var x = area.Left; x <= area.Right - width; x += step) + { + var box = new XRect(x, y, width, height); + var near = Nearest(box, anchor); + candidates.Add((box, System.Math.Pow(near.X - anchor.X, 2) + System.Math.Pow(near.Y - anchor.Y, 2))); + } + } + foreach (var (box, _) in candidates.OrderBy(candidate => candidate.Distance)) + { + var padded = box; + padded.Inflate(Clearance, Clearance); + if (!canvas.Holds(padded) || OnSheetEdge(sheet, padded) || boxes.Any(other => other.IntersectsWith(padded)) + || leaders.Any(leader => SegmentHitsRect(leader.From, leader.To, padded))) + continue; + var near = Nearest(box, anchor); + var model = ModelBox(fit, box); + var reachBox = ModelBox(fit, padded); + if (obstacles.Any(shape => shape.Overlaps(reachBox) && shape.Distance(model) * fit.Scale < Clearance)) + continue; + var center = Center(fit, box); + if (obstacles.Any(shape => shape.InMaterial(center))) + continue; + // The leader runs from the label's edge to the anchor: it may cross only its own + // part's outline, and no other label or leader. + var from = fit.Model(near); + var to = fit.Model(anchor); + if (others.Any(shape => shape.CrossesSegment(new Vector(from.X, from.Y), new Vector(to.X, to.Y))) + || boxes.Any(other => SegmentHitsRect(near, anchor, other)) + || leaders.Any(leader => SegmentsCross(leader.From, leader.To, near, anchor))) + continue; + found = box; + end = near; + break; + } + if (found != null) + break; + } + if (found is not { } spot) + continue; + labels.Add(new DiagramLabel(index, id, spot, anchor)); + boxes.Add(spot); + leaders.Add((end, anchor)); + } + } + + // How far, in label heights, the leader search looks past the part: near first, then wider. + private static readonly double[] LeaderReach = [4, 12]; + + /// The point of a rectangle (its border, for an outside point) nearest to a point. + private static XPoint Nearest(XRect box, XPoint point) => + new(System.Math.Clamp(point.X, box.Left, box.Right), System.Math.Clamp(point.Y, box.Top, box.Bottom)); + + /// Whether a canvas segment touches a canvas rectangle. + private static bool SegmentHitsRect(XPoint a, XPoint b, XRect rect) + { + if (rect.Contains(a) || rect.Contains(b)) + return true; + XPoint[] corners = [rect.TopLeft, rect.TopRight, rect.BottomRight, rect.BottomLeft]; + for (var i = 0; i < 4; i++) + { + if (SegmentsCross(a, b, corners[i], corners[(i + 1) % 4])) + return true; + } + return false; + } + + private static bool SegmentsCross(XPoint a, XPoint b, XPoint c, XPoint d) => + Shape.SegmentsCross(new Vector(a.X, a.Y), new Vector(b.X, b.Y), new Vector(c.X, c.Y), new Vector(d.X, d.Y)); + /// The model-space rectangle under a canvas rectangle. private static Box ModelBox(Fit fit, XRect rect) { @@ -500,17 +624,49 @@ internal static class NestReportDiagram if (!Box.Contains(point)) return false; var inside = false; + foreach (var ring in Rings) + inside ^= Inside(ring, point); + return inside; + } + + /// + /// Whether the point lies in one of the part's enclosed holes: inside its perimeter (the + /// largest ring) but not in its material. + /// + public bool InHole(Vector point) => + Rings.Count > 1 && Box.Contains(point) && Inside(Rings.MaxBy(ring => ring.Area())!, point) + && !InMaterial(point); + + /// Whether a model-space segment touches any contour edge. + public bool CrossesSegment(Vector a, Vector b) + { + // Box.Intersects is strict, which would miss a leader lying on the bounding box's edge. + if (System.Math.Max(a.X, b.X) < Box.Left || System.Math.Min(a.X, b.X) > Box.Right + || System.Math.Max(a.Y, b.Y) < Box.Bottom || System.Math.Min(a.Y, b.Y) > Box.Top) + return false; foreach (var ring in Rings) { var vertices = ring.Vertices; - for (int i = 0, j = vertices.Count - 1; i < vertices.Count; j = i++) + for (var i = 0; i < vertices.Count; i++) { - if ((vertices[i].Y > point.Y) != (vertices[j].Y > point.Y) - && point.X < (vertices[j].X - vertices[i].X) * (point.Y - vertices[i].Y) - / (vertices[j].Y - vertices[i].Y) + vertices[i].X) - inside = !inside; + if (SegmentsCross(a, b, vertices[i], vertices[(i + 1) % vertices.Count])) + return true; } } + return false; + } + + private static bool Inside(Polygon ring, Vector point) + { + var inside = false; + var vertices = ring.Vertices; + for (int i = 0, j = vertices.Count - 1; i < vertices.Count; j = i++) + { + if ((vertices[i].Y > point.Y) != (vertices[j].Y > point.Y) + && point.X < (vertices[j].X - vertices[i].X) * (point.Y - vertices[i].Y) + / (vertices[j].Y - vertices[i].Y) + vertices[i].X) + inside = !inside; + } return inside; } @@ -550,7 +706,7 @@ internal static class NestReportDiagram return System.Math.Sqrt(x * x + y * y); } - private static bool SegmentsCross(Vector a, Vector b, Vector c, Vector d) + internal static bool SegmentsCross(Vector a, Vector b, Vector c, Vector d) { static double Cross(Vector o, Vector p, Vector q) => (p.X - o.X) * (q.Y - o.Y) - (p.Y - o.Y) * (q.X - o.X); var d1 = Cross(c, d, a); diff --git a/OpenNest.Tests/Reporting/NestPdfLayoutTests.cs b/OpenNest.Tests/Reporting/NestPdfLayoutTests.cs index abde310a..7722dc16 100644 --- a/OpenNest.Tests/Reporting/NestPdfLayoutTests.cs +++ b/OpenNest.Tests/Reporting/NestPdfLayoutTests.cs @@ -212,7 +212,9 @@ public sealed class NestPdfLayoutTests : IDisposable var snapshot = NestReportBuilder.Capture(nest, NestReportTestData.GeneratedAt); var plan = NestReportDiagram.Plan(snapshot.Plates[0], 720, 320); Assert.Empty(plan.Groups); - Assert.Equal(2, plan.Labels.Count); + // The washers stay unlabeled; a lone obstacle part gets its ID on a leader. + Assert.DoesNotContain(plan.Labels, label => label.Id == "2"); + Assert.Equal(cutoff ? 2 : 3, plan.Labels.Count); } [Fact] @@ -298,12 +300,118 @@ public sealed class NestPdfLayoutTests : IDisposable var label = Assert.Single(plan.Labels); Assert.Empty(plan.Groups); + Assert.Null(label.Anchor); var center = plan.Fit.Model(new PdfSharp.Drawing.XPoint(label.Box.X + label.Box.Width / 2, label.Box.Y + label.Box.Height / 2)); var bounds = snapshot.Plates[0].Parts[0].Geometry.Bounds; Assert.InRange(center.X - (bounds.Left + bounds.Right) / 2, -0.5, 0.5); Assert.InRange(center.Y - (bounds.Bottom + bounds.Top) / 2, -0.5, 0.5); } + [Fact] + public void Plan_PartsTooThinForTheirIdsGetLeaderLabelsBesideThem() + { + // From N26-2CJ: a 0.5 x 20 in strip and a 1 in wide half ring on a 48 x 96 sheet are a + // few points wide at overview scale. The strip was left unlabeled; the ring's ID went in + // its open side, off the part, with nothing tying it to the ring. + var nest = new Nest("Thin parts") { Units = Units.Inches }; + var strip = NestReportTestData.Rectangle("Strip", 0.5, 20); + var ring = new Drawing("Half ring", HalfRing(outer: 10, inner: 9)); + var block = NestReportTestData.Rectangle("Block", 30, 20); + nest.Drawings.Add(strip); + nest.Drawings.Add(ring); + nest.Drawings.Add(block); + var plate = new Plate(48, 96) { Quantity = 1, PartSpacing = 0.25 }; + plate.Parts.Add(new Part(block, new Vector(1, 1))); + plate.Parts.Add(new Part(strip, new Vector(40, 1))); + plate.Parts.Add(new Part(ring, new Vector(30, 24))); + nest.Plates.Add(plate); + var snapshot = NestReportBuilder.Capture(nest, NestReportTestData.GeneratedAt); + + var plan = NestReportDiagram.Plan(snapshot.Plates[0], 720, 320); + + Assert.Equal(3, plan.Labels.Count); + Assert.Empty(plan.Groups); + Assert.Null(plan.Labels.Single(label => label.Part == 0).Anchor); + var parts = snapshot.Plates[0].Parts; + foreach (var index in new[] { 1, 2 }) + { + var label = plan.Labels.Single(label => label.Part == index); + var anchor = plan.Fit.Model(Assert.NotNull(label.Anchor)); + var bounds = parts[index].Geometry.Bounds; + Assert.InRange(anchor.X, bounds.Left, bounds.Right); + Assert.InRange(anchor.Y, bounds.Bottom, bounds.Top); + // The ID sits off the material, clear of the other parts, a short leader away. + foreach (var other in new[] { 0, 1 }) + Assert.False(label.Box.IntersectsWith(plan.Fit.Rect(parts[other].Geometry.Bounds))); + var center = plan.Fit.Model(new PdfSharp.Drawing.XPoint(label.Box.X + label.Box.Width / 2, label.Box.Y + label.Box.Height / 2)); + var radius = System.Math.Sqrt(System.Math.Pow(center.X - 40, 2) + System.Math.Pow(center.Y - 34, 2)); + Assert.False(radius is >= 9 and <= 10, "The ID covers the ring's band."); + var nearX = System.Math.Clamp(label.Anchor!.Value.X, label.Box.Left, label.Box.Right); + var nearY = System.Math.Clamp(label.Anchor.Value.Y, label.Box.Top, label.Box.Bottom); + Assert.InRange(System.Math.Sqrt(System.Math.Pow(nearX - label.Anchor.Value.X, 2) + + System.Math.Pow(nearY - label.Anchor.Value.Y, 2)), 0, 4 * label.Box.Height); + } + // Every anchor lies in its own part's band: the ring's is between its two radii. + var ringAnchor = plan.Fit.Model(plan.Labels.Single(label => label.Part == 2).Anchor!.Value); + Assert.InRange(System.Math.Sqrt(System.Math.Pow(ringAnchor.X - 40, 2) + System.Math.Pow(ringAnchor.Y - 34, 2)), 9, 10); + Assert.True(ringAnchor.X >= 40); + } + + [SkippableTheory] + [InlineData(0.5, true)] + [InlineData(3, false)] + public void Write_LeaderLabelDrawsADotOnThePart(double width, bool leader) + { + var nest = new Nest("Strip") { Units = Units.Inches }; + var strip = NestReportTestData.Rectangle("Strip", width, 20); + nest.Drawings.Add(strip); + var plate = new Plate(48, 96) { Quantity = 1 }; + plate.Parts.Add(new Part(strip, new Vector(40, 1))); + nest.Plates.Add(plate); + var snapshot = NestReportBuilder.Capture(nest, NestReportTestData.GeneratedAt); + Assert.Equal(leader, Assert.Single(NestReportDiagram.Plan(snapshot.Plates[0], 720, 320).Labels).Anchor != null); + + var path = Write(nest); + + using var pdf = PdfReader.Open(path, PdfDocumentOpenMode.Import); + var diagram = ReportPdf.ContentStreams(pdf.Pages[1]).Last(); + // Nothing else on this all-straight plate draws a curve: only the leader's anchor dot. + Assert.Equal(leader, Regex.IsMatch(diagram, @"(?m)\sc\s*$")); + } + + [Fact] + public void Plan_LoneTinyPartGetsALeaderButAnUngroupableClusterDoesNot() + { + // The dense nest's washer cluster cannot be grouped around the obstacle: its washers stay + // unlabeled rather than each sprouting a leader. A lone washer elsewhere gets one. + var nest = NestReportTestData.CreateDenseNest(); + nest.Plates[0].Parts.Add(new Part(NestReportTestData.Rectangle("Obstacle", 0.1, 0.1), new Vector(63.2, 31.2))); + var lone = new Drawing("Lone washer", NestReportTestData.HoledSquare(1, 0.25)); + nest.Drawings.Add(lone); + nest.Plates[0].Parts.Add(new Part(lone, new Vector(80, 80))); + var snapshot = NestReportBuilder.Capture(nest, NestReportTestData.GeneratedAt); + + var plan = NestReportDiagram.Plan(snapshot.Plates[0], 720, 320); + + Assert.Empty(plan.Groups); + Assert.DoesNotContain(plan.Labels, label => label.Id == "2"); + var leader = Assert.Single(plan.Labels, label => label.Part == snapshot.Plates[0].Parts.Length - 1); + Assert.NotNull(leader.Anchor); + } + + /// The right half of a ring centered at (, ). + private static Program HalfRing(double outer, double inner) + { + var center = new Vector(outer, outer); + var program = new Program(); + program.Codes.Add(new RapidMove(outer, 2 * outer)); + program.Codes.Add(new ArcMove(new Vector(outer, 0), center, RotationType.CW)); + program.Codes.Add(new LinearMove(outer, outer - inner)); + program.Codes.Add(new ArcMove(new Vector(outer, outer + inner), center, RotationType.CCW)); + program.Codes.Add(new LinearMove(outer, 2 * outer)); + return program; + } + [SkippableFact] public void Write_LabelOnHoledPartAvoidsTheHole() { diff --git a/docs/nest-reports.md b/docs/nest-reports.md index 3fdd5d0f..dab71cd1 100644 --- a/docs/nest-reports.md +++ b/docs/nest-reports.md @@ -144,10 +144,20 @@ Individual IDs use 7 pt text centered on the part's pole of inaccessibility (`PolyLabel`, as in `PlateView`), clear of edges, holes, cutoffs and other labels. The search uses a placement-independent quantized copy for consistent placement on identical parts. When the pole is too narrow (a ring around a large hole), the -ID goes in the clear spot within the part's own extents with the most room, such -as an empty hole, nearest the part's center. Labels are best effort: there are no -closeup or grid pages, and a part too small to label never prevents export. Every -part remains in the quantity tables even when its diagram label cannot fit. +ID goes in the clear spot of one of the part's own enclosed holes with the most +room, nearest the part's center. Open space beside a concave part (inside a C +shape's opening) never holds its ID that way, since it reads as belonging to +whatever is nearby. + +A part still unlabeled after the groups below (a thin strip or a narrow band with +no hole to hold its ID) gets its ID in the nearest clear space outside it, with a +thin leader to a dot at its pole. The label keeps the usual clearance; the leader +crosses no other part, cutoff, clamp, label or leader. Tiny parts (under two label +heights long) whose ID other unlabeled parts share get no leaders, so an ungroupable +cluster does not bury the sheet in them; a lone tiny part gets one. Labels are best +effort: there are no closeup or grid pages, and a part too small to label never +prevents export. Every part remains in the quantity tables even when its diagram +label cannot fit. Nearby small parts with the same report ID may share a dotted rectangular outline and one ID. Separate clusters get separate outlines; an outline stays within half