Merge branch 'refs/heads/claude/upbeat-feynman-1ca11e' into claude/etch-part-number-bend-group-096e0a

This commit is contained in:
aj committed 2026-11-22 17:37:27 -05:00
commit e173d6c987
20 files changed
+1163 -5

No files matched your search

+1
View File
@@ -74,6 +74,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
+6
View File
@@ -151,6 +151,12 @@ namespace OpenNest
/// </summary>
public List<Dimensions.DrawingDimension> Dimensions { get; set; } = new List<Dimensions.DrawingDimension>();
/// <summary>
/// Where the part number label would be etched, in the source frame, or null when none is
/// set. Placement only: it never affects <see cref="Program"/>, nesting or posts.
/// </summary>
public Labels.LabelBox LabelBox { get; set; }
/// <summary>
/// Complete set of source entities with stable GUIDs.
/// Null when the drawing was created from G-code or an older nest file.
+82
View File
@@ -0,0 +1,82 @@
using OpenNest.Geometry;
using OpenNest.Math;
namespace OpenNest.Labels
{
/// <summary>
/// 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.
/// </summary>
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; }
/// <summary>The side along the text, before <see cref="Rotation"/>.</summary>
public double Width { get; set; }
/// <summary>The side across the text, before <see cref="Rotation"/>.</summary>
public double Height { get; set; }
/// <summary>Counterclockwise turn about <see cref="Center"/>, in radians.</summary>
public double Rotation { get; set; }
/// <summary>True when the center, both sides and the rotation are finite and both sides are positive.</summary>
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);
/// <summary>The corners counterclockwise from the text's lower left.</summary>
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) };
}
/// <summary>A point in the box's own frame (x along the text, y across it), origin at the center.</summary>
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);
}
/// <summary>The point at <paramref name="local"/> in the box's own frame.</summary>
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;
}
}
}
+230
View File
@@ -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
{
/// <summary>What <see cref="LabelBoxFinder"/> must fit, in the drawing's units.</summary>
public sealed class LabelBoxOptions
{
/// <summary>Characters in the longest label: a part number and a few bend group letters ("1234-AB").</summary>
public const int DefaultCharacters = 7;
/// <summary>Etch stroke advance as a share of the character height.</summary>
public const double CharacterAdvance = 0.75;
/// <summary>The label's length along the text.</summary>
public double Width { get; set; }
/// <summary>The label's height across the text.</summary>
public double Height { get; set; }
/// <summary>The clearance kept from the part's edges, holes and cutouts.</summary>
public double Clearance { get; set; }
/// <summary>The clearance kept from each side of a bend line; <see cref="Clearance"/> when null.</summary>
public double? BendClearance { get; set; }
/// <summary>A label of <paramref name="characters"/> characters in a stroke font of height <paramref name="characterHeight"/>.</summary>
public static LabelBoxOptions ForText(int characters, double characterHeight, double clearance) =>
new()
{
Width = characters * characterHeight * CharacterAdvance,
Height = characterHeight,
Clearance = clearance,
};
/// <summary>A quarter inch (6 mm) label of <see cref="DefaultCharacters"/> characters, an eighth inch (3 mm) from anything else.</summary>
public static LabelBoxOptions Default(Units units) => units == Units.Millimeters
? ForText(DefaultCharacters, 6, 3)
: ForText(DefaultCharacters, 0.25, 0.125);
}
/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// 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 (<see cref="MaximalRectangles"/>) 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.
/// </remarks>
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);
/// <summary>
/// A box for the label, or null when nothing fits. <paramref name="entities"/> are the part as
/// it will be cut; marks and rapids are not material, and a tabbed cutout's slug counts as
/// part (<see cref="NestingMaterial.ForNesting"/>).
/// </summary>
/// <param name="entities">The part as it will be cut.</param>
/// <param name="bends">Bend lines to keep clear of.</param>
/// <param name="options">The label size and clearances.</param>
/// <param name="keepOut">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.</param>
public static LabelBox Find(IEnumerable<Entity> entities, IEnumerable<Bend> bends, LabelBoxOptions options,
IEnumerable<IEnumerable<Entity>> 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<Bend>())
.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<IEnumerable<Entity>>())
{
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<double> Orientations(List<Bend> bends, List<Shape> shapes)
{
var raw = new List<double> { 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<Line>()
.OrderByDescending(l => l.Length)
.FirstOrDefault();
if (edge != null)
raw.Add(edge.StartPoint.AngleTo(edge.EndPoint));
var angles = new List<double>();
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);
}
}
}
+6 -1
View File
@@ -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.
/// </param>
/// <param name="dimensions">Dimensions to keep on the drawing; they never affect the program.</param>
/// <param name="labelBox">The part number label box to keep on the drawing; it never affects the program.</param>
public static Drawing BuildDrawing(
CadImportResult result,
IEnumerable<Entity> entities,
@@ -197,7 +199,8 @@ namespace OpenNest.IO
IReadOnlyList<Breakoff> breakoffs = null,
IReadOnlyList<TabbedCutout> tabbedCutouts = null,
IReadOnlyDictionary<System.Guid, EntityRole> entityRoles = null,
IReadOnlyList<DrawingDimension> dimensions = null
IReadOnlyList<DrawingDimension> 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<Breakoff>();
drawing.TabbedCutouts = tabbedCutouts?.Select(c => c.Clone()).ToList() ?? new List<TabbedCutout>();
drawing.Dimensions = dimensions?.Select(d => d.Clone()).ToList() ?? new List<DrawingDimension>();
drawing.LabelBox = labelBox?.Clone();
drawing.Program = editedProgram ?? pgm;
var bendSources = new HashSet<Entity>(
@@ -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) =>
+16
View File
@@ -505,6 +505,22 @@ namespace OpenNest.IO
/// <summary>Dimension placements; values are measured when shown. Omitted when there are none.</summary>
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public List<DimensionDto> Dimensions { get; init; }
/// <summary>Where the part number label is etched, in the source frame. Omitted when none is set.</summary>
[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; }
/// <summary>Counterclockwise turn about the center in radians. Omitted when zero.</summary>
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public double Rotation { get; init; }
}
public record DimensionDto
+17
View File
@@ -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)
+10
View File
@@ -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,
}
);
}
@@ -0,0 +1,223 @@
using OpenNest.Bending;
using OpenNest.Geometry;
using OpenNest.Labels;
namespace OpenNest.Tests.Labels;
public class LabelBoxFinderTests
{
private static List<Entity> 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<Entity> 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<Bend> { 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<ArgumentException>(() => LabelBoxFinder.Find(Rectangle(0, 0, 10, 5), [], Options(width: 0)));
Assert.Throws<ArgumentException>(() => 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));
}
@@ -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<Entity> 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<Bend>(), 1, null, null);
var labeled = CadImporter.BuildDrawing(result, entities, new List<Bend>(), 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<Bend>(), 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<Bend>(), 1, null, null,
labelBox: new LabelBox(new Vector(2, 2), 1, 0.25, 0));
var edited = CadImporter.BuildDrawing(result, entities, new List<Bend>(), 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<Bend>(), 1, null, null));
Assert.Null(drawing.LabelBox);
}
}
@@ -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;
/// <summary>Drives the CAD Converter's part number label box through its real mouse handling.</summary>
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<EntityView>(form, "entityView1");
var item = Field<FileListControl>(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<EntityView>(form, "entityView1");
var item = Field<FileListControl>(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<FileListControl>(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<FileListControl>(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<EntityView>(form, "entityView1");
var item = Field<FileListControl>(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<Bend>? bends = null)
{
var entities = new List<Entity>
{
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<Bend>(), 1, null, null);
}
private static T Field<T>(object owner, string name) =>
TestReflection.Field<T>(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<string> Messages { get; } = new();
internal override void ShowLabelBoxMessage(string message) => Messages.Add(message);
}
}
+7 -1
View File
@@ -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;
}
+108
View File
@@ -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;
/// <summary>
/// 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.
/// </summary>
public Labels.LabelBox LabelBox { get; set; }
/// <summary>The label box was moved or resized; the argument is its new placement.</summary>
public event EventHandler<Labels.LabelBox> 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);
}
}
}
}
+1
View File
@@ -162,6 +162,7 @@ namespace OpenNest.Controls
DrawSelection(e.Graphics);
DrawTexts(e.Graphics);
DrawDimensions(e.Graphics);
DrawLabelBox(e.Graphics);
if (ShowEntityLabels)
DrawEntityLabels(e.Graphics);
+3
View File
@@ -31,6 +31,9 @@ namespace OpenNest.Controls
public List<Breakoffs.Breakoff> Breakoffs { get; set; } = new();
public List<TabbedCutouts.TabbedCutout> TabbedCutouts { get; set; } = new();
public List<Dimensions.DrawingDimension> Dimensions { get; set; } = new();
/// <summary>Where the part number label would be etched, in the entities' frame; null when none is set.</summary>
public Labels.LabelBox LabelBox { get; set; }
public HashSet<Guid> SuppressedEntityIds { get; set; }
/// <summary>Entities the user excluded one by one; they stay excluded whatever the filters show.</summary>
+16
View File
@@ -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;
@@ -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;
}
/// <summary>
/// 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.
/// </summary>
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<Geometry.Entity>)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);
}
}
+6 -1
View File
@@ -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<DimensionLayout>();
RefreshLabelBox(null);
entityView1.Invalidate();
RefreshHoleTable();
RefreshSeparable(null);
@@ -1440,6 +1443,7 @@ namespace OpenNest.Forms
Breakoffs = drawing.Breakoffs?.Select(b => b.Clone()).ToList() ?? new List<Breakoff>(),
TabbedCutouts = drawing.TabbedCutouts?.Select(c => c.Clone()).ToList() ?? new List<TabbedCutout>(),
Dimensions = drawing.Dimensions?.Select(d => d.Clone()).ToList() ?? new List<DrawingDimension>(),
LabelBox = drawing.LabelBox?.Clone(),
SuppressedEntityIds =
drawing.SuppressedEntityIds.Count > 0
? new HashSet<Guid>(drawing.SuppressedEntityIds)
@@ -1495,7 +1499,8 @@ namespace OpenNest.Forms
item.Breakoffs,
item.TabbedCutouts,
item.EntityRoles,
item.Dimensions
item.Dimensions,
item.LabelBox
);
drawings.Add(drawing);
+53
View File
@@ -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
```
+12 -2
View File
@@ -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