diff --git a/OpenNest.Core/Labels/LabelBox.cs b/OpenNest.Core/Labels/LabelBox.cs index 2ea9e2ef..2f314d6f 100644 --- a/OpenNest.Core/Labels/LabelBox.cs +++ b/OpenNest.Core/Labels/LabelBox.cs @@ -42,6 +42,26 @@ namespace OpenNest.Labels public LabelBox Clone() => new(Center, Width, Height, Rotation); + /// + /// The same box turned by instead, kept readable: a half turn + /// covers the same rectangle, so text is never turned past a quarter (upside down). + /// + public LabelBox WithRotation(double rotation) => new(Center, Width, Height, ReadableRotation(rotation)); + + /// + /// brought into (-π/2, π/2] by half turns, so text along it reads + /// left to right or bottom to top; a nonfinite value is returned as is. + /// + public static double ReadableRotation(double rotation) + { + if (!double.IsFinite(rotation)) + return rotation; + var turned = System.Math.IEEERemainder(rotation, System.Math.PI); + if (turned <= -Angle.HalfPI + Tolerance.Epsilon) + turned += System.Math.PI; + return System.Math.Abs(turned) < Tolerance.Epsilon ? 0 : turned; + } + /// The corners counterclockwise from the text's lower left. public Vector[] Corners() { diff --git a/OpenNest.Tests/Labels/LabelBoxRotationTests.cs b/OpenNest.Tests/Labels/LabelBoxRotationTests.cs new file mode 100644 index 00000000..e0b75d81 --- /dev/null +++ b/OpenNest.Tests/Labels/LabelBoxRotationTests.cs @@ -0,0 +1,40 @@ +using OpenNest.Geometry; +using OpenNest.Labels; + +namespace OpenNest.Tests.Labels; + +public class LabelBoxRotationTests +{ + [Theory] + [InlineData(0, 0)] + [InlineData(30, 30)] + [InlineData(90, 90)] + [InlineData(-90, 90)] + [InlineData(120, -60)] + [InlineData(180, 0)] + [InlineData(-135, 45)] + [InlineData(270, 90)] + [InlineData(405, 45)] + public void ReadableRotation_KeepsTextFromReadingUpsideDown(double degrees, double expected) + { + var turned = LabelBox.ReadableRotation(degrees * System.Math.PI / 180); + Assert.Equal(expected, turned * 180 / System.Math.PI, 9); + } + + [Fact] + public void WithRotation_CoversTheSameRectangleAsTheHalfTurn() + { + var box = new LabelBox(new Vector(3, 4), 2, 0.5, 0); + var turned = box.WithRotation(System.Math.PI * 1.25); + + Assert.Equal(System.Math.PI / 4, turned.Rotation, 9); + Assert.Equal(box.Center, turned.Center); + var halfTurn = new LabelBox(box.Center, 2, 0.5, System.Math.PI * 1.25).Corners(); + foreach (var corner in turned.Corners()) + Assert.Contains(halfTurn, c => c.DistanceTo(corner) < 1e-9); + } + + [Fact] + public void ReadableRotation_PassesNonfiniteThrough() => + Assert.True(double.IsNaN(LabelBox.ReadableRotation(double.NaN))); +} diff --git a/OpenNest.WinForms.Tests/Forms/CadConverterLabelBoxTests.cs b/OpenNest.WinForms.Tests/Forms/CadConverterLabelBoxTests.cs index 7e7e6a3e..58ca05d7 100644 --- a/OpenNest.WinForms.Tests/Forms/CadConverterLabelBoxTests.cs +++ b/OpenNest.WinForms.Tests/Forms/CadConverterLabelBoxTests.cs @@ -73,20 +73,88 @@ public class CadConverterLabelBoxTests }); [Fact] - public void NoRoom_ExplainsAndLeavesNoBox() => ArchUnitsTests.RunSta(() => + public void NoRoom_PlacesAFullSizeBoxOnTheRoomiestSpotToAdjustByHand() => ArchUnitsTests.RunSta(() => { using var form = new LabelTestForm(); Show(form); form.LoadDrawings([Part(1, 0.5)]); + var view = Field(form, "entityView1"); var item = Field(form, "fileList").SelectedItem!; Invoke(form, "OnLabelBoxClick", null, EventArgs.Empty); - Assert.Null(item.LabelBox); + var box = item.LabelBox!; + var full = LabelBoxOptions.Default(Units.Inches); + Assert.Equal(full.Width, box.Width, 6); + Assert.Equal(full.Height, box.Height, 6); + Assert.Equal(0.5, box.Center.X, 3); + Assert.Equal(0.25, box.Center.Y, 3); + Assert.NotNull(view.LabelBox); + Assert.Contains("adjust", Assert.Single(form.Messages)); + form.Close(); + }); + + [Fact] + public void NoRoomOnABentTab_StartsTheBoxOnAFlangeNotTheBendLine() => ArchUnitsTests.RunSta(() => + { + // A small angle like 4980 A01 PT103: 2.04 x 1, bent up the middle. + using var form = new LabelTestForm(); + Show(form); + form.LoadDrawings([Part(2.04, 1, [new Bend { StartPoint = new Vector(1.02, 0), EndPoint = new Vector(1.02, 1) }])]); + var item = Field(form, "fileList").SelectedItem!; + + Invoke(form, "OnLabelBoxClick", null, EventArgs.Empty); + + var center = item.LabelBox!.Center; + Assert.True(System.Math.Abs(center.X - 1.02) > 0.25, $"Box centered at {center.X} sits on the bend line."); Assert.Single(form.Messages); form.Close(); }); + [Fact] + public void DraggingTheRotateHandle_TurnsTheBoxAboutItsCenter_InFiveDegreeSteps() => ArchUnitsTests.RunSta(() => + { + using var form = new LabelTestForm(); + Show(form); + form.LoadDrawings([Part(10, 6)]); + var view = Field(form, "entityView1"); + var item = Field(form, "fileList").SelectedItem!; + Invoke(form, "OnLabelBoxClick", null, EventArgs.Empty); + var before = item.LabelBox!.Clone(); + Assert.Equal(0, before.Rotation, 9); + + // The knob sits straight above the center; drag it to 31 degrees left of straight up. + var knob = view.PointWorldToControl(before.ToWorld(new Vector(0, before.Height / 2))) - new System.Drawing.Size(0, 18); + var angle = 31 * System.Math.PI / 180; + var target = new Vector(before.Center.X - 2 * System.Math.Sin(angle), before.Center.Y + 2 * System.Math.Cos(angle)); + Mouse(view, "OnMouseDown", knob); + Mouse(view, "OnMouseMove", view.PointWorldToControl(target)); + Mouse(view, "OnMouseUp", view.PointWorldToControl(target)); + + var after = item.LabelBox!; + Assert.Equal(30, after.Rotation * 180 / System.Math.PI, 6); + Assert.Equal(before.Center, after.Center); + Assert.Equal(before.Width, after.Width, 9); + Assert.Equal(before.Height, after.Height, 9); + form.Close(); + }); + + [Fact] + public void RotateNinety_TurnsAQuarterAndBackWithoutGoingUpsideDown() => ArchUnitsTests.RunSta(() => + { + using var form = new LabelTestForm(); + Show(form); + form.LoadDrawings([Part(10, 6)]); + var item = Field(form, "fileList").SelectedItem!; + Invoke(form, "OnLabelBoxClick", null, EventArgs.Empty); + + Invoke(form, "TurnLabelBox", (Func)(b => b.Rotation + System.Math.PI / 2)); + Assert.Equal(System.Math.PI / 2, item.LabelBox!.Rotation, 9); + Invoke(form, "TurnLabelBox", (Func)(b => b.Rotation + System.Math.PI / 2)); + Assert.Equal(0, item.LabelBox!.Rotation, 9); + form.Close(); + }); + [Fact] public void ABendLine_IsKeptClear() => ArchUnitsTests.RunSta(() => { diff --git a/OpenNest/Controls/EntityView.LabelBox.cs b/OpenNest/Controls/EntityView.LabelBox.cs index a3b4b40d..977633e3 100644 --- a/OpenNest/Controls/EntityView.LabelBox.cs +++ b/OpenNest/Controls/EntityView.LabelBox.cs @@ -4,6 +4,7 @@ using System.Drawing.Drawing2D; using System.Linq; using System.Windows.Forms; using OpenNest.Geometry; +using OpenNest.Math; namespace OpenNest.Controls { @@ -11,21 +12,24 @@ namespace OpenNest.Controls { private const int LabelBoxHandlePixels = 4; private const int LabelBoxMinimumPixels = 6; + private const int LabelBoxRotateHandlePixels = 18; + private const int RotateHandlePart = 4; + private static readonly double RotateSnap = Angle.ToRadians(5); 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. + // The grabbed corner (0-3, as Labels.LabelBox.Corners orders them), 4 for the rotate + // handle or -1 for the body; null when nothing is being dragged. private int? draggedLabelBoxPart; private Vector labelBoxGrab; private Labels.LabelBox labelBoxAtPress; /// /// Where the part number label would be etched, in world coordinates, drawn as a dashed - /// rectangle the user can move and resize; null draws nothing. + /// rectangle the user can move, resize and turn; null draws nothing. /// public Labels.LabelBox LabelBox { get; set; } - /// The label box was moved or resized; the argument is its new placement. + /// The label box was moved, resized or turned; the argument is its new placement. public event EventHandler LabelBoxChanged; private bool BeginLabelBoxDrag(Point location) @@ -41,29 +45,55 @@ namespace OpenNest.Controls private void EndLabelBoxDrag() => draggedLabelBoxPart = null; - // A corner handle first, then anywhere inside the box. + // The rotate handle, then a corner handle, then anywhere inside the box. private int? HitTestLabelBox(Point location) { if (LabelBox is not { IsValid: true } box) return null; + var reach = LabelBoxHandlePixels + 3; + bool Near(Vector world) + { + var at = PointWorldToControl(world); + return System.Math.Abs(at.X - location.X) <= reach && System.Math.Abs(at.Y - location.Y) <= reach; + } + + if (Near(RotateHandle(box))) + return RotateHandlePart; + 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) + if (Near(corners[i])) return i; } return box.Contains(PointControlToWorld(location)) ? -1 : null; } + // The knob above the middle of the box's top side (across the text from its baseline). + private Vector RotateHandle(Labels.LabelBox box) => + box.ToWorld(new Vector(0, box.Height / 2 + LengthGuiToWorld(LabelBoxRotateHandlePixels))); + private void RaiseLabelBoxDragged(Point location) { if (draggedLabelBoxPart is not { } part || labelBoxAtPress == null) return; var point = PointControlToWorld(location); + if (part == RotateHandlePart) + { + // The handle points from the center toward the pointer. It snaps to 5 degree steps + // unless Shift is held, and the text never turns past a quarter (upside down). + var toPointer = point - labelBoxAtPress.Center; + if (point.DistanceTo(labelBoxAtPress.Center) < Tolerance.Epsilon) + return; + var rotation = System.Math.Atan2(toPointer.Y, toPointer.X) - Angle.HalfPI; + if ((ModifierKeys & Keys.Shift) == 0) + rotation = System.Math.Round(rotation / RotateSnap) * RotateSnap; + LabelBoxChanged?.Invoke(this, labelBoxAtPress.WithRotation(rotation)); + return; + } + if (part < 0) { LabelBoxChanged?.Invoke(this, new Labels.LabelBox(point + labelBoxGrab, labelBoxAtPress.Width, @@ -84,7 +114,12 @@ namespace OpenNest.Controls width, height, labelBoxAtPress.Rotation)); } - private Cursor LabelBoxCursor(int part) => part < 0 ? Cursors.SizeAll : Cursors.SizeNWSE; + private Cursor LabelBoxCursor(int part) => part switch + { + < 0 => Cursors.SizeAll, + RotateHandlePart => Cursors.Hand, + _ => Cursors.SizeNWSE, + }; private void DrawLabelBox(Graphics g) { @@ -103,6 +138,14 @@ namespace OpenNest.Controls g.FillRectangle(handleBrush, point.X - LabelBoxHandlePixels, point.Y - LabelBoxHandlePixels, LabelBoxHandlePixels * 2, LabelBoxHandlePixels * 2); } + + // The rotate handle: a stem from the top side to a round knob. + var top = PointWorldToGraph(box.ToWorld(new Vector(0, box.Height / 2))); + var knob = PointWorldToGraph(RotateHandle(box)); + using var stem = new Pen(LabelBoxColor); + g.DrawLine(stem, top, knob); + g.FillEllipse(handleBrush, knob.X - LabelBoxHandlePixels, knob.Y - LabelBoxHandlePixels, + LabelBoxHandlePixels * 2, LabelBoxHandlePixels * 2); } } } diff --git a/OpenNest/Forms/CadConverterForm.LabelBox.cs b/OpenNest/Forms/CadConverterForm.LabelBox.cs index 47ec3e94..b06d25de 100644 --- a/OpenNest/Forms/CadConverterForm.LabelBox.cs +++ b/OpenNest/Forms/CadConverterForm.LabelBox.cs @@ -37,6 +37,9 @@ namespace OpenNest.Forms if (CurrentItem is { } item) FindLabelBox(item); }); + menu.Items.Add("Rotate 90°", null, (_, _) => TurnLabelBox(box => box.Rotation + Math.Angle.HalfPI)); + menu.Items.Add("Make Horizontal", null, (_, _) => TurnLabelBox(_ => 0)); + menu.Items.Add(new ToolStripSeparator()); menu.Items.Add("Remove", null, (_, _) => { if (CurrentItem is not { } item) @@ -47,9 +50,15 @@ namespace OpenNest.Forms return menu; } + // A label that does not fit is tried at these shares of its size, to find the roomiest + // flat spot to start a hand placement from. + private static readonly double[] FallbackLabelScales = { 0.75, 0.5, 0.25 }; + /// - /// 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. + /// Places the label box on the best flat area of the part as it will be cut. When the label + /// does not fit, a box is still placed for the user to adjust by hand: the full-size box + /// centered on the roomiest flat spot a smaller label fits, else on the middle of the part, + /// and the user is told so. /// internal void FindLabelBox(FileListItem item) { @@ -61,15 +70,54 @@ namespace OpenNest.Forms .Select(l => (System.Collections.Generic.IEnumerable)l.Scrap) .ToList(); - var box = LabelBoxFinder.Find(DimensionedEntities(item), item.Bends, LabelBoxOptions.Default(DrawingUnits), scrap); - if (box == null) + var entities = DimensionedEntities(item); + var options = LabelBoxOptions.Default(DrawingUnits); + var box = LabelBoxFinder.Find(entities, item.Bends, options, 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."); + item.LabelBox = box; + RefreshLabelBox(item); return; } - item.LabelBox = box; + var spot = FallbackLabelScales + .Select(scale => LabelBoxFinder.Find(entities, item.Bends, new LabelBoxOptions + { + Width = options.Width * scale, + Height = options.Height * scale, + Clearance = options.Clearance, + BendClearance = options.BendClearance, + }, scrap)) + .FirstOrDefault(b => b != null); + var center = spot?.Center ?? PartCenter(entities); + if (center == null) + { + ShowLabelBoxMessage("This part has no closed outline to put the part number label on."); + return; + } + + item.LabelBox = new LabelBox(center.Value, options.Width, options.Height, spot?.Rotation ?? 0); + RefreshLabelBox(item); + ShowLabelBoxMessage("No flat area of this part is big enough for the part number label, " + + "clear of its edges, holes and bend lines. A box has been placed " + + (spot != null ? "on the roomiest flat spot" : "in the middle of the part") + + " for you to adjust: drag its body to move it, a corner to resize it and the round " + + "handle to turn it. Label Box... > Remove leaves it off."); + } + + private static Geometry.Vector? PartCenter(System.Collections.Generic.List entities) + { + if (entities.Count == 0) + return null; + var bounds = Geometry.BoundingBox.GetBoundingBox(entities.Cast()); + return bounds.Width > 0 || bounds.Length > 0 ? bounds.Center : null; + } + + private void TurnLabelBox(Func rotation) + { + if (CurrentItem is not { LabelBox: { } box } item) + return; + item.LabelBox = box.WithRotation(rotation(box)); RefreshLabelBox(item); } diff --git a/docs/label-box.md b/docs/label-box.md index 3266af84..c7655a5a 100644 --- a/docs/label-box.md +++ b/docs/label-box.md @@ -6,10 +6,18 @@ placement; Plan Cutting etches the text when **Etch part label** is not Off (see [Etching the label](#etching-the-label)). 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. +The box is drawn as a dashed rectangle. Drag its body to move it, a corner to resize it +(the opposite corner stays put) and the round handle above its top side to turn it about its +center, in 5° steps or freely with Shift held. Once a box exists the button offers **Find Best +Location** again, **Rotate 90°**, **Make Horizontal** and **Remove**. However it is turned, the +angle is kept within a quarter turn either way of horizontal, so the text never reads upside +down (a half turn covers the same rectangle). + +When the label fits nowhere, the button still places a full-size box for hand placement and +says so: centered on the roomiest flat spot a smaller label (three quarters, half, then a +quarter of its size) fits clear of everything, at that spot's angle, or in the middle of the +part's bounds when even the smallest does not fit. The box may then overlap edges or bend +lines until it is moved or resized. ## Contract