diff --git a/OpenNest.Core/CNC/CuttingStrategy/ContourCuttingStrategy.cs b/OpenNest.Core/CNC/CuttingStrategy/ContourCuttingStrategy.cs index efb90f82..41259542 100644 --- a/OpenNest.Core/CNC/CuttingStrategy/ContourCuttingStrategy.cs +++ b/OpenNest.Core/CNC/CuttingStrategy/ContourCuttingStrategy.cs @@ -85,7 +85,6 @@ namespace OpenNest.CNC.CuttingStrategy var result = new Program(Mode.Absolute); - EmitScribeContours(result, scribeEntities); EmitBreakCuts(result, breakCuts, BreakCutContours(profile)); foreach (var entry in cutoutEntries) @@ -109,6 +108,7 @@ namespace OpenNest.CNC.CuttingStrategy ContourType.External ); + PrependScribeContours(result, scribeEntities); result.Mode = Mode.Incremental; return new CuttingResult { Program = result, LastCutPoint = perimeterPt }; @@ -141,7 +141,6 @@ namespace OpenNest.CNC.CuttingStrategy var result = new Program(Mode.Absolute); - EmitScribeContours(result, scribeEntities); EmitBreakCuts(result, breakCuts, BreakCutContours(profile)); // Find the target shape that contains the clicked entity @@ -184,6 +183,7 @@ namespace OpenNest.CNC.CuttingStrategy EmitRawContour(result, profile.Perimeter); } + PrependScribeContours(result, scribeEntities); result.Mode = Mode.Incremental; return new CuttingResult { Program = result, LastCutPoint = point }; @@ -271,7 +271,6 @@ namespace OpenNest.CNC.CuttingStrategy CuttingPlanning.CommonLinePerimeter commonLine = null, IReadOnlyList slugSlices = null) { var result = new Program(Mode.Absolute); - EmitScribeContours(result, scribes); EmitBreakCuts(result, breakCuts, shapes); EmitSlugSlices(result, slugSlices); foreach (var cutout in tabbedCutouts ?? Array.Empty()) @@ -284,6 +283,7 @@ namespace OpenNest.CNC.CuttingStrategy var start = GetShapeStartPoint(displayTail); DisplayPerimeterTail.Append(result, ConvertShapeToMoves(displayTail, start, LayerType.DisplayPerimeter), start); } + PrependScribeContours(result, scribes); result.Mode = Mode.Incremental; return result; } @@ -298,9 +298,9 @@ namespace OpenNest.CNC.CuttingStrategy int? perimeterOrdinal = null, CuttingPlanning.CommonLinePerimeter commonLine = null) { var result = new Program(Mode.Absolute); - EmitScribeContours(result, scribes); EmitChosenContours(result, shapes, new[] { choice }, contourParameters, perimeterOrdinal ?? shapes.Length - 1, commonLine); + PrependScribeContours(result, scribes); result.Mode = Mode.Incremental; return result; } @@ -648,18 +648,136 @@ namespace OpenNest.CNC.CuttingStrategy ? winding == RotationType.CW ? RotationType.CCW : RotationType.CW : winding; - private void EmitScribeContours(Program program, List scribeEntities) + // Scribes are etched before any cut. They are put in front of an absolute program + // already holding the cuts, so their tour can end near where the first cut starts. + private void PrependScribeContours(Program program, List scribeEntities) { - if (scribeEntities.Count == 0) + if (scribeEntities == null || scribeEntities.Count == 0) return; - var shapes = ShapeBuilder.GetShapes(scribeEntities); - foreach (var shape in shapes) + var marks = new Program(Mode.Absolute); + foreach (var shape in SequenceScribes(ShapeBuilder.GetShapes(scribeEntities), FirstArrival(program))) { var startPt = GetShapeStartPoint(shape); - program.Codes.Add(new RapidMove(startPt)); - program.Codes.AddRange(ConvertShapeToMoves(shape, startPt, LayerType.Scribe)); + marks.Codes.Add(new RapidMove(startPt)); + marks.Codes.AddRange(ConvertShapeToMoves(shape, startPt, LayerType.Scribe)); } + program.Codes.InsertRange(0, marks.Codes); + } + + // Where the head first goes in an absolute program: its first rapid's end, or the first + // move of a hole cut as a sub-program at its offset. Null when the program starts otherwise. + private static Vector? FirstArrival(Program program) + { + foreach (var code in program.Codes) + { + if (code is RapidMove rapid) + return rapid.EndPoint; + if (code is SubProgramCall call) + return call.Program?.Codes.FirstOrDefault() is Motion first && call.Rotation == 0 + ? call.Offset + first.EndPoint + : call.Offset; + if (code is Motion) + return null; + } + return null; + } + + // Past this many marks the start search (quadratic per start) is skipped and the + // nearest-neighbor tour starts from the first mark. + private const int ScribeStartSearchLimit = 200; + + /// + /// Orders a part's scribe marks to shorten the rapids between them, and from the last of + /// them to (where the first cut starts) when it is known: a + /// nearest-neighbor tour, tried from every mark and either end of it, keeping the + /// shortest. An open mark + /// may be etched from either end; a closed one starts where it was drawn. Ties keep the + /// drawn order, so the result is deterministic. Reversed marks are copies, never the + /// caller's entities. + /// + internal static List SequenceScribes(IReadOnlyList shapes, Vector? next = null) + { + var count = shapes.Count; + if (count == 0) + return new List(); + + var starts = new Vector[count]; + var ends = new Vector[count]; + var open = new bool[count]; + for (var i = 0; i < count; i++) + { + starts[i] = GetShapeStartPoint(shapes[i]); + ends[i] = GetShapeEndPoint(shapes[i]); + open[i] = starts[i].DistanceTo(ends[i]) > Tolerance.Epsilon; + } + + (List<(int Index, bool Reversed)> Tour, double Travel) Tour(int first, bool firstReversed) + { + var used = new bool[count]; + var tour = new List<(int, bool)>(count) { (first, firstReversed) }; + used[first] = true; + var position = firstReversed ? starts[first] : ends[first]; + var travel = 0.0; + for (var step = 1; step < count; step++) + { + var best = -1; + var bestReversed = false; + var bestDistance = double.MaxValue; + for (var i = 0; i < count; i++) + { + if (used[i]) + continue; + var forward = position.DistanceTo(starts[i]); + if (forward < bestDistance) + { + best = i; + bestReversed = false; + bestDistance = forward; + } + if (!open[i]) + continue; + var backward = position.DistanceTo(ends[i]); + if (backward < bestDistance) + { + best = i; + bestReversed = true; + bestDistance = backward; + } + } + used[best] = true; + tour.Add((best, bestReversed)); + travel += bestDistance; + position = bestReversed ? starts[best] : ends[best]; + } + if (next is { } target) + travel += position.DistanceTo(target); + return (tour, travel); + } + + var bestTour = Tour(0, false); + if (count <= ScribeStartSearchLimit) + for (var first = 0; first < count; first++) + for (var reversed = 0; reversed < (open[first] ? 2 : 1); reversed++) + { + var candidate = Tour(first, reversed == 1); + if (candidate.Travel < bestTour.Travel - Tolerance.Epsilon) + bestTour = candidate; + } + + var ordered = new List(count); + foreach (var (index, reversed) in bestTour.Tour) + { + if (!reversed) + { + ordered.Add(shapes[index]); + continue; + } + var copy = (Shape)shapes[index].Clone(); + copy.Reverse(); + ordered.Add(copy); + } + return ordered; } private List SequenceCutouts(List cutouts, Vector startPoint) @@ -1876,5 +1994,15 @@ namespace OpenNest.CNC.CuttingStrategy return new Vector(circle.Center.X + circle.Radius, circle.Center.Y); return Vector.Zero; } + + private static Vector GetShapeEndPoint(Shape shape) + { + var last = shape.Entities[shape.Entities.Count - 1]; + if (last is Line line) + return line.EndPoint; + if (last is Arc arc) + return arc.EndPoint(); + return GetShapeStartPoint(shape); + } } } diff --git a/OpenNest.Core/Labels/PartLabels.cs b/OpenNest.Core/Labels/PartLabels.cs index 03596efb..d63e5660 100644 --- a/OpenNest.Core/Labels/PartLabels.cs +++ b/OpenNest.Core/Labels/PartLabels.cs @@ -96,7 +96,7 @@ namespace OpenNest.Labels /// /// The etch strokes of 's label for a part placed at - /// , as polylines in the drawing's program frame turned with + /// , as paths of lines and arcs in the drawing's program frame turned with /// the part (the frame Part.Program is in before it is located). Null when the drawing /// has no valid box, no text, or the text cannot be shrunk to fit the box legibly. /// @@ -105,7 +105,7 @@ namespace OpenNest.Labels /// less when the text is longer than the box: it is shrunk to fit, to /// of the box height at the least. /// - public static List> Strokes(Drawing drawing, double partRotation, double grainAngle, + public static List Strokes(Drawing drawing, double partRotation, double grainAngle, PartLabelMode mode = PartLabelMode.PartNumberAndBendGroups) { var box = drawing?.LabelBox; @@ -128,15 +128,12 @@ namespace OpenNest.Labels return null; var offset = drawing.Source?.Offset ?? Vector.Zero; - var strokes = StrokeFont.Strokes(text, height); - foreach (var stroke in strokes) - for (var i = 0; i < stroke.Count; i++) - { - var local = new Vector(stroke[i].X - width / 2, stroke[i].Y - height / 2); - // The source frame loses the program's offset, then turns with the part, as bends do. - var point = box.ToWorld(local) - offset; - stroke[i] = partRotation == 0 ? point : point.Rotate(partRotation); - } + // The source frame loses the program's offset, then turns with the part, as bends do. + var strokes = StrokeFont.Strokes(text, height).ConvertAll(stroke => stroke.Map(point => + { + var world = box.ToWorld(new Vector(point.X - width / 2, point.Y - height / 2)) - offset; + return partRotation == 0 ? world : world.Rotate(partRotation); + })); return strokes; } @@ -148,8 +145,8 @@ namespace OpenNest.Labels /// /// /// The strokes are points in the program's frame. An incremental program (every imported - /// drawing's) takes each move as a step from the last, so the moves are written as steps - /// from where the program stops. + /// drawing's) takes each move, and each arc's center, as a step from where the move starts, + /// so the moves are written as steps from where the program stops. /// public static bool AddTo(Program program, Drawing drawing, double partRotation, double grainAngle, PartLabelMode mode = PartLabelMode.PartNumberAndBendGroups) @@ -171,12 +168,23 @@ namespace OpenNest.Labels foreach (var stroke in strokes) { - if (stroke.Count < 2) + if (stroke.Segments.Count == 0) continue; - program.Codes.Add(new RapidMove(To(stroke[0]))); - for (var i = 1; i < stroke.Count; i++) - program.Codes.Add(new LinearMove(To(stroke[i])) { Layer = LayerType.Scribe }); + program.Codes.Add(new RapidMove(To(stroke.Start))); + foreach (var segment in stroke.Segments) + { + if (!segment.IsArc) + { + program.Codes.Add(new LinearMove(To(segment.End)) { Layer = LayerType.Scribe }); + continue; + } + // An incremental arc's center is a step from where the arc starts, as its end is. + var center = incremental ? segment.Center - position : segment.Center; + program.Codes.Add(new ArcMove(To(segment.End), center, + segment.Clockwise ? RotationType.CW : RotationType.CCW) + { Layer = LayerType.Scribe }); + } } return true; diff --git a/OpenNest.Core/Labels/Stroke.cs b/OpenNest.Core/Labels/Stroke.cs new file mode 100644 index 00000000..71f0384a --- /dev/null +++ b/OpenNest.Core/Labels/Stroke.cs @@ -0,0 +1,94 @@ +using System; +using System.Collections.Generic; +using OpenNest.Geometry; +using OpenNest.Math; + +namespace OpenNest.Labels +{ + /// + /// One segment of a : a straight line or an arc to . + /// An arc turns about , clockwise when is set, + /// and is always less than a full turn. + /// + public readonly record struct StrokeSegment(Vector End, bool IsArc = false, Vector Center = default, + bool Clockwise = false); + + /// A pen-down path of a single-stroke label: a start point and its segments. + public sealed class Stroke + { + // Arcs are sampled at most this many radians apart by Points. + private const double SampleStep = System.Math.PI / 36; + + public Stroke(Vector start) => Start = start; + + public Vector Start { get; } + + public List Segments { get; } = new(); + + /// Where the stroke ends: its last segment's end, or its start without segments. + public Vector End => Segments.Count == 0 ? Start : Segments[Segments.Count - 1].End; + + /// + /// The stroke with every point moved by , which must be a rigid + /// motion (a turn and a shift, never a mirror) or arcs keep the wrong direction. + /// + public Stroke Map(Func map) + { + var mapped = new Stroke(map(Start)); + foreach (var segment in Segments) + mapped.Segments.Add(segment with + { + End = map(segment.End), + Center = segment.IsArc ? map(segment.Center) : segment.Center, + }); + return mapped; + } + + /// + /// The stroke's points, with arcs sampled finely enough to bound it: for measuring and + /// drawing, not for etching. + /// + public IEnumerable Points() + { + yield return Start; + var position = Start; + foreach (var segment in Segments) + { + if (segment.IsArc) + { + var radius = segment.Center.DistanceTo(position); + var from = PortableMath.Atan2(position.Y - segment.Center.Y, position.X - segment.Center.X); + var sweep = Sweep(position, segment); + var steps = System.Math.Max(1, (int)System.Math.Ceiling(System.Math.Abs(sweep) / SampleStep)); + for (var step = 1; step < steps; step++) + { + var angle = from + sweep * step / steps; + yield return new Vector(segment.Center.X + radius * PortableMath.Cos(angle), + segment.Center.Y + radius * PortableMath.Sin(angle)); + } + } + yield return segment.End; + position = segment.End; + } + } + + // The signed sweep of an arc from start to its end: negative clockwise, never zero. + private static double Sweep(Vector start, StrokeSegment arc) + { + var from = PortableMath.Atan2(start.Y - arc.Center.Y, start.X - arc.Center.X); + var to = PortableMath.Atan2(arc.End.Y - arc.Center.Y, arc.End.X - arc.Center.X); + var sweep = to - from; + if (arc.Clockwise) + { + while (sweep >= -Tolerance.Epsilon) + sweep -= Angle.TwoPI; + } + else + { + while (sweep <= Tolerance.Epsilon) + sweep += Angle.TwoPI; + } + return sweep; + } + } +} diff --git a/OpenNest.Core/Labels/StrokeFont.cs b/OpenNest.Core/Labels/StrokeFont.cs index ef3a8b5e..a6b7e512 100644 --- a/OpenNest.Core/Labels/StrokeFont.cs +++ b/OpenNest.Core/Labels/StrokeFont.cs @@ -1,11 +1,13 @@ using System.Collections.Generic; using OpenNest.Geometry; +using OpenNest.Math; namespace OpenNest.Labels { /// /// A small built-in single-stroke font for etched labels: digits, capital letters and a few - /// marks, drawn as polylines. It needs no font file, so the same text etches on every machine. + /// marks, drawn as lines and arcs (the digits' bowls are round). It needs no font file, so the + /// same text etches on every machine. /// /// /// A glyph is drawn on a grid four wide and eight tall; at a character height of 1 a glyph is @@ -25,19 +27,26 @@ namespace OpenNest.Labels /// The distance from one character's start to the next, as a share of the character height. public const double Advance = GridAdvance / GridHeight; - // Each glyph is a list of strokes; each stroke is x,y pairs on the grid. - private static readonly Dictionary Glyphs = new() + private const double Root2 = 1.4142135623730951; + private const double Root3 = 1.7320508075688772; + private const bool Cw = true; + private const bool Ccw = false; + + // Each glyph is a list of strokes on the grid: polylines (P, x,y pairs) or paths of lines and arcs (S). + private static readonly Dictionary Glyphs = new() { - ['0'] = new[] { P(0, 0, 4, 0, 4, 8, 0, 8, 0, 0), P(0, 0, 4, 8) }, + // The round digits are drawn on circles of radius 2 centered at (2, 2) and (2, 6). + ['0'] = new[] { S(0, 2).L(0, 6).Arc(2, 6, 0, Cw).L(4, 2).Arc(2, 2, 180, Cw), + S(2 - Root2, 2 - Root2).L(2 + Root2, 6 + Root2) }, ['1'] = new[] { P(1, 6, 2, 8, 2, 0), P(1, 0, 3, 0) }, - ['2'] = new[] { P(0, 7, 1, 8, 3, 8, 4, 7, 4, 5, 0, 0, 4, 0) }, - ['3'] = new[] { P(0, 7, 1, 8, 3, 8, 4, 7, 4, 5, 3, 4, 1, 4), P(3, 4, 4, 3, 4, 1, 3, 0, 1, 0, 0, 1) }, + ['2'] = new[] { S(2 - Root3, 7).Arc(2, 6, -30, Cw).L(0, 0).L(4, 0) }, + ['3'] = new[] { S(2 - Root3, 7).Arc(2, 6, -90, Cw).Arc(2, 2, -150, Cw) }, ['4'] = new[] { P(3, 0, 3, 8, 0, 3, 4, 3) }, - ['5'] = new[] { P(4, 8, 0, 8, 0, 4, 3, 4, 4, 3, 4, 1, 3, 0, 1, 0, 0, 1) }, - ['6'] = new[] { P(4, 7, 3, 8, 1, 8, 0, 7, 0, 1, 1, 0, 3, 0, 4, 1, 4, 3, 3, 4, 0, 4) }, + ['5'] = new[] { S(4, 8).L(0, 8).L(0, 4).L(2, 4).Arc(2, 2, -150, Cw) }, + ['6'] = new[] { S(2 + Root2, 6 + Root2).Arc(2, 6, 180, Ccw).L(0, 2).Arc(2, 2, 0, Ccw).Arc(2, 2, 180, Ccw) }, ['7'] = new[] { P(0, 8, 4, 8, 1, 0) }, - ['8'] = new[] { P(1, 4, 0, 5, 0, 7, 1, 8, 3, 8, 4, 7, 4, 5, 3, 4, 1, 4, 0, 3, 0, 1, 1, 0, 3, 0, 4, 1, 4, 3, 3, 4) }, - ['9'] = new[] { P(0, 1, 1, 0, 3, 0, 4, 1, 4, 7, 3, 8, 1, 8, 0, 7, 0, 5, 1, 4, 4, 4) }, + ['8'] = new[] { S(2, 4).Arc(2, 6, 90, Ccw).Arc(2, 6, -90, Ccw).Arc(2, 2, -90, Cw).Arc(2, 2, 90, Cw) }, + ['9'] = new[] { S(2 - Root2, 2 - Root2).Arc(2, 2, 0, Ccw).L(4, 6).Arc(2, 6, 180, Ccw).Arc(2, 6, 0, Ccw) }, ['-'] = new[] { P(0, 4, 4, 4) }, ['_'] = new[] { P(0, 0, 4, 0) }, ['.'] = new[] { P(1.5, 0, 2.5, 0) }, @@ -70,7 +79,50 @@ namespace OpenNest.Labels ['Z'] = new[] { P(0, 8, 4, 8, 0, 0, 4, 0) }, }; - private static double[] P(params double[] coordinates) => coordinates; + private static GlyphStroke S(double x, double y) => new(x, y); + + private static GlyphStroke P(params double[] coordinates) + { + var stroke = S(coordinates[0], coordinates[1]); + for (var i = 2; i + 1 < coordinates.Length; i += 2) + stroke.L(coordinates[i], coordinates[i + 1]); + return stroke; + } + + // A glyph stroke on the grid, built from its start by straight lines and arcs. + private sealed class GlyphStroke + { + private readonly Stroke stroke; + private Vector position; + + public GlyphStroke(double x, double y) + { + position = new Vector(x, y); + stroke = new Stroke(position); + } + + public GlyphStroke L(double x, double y) + { + position = new Vector(x, y); + stroke.Segments.Add(new StrokeSegment(position)); + return this; + } + + // An arc about (cx, cy) from where the stroke is to the point at endDegrees on the + // same circle; the stroke must already be on it. + public GlyphStroke Arc(double cx, double cy, double endDegrees, bool clockwise) + { + var center = new Vector(cx, cy); + var radius = center.DistanceTo(position); + var angle = Angle.ToRadians(endDegrees); + position = new Vector(cx + radius * PortableMath.Cos(angle), cy + radius * PortableMath.Sin(angle)); + stroke.Segments.Add(new StrokeSegment(position, true, center, clockwise)); + return this; + } + + public Stroke Place(double left, double scale) => + stroke.Map(point => new Vector((left + point.X) * scale, point.Y * scale)); + } /// True when the font draws (case ignored). public static bool Has(char character) => Glyphs.ContainsKey(char.ToUpperInvariant(character)); @@ -84,12 +136,12 @@ namespace OpenNest.Labels } /// - /// The strokes of at , as polylines with - /// the text's lower left at the origin and reading along +X. + /// The strokes of at , as paths of lines + /// and arcs with the text's lower left at the origin and reading along +X. /// - public static List> Strokes(string text, double height) + public static List Strokes(string text, double height) { - var strokes = new List>(); + var strokes = new List(); if (string.IsNullOrEmpty(text)) return strokes; @@ -100,13 +152,8 @@ namespace OpenNest.Labels continue; var left = index * GridAdvance; - foreach (var coordinates in glyph) - { - var stroke = new List(coordinates.Length / 2); - for (var i = 0; i + 1 < coordinates.Length; i += 2) - stroke.Add(new Vector((left + coordinates[i]) * scale, coordinates[i + 1] * scale)); - strokes.Add(stroke); - } + foreach (var stroke in glyph) + strokes.Add(stroke.Place(left, scale)); } return strokes; diff --git a/OpenNest.Tests/CuttingPlanning/ScribeSequenceTests.cs b/OpenNest.Tests/CuttingPlanning/ScribeSequenceTests.cs new file mode 100644 index 00000000..c52f0c51 --- /dev/null +++ b/OpenNest.Tests/CuttingPlanning/ScribeSequenceTests.cs @@ -0,0 +1,75 @@ +using OpenNest.CNC.CuttingStrategy; +using OpenNest.Geometry; + +namespace OpenNest.Tests.CuttingPlanning; + +/// +/// A part's scribe marks are etched in a short tour: the marks on one side of the part before +/// the ones on the other, an open mark from whichever end is nearer. +/// +public class ScribeSequenceTests +{ + private static Shape Mark(double x1, double y1, double x2, double y2) + { + var shape = new Shape(); + shape.Entities.Add(new Line(new Vector(x1, y1), new Vector(x2, y2))); + return shape; + } + + private static double Travel(IReadOnlyList marks) + { + var travel = 0.0; + for (var i = 1; i < marks.Count; i++) + { + var end = ((Line)marks[i - 1].Entities[^1]).EndPoint; + travel += end.DistanceTo(((Line)marks[i].Entities[0]).StartPoint); + } + return travel; + } + + // Two bends 5 apart across a 40-wide part, each etched at both edges: drawn bend by bend, + // the marks cross the part three times; sequenced, they cross it once. + [Fact] + public void BendEtches_AreEtchedOneSideThenTheOther() + { + var drawn = new List + { + Mark(0, 5, 0.5, 5), Mark(39.5, 5, 40, 5), + Mark(0, 10, 0.5, 10), Mark(39.5, 10, 40, 10), + }; + + var ordered = ContourCuttingStrategy.SequenceScribes(drawn); + + Assert.Equal(4, ordered.Count); + var sides = ordered.Select(m => ((Line)m.Entities[0]).StartPoint.X < 20).ToList(); + Assert.Equal(1, sides.Zip(sides.Skip(1)).Count(pair => pair.First != pair.Second)); + Assert.True(Travel(ordered) < Travel(drawn)); + // Reversed marks are copies: the drawn entities are untouched. + Assert.Equal(new Vector(0, 5), ((Line)drawn[0].Entities[0]).StartPoint); + } + + // PT56: a bend mark at each end of two bends on an 80-long part, cut from its right end. + // Etching the right end first then the left leaves a rapid back across the part. + [Fact] + public void BendEtches_EndNearWhereTheCutStarts() + { + var drawn = new List + { + Mark(0, 5, 1, 5), Mark(79, 5, 80, 5), + Mark(0, 8, 1, 8), Mark(79, 8, 80, 8), + }; + + var ordered = ContourCuttingStrategy.SequenceScribes(drawn, new Vector(80, 6)); + + Assert.All(ordered.Take(2), m => Assert.True(((Line)m.Entities[0]).StartPoint.X < 40)); + Assert.All(ordered.Skip(2), m => Assert.True(((Line)m.Entities[0]).StartPoint.X > 40)); + } + + [Fact] + public void SingleMark_IsKept() + { + var mark = Mark(0, 0, 1, 0); + Assert.Same(mark, Assert.Single(ContourCuttingStrategy.SequenceScribes(new[] { mark }))); + Assert.Empty(ContourCuttingStrategy.SequenceScribes(Array.Empty())); + } +} diff --git a/OpenNest.Tests/Labels/PartLabelTests.cs b/OpenNest.Tests/Labels/PartLabelTests.cs index 4cc6b1de..6fe2dd90 100644 --- a/OpenNest.Tests/Labels/PartLabelTests.cs +++ b/OpenNest.Tests/Labels/PartLabelTests.cs @@ -49,9 +49,9 @@ public class PartLabelTests public double Top => Bottom + Height; } - private static Bounds BoundsOf(IEnumerable> strokes) + private static Bounds BoundsOf(IEnumerable strokes) { - var points = strokes.SelectMany(s => s).ToList(); + var points = strokes.SelectMany(s => s.Points()).ToList(); var minX = points.Min(p => p.X); var minY = points.Min(p => p.Y); return new Bounds(minX, minY, points.Max(p => p.X) - minX, points.Max(p => p.Y) - minY); @@ -67,7 +67,7 @@ public class PartLabelTests Assert.True(StrokeFont.Has(character), character.ToString()); var strokes = StrokeFont.Strokes(character.ToString(), 1); Assert.NotEmpty(strokes); - Assert.All(strokes, s => Assert.True(s.Count >= 2)); + Assert.All(strokes, s => Assert.NotEmpty(s.Segments)); var bounds = BoundsOf(strokes); Assert.InRange(bounds.Left, -1e-9, StrokeFont.GlyphWidth + 1e-9); Assert.InRange(bounds.Right, -1e-9, StrokeFont.GlyphWidth + 1e-9); @@ -76,6 +76,26 @@ public class PartLabelTests } } + [Fact] + public void Font_DrawsTheRoundDigitsWithArcs_AndEachStrokeIsContinuous() + { + foreach (var character in "0235689") + Assert.Contains(StrokeFont.Strokes(character.ToString(), 1), s => s.Segments.Any(g => g.IsArc)); + Assert.DoesNotContain(StrokeFont.Strokes("147", 1), s => s.Segments.Any(g => g.IsArc)); + + // Every arc keeps its radius from start to end, so its move stays on its circle. + foreach (var stroke in StrokeFont.Strokes("0123456789", 1)) + { + var position = stroke.Start; + foreach (var segment in stroke.Segments) + { + if (segment.IsArc) + Assert.Equal(segment.Center.DistanceTo(position), segment.Center.DistanceTo(segment.End), 9); + position = segment.End; + } + } + } + [Fact] public void Font_AdvanceMatchesTheLabelBoxSizing_AndLowercaseIsCapitals() { @@ -241,7 +261,9 @@ public class PartLabelTests var added = program.Codes.Skip(before).ToList(); Assert.IsType(added[0]); Assert.All(added.OfType(), move => Assert.Equal(LayerType.Scribe, move.Layer)); - Assert.True(added.OfType().Count() > 10); + Assert.All(added.OfType(), move => Assert.Equal(LayerType.Scribe, move.Layer)); + Assert.True(added.OfType().Count() > 5); + Assert.NotEmpty(added.OfType()); var untouched = (Program)drawing.Program.Clone(); drawing.LabelBox = null; @@ -264,8 +286,10 @@ public class PartLabelTests Assert.True(PartLabels.AddTo(incremental, drawing, Quarter, 0)); incremental.Mode = Mode.Absolute; - var expected = absolute.Codes.Skip(before).OfType().Select(m => m.EndPoint).ToList(); - var actual = incremental.Codes.Skip(before).OfType().Select(m => m.EndPoint).ToList(); + var expected = absolute.Codes.Skip(before).OfType().Select(m => m.EndPoint) + .Concat(absolute.Codes.Skip(before).OfType().Select(m => m.CenterPoint)).ToList(); + var actual = incremental.Codes.Skip(before).OfType().Select(m => m.EndPoint) + .Concat(incremental.Codes.Skip(before).OfType().Select(m => m.CenterPoint)).ToList(); Assert.Equal(expected.Count, actual.Count); for (var i = 0; i < expected.Count; i++) { diff --git a/docs/label-box.md b/docs/label-box.md index e86dd31f..3266af84 100644 --- a/docs/label-box.md +++ b/docs/label-box.md @@ -92,15 +92,20 @@ A `labelMode` number that names no choice (the reader accepts numbers) loads as rotated on the sheet, which is why the text is made when cutting is planned, not stored with the box. - **Font.** `StrokeFont` is a small built-in single-stroke font (digits, capitals, `- _ . /`), so - the label needs no font file. The CHR reader (`ChrFont`) loads vendor fonts from disk and is not - used. + the label needs no font file. Strokes are lines and arcs: the round digits (0, 2, 3, 5, 6, 8, 9) + are drawn on arcs and etch as arc moves; the zero keeps its slash so it never reads as the letter + O. The CHR reader (`ChrFont`) loads vendor fonts from disk and is not used. - **Fit.** The text is centered in the box and reads along it at the box's height. A name longer than the box is shrunk to fit, to half the box height at the least; a longer one is not etched. The text turns with the part, so it can read upside down or sideways on the sheet. - **Frames.** The box and the bends are in the source frame: the program's offset (`Drawing.Source.Offset`) comes off, then the part's rotation applies, as `BendToWorld` does. - Imported drawings are incremental programs, so the strokes are written as steps from where the - program stops, not as absolute points. + Imported drawings are incremental programs, so the strokes (and arc centers) are written as steps + from where the program stops, not as absolute points. +- **Etch order.** A part's marks (label strokes and bend etches alike) are etched before its cuts in + one short tour: tried from every mark, each open mark from either end, ending as near as it can + to where the part's first cut starts. Bend etches on one side of a part are done together before + the head crosses to the other side (`ContourCuttingStrategy.SequenceScribes`). - **Reopening.** The label lives only in the applied part programs. Loading a nest never takes it back into the drawing as a lost etch mark (`DrawingMarkRecovery` skips drawings with a label box), so it is not etched twice and turning the option off removes it at the next plan.