using System;
using System.Collections.Generic;
using System.Linq;
using Clipper2Lib;
using OpenNest.Geometry;
namespace OpenNest.Engine.Jobs;
///
/// Interactive-path walls of an outlined sheet (): the part of the
/// plate's work area that is not usable material (a missing corner, an obstacle, each grown by
/// the outline's edge spacing), as static obstacles for the directional pushes. The rectangular
/// work area stays the pushes' own box test; these walls add only what the outline takes away
/// from it, so a rectangular sheet has none and its pushes are unchanged.
///
/// A moving part is measured by its true material, as the edge review confirms it against an
/// outline: the perimeter of its clean drawing material, without leads, slid with its arcs as
/// arcs, so a round part rests on a wall as it rests on the plate edge and that review passes.
/// A box push rests the box on the wall. A part that already lies in a wall, deeper than the
/// review's slack, is not held by it, like a part already overlapping another: it can be
/// pushed back out.
///
///
internal sealed class InteractiveOutline
{
/// How far inside the work area the walls are clipped. The usable area and the work
/// area meet along every straight run of the sheet's own box; on Clipper's grid they can
/// differ by a unit there, and a sliver that thin would sit under every part resting on the
/// plate edge. The box test already holds that edge.
private static readonly double EdgeClip = 2 * System.Math.Pow(10, -ClipperBridge.Precision);
private static readonly InteractiveOutline None = new(new List());
private readonly List walls;
private InteractiveOutline(List walls)
{
this.walls = walls;
}
/// True when the plate has no outline wall: every push is as it was.
public bool IsEmpty => walls.Count == 0;
///
/// The plate's walls in the parts' placement frame; none for a rectangular sheet. The
/// usable area is the outline less its obstacles, eroded by the largest edge spacing, as
/// the layout check and the Irregular engine take it.
///
public static InteractiveOutline Of(Plate plate)
{
var outline = plate?.Outline;
if (outline == null)
return None;
var sheet = plate.BoundingBox(includeParts: false);
var edges = plate.EdgeSpacing;
var inset = System.Math.Max(0, System.Math.Max(System.Math.Max(edges.Left, edges.Right),
System.Math.Max(edges.Top, edges.Bottom)));
var usable = outline.Usable(inset, new Vector(sheet.X, sheet.Y));
var work = plate.WorkArea();
var left = work.Left + EdgeClip;
var bottom = work.Bottom + EdgeClip;
var right = work.Right - EdgeClip;
var top = work.Top - EdgeClip;
if (!(right > left) || !(top > bottom))
return None;
var frame = new PathD
{
new PointD(left, bottom), new PointD(right, bottom), new PointD(right, top), new PointD(left, top),
};
var clipper = new ClipperD(ClipperBridge.Precision);
clipper.AddSubject(new PathsD { frame });
clipper.AddClip(usable);
var tree = new PolyTreeD();
clipper.Execute(ClipType.Difference, FillRule.NonZero, tree);
var walls = new List();
AddWalls(tree, walls);
return walls.Count == 0 ? None : new InteractiveOutline(walls);
}
///
/// The shorter of and how far travels
/// along before the perimeter of its material meets a wall.
///
public double Travel(Part moving, Vector direction, double distance)
{
if (walls.Count == 0)
return distance;
// The material lies within the placed program's bounds, leads included.
return Travel(moving.BoundingBox, () => Material(moving), direction, distance);
}
/// As for a part's bounding box: the
/// box pushes move a part as its box, which rests on a wall.
public double Travel(Box moving, Vector direction, double distance)
{
if (walls.Count == 0)
return distance;
return Travel(moving, () => (BoxLines(moving), new PathsD { BoxPath(moving) }), direction, distance);
}
private double Travel(Box reach, Func<(List Boundary, PathsD Region)> material, Vector direction,
double distance)
{
var opposite = -direction;
List lines = null;
PathsD region = null;
foreach (var wall in walls)
{
// A wall wholly behind the part can only fall further behind.
if (SpatialQuery.DirectionalGap(reach, wall.Bounds, opposite) >= -OpenNest.Math.Tolerance.Epsilon)
continue;
if (SpatialQuery.DirectionalGap(reach, wall.Bounds, direction) >= distance)
continue;
if (!SpatialQuery.PerpendicularOverlap(reach, wall.Bounds, direction))
continue;
if (lines == null)
(lines, region) = material();
if (lines.Count == 0)
return distance;
// Already in this wall: the slide kernel answers for boundaries that start apart.
if (wall.Core.Count > 0 && Clipper.Intersect(region, wall.Core, FillRule.NonZero, ClipperBridge.Precision)
.Sum(path => System.Math.Abs(Clipper.Area(path))) > 0)
continue;
var d = SpatialQuery.DirectionalDistance(lines, wall.Entities, direction);
if (d < distance)
distance = d;
}
return distance;
}
/// One wall per outer loop with the holes directly inside it, the shape of a part
/// with cutouts; material inside a hole (an obstacle on an island) is a wall of its own.
private static void AddWalls(PolyPathD node, List walls)
{
for (var i = 0; i < node.Count; i++)
{
var outer = node[i];
var entities = new List();
var paths = new PathsD { outer.Polygon };
AddLoop(outer.Polygon, entities);
for (var k = 0; k < outer.Count; k++)
{
var hole = outer[k];
paths.Add(hole.Polygon);
AddLoop(hole.Polygon, entities);
AddWalls(hole, walls);
}
if (entities.Count < 3)
continue;
var core = Clipper.InflatePaths(paths, -SpacingOutline.SpacingSlack, JoinType.Miter, EndType.Polygon,
2.0, ClipperBridge.Precision);
core.RemoveAll(path => path.Count < 3);
walls.Add(new Wall(entities, Bounds(outer.Polygon), core));
}
}
private static void AddLoop(PathD path, List entities)
{
if (path == null || path.Count < 3)
return;
for (var i = 0; i < path.Count; i++)
{
var a = path[i];
var b = path[(i + 1) % path.Count];
entities.Add(new Line(new Vector(a.x, a.y), new Vector(b.x, b.y)));
}
}
private static Box Bounds(PathD path)
{
var box = Clipper.GetBounds(path); // RectD top is the minimum Y.
return new Box(box.left, box.top, box.Width, box.Height);
}
/// The part's material perimeter as the edge review takes it: the drawing's clean
/// material at the part's pose (no leads, seam overcut trimmed). The boundary is its native
/// lines and arcs, for the slide; the region is what the review confirms an outline with
/// (). Empty without a closed perimeter.
private static (List Boundary, PathsD Region) Material(Part part)
{
var boundary = new List();
ShapeProfile profile;
try
{
profile = Diagnostics.PartSpacingReview.Profile(part, new Dictionary<(CNC.Program, long), ShapeProfile>());
}
catch (ArgumentException)
{
return (boundary, new PathsD());
}
if (profile?.Perimeter == null)
return (boundary, new PathsD());
// The profile is the drawing's, at the origin: move copies, never its entities.
foreach (var entity in profile.Perimeter.Entities)
{
var moved = entity.Clone();
moved.Offset(part.Location);
boundary.Add(moved);
}
return (boundary, NativeContours.Region(profile.Perimeter, part.Location));
}
private static List BoxLines(Box box)
{
var lines = new List(4);
AddLoop(BoxPath(box), lines);
return lines;
}
private static PathD BoxPath(Box box) => new()
{
new PointD(box.Left, box.Bottom), new PointD(box.Right, box.Bottom),
new PointD(box.Right, box.Top), new PointD(box.Left, box.Top),
};
/// is the wall less the edge review's slack on every side: a
/// part resting on the wall never reaches it, a part lying in the wall does.
private sealed record Wall(List Entities, Box Bounds, PathsD Core);
}