diff --git a/OpenNest.Benchmark/JobProgressLog.cs b/OpenNest.Benchmark/JobProgressLog.cs index 627081b9..4108bb5b 100644 --- a/OpenNest.Benchmark/JobProgressLog.cs +++ b/OpenNest.Benchmark/JobProgressLog.cs @@ -52,7 +52,7 @@ namespace OpenNest.Benchmark public void Report(NestJobProgress value) { - if (value == null) + if (value == null || value.Stage == NestJobStage.PlanAlternative) return; if (value.Stage == NestJobStage.PlateCommitted) diff --git a/OpenNest.Desktop.Tests/Forms/NestLayoutChoicesTests.cs b/OpenNest.Desktop.Tests/Forms/NestLayoutChoicesTests.cs new file mode 100644 index 00000000..6757cc81 --- /dev/null +++ b/OpenNest.Desktop.Tests/Forms/NestLayoutChoicesTests.cs @@ -0,0 +1,176 @@ +using OpenNest.CNC; +using OpenNest.Engine.Jobs; +using OpenNest.Forms; +using OpenNest.Geometry; + +namespace OpenNest.Desktop.Tests.Forms; + +public class NestLayoutChoicesTests +{ + private static readonly Drawing Bracket = new("bracket", Rectangle()); + + // 10 long (X) by 20 wide (Y). + private static Program Rectangle() + { + var program = new Program(); + program.MoveTo(0, 0); + program.LineTo(10, 0); + program.LineTo(10, 20); + program.LineTo(0, 20); + program.LineTo(0, 0); + return program; + } + + // 96 long (X) by 48 wide (Y). + private static NestPlateStock Stock(int quadrant = 1) => + new("sheet", new Size(48, 96), quantity: null, partSpacing: 0.25, quadrant: quadrant); + + private static ProposedPlate Sheet(NestPlateStock stock, params (double X, double Y)[] at) + { + var parts = at.Select(p => + { + var part = new Part(Bracket) { Location = new Vector(p.X, p.Y) }; + part.UpdateBounds(); + return part; + }).ToList(); + return new ProposedPlate(0, stock, parts); + } + + private static NestLayoutChoice Layout(params ProposedPlate[] sheets) => new(sheets); + + [Fact] + public void VerticalStrips_LeaveTheDistanceToTheRightEdge() + { + // Two columns to the full height: 76 free along the length, nothing above. + var remnant = SheetRemnant.Of(Sheet(Stock(), (0, 0), (0, 28), (10, 0), (10, 28))); + + Assert.Equal(SheetEdge.Right, remnant!.Value.Edge); + Assert.Equal(76, remnant.Value.Distance, 6); + Assert.Equal("76 to right edge", remnant.Value.ToString()); + } + + [Fact] + public void HorizontalStrips_LeaveTheDistanceToTheTop() + { + // One row along the whole length: 28 free above it. + var remnant = SheetRemnant.Of(Sheet(Stock(), (0, 0), (40, 0), (86, 0))); + + Assert.Equal(SheetEdge.Top, remnant!.Value.Edge); + Assert.Equal(28, remnant.Value.Distance, 6); + Assert.Equal("28 to top", remnant.Value.ToString()); + } + + [Fact] + public void TheFreeStripIsMeasuredAwayFromTheSheetOrigin() + { + // Quadrant 3: the sheet spans -96..0 by -48..0 and parts pack from its top-right corner. + var remnant = SheetRemnant.Of(Sheet(Stock(3), (-10, -20), (-10, -48), (-20, -48), (-20, -20))); + + Assert.Equal(SheetEdge.Left, remnant!.Value.Edge); + Assert.Equal(76, remnant.Value.Distance, 6); + } + + [Fact] + public void AnEmptySheet_HasNoFreeStrip() => Assert.Null(SheetRemnant.Of(Sheet(Stock()))); + + [Fact] + public void TheSummaryNamesTheLastSheetsFreeStrip() + { + var stock = Stock(); + var layout = Layout(Sheet(stock, (0, 0), (86, 28)), Sheet(stock, (0, 0), (0, 28))); + + Assert.Equal(2, layout.SheetCount); + Assert.Equal(4, layout.PartCount); + Assert.EndsWith("86 to right edge on sheet 2", layout.Summary); + Assert.StartsWith("2 sheets · 4 parts", layout.Summary); + } + + [Fact] + public void ANewBestReplacesItsFamilyAndKeepsTheOtherDirection() + { + var stock = Stock(); + var choices = new NestLayoutChoices(); + var vertical = Layout(Sheet(stock, (0, 0), (0, 28), (10, 0))); + var horizontal = Layout(Sheet(stock, (0, 0), (40, 0), (86, 0))); + var tighter = Layout(Sheet(stock, (0, 0), (0, 28), (10.5, 0))); + + Assert.True(choices.Add(vertical, best: true)); + Assert.True(choices.Add(horizontal, best: false)); + Assert.Equal(new[] { vertical, horizontal }, choices.Top); + + // Same sheet count and direction as the old best: it takes its place. + Assert.True(choices.Add(tighter, best: true)); + Assert.Equal(new[] { tighter, horizontal }, choices.Top); + Assert.Same(tighter, choices.Best); + } + + [Fact] + public void AnAlternativeNeverDisplacesTheBestOfItsFamily_AndOnlyABetterOneDisplacesAnother() + { + var stock = Stock(); + var choices = new NestLayoutChoices(); + var best = Layout(Sheet(stock, (0, 0), (0, 28), (10, 0))); + var sameFamily = Layout(Sheet(stock, (0, 0), (0, 28), (10, 0), (10, 28))); + var row = Layout(Sheet(stock, (0, 0), (86, 0))); + var fullerRow = Layout(Sheet(stock, (0, 0), (40, 0), (86, 0))); + + choices.Add(best, best: true); + Assert.False(choices.Add(sameFamily, best: false)); + Assert.True(choices.Add(row, best: false)); + Assert.False(choices.Add(Layout(Sheet(stock, (0, 0), (86, 0))), best: false)); + Assert.True(choices.Add(fullerRow, best: false)); + + Assert.Equal(new[] { best, fullerRow }, choices.Top); + } + + [Fact] + public void TheListIsCappedBestFirstThenByPartsPlaced() + { + var stock = Stock(); + var choices = new NestLayoutChoices(capacity: 2); + var best = Layout(Sheet(stock, (0, 0), (0, 28))); + var twoSheets = Layout(Sheet(stock, (0, 0)), Sheet(stock, (0, 0))); + var row = Layout(Sheet(stock, (0, 0), (40, 0), (86, 0))); + + choices.Add(best, best: true); + choices.Add(twoSheets, best: false); + choices.Add(row, best: false); + + Assert.Equal(new[] { best, row }, choices.Top); + } + + [Fact] + public void LayoutReports_CarryEveryPlanAndMarkTheBest() + { + var reports = new List(); + var described = new List(); + var progress = JobEngineNest.CreateLayoutProgress("Irregular", new Inline(described.Add), + new Inline(reports.Add)); + var sheets = new[] { Sheet(Stock(), (0, 0)) }; + NestPipelineResult Accept(CancellationToken _) => null!; + + progress.Report(new NestJobProgress(NestJobStage.PlanImproved, "s", 0, 0, 0) { PlanSheets = sheets, AcceptPlan = Accept }); + progress.Report(new NestJobProgress(NestJobStage.PlanAlternative, "s", 0, 0, 0) { PlanSheets = sheets, AcceptPlan = Accept }); + + Assert.Empty(described); + Assert.Equal(new[] { true, false }, reports.Select(r => r.Best)); + Assert.All(reports, r => Assert.Same(sheets, r.Layout.Sheets)); + Assert.All(reports, r => Assert.NotNull(r.Layout.Accept)); + } + + [Fact] + public void AnAlternativePlan_IsNeverDescribedAsAStage() + { + var described = new List(); + + JobEngineNest.CreateProgress("Irregular", new Inline(described.Add)) + .Report(new NestJobProgress(NestJobStage.PlanAlternative, "s", 0, 0, 0) { PlanSheets = [] }); + + Assert.Empty(described); + } + + private sealed class Inline(Action report) : IProgress + { + public void Report(T value) => report(value); + } +} diff --git a/OpenNest.Desktop/Forms/JobEngineNest.cs b/OpenNest.Desktop/Forms/JobEngineNest.cs index dd9322c2..6a9800da 100644 --- a/OpenNest.Desktop/Forms/JobEngineNest.cs +++ b/OpenNest.Desktop/Forms/JobEngineNest.cs @@ -32,7 +32,23 @@ namespace OpenNest.Forms string engineName, IProgress progress, IProgress> plans - ) => new ProgressAdapter(engineName, progress, plans); + ) => new ProgressAdapter(engineName, progress, plans == null ? null : value => + { + if (value.Stage == NestJobStage.PlanImproved) + plans.Report(value.PlanSheets); + }); + + /// + /// As , and also sends every + /// plan the engine reports to as a layout the user may choose: + /// its best so far and the alternatives beside it. + /// + public static IProgress CreateLayoutProgress( + string engineName, + IProgress progress, + IProgress layouts + ) => new ProgressAdapter(engineName, progress, value => layouts.Report(new NestLayoutReport( + new NestLayoutChoice(value.PlanSheets, value.AcceptPlan), value.Stage == NestJobStage.PlanImproved))); public static string Describe(string engineName, NestJobProgress value) => value.Stage switch { @@ -50,7 +66,7 @@ namespace OpenNest.Forms private sealed class ProgressAdapter( string engineName, IProgress progress, - IProgress> plans + Action plans ) : IProgress { public void Report(NestJobProgress value) @@ -59,10 +75,12 @@ namespace OpenNest.Forms return; // A plan sink shows plans as sheets; the plate row keeps tracking the search. - if (value.Stage == NestJobStage.PlanImproved && plans != null) + // An alternative plan is never a stage of the search. + if (value.Stage == NestJobStage.PlanAlternative + || (value.Stage == NestJobStage.PlanImproved && plans != null)) { if (value.PlanSheets != null) - plans.Report(value.PlanSheets); + plans?.Invoke(value); return; } diff --git a/OpenNest.Desktop/Forms/NestLayoutChoices.cs b/OpenNest.Desktop/Forms/NestLayoutChoices.cs new file mode 100644 index 00000000..86550a18 --- /dev/null +++ b/OpenNest.Desktop/Forms/NestLayoutChoices.cs @@ -0,0 +1,214 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using OpenNest.Engine.Jobs; + +namespace OpenNest.Forms +{ + /// The sheet edge a layout leaves its free strip against. + internal enum SheetEdge + { + Right, + Left, + Top, + Bottom, + } + + /// + /// The free strip a sheet's parts leave: the distance from the parts to the sheet edge they + /// were packed away from. Parts packed in vertical strips advance along the sheet's length + /// and leave it against the right edge (left in quadrants 2 and 3); horizontal strips leave + /// it against the top (bottom in quadrants 3 and 4). Of the two, the strip with more area is + /// the one reported. + /// + internal readonly record struct SheetRemnant(SheetEdge Edge, double Distance, double Area) + { + /// True when the strip runs the sheet's full height (vertical strips). + public bool AlongLength => Edge is SheetEdge.Right or SheetEdge.Left; + + /// Null for an empty sheet and for an outlined one, which has no such edge. + public static SheetRemnant? Of(ProposedPlate plate) + { + var stock = plate?.Stock; + if (stock == null || stock.Outline != null || plate.Parts.Count == 0) + return null; + var length = stock.Size.Length; + var width = stock.Size.Width; + // Sheet extents around the origin, as the plate view places them for this quadrant. + var fromRight = stock.Quadrant is 2 or 3; + var fromTop = stock.Quadrant is 3 or 4; + var x = fromRight ? -length : 0; + var y = fromTop ? -width : 0; + var left = plate.Parts.Min(p => p.BoundingBox.Left); + var right = plate.Parts.Max(p => p.BoundingBox.Right); + var bottom = plate.Parts.Min(p => p.BoundingBox.Bottom); + var top = plate.Parts.Max(p => p.BoundingBox.Top); + var alongLength = System.Math.Max(0, fromRight ? left - x : x + length - right); + var alongWidth = System.Math.Max(0, fromTop ? bottom - y : y + width - top); + return alongLength * width >= alongWidth * length + ? new SheetRemnant(fromRight ? SheetEdge.Left : SheetEdge.Right, alongLength, alongLength * width) + : new SheetRemnant(fromTop ? SheetEdge.Bottom : SheetEdge.Top, alongWidth, alongWidth * length); + } + + public override string ToString() => $"{Distance:0.##} to {EdgeName}"; + + private string EdgeName => Edge switch + { + SheetEdge.Right => "right edge", + SheetEdge.Left => "left edge", + SheetEdge.Top => "top", + _ => "bottom", + }; + } + + /// + /// One whole-job layout a user may choose: its sheets, what it places, the free strip its + /// last sheet leaves, and how to turn it into a proposal. + /// + internal sealed class NestLayoutChoice + { + /// Validates and binds the layout; null for a layout that can only be shown. + public NestLayoutChoice(IReadOnlyList sheets, + Func accept = null) + { + Sheets = sheets ?? Array.Empty(); + Accept = accept; + SheetCount = Sheets.Sum(s => s.Quantity); + PartCount = Sheets.Sum(s => s.Quantity * s.Parts.Count); + SheetArea = Sheets.Sum(s => s.Quantity * s.Stock.Area); + PartArea = Sheets.Sum(s => s.Quantity * s.Parts.Sum(p => p.BaseDrawing.Area)); + // The last sheet holds the leftovers, so its free strip is the usable drop. + if (Sheets.Count > 0) + Remnant = SheetRemnant.Of(Sheets[^1]); + } + + public IReadOnlyList Sheets { get; } + public Func Accept { get; } + public int SheetCount { get; } + public int PartCount { get; } + public double SheetArea { get; } + public double PartArea { get; } + public double Utilization => SheetArea > 0 ? PartArea / SheetArea : 0; + + /// The free strip on the last sheet; null when it has none to measure. + public SheetRemnant? Remnant { get; } + + /// "2 sheets · 130 parts · 29.9% used · 112.4 to right edge on sheet 2". + public string Summary + { + get + { + var text = $"{SheetCount} {(SheetCount == 1 ? "sheet" : "sheets")} · {PartCount} parts · {Utilization:P1} used"; + if (Remnant is not { } remnant) + return text; + return SheetCount == 1 ? $"{text} · {remnant}" : $"{text} · {remnant} on sheet {SheetCount}"; + } + } + + /// + /// Layouts alike enough that only the better one is offered: the same number of sheets, + /// leaving the free strip the same way. + /// + internal (int Sheets, bool? AlongLength) Family => (SheetCount, Remnant?.AlongLength); + + /// True when both place the same parts at the same poses on the same stock. + public bool SameLayoutAs(NestLayoutChoice other) + { + if (ReferenceEquals(this, other)) + return true; + if (other == null || Sheets.Count != other.Sheets.Count) + return false; + for (var i = 0; i < Sheets.Count; i++) + { + var (a, b) = (Sheets[i], other.Sheets[i]); + if (a.Quantity != b.Quantity || a.Parts.Count != b.Parts.Count + || !string.Equals(a.Stock.Id, b.Stock.Id, StringComparison.Ordinal)) + return false; + for (var j = 0; j < a.Parts.Count; j++) + { + var (p, q) = (a.Parts[j], b.Parts[j]); + if (!string.Equals(p.BaseDrawing.Name, q.BaseDrawing.Name, StringComparison.Ordinal) + || System.Math.Abs(p.Location.X - q.Location.X) > 1e-6 + || System.Math.Abs(p.Location.Y - q.Location.Y) > 1e-6 + || System.Math.Abs(p.Rotation - q.Rotation) > 1e-9) + return false; + } + } + return true; + } + + /// More parts placed, then fewer sheets, less sheet area, the larger free strip. + internal bool IsBetterThan(NestLayoutChoice other) + { + if (PartCount != other.PartCount) + return PartCount > other.PartCount; + if (SheetCount != other.SheetCount) + return SheetCount < other.SheetCount; + if (System.Math.Abs(SheetArea - other.SheetArea) > 1e-6) + return SheetArea < other.SheetArea; + return (Remnant?.Area ?? 0) > (other.Remnant?.Area ?? 0); + } + } + + /// + /// The layouts a run offers: the engine's best first, then the best layout of every other + /// family (sheet count and free-strip direction), so the list holds real alternatives rather + /// than near copies of the best. Not thread-safe: use it from one thread. + /// + internal sealed class NestLayoutChoices + { + private readonly List kept = new(); + private readonly int capacity; + + public NestLayoutChoices(int capacity = 3) + { + this.capacity = capacity > 0 ? capacity : throw new ArgumentOutOfRangeException(nameof(capacity)); + } + + /// The engine's best layout so far; null before the first. + public NestLayoutChoice Best { get; private set; } + + /// The layouts offered, best first. + public IReadOnlyList Top { get; private set; } = Array.Empty(); + + /// + /// Adds a layout. marks the engine's new best, which replaces + /// every layout of its family; any other layout is kept only when its family has none + /// yet or it beats the one kept. Returns whether changed. + /// + public bool Add(NestLayoutChoice choice, bool best) + { + ArgumentNullException.ThrowIfNull(choice); + if (choice.Sheets.Count == 0) + return false; + if (best) + { + kept.RemoveAll(c => c.Family == choice.Family); + kept.Add(choice); + Best = choice; + } + else + { + var rival = kept.Find(c => c.Family == choice.Family); + if (rival != null && (ReferenceEquals(rival, Best) || !choice.IsBetterThan(rival))) + return false; + kept.Remove(rival); + kept.Add(choice); + } + + var top = new List(); + if (Best != null) + top.Add(Best); + var others = kept.Where(c => !ReferenceEquals(c, Best)).ToList(); + others.Sort((a, b) => a.IsBetterThan(b) ? -1 : b.IsBetterThan(a) ? 1 : 0); + top.AddRange(others.Take(capacity - top.Count)); + var changed = !top.SequenceEqual(Top); + Top = top; + return changed; + } + } + + /// A layout from a running solve; marks the engine's best so far. + internal sealed record NestLayoutReport(NestLayoutChoice Layout, bool Best); +} diff --git a/OpenNest.Desktop/Properties/AssemblyInfo.cs b/OpenNest.Desktop/Properties/AssemblyInfo.cs index 18995d42..3a87cf2f 100644 --- a/OpenNest.Desktop/Properties/AssemblyInfo.cs +++ b/OpenNest.Desktop/Properties/AssemblyInfo.cs @@ -6,3 +6,4 @@ using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("OpenNest")] [assembly: InternalsVisibleTo("OpenNest.Avalonia")] [assembly: InternalsVisibleTo("OpenNest.Desktop.Tests")] +[assembly: InternalsVisibleTo("OpenNest.WinForms.Tests")] diff --git a/OpenNest.Engine.Tests/Jobs/NestPipelineTests.cs b/OpenNest.Engine.Tests/Jobs/NestPipelineTests.cs index 7feb0c68..325006c0 100644 --- a/OpenNest.Engine.Tests/Jobs/NestPipelineTests.cs +++ b/OpenNest.Engine.Tests/Jobs/NestPipelineTests.cs @@ -80,6 +80,73 @@ public class NestPipelineTests Assert.Equal(0, item.Drawing.Quantity.Nested); } + [Fact] + public void AnAlternativePlanCanBeAcceptedAsAValidatedProposalBoundToCallerDrawings() + { + var item = Item("bracket", 2); + var engine = new AlternativeEngine( + job => OnePlate(job, + new NestJobPlacement(job.Parts[0].Id, 0, 1, 1, 0), + new NestJobPlacement(job.Parts[0].Id, 1, 20, 1, 0)), + job => OnePlate(job, + new NestJobPlacement(job.Parts[0].Id, 0, 1, 25, 0), + new NestJobPlacement(job.Parts[0].Id, 1, 20, 25, 0))); + var reports = new List(); + + var result = NestPipeline.Run(engine, "Stub", Request("Stub", item), new InlineProgress(reports.Add)); + + var alternative = Assert.Single(reports, r => r.Stage == NestJobStage.PlanAlternative); + Assert.Equal(new[] { 25.0, 25.0 }, Assert.Single(alternative.PlanSheets).Parts.Select(p => p.Location.Y)); + Assert.NotNull(Assert.Single(reports, r => r.Stage == NestJobStage.PlanImproved).AcceptPlan); + + var accepted = alternative.AcceptPlan(CancellationToken.None); + + Assert.True(accepted.IsValid, string.Join("; ", accepted.Violations)); + Assert.True(accepted.CanKeep); + var parts = Assert.Single(accepted.Plates).Parts; + Assert.Equal(new[] { 25.0, 25.0 }, parts.Select(p => p.Location.Y)); + Assert.All(parts, part => Assert.Same(item.Drawing, part.BaseDrawing)); + Assert.Empty(accepted.Unplaced); + // The engine's own result is untouched by the accepted alternative. + Assert.Equal(new[] { 1.0, 1.0 }, Assert.Single(result.Plates).Parts.Select(p => p.Location.Y)); + Assert.Equal(0, item.Drawing.Quantity.Nested); + } + + [Fact] + public void AnAcceptedPlanThatBreaksLayoutRulesIsReportedInvalid() + { + var item = Item("bracket", 2); + var engine = new AlternativeEngine( + job => OnePlate(job, + new NestJobPlacement(job.Parts[0].Id, 0, 1, 1, 0), + new NestJobPlacement(job.Parts[0].Id, 1, 20, 1, 0)), + job => OnePlate(job, + new NestJobPlacement(job.Parts[0].Id, 0, 1, 1, 0), + new NestJobPlacement(job.Parts[0].Id, 1, 1, 1, 0))); + var reports = new List(); + + NestPipeline.Run(engine, "Stub", Request("Stub", item), new InlineProgress(reports.Add)); + var accepted = reports.Single(r => r.Stage == NestJobStage.PlanAlternative).AcceptPlan(CancellationToken.None); + + Assert.False(accepted.IsValid); + } + + private sealed class AlternativeEngine(Func solve, Func alternative) + : INestingEngine + { + public NestJobResult Solve( + NestJob job, + IProgress? progress = null, + CancellationToken token = default + ) + { + var result = solve(job); + progress?.Report(new NestJobProgress(NestJobStage.PlanImproved, string.Empty, -1, 0, 0, Plan: result)); + progress?.Report(new NestJobProgress(NestJobStage.PlanAlternative, string.Empty, -1, 0, 0, Plan: alternative(job))); + return result; + } + } + private sealed class ReportingEngine(Func solve) : INestingEngine { public NestJobResult Solve( diff --git a/OpenNest.Engine/Jobs/NestJobProgress.cs b/OpenNest.Engine/Jobs/NestJobProgress.cs index 74471fc9..f17472ee 100644 --- a/OpenNest.Engine/Jobs/NestJobProgress.cs +++ b/OpenNest.Engine/Jobs/NestJobProgress.cs @@ -1,4 +1,6 @@ +using System; using System.Collections.Generic; +using System.Threading; namespace OpenNest.Engine.Jobs; @@ -12,6 +14,13 @@ public enum NestJobStage /// validated and possibly replaced by a later plan; never counts as committed. /// PlanImproved, + + /// + /// Another complete whole-job plan the engine found that is not its best, in + /// : a different layout a front end may offer beside the + /// best. Optional, unranked, not validated, and never the engine's result. + /// + PlanAlternative, } /// @@ -30,8 +39,17 @@ public sealed record NestJobProgress( { /// /// as displayable sheets, filled in by for - /// reports. Parts use detached drawings built from - /// the job geometry, so they never touch the caller's drawings or quantities. + /// and + /// reports. Parts use detached drawings built from the job geometry, so they never touch + /// the caller's drawings or quantities. /// public IReadOnlyList PlanSheets { get; init; } + + /// + /// Turns into a proposal exactly as the pipeline does an engine's result: + /// validated, then bound to the caller's drawings. Filled in with , + /// for a caller that stops the search to use this plan. Call it only once the solve that + /// reported the plan has ended. + /// + public Func AcceptPlan { get; init; } } diff --git a/OpenNest.Engine/Jobs/NestPipeline.cs b/OpenNest.Engine/Jobs/NestPipeline.cs index ad0d9336..bbd49d47 100644 --- a/OpenNest.Engine/Jobs/NestPipeline.cs +++ b/OpenNest.Engine/Jobs/NestPipeline.cs @@ -114,7 +114,8 @@ public static class NestPipeline { public void Report(NestJobProgress value) { - if (value != null && value.Stage is NestJobStage.EvaluatingCandidate or NestJobStage.PlanImproved) + if (value != null && value.Stage is NestJobStage.EvaluatingCandidate or NestJobStage.PlanImproved + or NestJobStage.PlanAlternative) inner.Report(value with { CommittedPlates = 0, CommittedParts = 0 }); } } @@ -125,7 +126,8 @@ public static class NestPipeline /// one per part, so a preview never touches the caller's drawings or their quantities. /// private sealed class PlanProgress(IProgress inner, NestJob engineJob, - IReadOnlyDictionary callerDrawings, CancellationToken token) + IReadOnlyDictionary callerDrawings, CancellationToken token, + Func accept) : IProgress { private readonly Dictionary parts = @@ -134,14 +136,20 @@ public static class NestPipeline public void Report(NestJobProgress value) { - if (value?.Stage == NestJobStage.PlanImproved && value.Plan != null && value.PlanSheets == null) + if (value?.Stage is NestJobStage.PlanImproved or NestJobStage.PlanAlternative + && value.Plan != null && value.PlanSheets == null) { lock (drawings) { // A plan naming unknown parts has nothing to draw; validation reports it later. if (value.Plan.Plates.Any(s => s.Placements.Any(p => p.PartId == null || !parts.ContainsKey(p.PartId)))) return; - value = value with { PlanSheets = PlanSheets(value.Plan, parts, callerDrawings, drawings, token) }; + var plan = value.Plan; + value = value with + { + PlanSheets = PlanSheets(plan, parts, callerDrawings, drawings, token), + AcceptPlan = t => accept(plan, t), + }; } } inner.Report(value); @@ -397,13 +405,17 @@ public static class NestPipeline ) { var engineJob = prepass?.EngineJob ?? job; - IReadOnlyDictionary released = new Dictionary(); if (prepass != null) NestJobValidator.Validate(engineJob); var clock = Stopwatch.StartNew(); + // A reported plan is accepted against the job as it was asked: last-resort clamp + // removal belongs to the engine's own result. + var askedJob = job; var engineProgress = progress == null ? null - : new PlanProgress(prepass == null ? progress : new PreviewProgress(progress), engineJob, drawingsByPartId, token); + : new PlanProgress(prepass == null ? progress : new PreviewProgress(progress), engineJob, drawingsByPartId, token, + (plan, accepting) => Finish(engineName, askedJob, prepass?.EngineJob ?? askedJob, prepass, plan, + drawingsByPartId, clock.Elapsed, accepting)); var raw = engine.Solve(engineJob, engineProgress, token) ?? throw new InvalidOperationException($"Engine '{engineName}' returned no result."); @@ -423,8 +435,27 @@ public static class NestPipeline } } token.ThrowIfCancellationRequested(); + return Finish(engineName, job, engineJob, prepass, raw, drawingsByPartId, solveTime, token); + } - clock.Restart(); + /// + /// Validates (an engine's result, or a plan it reported that the + /// caller chose instead) and binds it to the caller's drawings. + /// + private static NestPipelineResult Finish( + string engineName, + NestJob job, + NestJob engineJob, + IPipelinePrepass prepass, + NestJobResult raw, + IReadOnlyDictionary drawingsByPartId, + TimeSpan solveTime, + CancellationToken token + ) + { + token.ThrowIfCancellationRequested(); + IReadOnlyDictionary released = new Dictionary(); + var clock = Stopwatch.StartNew(); var names = drawingsByPartId.ToDictionary( kv => kv.Key, kv => kv.Value.Name ?? kv.Key, diff --git a/OpenNest.Engine/NestingEngines/CandidateProgress.cs b/OpenNest.Engine/NestingEngines/CandidateProgress.cs index 449cf39e..0cce28b4 100644 --- a/OpenNest.Engine/NestingEngines/CandidateProgress.cs +++ b/OpenNest.Engine/NestingEngines/CandidateProgress.cs @@ -39,6 +39,11 @@ internal sealed class CandidateProgress(IProgress inner) : IPro public static void ReportPlan(NestJobResult plan, IProgress? progress) => progress?.Report(new NestJobProgress(NestJobStage.PlanImproved, string.Empty, -1, 0, 0, Plan: plan)); + /// Reports a whole-job plan that is not the best so far as + /// . Reporting never changes the search. + public static void ReportAlternative(NestJobResult plan, IProgress? progress) => + progress?.Report(new NestJobProgress(NestJobStage.PlanAlternative, string.Empty, -1, 0, 0, Plan: plan)); + /// True when both results place the same parts at the same poses on the same stock, /// sheet by sheet. public static bool SameLayout(NestJobResult a, NestJobResult b) => diff --git a/OpenNest.Engine/NestingEngines/DeadlineNestingEngine.cs b/OpenNest.Engine/NestingEngines/DeadlineNestingEngine.cs index 37df7c91..0e1ff4e0 100644 --- a/OpenNest.Engine/NestingEngines/DeadlineNestingEngine.cs +++ b/OpenNest.Engine/NestingEngines/DeadlineNestingEngine.cs @@ -151,7 +151,11 @@ public sealed class DeadlineNestingEngine : INestingEngine return; } if (Best != null && Best.IsBetterThan(plan)) + { + if (plan.Valid) + CandidateProgress.ReportAlternative(plan.Result, inner); return; + } Best = plan; inner?.Report(value); } diff --git a/OpenNest.Engine/NestingEngines/Default/DefaultNestingEngine.cs b/OpenNest.Engine/NestingEngines/Default/DefaultNestingEngine.cs index eda5c916..dcf8c1c0 100644 --- a/OpenNest.Engine/NestingEngines/Default/DefaultNestingEngine.cs +++ b/OpenNest.Engine/NestingEngines/Default/DefaultNestingEngine.cs @@ -188,11 +188,16 @@ public sealed class DefaultNestingEngine : INestingEngine Offer(plan); } - /// Reports the plan when it beats every plan reported so far. + /// Reports the plan when it beats every plan reported so far; a valid plan that + /// does not is reported as an alternative. public void Offer(CandidateScore plan) { if (shown != null && !plan.IsBetterThan(shown)) + { + if (plan.Valid && !CandidateProgress.SameLayout(plan.Result, shown.Result)) + CandidateProgress.ReportAlternative(plan.Result, inner); return; + } shown = plan; CandidateProgress.ReportPlan(plan.Result, inner); } diff --git a/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.cs b/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.cs index aca4a621..b05ee34a 100644 --- a/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.cs +++ b/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.cs @@ -129,6 +129,8 @@ public sealed class IrregularNestingEngine : INestingEngine best = plan; ReportPlan(job, types, best, progress, token); } + else + ReportAlternative(job, types, plan, progress, token); if (best.Unplaced == 0 && best.Sheets.Count == 0) break; } @@ -151,7 +153,10 @@ public sealed class IrregularNestingEngine : INestingEngine break; var plan = solver.Plan(demand, axis, 1.0, grouped: true); if (!plan.IsBetterThan(improved)) + { + ReportAlternative(job, types, plan, progress, token); continue; + } ReportPlan(job, types, plan, progress, token); improved = solver.ImproveTail(plan, solver.Work.Value + WorkBudget * 2); if (!ReferenceEquals(improved, plan)) @@ -173,6 +178,8 @@ public sealed class IrregularNestingEngine : INestingEngine if (!ReferenceEquals(improved, plan)) ReportPlan(job, types, improved, progress, token); } + else + ReportAlternative(job, types, plan, progress, token); } // Then try to drop a sheet: split the parts over one sheet fewer and pack each sheet edge // first, the key part turned by its contacts. Replaces the result only by beating it. @@ -249,6 +256,16 @@ public sealed class IrregularNestingEngine : INestingEngine CandidateProgress.ReportPlan(BuildResult(job, types, plan, null, token), progress); } + /// Reports a whole-job plan that lost to the best so far, as another layout a front + /// end may offer; reporting never changes the search. + private static void ReportAlternative(NestJob job, IReadOnlyList types, Plan plan, + IProgress? progress, CancellationToken token) + { + if (progress == null || plan.Sheets.Count == 0) + return; + CandidateProgress.ReportAlternative(BuildResult(job, types, plan, null, token), progress); + } + /// Exercises the production physical-tail lifecycle from a test-owned incumbent. /// This does not alter normal Solve or expose a public packing API. internal NestJobResult ImproveTailForTesting(NestJob job, IReadOnlyList physicalPlan) diff --git a/OpenNest.Server.Worker/NestJobReporter.cs b/OpenNest.Server.Worker/NestJobReporter.cs index 4ef4c50f..2a378a09 100644 --- a/OpenNest.Server.Worker/NestJobReporter.cs +++ b/OpenNest.Server.Worker/NestJobReporter.cs @@ -18,7 +18,8 @@ public sealed class NestJobReporter : IProgress public void Report(NestJobProgress value) { - if (value is null) + // Alternative plans stay on the worker: the job stores only its best plan. + if (value is null || value.Stage == NestJobStage.PlanAlternative) return; // Copied here, on the engine's thread, so later changes to its objects cannot leak in; // serialized later, off that thread. diff --git a/OpenNest.WinForms.Tests/Forms/NestProgressFormLayoutsTests.cs b/OpenNest.WinForms.Tests/Forms/NestProgressFormLayoutsTests.cs new file mode 100644 index 00000000..3d4ff05c --- /dev/null +++ b/OpenNest.WinForms.Tests/Forms/NestProgressFormLayoutsTests.cs @@ -0,0 +1,154 @@ +using System.Windows.Forms; +using OpenNest.CNC; +using OpenNest.Controls; +using OpenNest.Engine.Jobs; +using OpenNest.Forms; +using OpenNest.Geometry; + +namespace OpenNest.WinForms.Tests.Forms; + +// The picks read here have already completed on this STA thread; nothing blocks. +#pragma warning disable xUnit1031 + +/// +/// The Auto Nest progress window's top layouts: one card per layout with its sheets, and the +/// pick of the layout to use, during the run and once it has finished. +/// +public class NestProgressFormLayoutsTests +{ + private static readonly Drawing Bracket = new("bracket", Rectangle()); + private static readonly NestPlateStock Stock = new("sheet", new Size(48, 96), quantity: null, partSpacing: 0.25); + + private static Program Rectangle() + { + var program = new Program(); + program.MoveTo(0, 0); + program.LineTo(10, 0); + program.LineTo(10, 20); + program.LineTo(0, 20); + program.LineTo(0, 0); + return program; + } + + private static NestLayoutChoice Layout(params (double X, double Y)[] at) + { + var parts = at.Select(p => + { + var part = new Part(Bracket) { Location = new Vector(p.X, p.Y) }; + part.UpdateBounds(); + return part; + }).ToList(); + return new NestLayoutChoice(new[] { new ProposedPlate(0, Stock, parts) }, _ => null!); + } + + private static NestLayoutChoice Columns() => Layout((0, 0), (0, 28), (10, 0)); + + private static NestLayoutChoice Row() => Layout((0, 0), (40, 0), (86, 0)); + + private static void WithForm(Action> test) => StaTestThread.Run(() => + { + using var cts = new CancellationTokenSource(); + var stopped = false; + using var form = new NestProgressForm(cts) { AllowAccept = false, HoldOpenUntilCompleted = true }; + form.ShowPlanStrip(new ColorScheme(), () => stopped = true); + form.Show(); + try + { + test(form, cts, () => stopped); + } + finally + { + form.ShowCompleted(); + form.Close(); + } + }, TimeSpan.FromSeconds(30), "The STA test did not complete."); + + private static Button Button(Form form, string name) => + Assert.IsType