From 924763493d75fc768a1f881ebaf5c5bf36b761be Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Thu, 5 Nov 2026 13:01:37 -0500 Subject: [PATCH] feat(report): place part IDs wherever they fit best, holes included Ring-shaped parts (a plate with a large center hole) were left unlabeled: the material at their pole is too narrow for the ID, and the label was never tried anywhere else. Group IDs were likewise only ever placed beside the dotted outline, so a cramped cluster lost its ID or straddled the sheet edge. A part whose pole spot is too tight now takes the roomiest clear spot within its own extents, such as its empty hole. A group ID takes the roomiest spot inside its outline or beside it; with none clear it may cover the group's own parts near the center, since operators read part detail from the parts list. No ID sits across the sheet outline. Co-Authored-By: Claude Opus 5.5 --- OpenNest.Reporting/NestReportDiagram.cs | 210 ++++++++++++++++-- .../Reporting/NestPdfLayoutTests.cs | 23 ++ docs/nest-reports.md | 24 +- 3 files changed, 232 insertions(+), 25 deletions(-) diff --git a/OpenNest.Reporting/NestReportDiagram.cs b/OpenNest.Reporting/NestReportDiagram.cs index 9884b862..0a07fdc3 100644 --- a/OpenNest.Reporting/NestReportDiagram.cs +++ b/OpenNest.Reporting/NestReportDiagram.cs @@ -63,6 +63,7 @@ internal static class NestReportDiagram var groups = new List(); // A small screen-space gap also accommodates tightly packed parts with unset spacing. var gap = System.Math.Max(4, plate.PartSpacing * fit.Scale * 2); + var sheet = fit.Rect(plate.Bounds); // Outlines stay under half the part spacing from their members, so the outlines of two // neighboring clusters (different IDs one spacing apart) never meet or overlap. var margin = plate.PartSpacing > 0 ? System.Math.Min(1, plate.PartSpacing * fit.Scale * 0.45) : 1; @@ -107,34 +108,106 @@ internal static class NestReportDiagram var labelHeight = size.Height + 2 * LabelPadding; var centerX = boundary.X + (boundary.Width - labelWidth) / 2; var centerY = boundary.Y + (boundary.Height - labelHeight) / 2; - // Put the ID beside the dotted boundary, never over a small part or its hole. - var candidates = new[] - { + var target = new XPoint(boundary.X + boundary.Width / 2, boundary.Y + boundary.Height / 2); + var inside = Grid(boundary, labelWidth, labelHeight).ToList(); + // The ID goes wherever it fits best: clear space inside the outline (between the parts + // or in a hole) or beside it. + var candidates = inside.Concat( + [ new XRect(centerX, boundary.Y - labelHeight - Clearance, labelWidth, labelHeight), new XRect(centerX, boundary.Bottom + Clearance, labelWidth, labelHeight), new XRect(boundary.Right + Clearance, centerY, labelWidth, labelHeight), new XRect(boundary.X - labelWidth - Clearance, centerY, labelWidth, labelHeight), - }; - foreach (var box in candidates) - { - var padded = box; - padded.Inflate(Clearance, Clearance); - if (!view.Contains(padded) || obstacles.Any(shape => shape.Crosses(ModelBox(fit, padded))) - || labels.Any(label => label.Box.IntersectsWith(padded)) - || groups.Any(group => group.Boundary.IntersectsWith(padded) || group.Label.Box.IntersectsWith(padded))) - continue; + ]); + bool Blocked(XRect padded) => !view.Contains(padded) || OnSheetEdge(sheet, padded) + || labels.Any(label => label.Box.IntersectsWith(padded)) + || groups.Any(group => group.Boundary.IntersectsWith(padded) || group.Label.Box.IntersectsWith(padded)); + var others = obstacles.Where((_, index) => !memberSet.Contains(index)).ToList(); + // With no clear space anywhere, the ID may cover the group's own parts (the parts + // list shows each part up close), but never another part or a cutoff. + var spot = BestSpot(candidates, obstacles, others, fit, Blocked, target) + ?? BestSpot(inside, others, others, fit, Blocked, target, required: 0, preferRoom: false); + if (spot is { } box) groups.Add(new DiagramGroup(members, boundary, new DiagramLabel(seed, id, box))); - break; - } } return groups; } + /// Whether a label would sit across the sheet outline and hide part of it. + private static bool OnSheetEdge(XRect sheet, XRect padded) => + sheet.IntersectsWith(padded) && !sheet.Contains(padded); + + /// Label-sized boxes tiling an area on a fine grid, centered when the area is too small. + private static IEnumerable Grid(XRect area, double width, double height) + { + yield return new XRect(area.X + (area.Width - width) / 2, area.Y + (area.Height - height) / 2, width, height); + var spanX = area.Width - width; + var spanY = area.Height - height; + if (spanX < 0 || spanY < 0) + yield break; + var step = System.Math.Max(1, System.Math.Max(spanX, spanY) / 60); + for (var y = 0.0; y <= spanY + 1e-9; y += step) + for (var x = 0.0; x <= spanX + 1e-9; x += step) + yield return new XRect(area.X + x, area.Y + y, width, height); + } + + /// + /// The candidate with the most room to the nearest contour (capped, so open space ties) and, + /// among ties, the one nearest . A candidate must keep at least + /// canvas points from every obstacle edge and may not sit inside + /// the material of any shape in , which would label the wrong part. + /// Without , only the distance to the target ranks candidates. + /// + private static XRect? BestSpot(IEnumerable candidates, IReadOnlyList obstacles, + IReadOnlyList foreign, Fit fit, Func blocked, XPoint target, double required = Clearance, + bool preferRoom = true) + { + XRect? best = null; + var bestRoom = double.NegativeInfinity; + var bestDistance = double.PositiveInfinity; + foreach (var box in candidates) + { + var padded = box; + padded.Inflate(Clearance, Clearance); + if (blocked(padded)) + continue; + var cap = 2 * box.Height; + var reach = box; + reach.Inflate(cap, cap); + var near = ModelBox(fit, reach); + var model = ModelBox(fit, box); + var room = cap; + foreach (var shape in obstacles) + { + if (room < required || !shape.Overlaps(near)) + continue; + room = System.Math.Min(room, shape.Distance(model) * fit.Scale); + } + if (room < required) + continue; + var center = fit.Model(new XPoint(box.X + box.Width / 2, box.Y + box.Height / 2)); + if (foreign.Any(shape => shape.InMaterial(new Vector(center.X, center.Y)))) + continue; + var distance = System.Math.Pow(box.X + box.Width / 2 - target.X, 2) + + System.Math.Pow(box.Y + box.Height / 2 - target.Y, 2); + if (!preferRoom) + room = 0; + if (room > bestRoom + 1e-6 || (room > bestRoom - 1e-6 && distance < bestDistance)) + { + best = box; + bestRoom = room; + bestDistance = distance; + } + } + return best; + } + /// /// Centers each ID on its part's pole of inaccessibility (, as PlateView /// does), so it sits deepest inside the material and clear of holes. A label box that would - /// touch an edge, hole, cutoff or another label is not moved elsewhere: the individual label is skipped here - /// and may share a group label or remain unlabeled. + /// touch an edge, hole, cutoff or another label falls back to the roomiest clear spot within the + /// part's own extents (such as an empty hole); failing that, the part may share a group label or + /// remain unlabeled. /// private static List PlaceLabels(ReportPlate plate, List shapes, List obstacles, List targets, Fit fit, XRect view, XFont font, out List failed) @@ -158,6 +231,24 @@ internal static class NestReportDiagram else 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. + foreach (var index in failed.ToList()) + { + var id = plate.Parts[index].ReportId; + var size = ReportText.Size(id, font); + 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, + padded => !view.Contains(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) + continue; + placed.Add(new DiagramLabel(index, id, found)); + failed.Remove(index); + } return placed; } @@ -248,6 +339,93 @@ internal static class NestReportDiagram return Rings.Any(ring => ring.Vertices.Any(box.Contains) || ring.Intersects(outline)); } + public bool Overlaps(Box box) => Box.Intersects(box); + + /// Distance from the rectangle to the nearest contour edge; zero when one touches it. + public double Distance(Box box) + { + var best = double.PositiveInfinity; + foreach (var ring in Rings) + { + var vertices = ring.Vertices; + for (var i = 0; i < vertices.Count; i++) + { + best = System.Math.Min(best, SegmentDistance(vertices[i], vertices[(i + 1) % vertices.Count], box)); + if (best <= 0) + return 0; + } + } + return best; + } + + /// Whether the point lies in material: inside an odd number of contours. + public bool InMaterial(Vector point) + { + if (!Box.Contains(point)) + return false; + var inside = false; + foreach (var ring in Rings) + { + 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; + } + + private static double SegmentDistance(Vector a, Vector b, Box box) + { + if (box.Contains(a) || box.Contains(b)) + return 0; + Vector[] corners = [new(box.Left, box.Bottom), new(box.Right, box.Bottom), + new(box.Right, box.Top), new(box.Left, box.Top)]; + for (var i = 0; i < 4; i++) + { + if (SegmentsCross(a, b, corners[i], corners[(i + 1) % 4])) + return 0; + } + var best = System.Math.Min(PointToBox(a, box), PointToBox(b, box)); + foreach (var corner in corners) + best = System.Math.Min(best, PointToSegment(corner, a, b)); + return best; + } + + private static double PointToBox(Vector point, Box box) + { + var dx = System.Math.Max(System.Math.Max(box.Left - point.X, 0), point.X - box.Right); + var dy = System.Math.Max(System.Math.Max(box.Bottom - point.Y, 0), point.Y - box.Top); + return System.Math.Sqrt(dx * dx + dy * dy); + } + + private static double PointToSegment(Vector point, Vector a, Vector b) + { + var dx = b.X - a.X; + var dy = b.Y - a.Y; + var lengthSquared = dx * dx + dy * dy; + var t = lengthSquared <= 0 ? 0 + : System.Math.Clamp(((point.X - a.X) * dx + (point.Y - a.Y) * dy) / lengthSquared, 0, 1); + var x = a.X + t * dx - point.X; + var y = a.Y + t * dy - point.Y; + return System.Math.Sqrt(x * x + y * y); + } + + private 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); + var d2 = Cross(c, d, b); + var d3 = Cross(a, b, c); + var d4 = Cross(a, b, d); + return ((d1 > 0) != (d2 > 0) || d1 == 0 || d2 == 0) && ((d3 > 0) != (d4 > 0) || d3 == 0 || d4 == 0) + && System.Math.Min(a.X, b.X) <= System.Math.Max(c.X, d.X) && System.Math.Min(c.X, d.X) <= System.Math.Max(a.X, b.X) + && System.Math.Min(a.Y, b.Y) <= System.Math.Max(c.Y, d.Y) && System.Math.Min(c.Y, d.Y) <= System.Math.Max(a.Y, b.Y); + } + private static OpenNest.Geometry.Shape ToShape(ReportContour contour) { var shape = new OpenNest.Geometry.Shape(); diff --git a/OpenNest.Tests/Reporting/NestPdfLayoutTests.cs b/OpenNest.Tests/Reporting/NestPdfLayoutTests.cs index fd0c079c..d1274d00 100644 --- a/OpenNest.Tests/Reporting/NestPdfLayoutTests.cs +++ b/OpenNest.Tests/Reporting/NestPdfLayoutTests.cs @@ -280,6 +280,29 @@ public sealed class NestPdfLayoutTests : IDisposable plan.Fit.Rect(snapshot.Plates[0].Parts[index].Geometry.Bounds)))); } + [Fact] + public void Plan_RingTooNarrowForItsIdIsLabeledInItsHole() + { + // A 6.5 in plate with a 4.56 in hole on a 60 x 96 sheet: the ring of material is ~5 pt wide + // at overview scale, too narrow for the ID, but the empty hole has plenty of room. + var nest = new Nest("Ring test") { Units = Units.Inches }; + var ring = new Drawing("Ring", NestReportTestData.HoledSquare(6.5, 2.28)); + nest.Drawings.Add(ring); + var plate = new Plate(60, 96) { Quantity = 1, PartSpacing = 0.25 }; + plate.Parts.Add(new Part(ring, new Vector(80, 50))); + nest.Plates.Add(plate); + var snapshot = NestReportBuilder.Capture(nest, NestReportTestData.GeneratedAt); + + var plan = NestReportDiagram.Plan(snapshot.Plates[0], 720, 320); + + var label = Assert.Single(plan.Labels); + Assert.Empty(plan.Groups); + 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); + } + [SkippableFact] public void Write_LabelOnHoledPartAvoidsTheHole() { diff --git a/docs/nest-reports.md b/docs/nest-reports.md index ff417188..078724ae 100644 --- a/docs/nest-reports.md +++ b/docs/nest-reports.md @@ -88,17 +88,23 @@ the totals. 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. 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. +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. Nearby small parts with the same report ID may share a dotted rectangular outline -and one ID beside it. Separate clusters get separate outlines; an outline stays -within half the part spacing of its parts, so clusters of different parts packed -one spacing apart each keep their own outline and ID. A group is omitted -if its rectangle includes any other part or cutoff, or if there is no clear space -for its label. Clearance is tested against real contours, not bounding boxes, so a -cluster nested in a larger part's cutout or notch is still grouped and labeled. Dotted group outlines are distinct from dashed scrap cutoffs. +and one ID. Separate clusters get separate outlines; an outline stays within half +the part spacing of its parts, so clusters of different parts packed one spacing +apart each keep their own outline and ID. The group ID goes wherever it has the +most room, inside the outline (between the parts or in a hole) or beside it. With +no clear spot, it covers the group's own parts near the outline's center (the +parts list shows each part up close), but never another part or a cutoff. No ID +sits across the sheet outline. A group is omitted if its rectangle includes any +other part or cutoff, or if even that fallback finds no place for its label. +Clearance is tested against real contours, not bounding boxes, so a cluster nested +in a larger part's cutout or notch is still grouped and labeled. Dotted group outlines are distinct from dashed scrap cutoffs. The writer still rejects, with `NotSupportedException` and before touching the destination: