using System.Collections.Generic;
using OpenNest.CutOffs;
using OpenNest.Geometry;
namespace OpenNest.Desktop.Interaction;
///
/// The WinForms Select Area action behind Tools > Measure Area, toolkit-neutral: as the pointer
/// moves, is the largest empty box around it inside the plate's work area,
/// clear of the parts (their bounding boxes grown by the part spacing) and the cut-off lines.
/// The box grows up and down first, then sideways; Space () grows
/// it sideways first instead. The tool stays active until Escape.
///
public sealed class MeasureAreaTool : PlateTool
{
private readonly List obstacles = new();
private Box bounds;
private Vector? lastPoint;
public MeasureAreaTool(IPlateToolHost host)
: base(host)
{
Collect();
}
public override string Name => "Measure Area";
public override bool IsBusy => false;
/// Whether the box grows sideways first (Space toggles it).
public bool Horizontal { get; private set; }
/// The box measured at the pointer, or null when there is none.
public Box Area { get; private set; }
/// The box's size as WinForms labels it (its to two decimals), or null.
public string Label => Area?.Size.ToString(2);
public override void Cancel() => Host.Invalidate();
public override bool PointerMoved(ToolPointer pointer)
{
lastPoint = pointer.World;
Update();
return true;
}
/// Space: switches which way the box grows first, at the pointer's last point.
public void ToggleDirection()
{
Horizontal = !Horizontal;
Update();
}
private void Update()
{
if (bounds == null || lastPoint is not { } point)
Area = null;
else
{
var area = Horizontal
? SpatialQuery.GetLargestBoxHorizontally(point, bounds, obstacles)
: SpatialQuery.GetLargestBoxVertically(point, bounds, obstacles);
Area = ReferenceEquals(area, Box.Empty) ? null : area;
}
Host.Invalidate();
}
// Read once when the tool starts, as WinForms: the parts and cut-offs the box must clear.
private void Collect()
{
var plate = Host.Plate;
if (plate == null)
return;
foreach (var part in plate.Parts)
{
if (part.BaseDrawing.IsCutOff)
continue;
obstacles.Add(part.BoundingBox.Offset(plate.PartSpacing));
}
// A cut-off part's bounds span from the plate origin (its program is absolute), so each
// cut-off is a thin box along its line, from its definition.
var plateBounds = plate.BoundingBox(includeParts: false);
foreach (var cutOff in plate.CutOffs)
{
var line = cutOff.Axis == CutOffAxis.Vertical
? new Box(cutOff.Position.X, plateBounds.Y, 0, plateBounds.Width)
: new Box(plateBounds.X, cutOff.Position.Y, plateBounds.Length, 0);
obstacles.Add(line.Offset(plate.PartSpacing));
}
bounds = plate.WorkArea();
}
}