diff --git a/OpenNest.Data/ClampSettings.cs b/OpenNest.Data/ClampSettings.cs
index 63d8047b..66adcef9 100644
--- a/OpenNest.Data/ClampSettings.cs
+++ b/OpenNest.Data/ClampSettings.cs
@@ -206,20 +206,9 @@ public sealed class ClampSettings
///
public static ClampSettings Load(string path, out ClampSettingsStatus status)
{
- if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
+ if (!SettingsFile.TryReadText(path, out var json, out var missing))
{
- status = ClampSettingsStatus.Missing;
- return Fallback;
- }
-
- string json;
- try
- {
- json = File.ReadAllText(path);
- }
- catch (Exception ex) when (SettingsFile.IsUnreadableFile(ex))
- {
- status = ClampSettingsStatus.Invalid;
+ status = missing ? ClampSettingsStatus.Missing : ClampSettingsStatus.Invalid;
return Fallback;
}
return Parse(json, out status);
diff --git a/OpenNest.Data/NestDefaults.cs b/OpenNest.Data/NestDefaults.cs
index e7879009..c278dedb 100644
--- a/OpenNest.Data/NestDefaults.cs
+++ b/OpenNest.Data/NestDefaults.cs
@@ -102,22 +102,11 @@ public sealed class NestDefaults
out NestDefaultsStatus status
)
{
- if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
+ // A file that exists but cannot be read (locked, access-denied)
+ // must never block creating a nest.
+ if (!SettingsFile.TryReadText(path, out var json, out var missing))
{
- status = NestDefaultsStatus.Missing;
- return WithUnits(Fallback, fallbackUnits);
- }
-
- string json;
- try
- {
- json = File.ReadAllText(path);
- }
- catch (Exception ex) when (SettingsFile.IsUnreadableFile(ex))
- {
- // A file that exists but cannot be read (locked, access-denied)
- // must never block creating a nest.
- status = NestDefaultsStatus.Invalid;
+ status = missing ? NestDefaultsStatus.Missing : NestDefaultsStatus.Invalid;
return WithUnits(Fallback, fallbackUnits);
}
return Parse(json, fallbackUnits, out status);
diff --git a/OpenNest.Data/SettingsFile.cs b/OpenNest.Data/SettingsFile.cs
index 6500e866..c2d0f014 100644
--- a/OpenNest.Data/SettingsFile.cs
+++ b/OpenNest.Data/SettingsFile.cs
@@ -1,3 +1,4 @@
+using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
namespace OpenNest.Data;
@@ -51,6 +52,32 @@ internal static class SettingsFile
}
}
+ ///
+ /// Reads the file's text. Returns false when the file is missing (
+ /// true) or exists but cannot be read, for example locked or access-denied.
+ ///
+ public static bool TryReadText(
+ string path,
+ [NotNullWhen(true)] out string? text,
+ out bool missing
+ )
+ {
+ text = null;
+ missing = string.IsNullOrWhiteSpace(path) || !File.Exists(path);
+ if (missing)
+ return false;
+
+ try
+ {
+ text = File.ReadAllText(path);
+ return true;
+ }
+ catch (Exception ex) when (IsUnreadableFile(ex))
+ {
+ return false;
+ }
+ }
+
public static bool IsUnreadableFile(Exception ex) =>
ex
is JsonException
diff --git a/OpenNest.Engine/BestFit/BestFitCache.cs b/OpenNest.Engine/BestFit/BestFitCache.cs
index 44d006c7..e6f706be 100644
--- a/OpenNest.Engine/BestFit/BestFitCache.cs
+++ b/OpenNest.Engine/BestFit/BestFitCache.cs
@@ -227,23 +227,13 @@ namespace OpenNest.Engine.BestFit
}
}
- private static Entry GetEntry(Drawing drawing)
- {
- var source = CanonicalFrame.SourceOf(drawing);
-
- if (_entries.TryGetValue(source, out var entry) && entry.IsCurrentFor(source))
- return entry;
-
- lock (_entriesLock)
- {
- if (_entries.TryGetValue(source, out entry) && entry.IsCurrentFor(source))
- return entry;
-
- entry = new Entry(source);
- _entries.AddOrUpdate(source, entry);
- return entry;
- }
- }
+ private static Entry GetEntry(Drawing drawing) =>
+ DrawingCacheEntry.GetOrCreate(
+ _entries,
+ _entriesLock,
+ CanonicalFrame.SourceOf(drawing),
+ static source => new Entry(source)
+ );
private static List GetCandidates(Entry entry, Drawing drawing, double spacing)
{
@@ -407,11 +397,8 @@ namespace OpenNest.Engine.BestFit
return copy;
}
- private sealed class Entry
+ private sealed class Entry : DrawingCacheEntry
{
- private readonly CNC.Program _program;
- private readonly double _sourceAngle;
-
public readonly ConcurrentDictionary>> Unfiltered = new();
public readonly ConcurrentDictionary<
@@ -420,14 +407,7 @@ namespace OpenNest.Engine.BestFit
> Filtered = new();
public Entry(Drawing source)
- {
- _program = source.Program;
- _sourceAngle = source.Source?.Angle ?? 0.0;
- }
-
- public bool IsCurrentFor(Drawing source) =>
- ReferenceEquals(_program, source.Program)
- && _sourceAngle == (source.Source?.Angle ?? 0.0);
+ : base(source) { }
}
/// The geometry a drawing was reconstructed from, and the program built then.
diff --git a/OpenNest.Engine/DrawingCacheEntry.cs b/OpenNest.Engine/DrawingCacheEntry.cs
new file mode 100644
index 00000000..114d3265
--- /dev/null
+++ b/OpenNest.Engine/DrawingCacheEntry.cs
@@ -0,0 +1,51 @@
+using System;
+using System.Runtime.CompilerServices;
+
+namespace OpenNest.Engine
+{
+ ///
+ /// A per-drawing cache entry that is current while the drawing keeps the program
+ /// reference and source angle it was built from.
+ ///
+ internal abstract class DrawingCacheEntry
+ {
+ private readonly CNC.Program program;
+ private readonly double sourceAngle;
+
+ protected DrawingCacheEntry(Drawing source)
+ {
+ program = source.Program;
+ sourceAngle = source.Source?.Angle ?? 0.0;
+ }
+
+ public bool IsCurrentFor(Drawing source) =>
+ ReferenceEquals(program, source.Program)
+ && sourceAngle == (source.Source?.Angle ?? 0.0);
+
+ ///
+ /// Returns the current entry for , replacing a missing or
+ /// stale one under .
+ ///
+ public static TEntry GetOrCreate(
+ ConditionalWeakTable entries,
+ object gate,
+ Drawing source,
+ Func create
+ )
+ where TEntry : DrawingCacheEntry
+ {
+ if (entries.TryGetValue(source, out var entry) && entry.IsCurrentFor(source))
+ return entry;
+
+ lock (gate)
+ {
+ if (entries.TryGetValue(source, out entry) && entry.IsCurrentFor(source))
+ return entry;
+
+ entry = create(source);
+ entries.AddOrUpdate(source, entry);
+ return entry;
+ }
+ }
+ }
+}
diff --git a/OpenNest.Engine/Fill/FillLinear.cs b/OpenNest.Engine/Fill/FillLinear.cs
index 18d01d08..49364f74 100644
--- a/OpenNest.Engine/Fill/FillLinear.cs
+++ b/OpenNest.Engine/Fill/FillLinear.cs
@@ -504,39 +504,7 @@ namespace OpenNest.Engine.Fill
List parts,
out int overlapA,
out int overlapB
- )
- {
- var checker = new PartOverlapChecker();
-
- for (var i = 0; i < parts.Count; i++)
- {
- var b1 = parts[i].BoundingBox;
-
- for (var j = i + 1; j < parts.Count; j++)
- {
- var b2 = parts[j].BoundingBox;
-
- var overlapX =
- System.Math.Min(b1.Right, b2.Right) - System.Math.Max(b1.Left, b2.Left);
- var overlapY =
- System.Math.Min(b1.Top, b2.Top) - System.Math.Max(b1.Bottom, b2.Bottom);
-
- if (overlapX <= Tolerance.Epsilon || overlapY <= Tolerance.Epsilon)
- continue;
-
- if (checker.Overlaps(parts[i], parts[j]))
- {
- overlapA = i;
- overlapB = j;
- return true;
- }
- }
- }
-
- overlapA = -1;
- overlapB = -1;
- return false;
- }
+ ) => Strategies.FillHelpers.HasOverlappingParts(parts, out overlapA, out overlapB);
///
/// Creates a seed pattern containing a single part positioned at the work area origin.
diff --git a/OpenNest.Engine/Fill/FillResultCache.cs b/OpenNest.Engine/Fill/FillResultCache.cs
index db9c81a4..321cc443 100644
--- a/OpenNest.Engine/Fill/FillResultCache.cs
+++ b/OpenNest.Engine/Fill/FillResultCache.cs
@@ -85,38 +85,20 @@ public static class FillResultCache
}
}
- private static Entry GetEntry(Drawing source)
+ private static Entry GetEntry(Drawing source) =>
+ DrawingCacheEntry.GetOrCreate(
+ _entries,
+ _entriesLock,
+ source,
+ static drawing => new Entry(drawing)
+ );
+
+ private sealed class Entry : DrawingCacheEntry
{
- if (_entries.TryGetValue(source, out var entry) && entry.IsCurrentFor(source))
- return entry;
-
- lock (_entriesLock)
- {
- if (_entries.TryGetValue(source, out entry) && entry.IsCurrentFor(source))
- return entry;
-
- entry = new Entry(source);
- _entries.AddOrUpdate(source, entry);
- return entry;
- }
- }
-
- private sealed class Entry
- {
- private readonly CNC.Program program;
- private readonly double sourceAngle;
-
public readonly ConcurrentDictionary> Results = new();
public Entry(Drawing source)
- {
- program = source.Program;
- sourceAngle = source.Source?.Angle ?? 0.0;
- }
-
- public bool IsCurrentFor(Drawing source) =>
- ReferenceEquals(program, source.Program)
- && sourceAngle == (source.Source?.Angle ?? 0.0);
+ : base(source) { }
}
private readonly record struct CacheKey(bool IsCanonical, double Width, double Height, double Spacing)
@@ -127,6 +109,7 @@ public static class FillResultCache
System.Math.Round(width, 2),
System.Math.Round(height, 2),
spacing
- ) { }
+ )
+ { }
}
}
diff --git a/OpenNest.Engine/Strategies/FillHelpers.cs b/OpenNest.Engine/Strategies/FillHelpers.cs
index f508a6c2..5cf27599 100644
--- a/OpenNest.Engine/Strategies/FillHelpers.cs
+++ b/OpenNest.Engine/Strategies/FillHelpers.cs
@@ -222,7 +222,18 @@ namespace OpenNest.Engine.Strategies
/// Checks if any pair of parts geometrically overlap. Uses bounding box
/// pre-filtering for performance, then falls back to shape intersection.
///
- internal static bool HasOverlappingParts(List parts)
+ internal static bool HasOverlappingParts(List parts) =>
+ HasOverlappingParts(parts, out _, out _);
+
+ ///
+ /// Finds the first pair of overlapping parts, reporting their indices
+ /// (or -1 when none overlap).
+ ///
+ internal static bool HasOverlappingParts(
+ List parts,
+ out int overlapA,
+ out int overlapB
+ )
{
var checker = new PartOverlapChecker();
@@ -243,10 +254,16 @@ namespace OpenNest.Engine.Strategies
continue;
if (checker.Overlaps(parts[i], parts[j]))
+ {
+ overlapA = i;
+ overlapB = j;
return true;
+ }
}
}
+ overlapA = -1;
+ overlapB = -1;
return false;
}
}
diff --git a/OpenNest.Mcp/Tools/NestingTools.cs b/OpenNest.Mcp/Tools/NestingTools.cs
index 7fc65249..37dd2967 100644
--- a/OpenNest.Mcp/Tools/NestingTools.cs
+++ b/OpenNest.Mcp/Tools/NestingTools.cs
@@ -54,50 +54,15 @@ namespace OpenNest.Mcp.Tools
[Description("Maximum quantity to place (0 = unlimited)")] int quantity = 0,
[Description(FillStrategies)]
string engine = null
- )
- {
- var plate = _session.GetPlate(plateIndex);
- if (plate == null)
- return $"Error: plate {plateIndex} not found";
- if (_session.IsConsumedStockPlate(plate))
- return "Error: this empty entry was consumed by a repeated layout; select or create an unused stock plate. Nothing committed.";
-
- var drawing = _session.GetDrawing(drawingName);
- if (drawing == null)
- return $"Error: drawing '{drawingName}' not found";
-
- var strategy = ResolveStrategy(engine);
- if (strategy == null)
- return EngineError(engine);
- if (OutlinedSheetRefusal(plate) is { } refusal)
- return refusal;
-
- var countBefore = plate.Parts.Count;
- var item = new NestItem { Drawing = drawing, Quantity = quantity };
- var parts = PlateFillService.FillItem(
- strategy,
- plate,
- item,
- plate.WorkArea(),
- null,
- CancellationToken.None
+ ) =>
+ FillWithDrawing(
+ plateIndex,
+ drawingName,
+ quantity,
+ engine,
+ plate => plate.WorkArea(),
+ $"plate {plateIndex}"
);
- plate.Parts.AddRange(parts);
- var success = parts.Count > 0;
-
- var countAfter = plate.Parts.Count;
- var added = countAfter - countBefore;
-
- var sb = new StringBuilder();
- sb.AppendLine(
- $"Fill plate {plateIndex} with '{drawingName}' ({strategy}): {(success ? "success" : "failed")}"
- );
- sb.AppendLine($" Parts added: {added}");
- sb.AppendLine($" Total parts: {countAfter}");
- sb.AppendLine($" Utilization: {plate.Utilization():P1}");
-
- return sb.ToString();
- }
[McpServerTool(Name = "fill_area")]
[Description("Fill a specific rectangular area on a plate with a single drawing.")]
@@ -111,6 +76,23 @@ namespace OpenNest.Mcp.Tools
[Description("Maximum quantity to place (0 = unlimited)")] int quantity = 0,
[Description(FillStrategies)]
string engine = null
+ ) =>
+ FillWithDrawing(
+ plateIndex,
+ drawingName,
+ quantity,
+ engine,
+ _ => new Box(x, y, width, length),
+ $"area ({x:F1},{y:F1} {width:F1}x{length:F1}) on plate {plateIndex}"
+ );
+
+ private string FillWithDrawing(
+ int plateIndex,
+ string drawingName,
+ int quantity,
+ string engine,
+ Func area,
+ string target
)
{
var plate = _session.GetPlate(plateIndex);
@@ -131,27 +113,22 @@ namespace OpenNest.Mcp.Tools
var countBefore = plate.Parts.Count;
var item = new NestItem { Drawing = drawing, Quantity = quantity };
- var area = new Box(x, y, width, length);
var parts = PlateFillService.FillItem(
strategy,
plate,
item,
- area,
+ area(plate),
null,
CancellationToken.None
);
plate.Parts.AddRange(parts);
- var success = parts.Count > 0;
-
- var countAfter = plate.Parts.Count;
- var added = countAfter - countBefore;
var sb = new StringBuilder();
sb.AppendLine(
- $"Fill area ({x:F1},{y:F1} {width:F1}x{length:F1}) on plate {plateIndex} with '{drawingName}' ({strategy}): {(success ? "success" : "failed")}"
+ $"Fill {target} with '{drawingName}' ({strategy}): {(parts.Count > 0 ? "success" : "failed")}"
);
- sb.AppendLine($" Parts added: {added}");
- sb.AppendLine($" Total parts: {countAfter}");
+ sb.AppendLine($" Parts added: {plate.Parts.Count - countBefore}");
+ sb.AppendLine($" Total parts: {plate.Parts.Count}");
sb.AppendLine($" Utilization: {plate.Utilization():P1}");
return sb.ToString();
diff --git a/OpenNest/Forms/MainForm.View.cs b/OpenNest/Forms/MainForm.View.cs
index 4b1d03af..02f3f544 100644
--- a/OpenNest/Forms/MainForm.View.cs
+++ b/OpenNest/Forms/MainForm.View.cs
@@ -91,60 +91,40 @@ namespace OpenNest.Forms
activeForm.OverlapDisplay = OverlapDisplayMode.Both;
}
- private void ToggleDrawRapids_Click(object sender, EventArgs e)
- {
- if (activeForm == null)
- return;
- activeForm.ToggleRapid();
- mnuViewDrawRapids.Checked = activeForm.PlateView.DrawRapid;
- }
+ private void ToggleDrawRapids_Click(object sender, EventArgs e) =>
+ ToggleView(mnuViewDrawRapids, f => f.ToggleRapid(), v => v.DrawRapid);
- private void ToggleDrawPiercePoints_Click(object sender, EventArgs e)
- {
- if (activeForm == null)
- return;
- activeForm.TogglePiercePoints();
- mnuViewDrawPiercePoints.Checked = activeForm.PlateView.DrawPiercePoints;
- }
+ private void ToggleDrawPiercePoints_Click(object sender, EventArgs e) =>
+ ToggleView(mnuViewDrawPiercePoints, f => f.TogglePiercePoints(), v => v.DrawPiercePoints);
- private void ToggleDrawBounds_Click(object sender, EventArgs e)
- {
- if (activeForm == null)
- return;
- activeForm.ToggleDrawBounds();
- mnuViewDrawBounds.Checked = activeForm.PlateView.DrawBounds;
- }
+ private void ToggleDrawBounds_Click(object sender, EventArgs e) =>
+ ToggleView(mnuViewDrawBounds, f => f.ToggleDrawBounds(), v => v.DrawBounds);
- private void ToggleDrawOffset_Click(object sender, EventArgs e)
- {
- if (activeForm == null)
- return;
- activeForm.ToggleDrawOffset();
- mnuViewDrawOffset.Checked = activeForm.PlateView.DrawOffset;
- }
+ private void ToggleDrawOffset_Click(object sender, EventArgs e) =>
+ ToggleView(mnuViewDrawOffset, f => f.ToggleDrawOffset(), v => v.DrawOffset);
- private void ToggleDrawCutDirection_Click(object sender, EventArgs e)
- {
- if (activeForm == null)
- return;
- activeForm.ToggleCutDirection();
- mnuViewDrawCutDirection.Checked = activeForm.PlateView.DrawCutDirection;
- }
+ private void ToggleDrawCutDirection_Click(object sender, EventArgs e) =>
+ ToggleView(mnuViewDrawCutDirection, f => f.ToggleCutDirection(), v => v.DrawCutDirection);
- private void ToggleDrawSupport_Click(object sender, EventArgs e)
- {
- if (activeForm == null)
- return;
- activeForm.ToggleSupport();
- mnuViewDrawSupport.Checked = activeForm.PlateView.DrawSupport;
- }
+ private void ToggleDrawSupport_Click(object sender, EventArgs e) =>
+ ToggleView(mnuViewDrawSupport, f => f.ToggleSupport(), v => v.DrawSupport);
- private void ToggleShowBendLines_Click(object sender, EventArgs e)
+ private void ToggleShowBendLines_Click(object sender, EventArgs e) =>
+ ToggleView(mnuViewShowBendLines, f => f.ToggleBendLines(), v => v.ShowBendLines);
+
+ ///
+ /// Flips a plate-view display option on the active nest and checks its menu item to match.
+ ///
+ private void ToggleView(
+ System.Windows.Forms.ToolStripMenuItem item,
+ Action toggle,
+ Func isOn
+ )
{
if (activeForm == null)
return;
- activeForm.ToggleBendLines();
- mnuViewShowBendLines.Checked = activeForm.PlateView.ShowBendLines;
+ toggle(activeForm);
+ item.Checked = isOn(activeForm.PlateView);
}
private void ZoomToArea_Click(object sender, EventArgs e) => WithActive(f => f.PlateView.SetAction(typeof(ActionZoomWindow)));