diff --git a/OpenNest.Engine.Tests/Fill/OutlineOverlapMemoTests.cs b/OpenNest.Engine.Tests/Fill/OutlineOverlapMemoTests.cs new file mode 100644 index 00000000..e8caed53 --- /dev/null +++ b/OpenNest.Engine.Tests/Fill/OutlineOverlapMemoTests.cs @@ -0,0 +1,110 @@ +using OpenNest.Engine.Fill; +using OpenNest.Geometry; + +namespace OpenNest.Engine.Tests.Fill; + +/// +/// The memo may only ever answer what answers for the +/// same two perimeters: it saves the test, never changes its verdict. +/// +public class OutlineOverlapMemoTests +{ + [Fact] + public void VerdictsMatchTheDirectTest_FirstAndRemembered() + { + var memo = new OutlineOverlapMemo(10_000, 10_000); + var outlines = Outlines().ToList(); + + // Twice: the first pass tests and remembers, the second answers from memory, with fresh + // outline objects of the same vertices as a later fill would bring. + for (var pass = 0; pass < 2; pass++) + { + var fresh = Outlines().ToList(); + for (var i = 0; i < fresh.Count; i++) + for (var j = 0; j < fresh.Count; j++) + { + var expected = outlines[i].Overlaps(outlines[j]); + var actual = memo.Overlaps(fresh[i], memo.ShapeOf(fresh[i]), fresh[j], memo.ShapeOf(fresh[j])); + Assert.True(expected == actual, $"pass {pass}, outlines {i} and {j}"); + } + } + } + + [Fact] + public void OutlinesOfTheSameVerticesShareAnEntry_OthersDoNot() + { + var memo = new OutlineOverlapMemo(10_000, 10_000); + var shape = memo.ShapeOf(Bar(0, 0)); + + Assert.Same(shape, memo.ShapeOf(Bar(0, 0))); + Assert.NotSame(shape, memo.ShapeOf(Bar(0, 1e-12))); + // The same loop started at another vertex is another vertex order. + Assert.NotSame(shape, memo.ShapeOf(Rotated(Bar(0, 0)))); + } + + [Fact] + public void OutlinesWithCutoutsAreTestedDirectly() + { + var memo = new OutlineOverlapMemo(10_000, 10_000); + var ring = new SpacingOutline(Loop((0, 0), (10, 0), (10, 10), (0, 10)), + new List { Loop((2, 2), (8, 2), (8, 8), (2, 8)) }); + var inside = new SpacingOutline(Loop((4, 4), (6, 4), (6, 6), (4, 6)), new List()); + + Assert.Null(memo.ShapeOf(ring)); + Assert.False(memo.Overlaps(inside, memo.ShapeOf(inside), ring, memo.ShapeOf(ring))); + Assert.False(memo.Overlaps(ring, memo.ShapeOf(ring), inside, memo.ShapeOf(inside))); + } + + [Fact] + public void FullGenerationsDropOldEntriesWithoutChangingVerdicts() + { + // Room for two bars and one verdict per generation: nearly every lookup turns one over. + var memo = new OutlineOverlapMemo(8, 1); + for (var pass = 0; pass < 3; pass++) + for (var i = 0; i < 12; i++) + for (var j = 0; j < 12; j++) + { + var a = Bar(i * 0.75, 0); + var b = Bar(j * 0.75, 0.5); + var expected = Bar(i * 0.75, 0).Overlaps(Bar(j * 0.75, 0.5)); + Assert.Equal(expected, memo.Overlaps(a, memo.ShapeOf(a), b, memo.ShapeOf(b))); + } + } + + // Convex and concave outlines that overlap, touch, nest and miss each other. + private static IEnumerable Outlines() + { + yield return Bar(0, 0); + yield return Bar(0.5, 0.25); + yield return Bar(2, 0); // Shares an edge with the first. + yield return Bar(5, 5); + yield return Outline((0, 0), (6, 0), (6, 1), (1, 1), (1, 6), (0, 6)); // An L. + yield return Outline((1.5, 1.5), (4, 1.5), (4, 4), (1.5, 4)); // In the L's notch. + yield return Outline((0.5, 0.5), (3, 0.5), (3, 3), (0.5, 3)); // Over the L's corner. + yield return Outline((0.2, 0.2), (0.4, 0.2), (0.4, 0.4), (0.2, 0.4)); // Inside the first bar. + } + + private static SpacingOutline Bar(double x, double y) => + Outline((x, y), (x + 2, y), (x + 2, y + 1), (x, y + 1)); + + private static SpacingOutline Rotated(SpacingOutline outline) + { + var vertices = outline.Perimeter.Vertices.Take(outline.Perimeter.Vertices.Count - 1).ToList(); + vertices.Add(vertices[0]); + vertices.RemoveAt(0); + return Outline(vertices.Select(v => (v.X, v.Y)).ToArray()); + } + + private static SpacingOutline Outline(params (double X, double Y)[] points) => + new(Loop(points), new List()); + + private static Polygon Loop(params (double X, double Y)[] points) + { + var polygon = new Polygon(); + foreach (var (x, y) in points) + polygon.Vertices.Add(new Vector(x, y)); + polygon.Close(); + polygon.UpdateBounds(); + return polygon; + } +} diff --git a/OpenNest.Engine/Fill/OutlineOverlapMemo.cs b/OpenNest.Engine/Fill/OutlineOverlapMemo.cs new file mode 100644 index 00000000..6aafbfce --- /dev/null +++ b/OpenNest.Engine/Fill/OutlineOverlapMemo.cs @@ -0,0 +1,161 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using OpenNest.Geometry; + +namespace OpenNest.Engine.Fill +{ + /// + /// Remembers whether two spacing outlines overlap, by the exact coordinates of their + /// perimeters. Auto Nest fills one box with one part once per remaining quantity, and each + /// of those fills tests the same outlines at the same places; triangulating an outline to + /// test it costs far more than comparing its vertices. + /// + /// The answer for a pair is the one gave for outlines + /// of the same vertices, bit for bit and in the same order, so a remembered verdict is the + /// verdict the test would give: the memo changes how long a fill takes, never its result. + /// Outlines with cutouts are not remembered and are tested directly. + /// + /// One memo serves the fills of one solve, from any thread, and goes with it. It is bounded + /// meanwhile: outlines and verdicts are kept in two generations, the older dropped when the + /// newer fills up, so what a run of fills keeps asking for stays and the rest goes. + /// + internal sealed class OutlineOverlapMemo + { + /// Perimeter vertices a generation of outlines holds: 16 bytes each. + private const int DefaultMaxVertices = 2_000_000; + + /// Verdicts a generation holds. + private const int DefaultMaxVerdicts = 500_000; + + private readonly object gate = new(); + private readonly int maxVertices; + private readonly int maxVerdicts; + + private Dictionary shapes = new(); + private Dictionary olderShapes = new(); + private int vertices; + + private Dictionary<(Shape, Shape), bool> verdicts = new(); + private Dictionary<(Shape, Shape), bool> olderVerdicts = new(); + + public OutlineOverlapMemo() + : this(DefaultMaxVertices, DefaultMaxVerdicts) { } + + /// Perimeter vertices a generation of outlines may hold. + /// Verdicts a generation may hold. + internal OutlineOverlapMemo(int maxVertices, int maxVerdicts) + { + this.maxVertices = maxVertices; + this.maxVerdicts = maxVerdicts; + } + + /// + /// The outline's entry: one per distinct perimeter, so two outlines of the same vertices + /// share it. Null for an outline with cutouts, which the memo does not hold. + /// + public Shape ShapeOf(SpacingOutline outline) + { + if (outline.Holes.Count != 0) + return null; + + var key = new Key(outline.Perimeter); + lock (gate) + { + if (shapes.TryGetValue(key, out var shape)) + return shape; + + if (!olderShapes.Remove(key, out shape)) + shape = new Shape(); + + if (vertices + key.VertexCount > maxVertices && shapes.Count > 0) + { + olderShapes = shapes; + shapes = new Dictionary(); + vertices = 0; + } + + shapes[key] = shape; + vertices += key.VertexCount; + return shape; + } + } + + /// + /// a.Overlaps(b), remembered when both outlines have an entry + /// ( and , from ). + /// + public bool Overlaps(SpacingOutline a, Shape shapeA, SpacingOutline b, Shape shapeB) + { + if (shapeA == null || shapeB == null) + return a.Overlaps(b); + + var pair = (shapeA, shapeB); + lock (gate) + { + if (verdicts.TryGetValue(pair, out var known)) + return known; + if (olderVerdicts.TryGetValue(pair, out known)) + { + Keep(pair, known); + return known; + } + } + + var overlaps = a.Overlaps(b); + lock (gate) + Keep(pair, overlaps); + return overlaps; + } + + // Caller holds the gate. + private void Keep((Shape, Shape) pair, bool overlaps) + { + if (verdicts.Count >= maxVerdicts) + { + olderVerdicts = verdicts; + verdicts = new Dictionary<(Shape, Shape), bool>(); + } + + verdicts[pair] = overlaps; + } + + /// One distinct perimeter; verdicts are kept by the two entries of a pair. + internal sealed class Shape { } + + /// A perimeter's vertices, equal only to the same coordinates bit for bit in the + /// same order. + private readonly struct Key : IEquatable + { + private readonly double[] coordinates; + private readonly int hash; + + public Key(Polygon perimeter) + { + var source = perimeter.Vertices; + coordinates = new double[source.Count * 2]; + var code = new HashCode(); + for (var i = 0; i < source.Count; i++) + { + coordinates[2 * i] = source[i].X; + coordinates[2 * i + 1] = source[i].Y; + code.Add(BitConverter.DoubleToInt64Bits(source[i].X)); + code.Add(BitConverter.DoubleToInt64Bits(source[i].Y)); + } + + hash = code.ToHashCode(); + } + + public int VertexCount => coordinates.Length / 2; + + public bool Equals(Key other) => + hash == other.hash + && MemoryMarshal.Cast(coordinates) + .SequenceEqual(MemoryMarshal.Cast(other.coordinates)); + + public override bool Equals(object obj) => obj is Key other && Equals(other); + + public override int GetHashCode() => hash; + } + } +} diff --git a/OpenNest.Engine/Fill/TiltedRemnantFiller.cs b/OpenNest.Engine/Fill/TiltedRemnantFiller.cs index 6a617b96..96d1ccc8 100644 --- a/OpenNest.Engine/Fill/TiltedRemnantFiller.cs +++ b/OpenNest.Engine/Fill/TiltedRemnantFiller.cs @@ -30,6 +30,10 @@ namespace OpenNest.Engine.Fill // Placed copies are tested against every layout variant; reference keys are per copy. private readonly Dictionary inflatedOutlines = new(ReferenceEqualityComparer.Instance); + // Each outline's entry in the overlap memo, looked up once per outline. + private readonly Dictionary shapes = + new(ReferenceEqualityComparer.Instance); + public TiltedRemnantFiller(Box workArea, double partSpacing, IFillComparer comparer) { this.workArea = workArea; @@ -37,6 +41,12 @@ namespace OpenNest.Engine.Fill this.comparer = comparer; } + /// + /// Overlap verdicts shared with other fills of the same part, which test the same + /// outlines at the same places; null tests every pair. See . + /// + internal OutlineOverlapMemo OverlapMemo { get; init; } + /// /// Returns (possibly moved) plus tilted parts when that beats /// the layout, or null when no tilted placement helps. @@ -325,6 +335,23 @@ namespace OpenNest.Engine.Fill return outline; } + /// Whether the outlines share material, from the memo when there is one. + private bool Overlap(SpacingOutline inflated, SpacingOutline raw) => + OverlapMemo == null + ? inflated.Overlaps(raw) + : OverlapMemo.Overlaps(inflated, ShapeOf(inflated), raw, ShapeOf(raw)); + + private OutlineOverlapMemo.Shape ShapeOf(SpacingOutline outline) + { + if (!shapes.TryGetValue(outline, out var shape)) + { + shape = OverlapMemo.ShapeOf(outline); + shapes[outline] = shape; + } + + return shape; + } + private static double Low(Box box, bool alongX) => alongX ? box.Left : box.Bottom; private static double High(Box box, bool alongX) => alongX ? box.Right : box.Top; @@ -367,7 +394,7 @@ namespace OpenNest.Engine.Fill inflated ??= owner.InflatedOutline(part); outlines[i] ??= owner.Outline(Parts[i], 0); - if (inflated == null || outlines[i] == null || inflated.Overlaps(outlines[i])) + if (inflated == null || outlines[i] == null || owner.Overlap(inflated, outlines[i])) return false; } diff --git a/OpenNest.Engine/Jobs/Placement/Fillers/PlateFiller.cs b/OpenNest.Engine/Jobs/Placement/Fillers/PlateFiller.cs index 23688720..98e7dde5 100644 --- a/OpenNest.Engine/Jobs/Placement/Fillers/PlateFiller.cs +++ b/OpenNest.Engine/Jobs/Placement/Fillers/PlateFiller.cs @@ -91,6 +91,12 @@ internal class PlateFiller /// internal bool WholePairGrids { get; init; } = true; + /// + /// Outline overlap verdicts this fill shares with the caller's other fills of the same part + /// (); null, the default, keeps the fill to itself. + /// + internal OutlineOverlapMemo OverlapMemo { get; init; } + public virtual List BuildAngles( NestItem item, ClassificationResult classification, @@ -470,6 +476,7 @@ internal class PlateFiller ), MaxQuantity = StopAtQuantity ? System.Math.Max(0, item.Quantity) : 0, WholePairGrids = WholePairGrids, + OverlapMemo = OverlapMemo, }; RunPipeline(context); diff --git a/OpenNest.Engine/Jobs/Placement/PrivatePlateFill.cs b/OpenNest.Engine/Jobs/Placement/PrivatePlateFill.cs index e7c7dae4..9a5b8634 100644 --- a/OpenNest.Engine/Jobs/Placement/PrivatePlateFill.cs +++ b/OpenNest.Engine/Jobs/Placement/PrivatePlateFill.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading; using OpenNest.Engine.BestFit; +using OpenNest.Engine.Fill; using OpenNest.Engine.Jobs.Adapters; using OpenNest.Engine.Jobs.Placement.Fillers; using OpenNest.Geometry; @@ -20,8 +21,11 @@ internal static class PrivatePlateFill /// Y extent of the plate and work area. /// Copies wanted; zero fills the whole area. /// See . + /// See : a caller filling one + /// part again and again passes the same memo to each fill. internal static List Run(Drawing drawing, RotationPolicy rotation, double spacing, - double length, double width, int quantity, CancellationToken token, bool wholePairGrids = true) + double length, double width, int quantity, CancellationToken token, bool wholePairGrids = true, + OutlineOverlapMemo overlapMemo = null) { var plate = new Plate(new Size(width, length)) { PartSpacing = spacing }; // The drawing is private: stabilize this cache entry before Fill's candidate pruning. @@ -35,7 +39,12 @@ internal static class PrivatePlateFill fits.AddRange(sorted); // A positive quantity lets supporting strategies avoid surplus rows. Zero still // fills the whole area (the cutout lattice caller requires an uncapped lattice). - var filler = new PlateFiller(plate) { StopAtQuantity = true, WholePairGrids = wholePairGrids }; + var filler = new PlateFiller(plate) + { + StopAtQuantity = true, + WholePairGrids = wholePairGrids, + OverlapMemo = overlapMemo, + }; return filler.Fill(new NestItem { Drawing = drawing, diff --git a/OpenNest.Engine/NestingEngines/Irregular/BlockCatalog.cs b/OpenNest.Engine/NestingEngines/Irregular/BlockCatalog.cs index d529b9b7..f1053c9d 100644 --- a/OpenNest.Engine/NestingEngines/Irregular/BlockCatalog.cs +++ b/OpenNest.Engine/NestingEngines/Irregular/BlockCatalog.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Threading; using Clipper2Lib; using OpenNest.Engine.BestFit; +using OpenNest.Engine.Fill; using OpenNest.Engine.Jobs; using OpenNest.Engine.Jobs.Adapters; using OpenNest.Engine.Jobs.Placement; @@ -77,6 +78,12 @@ internal sealed class BlockCatalog : IDisposable /// public bool Frozen { get; set; } + /// + /// Overlap verdicts every Fill proposal of this catalog shares: the same part is filled in + /// the same box for one quantity after another, testing the same outlines each time. + /// + private readonly OutlineOverlapMemo overlapMemo = new(); + /// Guarded by its own lock, as are its entries' members and charge. private readonly Dictionary bands = new(); @@ -417,7 +424,7 @@ internal sealed class BlockCatalog : IDisposable try { var members = PrivatePlateFill.Run(drawing, type.Part.Rotation, fillSpacing, - rectangle.Length, rectangle.Width, quantity, token); + rectangle.Length, rectangle.Width, quantity, token, overlapMemo: overlapMemo); token.ThrowIfCancellationRequested(); var kept = members.Take(quantity).ToArray(); var poses = Certify(type, kept, spacing, token); diff --git a/OpenNest.Engine/Strategies/FillContext.cs b/OpenNest.Engine/Strategies/FillContext.cs index b4d51918..9e94792f 100644 --- a/OpenNest.Engine/Strategies/FillContext.cs +++ b/OpenNest.Engine/Strategies/FillContext.cs @@ -28,6 +28,13 @@ namespace OpenNest.Engine.Strategies /// (). /// public bool WholePairGrids { get; init; } = true; + + /// + /// Outline overlap verdicts shared by a caller's fills of the same part; null keeps + /// each fill to itself (see ). + /// + internal Fill.OutlineOverlapMemo OverlapMemo { get; init; } + public PartType PartType { get; set; } /// diff --git a/OpenNest.Engine/Strategies/TiltedRemnantStrategy.cs b/OpenNest.Engine/Strategies/TiltedRemnantStrategy.cs index 6764d4e7..3d5641d4 100644 --- a/OpenNest.Engine/Strategies/TiltedRemnantStrategy.cs +++ b/OpenNest.Engine/Strategies/TiltedRemnantStrategy.cs @@ -33,7 +33,10 @@ public class TiltedRemnantStrategy : IFillStrategy context.WorkArea, context.Plate.PartSpacing, context.Policy.Comparer - ); + ) + { + OverlapMemo = context.OverlapMemo, + }; var result = filler.Fill(item.Drawing, layout, context.Token); if (result != null)