mirror of
https://github.com/ajisaacs/OpenNest.git
synced 2026-11-18 07:07:40 -05:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7f92a637d7 | ||
|
|
ac6de33a9e | ||
|
|
e589731828 | ||
|
|
08a47dafa5 | ||
|
|
fcf205ab44 | ||
|
|
683ece4d3c | ||
|
|
538ccebd6d | ||
|
|
7ae01978f5 | ||
|
|
fd15c13d88 | ||
|
|
4f1779376b | ||
|
|
04c0e3bca3 | ||
|
|
244f946912 | ||
|
|
480efb2893 | ||
|
|
6f7d8049a7 | ||
|
|
f11f77f879 | ||
|
|
810cc1ed01 | ||
|
|
587613ff89 | ||
|
|
d7f550dda4 | ||
|
|
c00ae58ac0 |
No files matched your search
@@ -141,8 +141,8 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Isolate logs, safe metadata and ephemeral auth
|
- name: Isolate logs, safe metadata and ephemeral auth
|
||||||
run: |
|
run: |
|
||||||
printf 'METADATA_DIR=%s/server-image-metadata\nRESULTS=%s/server-image-results\nDOCKER_CONFIG=%s/server-image-auth\n' \
|
printf 'METADATA_DIR=%s/server-image-metadata\nRESULTS=%s/server-image-results\nDOCKER_CONFIG=%s/server-image-auth\nRELEASE_POLICY=%s/release-policy/server_image_release.py\n' \
|
||||||
"$RUNNER_TEMP" "$RUNNER_TEMP" "$RUNNER_TEMP" >> "$GITHUB_ENV"
|
"$RUNNER_TEMP" "$RUNNER_TEMP" "$RUNNER_TEMP" "$RUNNER_TEMP" >> "$GITHUB_ENV"
|
||||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||||
with:
|
with:
|
||||||
ref: master
|
ref: master
|
||||||
@@ -153,6 +153,10 @@ jobs:
|
|||||||
env:
|
env:
|
||||||
TAG: ${{ github.event.release.tag_name || inputs.tag }}
|
TAG: ${{ github.event.release.tag_name || inputs.tag }}
|
||||||
run: python3 scripts/server_image_release.py source
|
run: python3 scripts/server_image_release.py source
|
||||||
|
- name: Keep master's publication policy (an older tag's helper must not decide visibility)
|
||||||
|
run: |
|
||||||
|
mkdir -p "$(dirname "$RELEASE_POLICY")"
|
||||||
|
cp scripts/server_image_release.py "$RELEASE_POLICY"
|
||||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||||
with:
|
with:
|
||||||
ref: ${{ steps.source.outputs.source_sha }}
|
ref: ${{ steps.source.outputs.source_sha }}
|
||||||
@@ -203,7 +207,7 @@ jobs:
|
|||||||
- name: Refuse unknown visibility, wrong association, and both existing tags
|
- name: Refuse unknown visibility, wrong association, and both existing tags
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
run: python3 scripts/server_image_release.py preflight
|
run: python3 "$RELEASE_POLICY" preflight
|
||||||
- name: Login and publish only the two immutable tags (no rebuild)
|
- name: Login and publish only the two immutable tags (no rebuild)
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
@@ -219,7 +223,7 @@ jobs:
|
|||||||
id: readback
|
id: readback
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
run: python3 scripts/server_image_release.py readback
|
run: python3 "$RELEASE_POLICY" readback
|
||||||
- name: Remove ephemeral Docker credentials
|
- name: Remove ephemeral Docker credentials
|
||||||
if: always()
|
if: always()
|
||||||
run: rm -rf -- "$DOCKER_CONFIG"
|
run: rm -rf -- "$DOCKER_CONFIG"
|
||||||
@@ -244,16 +248,15 @@ jobs:
|
|||||||
timeout-minutes: 25
|
timeout-minutes: 25
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
packages: read
|
|
||||||
env:
|
env:
|
||||||
VERSION: ${{ needs.publish.outputs.version }}
|
VERSION: ${{ needs.publish.outputs.version }}
|
||||||
SOURCE_SHA: ${{ needs.publish.outputs.source_sha }}
|
SOURCE_SHA: ${{ needs.publish.outputs.source_sha }}
|
||||||
MANIFEST_DIGEST: ${{ needs.publish.outputs.manifest_digest }}
|
MANIFEST_DIGEST: ${{ needs.publish.outputs.manifest_digest }}
|
||||||
CONFIG_DIGEST: ${{ needs.publish.outputs.config_digest }}
|
CONFIG_DIGEST: ${{ needs.publish.outputs.config_digest }}
|
||||||
steps:
|
steps:
|
||||||
- name: Isolate logs, safe metadata and ephemeral auth
|
- name: Isolate logs, safe metadata and an empty Docker config
|
||||||
run: |
|
run: |
|
||||||
printf 'METADATA_DIR=%s/server-image-metadata\nRESULTS=%s/server-image-results\nDOCKER_CONFIG=%s/server-image-auth\n' \
|
printf 'METADATA_DIR=%s/server-image-metadata\nRESULTS=%s/server-image-results\nDOCKER_CONFIG=%s/server-image-anonymous\n' \
|
||||||
"$RUNNER_TEMP" "$RUNNER_TEMP" "$RUNNER_TEMP" >> "$GITHUB_ENV"
|
"$RUNNER_TEMP" "$RUNNER_TEMP" "$RUNNER_TEMP" >> "$GITHUB_ENV"
|
||||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||||
with:
|
with:
|
||||||
@@ -264,25 +267,19 @@ jobs:
|
|||||||
DOTNET_INSTALL_DIR: ${{ runner.temp }}/dotnet8
|
DOTNET_INSTALL_DIR: ${{ runner.temp }}/dotnet8
|
||||||
with:
|
with:
|
||||||
dotnet-version: '8.0.x'
|
dotnet-version: '8.0.x'
|
||||||
- name: Pull returned digest on a clean runner
|
- name: Pull returned digest anonymously on a clean runner
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
run: |
|
run: |
|
||||||
python3 -c 'import os,sys; sys.path.insert(0,"scripts"); from server_image_release import sha256,commit,version; sha256(os.environ["MANIFEST_DIGEST"]); sha256(os.environ["CONFIG_DIGEST"]); commit(os.environ["SOURCE_SHA"]); version("v"+os.environ["VERSION"])'
|
python3 -c 'import os,sys; sys.path.insert(0,"scripts"); from server_image_release import sha256,commit,version; sha256(os.environ["MANIFEST_DIGEST"]); sha256(os.environ["CONFIG_DIGEST"]); commit(os.environ["SOURCE_SHA"]); version("v"+os.environ["VERSION"])'
|
||||||
mkdir -m 700 -p "$DOCKER_CONFIG"
|
mkdir -m 700 -p "$DOCKER_CONFIG"
|
||||||
printf '%s' "$GITHUB_TOKEN" | docker login ghcr.io -u "$GITHUB_ACTOR" --password-stdin
|
|
||||||
image="ghcr.io/ajisaacs/opennest-server@$MANIFEST_DIGEST"
|
image="ghcr.io/ajisaacs/opennest-server@$MANIFEST_DIGEST"
|
||||||
docker pull --platform linux/amd64 "$image"
|
docker pull --platform linux/amd64 "$image"
|
||||||
printf 'LOCAL_IMAGE=%s\n' "$image" >> "$GITHUB_ENV"
|
printf 'LOCAL_IMAGE=%s\n' "$image" >> "$GITHUB_ENV"
|
||||||
- name: Remove ephemeral Docker credentials
|
|
||||||
if: always()
|
|
||||||
run: rm -rf -- "$DOCKER_CONFIG"
|
|
||||||
- name: Verify pulled digest, config, platform and provenance
|
- name: Verify pulled digest, config, platform and provenance
|
||||||
run: python3 scripts/server_image_release.py pulled
|
run: python3 scripts/server_image_release.py pulled
|
||||||
- name: Real-client persistence smoke of pulled digest
|
- name: Real-client persistence smoke of pulled digest
|
||||||
run: scripts/Test-ServerContainer.sh --image "$LOCAL_IMAGE" --results "$RESULTS/smoke"
|
run: scripts/Test-ServerContainer.sh --image "$LOCAL_IMAGE" --results "$RESULTS/smoke"
|
||||||
- name: Mark verified only after pulled-image smoke passes
|
- name: Mark verified only after pulled-image smoke passes
|
||||||
run: printf 'Verified private server image `%s` from `%s`.\n' "$LOCAL_IMAGE" "$SOURCE_SHA" >> "$GITHUB_STEP_SUMMARY"
|
run: printf 'Verified public server image `%s` from `%s`.\n' "$LOCAL_IMAGE" "$SOURCE_SHA" >> "$GITHUB_STEP_SUMMARY"
|
||||||
- name: Retain logs and safe pulled-image provenance only
|
- name: Retain logs and safe pulled-image provenance only
|
||||||
if: always()
|
if: always()
|
||||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ using OpenNest.CommonLines;
|
|||||||
using OpenNest.CutOffs;
|
using OpenNest.CutOffs;
|
||||||
using OpenNest.Desktop.Interaction;
|
using OpenNest.Desktop.Interaction;
|
||||||
using OpenNest.Desktop.Rendering;
|
using OpenNest.Desktop.Rendering;
|
||||||
|
using OpenNest.Engine.Fill;
|
||||||
using OpenNest.Geometry;
|
using OpenNest.Geometry;
|
||||||
using OpenNest.Support;
|
using OpenNest.Support;
|
||||||
using SkiaSharp;
|
using SkiaSharp;
|
||||||
@@ -117,6 +118,40 @@ namespace OpenNest.Avalonia.Controls
|
|||||||
/// <summary>No edits while Auto Nest works on the nest (WinForms EditsLocked).</summary>
|
/// <summary>No edits while Auto Nest works on the nest (WinForms EditsLocked).</summary>
|
||||||
public bool EditsLocked { get; set; }
|
public bool EditsLocked { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Which way Shift+click and Ctrl+click settle a placed copy (Tools > Options > Clone
|
||||||
|
/// push placement), read at each click.
|
||||||
|
/// </summary>
|
||||||
|
public Func<SettleOrder> PlacementOrder { get; set; } = () => SettleOrder.ClosestToCorner;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Edit > Copy: places copies of the selected parts with the place tool; false when
|
||||||
|
/// nothing is selected or edits are locked.
|
||||||
|
/// </summary>
|
||||||
|
public bool CopySelection() => PlateClipboard.Copy(this, tools, ReadPlacementOrder) != null;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Edit > Cut: as <see cref="CopySelection"/>, then removes the parts as one Cut step.
|
||||||
|
/// </summary>
|
||||||
|
public bool CutSelection() => PlateClipboard.Cut(this, tools, ReadPlacementOrder) != null;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A drawing picked in the drawing list and carried into the view: the place tool with one
|
||||||
|
/// new part of it.
|
||||||
|
/// </summary>
|
||||||
|
public void PlaceDrawing(Drawing drawing) =>
|
||||||
|
tools.SetTool(DrawingPlacement.CreatePlaceTool(this, drawing, ReadPlacementOrder));
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A drawing dragged from the drawing list and dropped at <paramref name="at"/> (view
|
||||||
|
/// coordinates): one part centred there, or null while edits are locked.
|
||||||
|
/// </summary>
|
||||||
|
public Part DropDrawing(Drawing drawing, Point at) =>
|
||||||
|
DrawingPlacement.AddPart(this, drawing, ToWorld(at));
|
||||||
|
|
||||||
|
private SettleOrder ReadPlacementOrder() =>
|
||||||
|
PlacementOrder?.Invoke() ?? SettleOrder.ClosestToCorner;
|
||||||
|
|
||||||
Undo.ChangeScope IPlateToolHost.BeginChange(string label, object coalesceKey) =>
|
Undo.ChangeScope IPlateToolHost.BeginChange(string label, object coalesceKey) =>
|
||||||
BeginChangeHandler?.Invoke(label, coalesceKey) ?? Undo.ChangeScope.Detached();
|
BeginChangeHandler?.Invoke(label, coalesceKey) ?? Undo.ChangeScope.Detached();
|
||||||
|
|
||||||
@@ -137,13 +172,19 @@ namespace OpenNest.Avalonia.Controls
|
|||||||
Focusable = true;
|
Focusable = true;
|
||||||
hitTester = new PlateHitTester(part => PathsFor(part).Geometry);
|
hitTester = new PlateHitTester(part => PathsFor(part).Geometry);
|
||||||
tools = new PlateToolManager(this);
|
tools = new PlateToolManager(this);
|
||||||
Edits = new PlateEdits(this);
|
// While the place tool is active, edits move its copies.
|
||||||
|
Edits = new PlateEdits(this) { Tools = tools };
|
||||||
selection.Changed += (_, _) =>
|
selection.Changed += (_, _) =>
|
||||||
{
|
{
|
||||||
InvalidateVisual();
|
InvalidateVisual();
|
||||||
ViewChanged?.Invoke(this, EventArgs.Empty);
|
ViewChanged?.Invoke(this, EventArgs.Empty);
|
||||||
};
|
};
|
||||||
tools.StatusChanged += (_, _) => ViewChanged?.Invoke(this, EventArgs.Empty);
|
tools.StatusChanged += (_, _) =>
|
||||||
|
{
|
||||||
|
// A place tool's copies leave the cache when the tool ends.
|
||||||
|
TrimCache();
|
||||||
|
ViewChanged?.Invoke(this, EventArgs.Empty);
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
void IPlateToolHost.Invalidate() => InvalidateVisual();
|
void IPlateToolHost.Invalidate() => InvalidateVisual();
|
||||||
@@ -158,7 +199,8 @@ namespace OpenNest.Avalonia.Controls
|
|||||||
commonLineChecks.Clear();
|
commonLineChecks.Clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Keeps only the shown plate's parts, so closed plates do not hold their paths.
|
// Keeps only the shown plate's parts and the place tool's copies, so closed plates and
|
||||||
|
// ended tools do not hold their paths.
|
||||||
private void TrimCache()
|
private void TrimCache()
|
||||||
{
|
{
|
||||||
if (plate == null)
|
if (plate == null)
|
||||||
@@ -168,6 +210,8 @@ namespace OpenNest.Avalonia.Controls
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
var shown = new HashSet<Part>(plate.Parts);
|
var shown = new HashSet<Part>(plate.Parts);
|
||||||
|
if (tools?.Current is PlaceTool place)
|
||||||
|
shown.UnionWith(place.Previews);
|
||||||
foreach (var stale in paths.Keys.Where(part => !shown.Contains(part)).ToList())
|
foreach (var stale in paths.Keys.Where(part => !shown.Contains(part)).ToList())
|
||||||
paths.Remove(stale);
|
paths.Remove(stale);
|
||||||
var drawings = new HashSet<Drawing>(plate.Parts.Select(part => part.BaseDrawing));
|
var drawings = new HashSet<Drawing>(plate.Parts.Select(part => part.BaseDrawing));
|
||||||
@@ -289,6 +333,21 @@ namespace OpenNest.Avalonia.Controls
|
|||||||
(i + 1).ToString(), LabelPoint(part), selection.Contains(part),
|
(i + 1).ToString(), LabelPoint(part), selection.Contains(part),
|
||||||
ReferenceEquals(part, HoveredPart), part.BaseDrawing.IsCutOff));
|
ReferenceEquals(part, HoveredPart), part.BaseDrawing.IsCutOff));
|
||||||
}
|
}
|
||||||
|
// The place tool's copies, drawn selected and unnumbered over the plate, as WinForms.
|
||||||
|
if (tools.Current is PlaceTool { Previews: var previews })
|
||||||
|
{
|
||||||
|
foreach (var preview in previews)
|
||||||
|
{
|
||||||
|
var bounds = PathsFor(preview).StrokeBounds;
|
||||||
|
if (bounds == null)
|
||||||
|
continue;
|
||||||
|
var placed = bounds.Translate(preview.Location.X, preview.Location.Y);
|
||||||
|
var color = ToSkColor(preview.BaseDrawing.Color);
|
||||||
|
scene.Parts.Add(new PartItem(PathsFor(preview), preview.Location, placed, color,
|
||||||
|
palette.PartOutline(color), Label: null, preview.Location, Selected: true,
|
||||||
|
Hovered: false, IsCutOff: false));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (options.DrawOffset && plate.PartSpacing > 0)
|
if (options.DrawOffset && plate.PartSpacing > 0)
|
||||||
{
|
{
|
||||||
@@ -392,7 +451,7 @@ namespace OpenNest.Avalonia.Controls
|
|||||||
{
|
{
|
||||||
// As WinForms: Shift+wheel turns the selection (Ctrl+Shift by a tenth); without a
|
// As WinForms: Shift+wheel turns the selection (Ctrl+Shift by a tenth); without a
|
||||||
// selection the wheel zooms. Some platforms report Shift+wheel as horizontal.
|
// selection the wheel zooms. Some platforms report Shift+wheel as horizontal.
|
||||||
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift) && selection.Parts.Count > 0
|
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift) && Edits.HasPartsToEdit
|
||||||
&& !EditsLocked)
|
&& !EditsLocked)
|
||||||
{
|
{
|
||||||
var delta = e.Delta.Y != 0 ? e.Delta.Y : e.Delta.X;
|
var delta = e.Delta.Y != 0 ? e.Delta.Y : e.Delta.X;
|
||||||
@@ -417,7 +476,7 @@ namespace OpenNest.Avalonia.Controls
|
|||||||
{
|
{
|
||||||
// As WinForms: a middle double-click fits only with nothing selected; with a
|
// As WinForms: a middle double-click fits only with nothing selected; with a
|
||||||
// selection each click turns it, so a double-click turns it 180 degrees.
|
// selection each click turns it, so a double-click turns it 180 degrees.
|
||||||
if (e.ClickCount == 2 && selection.Parts.Count == 0)
|
if (e.ClickCount == 2 && (EditsLocked || !Edits.HasPartsToEdit))
|
||||||
{
|
{
|
||||||
ZoomToFit();
|
ZoomToFit();
|
||||||
return;
|
return;
|
||||||
@@ -455,8 +514,10 @@ namespace OpenNest.Avalonia.Controls
|
|||||||
var button = point.Properties.IsLeftButtonPressed ? ToolButton.Left
|
var button = point.Properties.IsLeftButtonPressed ? ToolButton.Left
|
||||||
: point.Properties.IsRightButtonPressed ? ToolButton.Right : ToolButton.None;
|
: point.Properties.IsRightButtonPressed ? ToolButton.Right : ToolButton.None;
|
||||||
tools.Current.PointerMoved(ToolPointerAt(at, button, e.KeyModifiers));
|
tools.Current.PointerMoved(ToolPointerAt(at, button, e.KeyModifiers));
|
||||||
// As WinForms: the part under the cursor is highlighted only while no button is held.
|
// As WinForms: the part under the cursor is highlighted only in Select, while no
|
||||||
var hovered = button == ToolButton.None ? hitTester.PartAt(plate, CursorWorld.Value) : null;
|
// button is held.
|
||||||
|
var hovered = button == ToolButton.None && tools.Current is SelectTool
|
||||||
|
? hitTester.PartAt(plate, CursorWorld.Value) : null;
|
||||||
if (!ReferenceEquals(hovered, HoveredPart))
|
if (!ReferenceEquals(hovered, HoveredPart))
|
||||||
{
|
{
|
||||||
HoveredPart = hovered;
|
HoveredPart = hovered;
|
||||||
@@ -480,7 +541,7 @@ namespace OpenNest.Avalonia.Controls
|
|||||||
panStart = null;
|
panStart = null;
|
||||||
// A middle click, not a drag, turns the selection 90 degrees.
|
// A middle click, not a drag, turns the selection 90 degrees.
|
||||||
var at = e.GetPosition(this);
|
var at = e.GetPosition(this);
|
||||||
if (middleDown is { } down && selection.Parts.Count > 0
|
if (middleDown is { } down && Edits.HasPartsToEdit
|
||||||
&& (at.X - down.X) * (at.X - down.X) + (at.Y - down.Y) * (at.Y - down.Y) < 25)
|
&& (at.X - down.X) * (at.X - down.X) + (at.Y - down.Y) * (at.Y - down.Y) < 25)
|
||||||
Edits.RotateQuarterTurn();
|
Edits.RotateQuarterTurn();
|
||||||
middleDown = null;
|
middleDown = null;
|
||||||
@@ -506,6 +567,15 @@ namespace OpenNest.Avalonia.Controls
|
|||||||
tools.Current.PointerCaptureLost();
|
tools.Current.PointerCaptureLost();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// As the WinForms plate view: the pointer entering the view gives it the keyboard, which
|
||||||
|
// also places a drawing picked up in the drawing list.
|
||||||
|
protected override void OnPointerEntered(PointerEventArgs e)
|
||||||
|
{
|
||||||
|
base.OnPointerEntered(e);
|
||||||
|
if (!IsFocused)
|
||||||
|
Focus();
|
||||||
|
}
|
||||||
|
|
||||||
protected override void OnPointerExited(PointerEventArgs e)
|
protected override void OnPointerExited(PointerEventArgs e)
|
||||||
{
|
{
|
||||||
CursorWorld = null;
|
CursorWorld = null;
|
||||||
@@ -521,7 +591,10 @@ namespace OpenNest.Avalonia.Controls
|
|||||||
InvalidateVisual();
|
InvalidateVisual();
|
||||||
}
|
}
|
||||||
|
|
||||||
private ToolPointer ToolPointerAt(Point at, ToolButton button, KeyModifiers keys)
|
private ToolPointer ToolPointerAt(Point at, ToolButton button, KeyModifiers keys) =>
|
||||||
|
new(ToWorld(at), new ScreenPoint(at.X, at.Y), button, ModifiersOf(keys));
|
||||||
|
|
||||||
|
private static ToolModifiers ModifiersOf(KeyModifiers keys)
|
||||||
{
|
{
|
||||||
var modifiers = ToolModifiers.None;
|
var modifiers = ToolModifiers.None;
|
||||||
if (keys.HasFlag(KeyModifiers.Shift))
|
if (keys.HasFlag(KeyModifiers.Shift))
|
||||||
@@ -531,7 +604,7 @@ namespace OpenNest.Avalonia.Controls
|
|||||||
modifiers |= ToolModifiers.Control;
|
modifiers |= ToolModifiers.Control;
|
||||||
if (keys.HasFlag(KeyModifiers.Alt))
|
if (keys.HasFlag(KeyModifiers.Alt))
|
||||||
modifiers |= ToolModifiers.Alt;
|
modifiers |= ToolModifiers.Alt;
|
||||||
return new ToolPointer(ToWorld(at), new ScreenPoint(at.X, at.Y), button, modifiers);
|
return modifiers;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override void OnKeyDown(KeyEventArgs e)
|
protected override void OnKeyDown(KeyEventArgs e)
|
||||||
@@ -546,6 +619,12 @@ namespace OpenNest.Avalonia.Controls
|
|||||||
ZoomToFit();
|
ZoomToFit();
|
||||||
e.Handled = true;
|
e.Handled = true;
|
||||||
}
|
}
|
||||||
|
else if (e.Key is Key.Enter or Key.F1 && tools.Current is PlaceTool place)
|
||||||
|
{
|
||||||
|
// As WinForms: Enter and F1 place a copy, Shift or Ctrl held settling it.
|
||||||
|
place.Apply(ModifiersOf(e.KeyModifiers));
|
||||||
|
e.Handled = true;
|
||||||
|
}
|
||||||
else if (EditFor(e.Key, e.KeyModifiers) is { } edit)
|
else if (EditFor(e.Key, e.KeyModifiers) is { } edit)
|
||||||
{
|
{
|
||||||
edit();
|
edit();
|
||||||
@@ -879,7 +958,7 @@ namespace OpenNest.Avalonia.Controls
|
|||||||
canvas.Restore();
|
canvas.Restore();
|
||||||
|
|
||||||
// A number shows only once the part is big enough on screen to hold it.
|
// A number shows only once the part is big enough on screen to hold it.
|
||||||
if (item.IsCutOff)
|
if (item.IsCutOff || item.Label == null)
|
||||||
continue;
|
continue;
|
||||||
var bounds = Screen(item.Bounds);
|
var bounds = Screen(item.Bounds);
|
||||||
var width = text.MeasureText(item.Label);
|
var width = text.MeasureText(item.Label);
|
||||||
|
|||||||
@@ -28,6 +28,10 @@
|
|||||||
<MenuItem x:Name="UndoMenuItem" Header="_Undo" InputGesture="Ctrl+Z" Click="OnUndo" />
|
<MenuItem x:Name="UndoMenuItem" Header="_Undo" InputGesture="Ctrl+Z" Click="OnUndo" />
|
||||||
<MenuItem x:Name="RedoMenuItem" Header="_Redo" InputGesture="Ctrl+Y" Click="OnRedo" />
|
<MenuItem x:Name="RedoMenuItem" Header="_Redo" InputGesture="Ctrl+Y" Click="OnRedo" />
|
||||||
<Separator />
|
<Separator />
|
||||||
|
<!-- Into the place tool, not the system clipboard, as WinForms. -->
|
||||||
|
<MenuItem x:Name="CutMenuItem" Header="Cu_t" InputGesture="Ctrl+X" Click="OnCut" />
|
||||||
|
<MenuItem x:Name="CopyMenuItem" Header="_Copy" InputGesture="Ctrl+C" Click="OnCopy" />
|
||||||
|
<Separator />
|
||||||
<MenuItem x:Name="SelectAllMenuItem" Header="Select _All" InputGesture="Ctrl+A" Click="OnSelectAll" />
|
<MenuItem x:Name="SelectAllMenuItem" Header="Select _All" InputGesture="Ctrl+A" Click="OnSelectAll" />
|
||||||
</MenuItem>
|
</MenuItem>
|
||||||
<MenuItem Header="_Nest">
|
<MenuItem Header="_Nest">
|
||||||
|
|||||||
@@ -89,6 +89,16 @@ namespace OpenNest.Avalonia
|
|||||||
Command = new Command(() => OnExit(null, null)),
|
Command = new Command(() => OnExit(null, null)),
|
||||||
});
|
});
|
||||||
KeyBindings.Add(new KeyBinding
|
KeyBindings.Add(new KeyBinding
|
||||||
|
{
|
||||||
|
Gesture = new KeyGesture(Key.X, KeyModifiers.Control),
|
||||||
|
Command = new Command(() => OnCut(null, null)),
|
||||||
|
});
|
||||||
|
KeyBindings.Add(new KeyBinding
|
||||||
|
{
|
||||||
|
Gesture = new KeyGesture(Key.C, KeyModifiers.Control),
|
||||||
|
Command = new Command(() => OnCopy(null, null)),
|
||||||
|
});
|
||||||
|
KeyBindings.Add(new KeyBinding
|
||||||
{
|
{
|
||||||
Gesture = new KeyGesture(Key.A, KeyModifiers.Control),
|
Gesture = new KeyGesture(Key.A, KeyModifiers.Control),
|
||||||
Command = new Command(() => OnSelectAll(null, null)),
|
Command = new Command(() => OnSelectAll(null, null)),
|
||||||
@@ -202,6 +212,7 @@ namespace OpenNest.Avalonia
|
|||||||
private void AddView(NestTab tab)
|
private void AddView(NestTab tab)
|
||||||
{
|
{
|
||||||
var view = new NestView(tab);
|
var view = new NestView(tab);
|
||||||
|
view.PlateView.PlacementOrder = ReadClonePlacementOrder;
|
||||||
RestoreViewToggles(view);
|
RestoreViewToggles(view);
|
||||||
view.ViewChanged += (_, _) => { if (view == ActiveView) UpdateStatus(); };
|
view.ViewChanged += (_, _) => { if (view == ActiveView) UpdateStatus(); };
|
||||||
views[tab] = view;
|
views[tab] = view;
|
||||||
@@ -307,6 +318,8 @@ namespace OpenNest.Avalonia
|
|||||||
CloseAllMenuItem.IsEnabled = view != null;
|
CloseAllMenuItem.IsEnabled = view != null;
|
||||||
SetOffsetIncrementMenuItem.IsEnabled = view != null;
|
SetOffsetIncrementMenuItem.IsEnabled = view != null;
|
||||||
SetRotationIncrementMenuItem.IsEnabled = view != null;
|
SetRotationIncrementMenuItem.IsEnabled = view != null;
|
||||||
|
CutMenuItem.IsEnabled = view != null;
|
||||||
|
CopyMenuItem.IsEnabled = view != null;
|
||||||
UpdateExportCommands(view != null);
|
UpdateExportCommands(view != null);
|
||||||
Title = view == null
|
Title = view == null
|
||||||
? "OpenNest (Avalonia prototype)"
|
? "OpenNest (Avalonia prototype)"
|
||||||
@@ -855,6 +868,33 @@ namespace OpenNest.Avalonia
|
|||||||
|
|
||||||
private void OnSelectAll(object sender, RoutedEventArgs e) => ActiveView?.PlateView.SelectAll();
|
private void OnSelectAll(object sender, RoutedEventArgs e) => ActiveView?.PlateView.SelectAll();
|
||||||
|
|
||||||
|
// Edit > Cut and Copy, as WinForms: the selected parts go to the place tool (not the
|
||||||
|
// system clipboard); Cut also removes them from the plate. The view keeps the keyboard,
|
||||||
|
// so Enter, arrows and Delete reach the tool after a menu click.
|
||||||
|
private void OnCut(object sender, RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
if (ActiveView is { PlateView: { } canvas } view && canvas.CutSelection())
|
||||||
|
{
|
||||||
|
// Focusing the view would otherwise place a drawing picked up in the list.
|
||||||
|
view.CancelPickup();
|
||||||
|
canvas.Focus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnCopy(object sender, RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
if (ActiveView is { PlateView: { } canvas } view && canvas.CopySelection())
|
||||||
|
{
|
||||||
|
view.CancelPickup();
|
||||||
|
canvas.Focus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read at each click, as WinForms reads its setting, so a change in Options applies now.
|
||||||
|
private static Engine.Fill.SettleOrder ReadClonePlacementOrder() =>
|
||||||
|
DesktopOptions.Read(Data.UserSettingsFile.Read(Data.UserSettingsFile.DefaultPath))
|
||||||
|
.ClonePlacementOrder;
|
||||||
|
|
||||||
private void OnPreviousPlate(object sender, RoutedEventArgs e) => StepPlate(-1);
|
private void OnPreviousPlate(object sender, RoutedEventArgs e) => StepPlate(-1);
|
||||||
|
|
||||||
private void OnNextPlate(object sender, RoutedEventArgs e) => StepPlate(1);
|
private void OnNextPlate(object sender, RoutedEventArgs e) => StepPlate(1);
|
||||||
|
|||||||
@@ -11,6 +11,7 @@
|
|||||||
</TabItem>
|
</TabItem>
|
||||||
<TabItem Header="Drawings" FontSize="14" MinHeight="34">
|
<TabItem Header="Drawings" FontSize="14" MinHeight="34">
|
||||||
<DataGrid x:Name="DrawingGrid" x:DataType="local:DrawingRow" IsReadOnly="True"
|
<DataGrid x:Name="DrawingGrid" x:DataType="local:DrawingRow" IsReadOnly="True"
|
||||||
|
SelectionMode="Single"
|
||||||
FontSize="13" AutoGenerateColumns="False"
|
FontSize="13" AutoGenerateColumns="False"
|
||||||
GridLinesVisibility="Horizontal" CanUserSortColumns="True">
|
GridLinesVisibility="Horizontal" CanUserSortColumns="True">
|
||||||
<DataGrid.Columns>
|
<DataGrid.Columns>
|
||||||
|
|||||||
@@ -1,14 +1,18 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
using Avalonia;
|
||||||
using Avalonia.Controls;
|
using Avalonia.Controls;
|
||||||
|
using Avalonia.Input;
|
||||||
using Avalonia.Interactivity;
|
using Avalonia.Interactivity;
|
||||||
|
using Avalonia.VisualTree;
|
||||||
using OpenNest.Avalonia.Controls;
|
using OpenNest.Avalonia.Controls;
|
||||||
using OpenNest.Desktop;
|
using OpenNest.Desktop;
|
||||||
|
using OpenNest.Desktop.Interaction;
|
||||||
|
|
||||||
namespace OpenNest.Avalonia
|
namespace OpenNest.Avalonia
|
||||||
{
|
{
|
||||||
public sealed record DrawingRow(string Name, int Nested, int Required);
|
public sealed record DrawingRow(string Name, int Nested, int Required, Drawing Drawing);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// One open nest: Plates and Drawings tabs on the left, the plate header and plate view on
|
/// One open nest: Plates and Drawings tabs on the left, the plate header and plate view on
|
||||||
@@ -35,6 +39,126 @@ namespace OpenNest.Avalonia
|
|||||||
// Starts watching the last two plates (the tab already put the empty plate there).
|
// Starts watching the last two plates (the tab already put the empty plate there).
|
||||||
plates.EnsureSentinel();
|
plates.EnsureSentinel();
|
||||||
Refresh(0);
|
Refresh(0);
|
||||||
|
// Adding parts from the drawing list, as the WinForms nest window: a press picks a
|
||||||
|
// drawing up for the plate view, a drag drops one part on the plate.
|
||||||
|
DrawingGrid.AddHandler(PointerPressedEvent, OnDrawingPressed, RoutingStrategies.Tunnel,
|
||||||
|
handledEventsToo: true);
|
||||||
|
DrawingGrid.AddHandler(PointerMovedEvent, OnDrawingDragged, RoutingStrategies.Tunnel,
|
||||||
|
handledEventsToo: true);
|
||||||
|
DrawingGrid.AddHandler(PointerReleasedEvent, (_, _) => pressedDrawing = null,
|
||||||
|
RoutingStrategies.Tunnel, handledEventsToo: true);
|
||||||
|
Canvas.GotFocus += OnCanvasFocused;
|
||||||
|
DragDrop.SetAllowDrop(Canvas, true);
|
||||||
|
Canvas.AddHandler(DragDrop.DragEnterEvent, OnDrawingDragOver);
|
||||||
|
Canvas.AddHandler(DragDrop.DragOverEvent, OnDrawingDragOver);
|
||||||
|
Canvas.AddHandler(DragDrop.DropEvent, OnDrawingDrop);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The drag format carrying a <see cref="Drawing"/> from the list.</summary>
|
||||||
|
public const string DrawingFormat = "OpenNest.Drawing";
|
||||||
|
|
||||||
|
private readonly DrawingPickup pickup = new();
|
||||||
|
private Drawing pressedDrawing;
|
||||||
|
private Point pressPoint;
|
||||||
|
|
||||||
|
private static Drawing DrawingUnder(PointerEventArgs e) =>
|
||||||
|
(e.Source as Visual)?.FindAncestorOfType<DataGridRow>(includeSelf: true)
|
||||||
|
?.DataContext is DrawingRow row
|
||||||
|
? row.Drawing
|
||||||
|
: null;
|
||||||
|
|
||||||
|
// As the WinForms list: a single left press picks the drawing up (a drag can start from
|
||||||
|
// it); a double-click puts it down.
|
||||||
|
private void OnDrawingPressed(object sender, PointerPressedEventArgs e)
|
||||||
|
{
|
||||||
|
var point = e.GetCurrentPoint(DrawingGrid);
|
||||||
|
pressPoint = point.Position;
|
||||||
|
pressedDrawing = null;
|
||||||
|
if (!point.Properties.IsLeftButtonPressed)
|
||||||
|
return;
|
||||||
|
if (e.ClickCount != 1)
|
||||||
|
{
|
||||||
|
pickup.PutDown();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
pressedDrawing = DrawingUnder(e);
|
||||||
|
if (pressedDrawing != null)
|
||||||
|
pickup.PickUp();
|
||||||
|
}
|
||||||
|
|
||||||
|
// A press moved more than 3 pixels drags the drawing; a drop on the plate puts it down.
|
||||||
|
private async void OnDrawingDragged(object sender, PointerEventArgs e)
|
||||||
|
{
|
||||||
|
var drawing = pressedDrawing;
|
||||||
|
var point = e.GetCurrentPoint(DrawingGrid);
|
||||||
|
if (drawing == null || !point.Properties.IsLeftButtonPressed)
|
||||||
|
return;
|
||||||
|
var dx = point.Position.X - pressPoint.X;
|
||||||
|
var dy = point.Position.Y - pressPoint.Y;
|
||||||
|
if (dx * dx + dy * dy <= 9)
|
||||||
|
return;
|
||||||
|
pressedDrawing = null;
|
||||||
|
var data = new DataObject();
|
||||||
|
data.Set(DrawingFormat, drawing);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await DragDrop.DoDragDrop(e, data, DragDropEffects.Copy);
|
||||||
|
if (result != DragDropEffects.None)
|
||||||
|
pickup.PutDown();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
// A platform drag failure leaves the drawing picked up, as a cancelled drag does.
|
||||||
|
System.Diagnostics.Debug.WriteLine($"Drawing drag failed: {ex}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Puts a picked-up drawing down: Edit > Cut and Copy start their own place tool and
|
||||||
|
/// then focus the view, which would otherwise swap in the picked drawing.
|
||||||
|
/// </summary>
|
||||||
|
public void CancelPickup()
|
||||||
|
{
|
||||||
|
pickup.PutDown();
|
||||||
|
pressedDrawing = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnCanvasFocused(object sender, GotFocusEventArgs e)
|
||||||
|
{
|
||||||
|
var selected = (DrawingGrid.SelectedItem as DrawingRow)?.Drawing;
|
||||||
|
if (pickup.TakeOnPlateEnter(selected) is { } drawing)
|
||||||
|
Canvas.PlaceDrawing(drawing);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only this nest's drawings, and none while edits are locked (WinForms refuses the drop).
|
||||||
|
private Drawing DroppedDrawing(DragEventArgs e) =>
|
||||||
|
e.Data.Get(DrawingFormat) is Drawing drawing
|
||||||
|
&& Tab.Document.Nest.Drawings.Any(d => ReferenceEquals(d, drawing))
|
||||||
|
&& !Canvas.EditsLocked
|
||||||
|
? drawing
|
||||||
|
: null;
|
||||||
|
|
||||||
|
private void OnDrawingDragOver(object sender, DragEventArgs e)
|
||||||
|
{
|
||||||
|
if (!e.Data.Contains(DrawingFormat))
|
||||||
|
return;
|
||||||
|
e.DragEffects = DroppedDrawing(e) != null ? DragDropEffects.Copy : DragDropEffects.None;
|
||||||
|
e.Handled = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnDrawingDrop(object sender, DragEventArgs e)
|
||||||
|
{
|
||||||
|
if (!e.Data.Contains(DrawingFormat))
|
||||||
|
return;
|
||||||
|
var drawing = DroppedDrawing(e);
|
||||||
|
var dropped = drawing != null
|
||||||
|
&& Canvas.DropDrawing(drawing, e.GetPosition(Canvas)) != null;
|
||||||
|
// Put down now, not when the drag returns: on X11 and macOS the pointer can enter the
|
||||||
|
// plate (and focus it) before the awaiting drag source resumes.
|
||||||
|
if (dropped)
|
||||||
|
pickup.PutDown();
|
||||||
|
e.DragEffects = dropped ? DragDropEffects.Copy : DragDropEffects.None;
|
||||||
|
e.Handled = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Undo and Redo: puts the copy read back from the history in the document and shows it
|
// Undo and Redo: puts the copy read back from the history in the document and shows it
|
||||||
@@ -49,6 +173,11 @@ namespace OpenNest.Avalonia
|
|||||||
: (Array.Empty<int>(), -1);
|
: (Array.Empty<int>(), -1);
|
||||||
// Read first: a throw here leaves the live nest in place, as the recorder expects.
|
// Read first: a throw here leaves the live nest in place, as the recorder expects.
|
||||||
var cutOffSettings = CutOffSettingsFor(restored);
|
var cutOffSettings = CutOffSettingsFor(restored);
|
||||||
|
// As WinForms (EditNestForm EndAction): a tool holds the old nest's parts, so it ends
|
||||||
|
// and Escape cannot bring it back.
|
||||||
|
Canvas.Tools.EndTool();
|
||||||
|
pickup.PutDown();
|
||||||
|
pressedDrawing = null;
|
||||||
Tab.Document.Nest = restored;
|
Tab.Document.Nest = restored;
|
||||||
Canvas.CutOffSettings = cutOffSettings;
|
Canvas.CutOffSettings = cutOffSettings;
|
||||||
plates.Dispose();
|
plates.Dispose();
|
||||||
@@ -103,10 +232,15 @@ namespace OpenNest.Avalonia
|
|||||||
PlateList.SelectedIndex = nest.Plates.Count > 0
|
PlateList.SelectedIndex = nest.Plates.Count > 0
|
||||||
? System.Math.Clamp(selectIndex, 0, nest.Plates.Count - 1)
|
? System.Math.Clamp(selectIndex, 0, nest.Plates.Count - 1)
|
||||||
: -1;
|
: -1;
|
||||||
|
// As the WinForms list: the selected drawing stays selected when the list is rebuilt,
|
||||||
|
// matched as WinForms matches it (by name), so it survives an Undo's new objects.
|
||||||
|
var selected = (DrawingGrid.SelectedItem as DrawingRow)?.Drawing;
|
||||||
DrawingGrid.ItemsSource = nest.Drawings
|
DrawingGrid.ItemsSource = nest.Drawings
|
||||||
.Where(d => !d.IsCutOff)
|
.Where(d => !d.IsCutOff)
|
||||||
.Select(d => new DrawingRow(d.Name, d.Quantity.Nested, d.Quantity.Required))
|
.Select(d => new DrawingRow(d.Name, d.Quantity.Nested, d.Quantity.Required, d))
|
||||||
.ToList();
|
.ToList();
|
||||||
|
DrawingGrid.SelectedItem = ((IEnumerable<DrawingRow>)DrawingGrid.ItemsSource)
|
||||||
|
.FirstOrDefault(row => Equals(row.Drawing, selected));
|
||||||
shownCounts = CountsText(nest);
|
shownCounts = CountsText(nest);
|
||||||
ShowPlate();
|
ShowPlate();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
namespace OpenNest.Bending
|
||||||
|
{
|
||||||
|
public static class BendMath
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// The length of the neutral axis through a bend: the arc at the inside radius plus
|
||||||
|
/// <paramref name="kFactor"/> of the thickness.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="angle">The bend angle in radians.</param>
|
||||||
|
public static double Allowance(double angle, double insideRadius, double thickness, double kFactor) =>
|
||||||
|
angle * (insideRadius + kFactor * thickness);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
using OpenNest.Math;
|
using OpenNest.Math;
|
||||||
|
|
||||||
namespace OpenNest.Geometry
|
namespace OpenNest.Geometry
|
||||||
@@ -82,6 +83,24 @@ namespace OpenNest.Geometry
|
|||||||
return OverlapRegions(trianglesA(), trianglesB(), holesA, holesB, verdictOnly: true).Count > 0;
|
return OverlapRegions(trianglesA(), trianglesB(), holesA, holesB, verdictOnly: true).Count > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// <see cref="HasOverlap(Polygon, Polygon, List{Polygon}, List{Polygon})"/> with each
|
||||||
|
/// polygon's <see cref="TriangulateForClipping"/> supplied by the caller and resolved
|
||||||
|
/// lazily, only after the bounding boxes overlap; the verdict is then identical.
|
||||||
|
/// </summary>
|
||||||
|
internal static bool HasOverlapTriangulated(
|
||||||
|
Polygon a,
|
||||||
|
Func<List<CollisionTriangle>> trianglesA,
|
||||||
|
Polygon b,
|
||||||
|
Func<List<CollisionTriangle>> trianglesB
|
||||||
|
)
|
||||||
|
{
|
||||||
|
if (!BoundingBoxesOverlap(a.BoundingBox, b.BoundingBox))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
return OverlapRegions(trianglesA(), trianglesB(), null, null, verdictOnly: true).Count > 0;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The triangulation <see cref="Check"/> and <see cref="HasOverlap(Polygon, Polygon, List{Polygon}, List{Polygon})"/>
|
/// The triangulation <see cref="Check"/> and <see cref="HasOverlap(Polygon, Polygon, List{Polygon}, List{Polygon})"/>
|
||||||
/// use for <paramref name="polygon"/>: ear-clipped triangles with bounds updated. Callers
|
/// use for <paramref name="polygon"/>: ear-clipped triangles with bounds updated. Callers
|
||||||
@@ -89,6 +108,28 @@ namespace OpenNest.Geometry
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
internal static List<Polygon> Triangulate(Polygon polygon) => TriangulateWithBounds(polygon);
|
internal static List<Polygon> Triangulate(Polygon polygon) => TriangulateWithBounds(polygon);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// <see cref="Triangulate"/> as the clip loop reads it, without a polygon per triangle:
|
||||||
|
/// the same triangles, vertices and bounds. Callers may reuse it for the same polygon.
|
||||||
|
/// </summary>
|
||||||
|
internal static List<CollisionTriangle> TriangulateForClipping(Polygon polygon)
|
||||||
|
{
|
||||||
|
PerfCounters.CountPolygonTriangulation();
|
||||||
|
var sink = new TriangleSink(new List<CollisionTriangle>(polygon.Vertices.Count));
|
||||||
|
ConvexDecomposition.Triangulate(polygon, ref sink);
|
||||||
|
return sink.Triangles;
|
||||||
|
}
|
||||||
|
|
||||||
|
private readonly struct TriangleSink : ConvexDecomposition.IEarSink
|
||||||
|
{
|
||||||
|
public TriangleSink(List<CollisionTriangle> triangles) => Triangles = triangles;
|
||||||
|
|
||||||
|
public List<CollisionTriangle> Triangles { get; }
|
||||||
|
|
||||||
|
public void Add(Vector prev, Vector curr, Vector next) =>
|
||||||
|
Triangles.Add(new CollisionTriangle(prev, curr, next));
|
||||||
|
}
|
||||||
|
|
||||||
public static List<CollisionResult> CheckAll(
|
public static List<CollisionResult> CheckAll(
|
||||||
List<Polygon> polygons,
|
List<Polygon> polygons,
|
||||||
List<List<Polygon>> holes = null
|
List<List<Polygon>> holes = null
|
||||||
@@ -140,7 +181,32 @@ namespace OpenNest.Geometry
|
|||||||
List<Polygon> holesA,
|
List<Polygon> holesA,
|
||||||
List<Polygon> holesB,
|
List<Polygon> holesB,
|
||||||
bool verdictOnly = false
|
bool verdictOnly = false
|
||||||
) => OverlapRegions(TriangulateWithBounds(a), TriangulateWithBounds(b), holesA, holesB, verdictOnly);
|
) => OverlapRegions(TriangulateForClipping(a), TriangulateForClipping(b), holesA, holesB, verdictOnly);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// <see cref="OverlapRegions(List{Polygon}, List{Polygon}, List{Polygon}, List{Polygon}, bool)"/>
|
||||||
|
/// over <see cref="TriangulateForClipping"/> triangles: the same pairs clipped in the same
|
||||||
|
/// order, so the same regions.
|
||||||
|
/// </summary>
|
||||||
|
private static List<Polygon> OverlapRegions(
|
||||||
|
List<CollisionTriangle> trisA,
|
||||||
|
List<CollisionTriangle> trisB,
|
||||||
|
List<Polygon> holesA,
|
||||||
|
List<Polygon> holesB,
|
||||||
|
bool verdictOnly = false
|
||||||
|
)
|
||||||
|
{
|
||||||
|
var regions = new List<Polygon>();
|
||||||
|
var stopAtFirst = verdictOnly
|
||||||
|
&& (holesA == null || holesA.Count == 0)
|
||||||
|
&& (holesB == null || holesB.Count == 0);
|
||||||
|
ClipTrianglePairs(trisA, trisB, regions, stopAtFirst);
|
||||||
|
|
||||||
|
if (regions.Count > 0)
|
||||||
|
regions = SubtractHoles(regions, holesA, holesB);
|
||||||
|
|
||||||
|
return regions;
|
||||||
|
}
|
||||||
|
|
||||||
private static List<Polygon> OverlapRegions(
|
private static List<Polygon> OverlapRegions(
|
||||||
List<Polygon> trisA,
|
List<Polygon> trisA,
|
||||||
@@ -219,6 +285,215 @@ namespace OpenNest.Geometry
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// <see cref="ClipTrianglePairs(List{Polygon}, List{Polygon}, List{Polygon}, bool)"/> over
|
||||||
|
/// <see cref="CollisionTriangle"/>s, clipping in two reused buffers: the same pairs in the
|
||||||
|
/// same order with the same arithmetic, and a region polygon built only for a pair that
|
||||||
|
/// overlaps.
|
||||||
|
/// </summary>
|
||||||
|
private static void ClipTrianglePairs(
|
||||||
|
List<CollisionTriangle> trisA,
|
||||||
|
List<CollisionTriangle> trisB,
|
||||||
|
List<Polygon> regions,
|
||||||
|
bool stopAtFirst
|
||||||
|
)
|
||||||
|
{
|
||||||
|
if (trisA.Count == 0 || trisB.Count == 0)
|
||||||
|
return;
|
||||||
|
|
||||||
|
var candidatesA = TrianglesTouching(trisA, UnionBounds(trisB));
|
||||||
|
if (candidatesA.Count == 0)
|
||||||
|
return;
|
||||||
|
|
||||||
|
var candidatesB = TrianglesTouching(trisB, UnionBounds(trisA));
|
||||||
|
if (candidatesB.Count == 0)
|
||||||
|
return;
|
||||||
|
|
||||||
|
Span<Vector> first = stackalloc Vector[MaxClippedVertices];
|
||||||
|
Span<Vector> second = stackalloc Vector[MaxClippedVertices];
|
||||||
|
Span<double> distances = stackalloc double[MaxClippedVertices];
|
||||||
|
var spanA = CollectionsMarshal.AsSpan(trisA);
|
||||||
|
var spanB = CollectionsMarshal.AsSpan(trisB);
|
||||||
|
|
||||||
|
foreach (var a in candidatesA)
|
||||||
|
{
|
||||||
|
ref readonly var triA = ref spanA[a];
|
||||||
|
|
||||||
|
foreach (var b in candidatesB)
|
||||||
|
{
|
||||||
|
ref readonly var triB = ref spanB[b];
|
||||||
|
if (!BoundingBoxesOverlap(triA, triB))
|
||||||
|
continue;
|
||||||
|
|
||||||
|
var clipped = ClipConvex(triA, triB, first, second, distances);
|
||||||
|
if (clipped == null)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
regions.Add(clipped);
|
||||||
|
if (stopAtFirst)
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Most vertices clipping a triangle by a triangle's three half-spaces can leave: each
|
||||||
|
/// half-space keeps each vertex and adds at most one crossing after it.
|
||||||
|
/// </summary>
|
||||||
|
private const int MaxClippedVertices = 3 * 2 * 2 * 2;
|
||||||
|
|
||||||
|
private static (double Left, double Right, double Bottom, double Top) UnionBounds(
|
||||||
|
List<CollisionTriangle> triangles
|
||||||
|
)
|
||||||
|
{
|
||||||
|
var left = double.PositiveInfinity;
|
||||||
|
var right = double.NegativeInfinity;
|
||||||
|
var bottom = double.PositiveInfinity;
|
||||||
|
var top = double.NegativeInfinity;
|
||||||
|
|
||||||
|
foreach (var triangle in triangles)
|
||||||
|
{
|
||||||
|
left = System.Math.Min(left, triangle.Left);
|
||||||
|
right = System.Math.Max(right, triangle.Right);
|
||||||
|
bottom = System.Math.Min(bottom, triangle.Bottom);
|
||||||
|
top = System.Math.Max(top, triangle.Top);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (left, right, bottom, top);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Indices of the triangles the polygon form of this test keeps, in order.</summary>
|
||||||
|
private static List<int> TrianglesTouching(
|
||||||
|
List<CollisionTriangle> triangles,
|
||||||
|
(double Left, double Right, double Bottom, double Top) union
|
||||||
|
)
|
||||||
|
{
|
||||||
|
var result = new List<int>(triangles.Count);
|
||||||
|
|
||||||
|
for (var i = 0; i < triangles.Count; i++)
|
||||||
|
{
|
||||||
|
var box = triangles[i];
|
||||||
|
var overlapX = System.Math.Min(box.Right, union.Right) - System.Math.Max(box.Left, union.Left);
|
||||||
|
var overlapY = System.Math.Min(box.Top, union.Top) - System.Math.Max(box.Bottom, union.Bottom);
|
||||||
|
|
||||||
|
if (overlapX > Tolerance.Epsilon && overlapY > Tolerance.Epsilon)
|
||||||
|
result.Add(i);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool BoundingBoxesOverlap(in CollisionTriangle a, in CollisionTriangle b)
|
||||||
|
{
|
||||||
|
var overlapX = System.Math.Min(a.Right, b.Right) - System.Math.Max(a.Left, b.Left);
|
||||||
|
var overlapY = System.Math.Min(a.Top, b.Top) - System.Math.Max(a.Bottom, b.Bottom);
|
||||||
|
|
||||||
|
return overlapX > Tolerance.Epsilon && overlapY > Tolerance.Epsilon;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// <see cref="ClipConvex(List{Vector}, List{Vector})"/> of two triangles' open vertices,
|
||||||
|
/// alternating between two caller buffers of <see cref="MaxClippedVertices"/>.
|
||||||
|
/// </summary>
|
||||||
|
private static Polygon ClipConvex(
|
||||||
|
in CollisionTriangle subject,
|
||||||
|
in CollisionTriangle clip,
|
||||||
|
Span<Vector> first,
|
||||||
|
Span<Vector> second,
|
||||||
|
Span<double> distances
|
||||||
|
)
|
||||||
|
{
|
||||||
|
var count = subject.Count;
|
||||||
|
for (var i = 0; i < count; i++)
|
||||||
|
first[i] = subject[i];
|
||||||
|
|
||||||
|
var output = first;
|
||||||
|
var spare = second;
|
||||||
|
for (var i = 0; i < clip.Count && count >= 3; i++)
|
||||||
|
{
|
||||||
|
count = ClipHalfSpaceInside(output.Slice(0, count), clip[i], clip[(i + 1) % clip.Count], spare,
|
||||||
|
distances);
|
||||||
|
var swap = output;
|
||||||
|
output = spare;
|
||||||
|
spare = swap;
|
||||||
|
}
|
||||||
|
|
||||||
|
return PositiveAreaPolygon(output.Slice(0, count));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// <see cref="ClipHalfSpace"/> keeping the inside, written to <paramref name="kept"/>;
|
||||||
|
/// returns how many it kept. Each vertex's signed distance is computed once into
|
||||||
|
/// <paramref name="distances"/>, the same value ClipHalfSpace computes for it twice.
|
||||||
|
/// </summary>
|
||||||
|
private static int ClipHalfSpaceInside(
|
||||||
|
ReadOnlySpan<Vector> vertices,
|
||||||
|
Vector edgeStart,
|
||||||
|
Vector edgeEnd,
|
||||||
|
Span<Vector> kept,
|
||||||
|
Span<double> distances
|
||||||
|
)
|
||||||
|
{
|
||||||
|
var inside = false;
|
||||||
|
for (var i = 0; i < vertices.Length; i++)
|
||||||
|
{
|
||||||
|
distances[i] = Cross(edgeStart, edgeEnd, vertices[i]);
|
||||||
|
inside |= distances[i] >= 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every vertex strictly outside keeps nothing and crosses nowhere.
|
||||||
|
if (!inside)
|
||||||
|
return 0;
|
||||||
|
|
||||||
|
var count = 0;
|
||||||
|
for (var i = 0; i < vertices.Length; i++)
|
||||||
|
{
|
||||||
|
var current = vertices[i];
|
||||||
|
var nextIndex = i + 1 == vertices.Length ? 0 : i + 1;
|
||||||
|
var next = vertices[nextIndex];
|
||||||
|
var currentDistance = distances[i];
|
||||||
|
var nextDistance = distances[nextIndex];
|
||||||
|
if (currentDistance >= 0)
|
||||||
|
AddDistinct(kept, ref count, current);
|
||||||
|
|
||||||
|
if ((currentDistance < 0 && nextDistance > 0) || (currentDistance > 0 && nextDistance < 0))
|
||||||
|
{
|
||||||
|
var t = currentDistance / (currentDistance - nextDistance);
|
||||||
|
AddDistinct(kept, ref count, new Vector(
|
||||||
|
current.X + t * (next.X - current.X),
|
||||||
|
current.Y + t * (next.Y - current.Y)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (count > 1 && SamePoint(kept[0], kept[count - 1]))
|
||||||
|
count--;
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void AddDistinct(Span<Vector> vertices, ref int count, Vector point)
|
||||||
|
{
|
||||||
|
if (count == 0 || !SamePoint(vertices[count - 1], point))
|
||||||
|
vertices[count++] = point;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Polygon PositiveAreaPolygon(ReadOnlySpan<Vector> vertices)
|
||||||
|
{
|
||||||
|
if (vertices.Length < 3)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var twiceArea = 0.0;
|
||||||
|
for (var i = 1; i + 1 < vertices.Length; i++)
|
||||||
|
twiceArea += Cross(vertices[0], vertices[i], vertices[i + 1]);
|
||||||
|
if (System.Math.Abs(twiceArea) <= 2 * Tolerance.Epsilon)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var polygon = new Polygon();
|
||||||
|
foreach (var vertex in vertices)
|
||||||
|
polygon.Vertices.Add(vertex);
|
||||||
|
polygon.Vertices.Add(vertices[0]);
|
||||||
|
polygon.UpdateBounds();
|
||||||
|
return polygon;
|
||||||
|
}
|
||||||
|
|
||||||
private static (double Left, double Right, double Bottom, double Top) UnionBounds(
|
private static (double Left, double Right, double Bottom, double Top) UnionBounds(
|
||||||
List<Polygon> polygons
|
List<Polygon> polygons
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
namespace OpenNest.Geometry
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// One ear of <see cref="ConvexDecomposition.Triangulate(Polygon)"/> as the collision clip loop
|
||||||
|
/// reads its triangle polygon: the open vertices and the bounding-box sides, without building
|
||||||
|
/// the polygon. Every value is bit for bit what the loop reads from the polygon.
|
||||||
|
/// </summary>
|
||||||
|
internal readonly struct CollisionTriangle
|
||||||
|
{
|
||||||
|
public CollisionTriangle(Vector prev, Vector curr, Vector next)
|
||||||
|
{
|
||||||
|
// The polygon is [prev, curr, next], closed with prev by Polygon.Close only when prev
|
||||||
|
// and next differ by its fuzzy equality. Its open vertices drop a last vertex exactly
|
||||||
|
// equal to the first: the closing vertex, or next when it was not closed.
|
||||||
|
V0 = prev;
|
||||||
|
V1 = curr;
|
||||||
|
V2 = next;
|
||||||
|
Count = prev != next || !(prev.X == next.X && prev.Y == next.Y) ? 3 : 2;
|
||||||
|
|
||||||
|
// Polygon.UpdateBounds over the same vertices; the closing vertex repeats prev.
|
||||||
|
var minX = prev.X;
|
||||||
|
var maxX = prev.X;
|
||||||
|
var minY = prev.Y;
|
||||||
|
var maxY = prev.Y;
|
||||||
|
Include(curr, ref minX, ref maxX, ref minY, ref maxY);
|
||||||
|
Include(next, ref minX, ref maxX, ref minY, ref maxY);
|
||||||
|
|
||||||
|
// Box sides as Box computes them from its location and size.
|
||||||
|
Left = minX;
|
||||||
|
Bottom = minY;
|
||||||
|
Right = minX + (maxX - minX);
|
||||||
|
Top = minY + (maxY - minY);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Vector V0 { get; }
|
||||||
|
public Vector V1 { get; }
|
||||||
|
public Vector V2 { get; }
|
||||||
|
|
||||||
|
/// <summary>Open vertices: 3, or 2 when next is exactly prev.</summary>
|
||||||
|
public int Count { get; }
|
||||||
|
|
||||||
|
public double Left { get; }
|
||||||
|
public double Right { get; }
|
||||||
|
public double Bottom { get; }
|
||||||
|
public double Top { get; }
|
||||||
|
|
||||||
|
public Vector this[int index] => index switch
|
||||||
|
{
|
||||||
|
0 => V0,
|
||||||
|
1 => V1,
|
||||||
|
_ => V2,
|
||||||
|
};
|
||||||
|
|
||||||
|
private static void Include(Vector vertex, ref double minX, ref double maxX, ref double minY, ref double maxY)
|
||||||
|
{
|
||||||
|
if (vertex.X < minX)
|
||||||
|
minX = vertex.X;
|
||||||
|
else if (vertex.X > maxX)
|
||||||
|
maxX = vertex.X;
|
||||||
|
|
||||||
|
if (vertex.Y < minY)
|
||||||
|
minY = vertex.Y;
|
||||||
|
else if (vertex.Y > maxY)
|
||||||
|
maxY = vertex.Y;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,7 +15,45 @@ namespace OpenNest.Geometry
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public static List<Polygon> Triangulate(Polygon polygon)
|
public static List<Polygon> Triangulate(Polygon polygon)
|
||||||
{
|
{
|
||||||
var triangles = new List<Polygon>();
|
var sink = new PolygonSink(new List<Polygon>());
|
||||||
|
Triangulate(polygon, ref sink);
|
||||||
|
return sink.Triangles;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Receives each ear <see cref="Triangulate(Polygon)"/> cuts, in order, as the three
|
||||||
|
/// vertices it would build its triangle from (previous, ear, next).
|
||||||
|
/// </summary>
|
||||||
|
internal interface IEarSink
|
||||||
|
{
|
||||||
|
void Add(Vector prev, Vector curr, Vector next);
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct PolygonSink : IEarSink
|
||||||
|
{
|
||||||
|
public PolygonSink(List<Polygon> triangles) => Triangles = triangles;
|
||||||
|
|
||||||
|
public List<Polygon> Triangles { get; }
|
||||||
|
|
||||||
|
public void Add(Vector prev, Vector curr, Vector next)
|
||||||
|
{
|
||||||
|
var tri = new Polygon();
|
||||||
|
tri.Vertices.Add(prev);
|
||||||
|
tri.Vertices.Add(curr);
|
||||||
|
tri.Vertices.Add(next);
|
||||||
|
tri.Close();
|
||||||
|
Triangles.Add(tri);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The ear-clipping of <see cref="Triangulate(Polygon)"/>, handing each ear to
|
||||||
|
/// <paramref name="sink"/> instead of building a triangle polygon for it: the same ears,
|
||||||
|
/// from the same vertices, in the same order.
|
||||||
|
/// </summary>
|
||||||
|
internal static void Triangulate<TSink>(Polygon polygon, ref TSink sink)
|
||||||
|
where TSink : struct, IEarSink
|
||||||
|
{
|
||||||
var verts = new List<Vector>(polygon.Vertices);
|
var verts = new List<Vector>(polygon.Vertices);
|
||||||
|
|
||||||
// Remove closing vertex if polygon is closed.
|
// Remove closing vertex if polygon is closed.
|
||||||
@@ -27,7 +65,7 @@ namespace OpenNest.Geometry
|
|||||||
verts.RemoveAt(verts.Count - 1);
|
verts.RemoveAt(verts.Count - 1);
|
||||||
|
|
||||||
if (verts.Count < 3)
|
if (verts.Count < 3)
|
||||||
return triangles;
|
return;
|
||||||
|
|
||||||
// Ensure counter-clockwise winding for ear detection.
|
// Ensure counter-clockwise winding for ear detection.
|
||||||
if (SignedArea(verts) < 0)
|
if (SignedArea(verts) < 0)
|
||||||
@@ -85,12 +123,7 @@ namespace OpenNest.Geometry
|
|||||||
var blocker = failedBlocker[currVertex];
|
var blocker = failedBlocker[currVertex];
|
||||||
if (!knownNotEar && IsEar(prev, curr, next, verts, nextOf, head, n, out blocker))
|
if (!knownNotEar && IsEar(prev, curr, next, verts, nextOf, head, n, out blocker))
|
||||||
{
|
{
|
||||||
var tri = new Polygon();
|
sink.Add(prev, curr, next);
|
||||||
tri.Vertices.Add(prev);
|
|
||||||
tri.Vertices.Add(curr);
|
|
||||||
tri.Vertices.Add(next);
|
|
||||||
tri.Close();
|
|
||||||
triangles.Add(tri);
|
|
||||||
|
|
||||||
nextOf[prevVertex] = nextVertex;
|
nextOf[prevVertex] = nextVertex;
|
||||||
prevOf[nextVertex] = prevVertex;
|
prevOf[nextVertex] = prevVertex;
|
||||||
@@ -113,8 +146,6 @@ namespace OpenNest.Geometry
|
|||||||
cursor = nextVertex;
|
cursor = nextVertex;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return triangles;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ namespace OpenNest
|
|||||||
if (world1.Polygon == null || world2.Polygon == null)
|
if (world1.Polygon == null || world2.Polygon == null)
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
return Collision.HasOverlap(
|
return Collision.HasOverlapTriangulated(
|
||||||
world1.Polygon,
|
world1.Polygon,
|
||||||
world1.Triangles,
|
world1.Triangles,
|
||||||
world2.Polygon,
|
world2.Polygon,
|
||||||
@@ -144,7 +144,7 @@ namespace OpenNest
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
private sealed class PreparedPart
|
private sealed class PreparedPart
|
||||||
{
|
{
|
||||||
private List<Polygon> triangles;
|
private List<CollisionTriangle> triangles;
|
||||||
|
|
||||||
public PreparedPart(Polygon polygon)
|
public PreparedPart(Polygon polygon)
|
||||||
{
|
{
|
||||||
@@ -154,9 +154,10 @@ namespace OpenNest
|
|||||||
|
|
||||||
public Polygon Polygon { get; }
|
public Polygon Polygon { get; }
|
||||||
|
|
||||||
public Func<List<Polygon>> Triangles { get; }
|
public Func<List<CollisionTriangle>> Triangles { get; }
|
||||||
|
|
||||||
private List<Polygon> GetTriangles() => triangles ??= Collision.Triangulate(Polygon);
|
private List<CollisionTriangle> GetTriangles() =>
|
||||||
|
triangles ??= Collision.TriangulateForClipping(Polygon);
|
||||||
}
|
}
|
||||||
|
|
||||||
private sealed class PreparedProgram
|
private sealed class PreparedProgram
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.ComponentModel;
|
||||||
|
using OpenNest.Geometry;
|
||||||
|
|
||||||
|
namespace OpenNest.Shapes
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// The flat blank of a formed angle: two legs and one 90° bend, sized from the outside
|
||||||
|
/// dimensions with the bend allowance at <see cref="KFactor"/>.
|
||||||
|
/// </summary>
|
||||||
|
public class AngleShape : ShapeDefinition
|
||||||
|
{
|
||||||
|
public double OutsideWidth { get; set; }
|
||||||
|
public double OutsideHeight { get; set; }
|
||||||
|
public double Thickness { get; set; }
|
||||||
|
public double InsideRadius { get; set; }
|
||||||
|
|
||||||
|
[Unitless]
|
||||||
|
[DisplayName("K-Factor")]
|
||||||
|
public double KFactor { get; set; }
|
||||||
|
|
||||||
|
public double Length { get; set; }
|
||||||
|
|
||||||
|
public double InsideWidth => OutsideWidth - Thickness;
|
||||||
|
|
||||||
|
public double InsideHeight => OutsideHeight - Thickness;
|
||||||
|
|
||||||
|
public double BendAllowance => SheetMetal.BendAllowance(InsideRadius, Thickness, KFactor);
|
||||||
|
|
||||||
|
/// <summary>The developed width of the blank: both legs' flats plus the bend.</summary>
|
||||||
|
public double FlatLength => InsideHeight - InsideRadius + InsideWidth - InsideRadius + BendAllowance;
|
||||||
|
|
||||||
|
/// <summary>The bend line's distance from the edge of the shorter leg.</summary>
|
||||||
|
public double BendLineDim => System.Math.Min(InsideWidth, InsideHeight) - InsideRadius + BendAllowance / 2;
|
||||||
|
|
||||||
|
public override string GenerateName() =>
|
||||||
|
$"Angle {Dim(OutsideWidth)}x{Dim(OutsideHeight)}x{Dim(Thickness)} x {Dim(Length)}";
|
||||||
|
|
||||||
|
public override void SetPreviewDefaults()
|
||||||
|
{
|
||||||
|
OutsideWidth = 4;
|
||||||
|
OutsideHeight = 2;
|
||||||
|
Thickness = 0.125;
|
||||||
|
InsideRadius = 0.3125;
|
||||||
|
KFactor = 0.42;
|
||||||
|
Length = 12;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override IReadOnlyList<ShapeDimension> GetDimensions() =>
|
||||||
|
new[]
|
||||||
|
{
|
||||||
|
ShapeDimension.Linear(nameof(Length), new Vector(0, 0), new Vector(Length, 0), ShapeDimension.Down),
|
||||||
|
};
|
||||||
|
|
||||||
|
public override ShapeSideView GetSideView() =>
|
||||||
|
SheetMetal.Section(false, OutsideWidth, OutsideHeight, Thickness, InsideRadius,
|
||||||
|
nameof(OutsideWidth), nameof(OutsideHeight), nameof(Thickness), nameof(InsideRadius));
|
||||||
|
|
||||||
|
public override Drawing GetDrawing()
|
||||||
|
{
|
||||||
|
SheetMetal.Validate(Thickness, Length, KFactor);
|
||||||
|
if (!(InsideHeight - InsideRadius > 0) || !(InsideWidth - InsideRadius > 0))
|
||||||
|
throw new InvalidOperationException("Each leg must be longer than the thickness plus the inside radius.");
|
||||||
|
|
||||||
|
// The shorter leg runs along the bottom edge, so the bend line sits BendLineDim up.
|
||||||
|
var entities = SheetMetal.Entities(Length, FlatLength, new[] { BendLineDim }, InsideRadius, out var bends);
|
||||||
|
var drawing = CreateDrawing(entities);
|
||||||
|
drawing.Bends.AddRange(bends);
|
||||||
|
return drawing;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.ComponentModel;
|
||||||
|
using OpenNest.Geometry;
|
||||||
|
|
||||||
|
namespace OpenNest.Shapes
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// The flat blank of a formed channel: two equal sides, a bottom and two 90° bends, sized
|
||||||
|
/// from the outside dimensions with the bend allowance at <see cref="KFactor"/>.
|
||||||
|
/// </summary>
|
||||||
|
public class ChannelShape : ShapeDefinition
|
||||||
|
{
|
||||||
|
public double OutsideWidth { get; set; }
|
||||||
|
public double OutsideHeight { get; set; }
|
||||||
|
public double Thickness { get; set; }
|
||||||
|
public double InsideRadius { get; set; }
|
||||||
|
|
||||||
|
[Unitless]
|
||||||
|
[DisplayName("K-Factor")]
|
||||||
|
public double KFactor { get; set; }
|
||||||
|
|
||||||
|
public double Length { get; set; }
|
||||||
|
|
||||||
|
public double InsideWidth => OutsideWidth - Thickness * 2;
|
||||||
|
|
||||||
|
public double InsideHeight => OutsideHeight - Thickness;
|
||||||
|
|
||||||
|
public double BendAllowance => SheetMetal.BendAllowance(InsideRadius, Thickness, KFactor);
|
||||||
|
|
||||||
|
/// <summary>The developed width of the blank: both sides' and the bottom's flats plus the bends.</summary>
|
||||||
|
public double FlatLength =>
|
||||||
|
(InsideHeight - InsideRadius) * 2 + InsideWidth - InsideRadius * 2 + BendAllowance * 2;
|
||||||
|
|
||||||
|
/// <summary>Each bend line's distance from its side's edge.</summary>
|
||||||
|
public double BendLineDim => InsideHeight - InsideRadius + BendAllowance / 2;
|
||||||
|
|
||||||
|
public override string GenerateName() =>
|
||||||
|
$"Channel {Dim(OutsideWidth)}x{Dim(OutsideHeight)}x{Dim(Thickness)} x {Dim(Length)}";
|
||||||
|
|
||||||
|
public override void SetPreviewDefaults()
|
||||||
|
{
|
||||||
|
OutsideWidth = 4;
|
||||||
|
OutsideHeight = 2;
|
||||||
|
Thickness = 0.125;
|
||||||
|
InsideRadius = 0.3125;
|
||||||
|
KFactor = 0.42;
|
||||||
|
Length = 12;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override IReadOnlyList<ShapeDimension> GetDimensions() =>
|
||||||
|
new[]
|
||||||
|
{
|
||||||
|
ShapeDimension.Linear(nameof(Length), new Vector(0, 0), new Vector(Length, 0), ShapeDimension.Down),
|
||||||
|
};
|
||||||
|
|
||||||
|
public override ShapeSideView GetSideView() =>
|
||||||
|
SheetMetal.Section(true, OutsideWidth, OutsideHeight, Thickness, InsideRadius,
|
||||||
|
nameof(OutsideWidth), nameof(OutsideHeight), nameof(Thickness), nameof(InsideRadius));
|
||||||
|
|
||||||
|
public override Drawing GetDrawing()
|
||||||
|
{
|
||||||
|
SheetMetal.Validate(Thickness, Length, KFactor);
|
||||||
|
if (!(InsideHeight - InsideRadius > 0))
|
||||||
|
throw new InvalidOperationException("The sides must be longer than the thickness plus the inside radius.");
|
||||||
|
if (InsideWidth - InsideRadius * 2 < 0)
|
||||||
|
throw new InvalidOperationException("The width must fit both sides' thickness and inside radius.");
|
||||||
|
|
||||||
|
var flat = FlatLength;
|
||||||
|
var bendLine = BendLineDim;
|
||||||
|
var entities = SheetMetal.Entities(Length, flat, new[] { bendLine, flat - bendLine }, InsideRadius, out var bends);
|
||||||
|
var drawing = CreateDrawing(entities);
|
||||||
|
drawing.Bends.AddRange(bends);
|
||||||
|
return drawing;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.ComponentModel;
|
||||||
|
using OpenNest.Geometry;
|
||||||
|
|
||||||
|
namespace OpenNest.Shapes
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// The flat blank of a plate rolled into a cylinder: <see cref="Length"/> by the
|
||||||
|
/// circumference of the neutral axis, <see cref="KFactor"/> of the thickness out from the
|
||||||
|
/// inside diameter.
|
||||||
|
/// </summary>
|
||||||
|
public class RolledPlateShape : ShapeDefinition
|
||||||
|
{
|
||||||
|
public double InsideDiameter { get; set; }
|
||||||
|
public double Thickness { get; set; }
|
||||||
|
|
||||||
|
[Unitless]
|
||||||
|
[DisplayName("K-Factor")]
|
||||||
|
public double KFactor { get; set; }
|
||||||
|
|
||||||
|
public double Length { get; set; }
|
||||||
|
|
||||||
|
public double InsideRadius => InsideDiameter / 2;
|
||||||
|
|
||||||
|
public double OutsideDiameter => InsideDiameter + Thickness * 2;
|
||||||
|
|
||||||
|
/// <summary>The developed width of the blank: the neutral axis's circumference.</summary>
|
||||||
|
public double FlatLength => System.Math.PI * 2 * (InsideRadius + Thickness * KFactor);
|
||||||
|
|
||||||
|
public override string GenerateName() =>
|
||||||
|
$"Rolled Plate {Dim(InsideDiameter)} ID x {Dim(Thickness)} x {Dim(Length)}";
|
||||||
|
|
||||||
|
public override void SetPreviewDefaults()
|
||||||
|
{
|
||||||
|
InsideDiameter = 10;
|
||||||
|
Thickness = 0.1875;
|
||||||
|
KFactor = 0.42;
|
||||||
|
Length = 12;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override IReadOnlyList<ShapeDimension> GetDimensions() =>
|
||||||
|
new[]
|
||||||
|
{
|
||||||
|
ShapeDimension.Linear(nameof(Length), new Vector(0, 0), new Vector(Length, 0), ShapeDimension.Down),
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>The rolled ring, with its inside diameter across the middle and a leader from its wall to the thickness.</summary>
|
||||||
|
public override ShapeSideView GetSideView()
|
||||||
|
{
|
||||||
|
var inside = InsideRadius;
|
||||||
|
var outside = InsideRadius + Thickness;
|
||||||
|
return new ShapeSideView(
|
||||||
|
new Entity[] { new Circle(0, 0, outside), new Circle(0, 0, inside) },
|
||||||
|
new[]
|
||||||
|
{
|
||||||
|
ShapeDimension.Inline(nameof(InsideDiameter), new Vector(-inside, 0), new Vector(inside, 0), "Ø"),
|
||||||
|
ShapeDimension.Leader(nameof(Thickness), new Vector(outside * System.Math.Sqrt(0.5), outside * System.Math.Sqrt(0.5)), new Vector(1, 1)),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public override Drawing GetDrawing()
|
||||||
|
{
|
||||||
|
SheetMetal.Validate(Thickness, Length, KFactor);
|
||||||
|
if (!(InsideDiameter > 0))
|
||||||
|
throw new InvalidOperationException("The inside diameter must be more than zero.");
|
||||||
|
|
||||||
|
var entities = SheetMetal.Entities(Length, FlatLength, Array.Empty<double>(), 0, out _);
|
||||||
|
return CreateDrawing(entities);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -42,6 +42,12 @@ namespace OpenNest.Shapes
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public virtual IReadOnlyList<ShapeDimension> GetDimensions() => Array.Empty<ShapeDimension>();
|
public virtual IReadOnlyList<ShapeDimension> GetDimensions() => Array.Empty<ShapeDimension>();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A sheet metal part's cross-section that the Shape Library draws beside the flat blank,
|
||||||
|
/// with the dimensions of parameters the blank cannot show; null for a flat shape.
|
||||||
|
/// </summary>
|
||||||
|
public virtual ShapeSideView GetSideView() => null;
|
||||||
|
|
||||||
public static List<T> LoadFromJson<T>(string path)
|
public static List<T> LoadFromJson<T>(string path)
|
||||||
where T : ShapeDefinition
|
where T : ShapeDefinition
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using OpenNest.Geometry;
|
||||||
|
|
||||||
|
namespace OpenNest.Shapes
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// A sheet metal part's cross-section, which the Shape Library draws beside the flat blank with
|
||||||
|
/// its own dimensions. Annotation only: it never affects the drawing.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class ShapeSideView
|
||||||
|
{
|
||||||
|
public ShapeSideView(IReadOnlyList<Entity> entities, IReadOnlyList<ShapeDimension> dimensions)
|
||||||
|
{
|
||||||
|
Entities = entities;
|
||||||
|
Dimensions = dimensions;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The section's closed outlines, in the view's own coordinates.</summary>
|
||||||
|
public IReadOnlyList<Entity> Entities { get; }
|
||||||
|
|
||||||
|
/// <summary>The section's dimensions, in the same coordinates as <see cref="Entities"/>.</summary>
|
||||||
|
public IReadOnlyList<ShapeDimension> Dimensions { get; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using OpenNest.Bending;
|
||||||
|
using OpenNest.Geometry;
|
||||||
|
|
||||||
|
namespace OpenNest.Shapes
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Flat blanks and sections for the sheet metal shapes: parts bent or rolled along their
|
||||||
|
/// length, cut as a rectangle <c>length</c> along X by the developed width along Y.
|
||||||
|
/// </summary>
|
||||||
|
internal static class SheetMetal
|
||||||
|
{
|
||||||
|
public const double BendAngle = 90;
|
||||||
|
|
||||||
|
public static void Validate(double thickness, double length, double kFactor)
|
||||||
|
{
|
||||||
|
if (!(thickness > 0))
|
||||||
|
throw new InvalidOperationException("The thickness must be more than zero.");
|
||||||
|
if (!(length > 0))
|
||||||
|
throw new InvalidOperationException("The length must be more than zero.");
|
||||||
|
if (!(kFactor >= 0 && kFactor <= 1))
|
||||||
|
throw new InvalidOperationException("The K-factor must be from 0 to 1.");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static double BendAllowance(double insideRadius, double thickness, double kFactor) =>
|
||||||
|
BendMath.Allowance(Math.Angle.ToRadians(BendAngle), insideRadius, thickness, kFactor);
|
||||||
|
|
||||||
|
/// <summary>The blank's outline, with a 90° up bend across it, etched, at each bend line.</summary>
|
||||||
|
/// <param name="bendLines">Each bend line's distance from the blank's bottom edge.</param>
|
||||||
|
public static List<Entity> Entities(double length, double width, IReadOnlyList<double> bendLines, double insideRadius, out List<Bend> bends)
|
||||||
|
{
|
||||||
|
var entities = new List<Entity>
|
||||||
|
{
|
||||||
|
new Line(0, 0, length, 0),
|
||||||
|
new Line(length, 0, length, width),
|
||||||
|
new Line(length, width, 0, width),
|
||||||
|
new Line(0, width, 0, 0),
|
||||||
|
};
|
||||||
|
|
||||||
|
bends = bendLines
|
||||||
|
.Select(y => new Bend
|
||||||
|
{
|
||||||
|
StartPoint = new Vector(0, y),
|
||||||
|
EndPoint = new Vector(length, y),
|
||||||
|
Direction = BendDirection.Up,
|
||||||
|
Angle = BendAngle,
|
||||||
|
Radius = insideRadius,
|
||||||
|
})
|
||||||
|
.ToList();
|
||||||
|
foreach (var bend in bends)
|
||||||
|
entities.AddRange(bend.GetEtchEntities());
|
||||||
|
|
||||||
|
return entities;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The section of a part bent up 90° at its right end (an angle, "_|") or at both ends
|
||||||
|
/// (a channel, "U"): the bottom on Y = 0 from X = 0 to <paramref name="outsideWidth"/>,
|
||||||
|
/// the sides up to <paramref name="outsideHeight"/>, every bend at
|
||||||
|
/// <paramref name="insideRadius"/>. Dimensioned with the outside sizes, the thickness
|
||||||
|
/// across the right side's top and the inside radius of its bend.
|
||||||
|
/// </summary>
|
||||||
|
public static ShapeSideView Section(
|
||||||
|
bool bothSides, double outsideWidth, double outsideHeight, double thickness, double insideRadius,
|
||||||
|
string widthProperty, string heightProperty, string thicknessProperty, string radiusProperty)
|
||||||
|
{
|
||||||
|
const double quarter = System.Math.PI / 2;
|
||||||
|
var outsideRadius = insideRadius + thickness;
|
||||||
|
var right = new Vector(outsideWidth - outsideRadius, outsideRadius);
|
||||||
|
var left = new Vector(outsideRadius, outsideRadius);
|
||||||
|
var w = outsideWidth;
|
||||||
|
var h = outsideHeight;
|
||||||
|
var t = thickness;
|
||||||
|
|
||||||
|
// Round the outside, counterclockwise from the bottom's left end, then back inside
|
||||||
|
// (a reversed arc runs clockwise from its start angle to its end angle).
|
||||||
|
var entities = new List<Entity>();
|
||||||
|
if (bothSides)
|
||||||
|
{
|
||||||
|
entities.Add(new Line(0, h, 0, outsideRadius));
|
||||||
|
entities.Add(new Arc(left, outsideRadius, 2 * quarter, 3 * quarter));
|
||||||
|
entities.Add(new Line(outsideRadius, 0, right.X, 0));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
entities.Add(new Line(0, 0, right.X, 0));
|
||||||
|
}
|
||||||
|
entities.Add(new Arc(right, outsideRadius, 3 * quarter, 4 * quarter));
|
||||||
|
entities.Add(new Line(w, outsideRadius, w, h));
|
||||||
|
entities.Add(new Line(w, h, w - t, h));
|
||||||
|
entities.Add(new Line(w - t, h, w - t, outsideRadius));
|
||||||
|
entities.Add(new Arc(right, insideRadius, 0, 3 * quarter, true));
|
||||||
|
if (bothSides)
|
||||||
|
{
|
||||||
|
entities.Add(new Line(right.X, t, outsideRadius, t));
|
||||||
|
entities.Add(new Arc(left, insideRadius, 3 * quarter, 2 * quarter, true));
|
||||||
|
entities.Add(new Line(t, outsideRadius, t, h));
|
||||||
|
entities.Add(new Line(t, h, 0, h));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
entities.Add(new Line(right.X, t, 0, t));
|
||||||
|
entities.Add(new Line(0, t, 0, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
var dimensions = new[]
|
||||||
|
{
|
||||||
|
ShapeDimension.Linear(widthProperty, new Vector(0, 0), new Vector(w, 0), ShapeDimension.Down),
|
||||||
|
ShapeDimension.Linear(heightProperty, new Vector(w, 0), new Vector(w, h), ShapeDimension.Right),
|
||||||
|
ShapeDimension.Linear(thicknessProperty, new Vector(w - t, h), new Vector(w, h), ShapeDimension.Up),
|
||||||
|
ShapeDimension.ArcLeader(radiusProperty, right, insideRadius, 3 * quarter, 4 * quarter, "R"),
|
||||||
|
};
|
||||||
|
|
||||||
|
return new ShapeSideView(entities, dimensions);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace OpenNest.Shapes
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Marks a <see cref="double"/> shape parameter that is a plain number, such as a K-factor,
|
||||||
|
/// rather than a length: the Shape Library shows it without fractions or an inch mark.
|
||||||
|
/// </summary>
|
||||||
|
[AttributeUsage(AttributeTargets.Property)]
|
||||||
|
public sealed class UnitlessAttribute : Attribute
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
using System.Linq;
|
||||||
|
using OpenNest.Desktop.Interaction;
|
||||||
|
using OpenNest.Engine.Fill;
|
||||||
|
using OpenNest.Geometry;
|
||||||
|
|
||||||
|
namespace OpenNest.Desktop.Tests.Interaction;
|
||||||
|
|
||||||
|
public class DrawingPlacementTests
|
||||||
|
{
|
||||||
|
private readonly Plate plate = InteractionFixtures.Plate();
|
||||||
|
private readonly TestToolHost host;
|
||||||
|
private readonly Drawing drawing = new("dropped", InteractionFixtures.Rect(10, 6));
|
||||||
|
|
||||||
|
public DrawingPlacementTests()
|
||||||
|
{
|
||||||
|
host = new TestToolHost(plate);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static SettleOrder Order() => SettleOrder.ClosestToCorner;
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_drop_adds_one_part_centred_on_the_drop_point_as_one_step()
|
||||||
|
{
|
||||||
|
var recorder = host.RecordHistory();
|
||||||
|
var count = plate.Parts.Count;
|
||||||
|
|
||||||
|
var part = DrawingPlacement.AddPart(host, drawing, new Vector(60, 50));
|
||||||
|
|
||||||
|
Assert.NotNull(part);
|
||||||
|
Assert.Equal(count + 1, plate.Parts.Count);
|
||||||
|
Assert.Same(part, plate.Parts[^1]);
|
||||||
|
Assert.Same(drawing, part.BaseDrawing);
|
||||||
|
Assert.True(part.BoundingBox.Center.DistanceTo(new Vector(60, 50)) < 1e-9,
|
||||||
|
$"centred at {part.BoundingBox.Center}");
|
||||||
|
Assert.Equal(new[] { "Add Part" }, host.ChangeLabels);
|
||||||
|
Assert.Equal(1, recorder.History.UndoCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_drop_keeps_the_cut_offs_as_they_are()
|
||||||
|
{
|
||||||
|
var crossing = new Part(plate.Parts[1].BaseDrawing, new Vector(75, 40));
|
||||||
|
plate.Parts.Add(crossing);
|
||||||
|
plate.RegenerateCutOffs(host.CutOffSettings);
|
||||||
|
var strokes = PlateEditsTests.CutOffStrokes(plate);
|
||||||
|
host.ThrowOnCutOffSettings = true;
|
||||||
|
|
||||||
|
DrawingPlacement.AddPart(host, drawing, new Vector(20, 80));
|
||||||
|
|
||||||
|
Assert.Equal(strokes, PlateEditsTests.CutOffStrokes(plate));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_drop_does_nothing_while_locked()
|
||||||
|
{
|
||||||
|
var count = plate.Parts.Count;
|
||||||
|
host.EditsLocked = true;
|
||||||
|
|
||||||
|
Assert.Null(DrawingPlacement.AddPart(host, drawing, new Vector(60, 50)));
|
||||||
|
|
||||||
|
Assert.Equal(count, plate.Parts.Count);
|
||||||
|
Assert.Empty(host.ChangeLabels);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_drop_does_nothing_without_a_plate()
|
||||||
|
{
|
||||||
|
var count = plate.Parts.Count;
|
||||||
|
host.Plate = null;
|
||||||
|
|
||||||
|
Assert.Null(DrawingPlacement.AddPart(host, drawing, new Vector(60, 50)));
|
||||||
|
|
||||||
|
Assert.Equal(count, plate.Parts.Count);
|
||||||
|
Assert.Empty(host.ChangeLabels);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Undo_takes_a_dropped_part_off_and_redo_puts_it_back()
|
||||||
|
{
|
||||||
|
var recorder = host.RecordHistory();
|
||||||
|
// The list offers the nest's own drawings.
|
||||||
|
recorder.Document.Nest.Drawings.Add(drawing);
|
||||||
|
recorder.Reset();
|
||||||
|
static int Real(Plate p) => p.Parts.Count(part => !part.BaseDrawing.IsCutOff);
|
||||||
|
DrawingPlacement.AddPart(host, drawing, new Vector(60, 50));
|
||||||
|
|
||||||
|
recorder.Undo();
|
||||||
|
var undone = recorder.Document.Nest.Plates[0];
|
||||||
|
Assert.DoesNotContain(undone.Parts, p => p.BaseDrawing.Name == "dropped");
|
||||||
|
var count = Real(undone);
|
||||||
|
recorder.Redo();
|
||||||
|
|
||||||
|
var restored = recorder.Document.Nest.Plates[0];
|
||||||
|
Assert.Equal(count + 1, Real(restored));
|
||||||
|
var dropped = restored.Parts.Single(p => p.BaseDrawing.Name == "dropped");
|
||||||
|
Assert.True(dropped.BoundingBox.Center.DistanceTo(new Vector(60, 50)) < 1e-9);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void An_off_centre_drawing_is_centred_on_its_bounding_box()
|
||||||
|
{
|
||||||
|
// A drawing whose program does not start at its bounding box's corner.
|
||||||
|
var offset = new Drawing("offset", InteractionFixtures.Rect(8, 4, 3, 7));
|
||||||
|
|
||||||
|
var part = DrawingPlacement.AddPart(host, offset, new Vector(40, 30));
|
||||||
|
|
||||||
|
Assert.True(part.BoundingBox.Center.DistanceTo(new Vector(40, 30)) < 1e-9,
|
||||||
|
$"centred at {part.BoundingBox.Center}");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void The_place_tool_for_a_drawing_places_a_new_part_of_it()
|
||||||
|
{
|
||||||
|
var tool = DrawingPlacement.CreatePlaceTool(host, drawing, Order);
|
||||||
|
host.Tools.SetTool(tool);
|
||||||
|
var count = plate.Parts.Count;
|
||||||
|
|
||||||
|
tool.PointerMoved(host.At(30, 60));
|
||||||
|
tool.Apply(ToolModifiers.None);
|
||||||
|
|
||||||
|
Assert.Single(tool.Previews);
|
||||||
|
Assert.Equal(count + 1, plate.Parts.Count);
|
||||||
|
Assert.Same(drawing, plate.Parts[^1].BaseDrawing);
|
||||||
|
Assert.True(plate.Parts[^1].BoundingBox.Location.DistanceTo(new Vector(30, 60)) < 1e-9);
|
||||||
|
Assert.Equal(new[] { "Add Part" }, host.ChangeLabels);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Delete_with_a_drawing_tool_removes_nothing()
|
||||||
|
{
|
||||||
|
var tool = DrawingPlacement.CreatePlaceTool(host, drawing, Order);
|
||||||
|
host.Tools.SetTool(tool);
|
||||||
|
var count = plate.Parts.Count;
|
||||||
|
var recorder = host.RecordHistory();
|
||||||
|
|
||||||
|
tool.DeleteSources();
|
||||||
|
|
||||||
|
Assert.Equal(count, plate.Parts.Count);
|
||||||
|
Assert.Equal(0, recorder.History.UndoCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_pick_up_is_taken_once_by_the_plate()
|
||||||
|
{
|
||||||
|
var pickup = new DrawingPickup();
|
||||||
|
Assert.Null(pickup.TakeOnPlateEnter(drawing));
|
||||||
|
|
||||||
|
pickup.PickUp();
|
||||||
|
|
||||||
|
Assert.Same(drawing, pickup.TakeOnPlateEnter(drawing));
|
||||||
|
Assert.Null(pickup.TakeOnPlateEnter(drawing));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_pick_up_with_nothing_selected_stays_armed()
|
||||||
|
{
|
||||||
|
var pickup = new DrawingPickup();
|
||||||
|
pickup.PickUp();
|
||||||
|
|
||||||
|
Assert.Null(pickup.TakeOnPlateEnter(null));
|
||||||
|
|
||||||
|
Assert.True(pickup.IsArmed);
|
||||||
|
Assert.Same(drawing, pickup.TakeOnPlateEnter(drawing));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Putting_down_disarms_the_pick_up()
|
||||||
|
{
|
||||||
|
var pickup = new DrawingPickup();
|
||||||
|
pickup.PickUp();
|
||||||
|
|
||||||
|
pickup.PutDown();
|
||||||
|
|
||||||
|
Assert.False(pickup.IsArmed);
|
||||||
|
Assert.Null(pickup.TakeOnPlateEnter(drawing));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,548 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using OpenNest.CNC;
|
||||||
|
using OpenNest.CutOffs;
|
||||||
|
using OpenNest.Desktop.Interaction;
|
||||||
|
using OpenNest.Engine.Fill;
|
||||||
|
using OpenNest.Geometry;
|
||||||
|
|
||||||
|
namespace OpenNest.Desktop.Tests.Interaction;
|
||||||
|
|
||||||
|
public class PlaceToolTests
|
||||||
|
{
|
||||||
|
private readonly Plate plate = InteractionFixtures.Plate();
|
||||||
|
private readonly TestToolHost host;
|
||||||
|
private readonly PlateEdits edits;
|
||||||
|
private int orderReads;
|
||||||
|
|
||||||
|
public PlaceToolTests()
|
||||||
|
{
|
||||||
|
host = new TestToolHost(plate);
|
||||||
|
edits = new PlateEdits(host) { Tools = host.Tools };
|
||||||
|
}
|
||||||
|
|
||||||
|
private SettleOrder Order()
|
||||||
|
{
|
||||||
|
orderReads++;
|
||||||
|
return SettleOrder.ClosestToCorner;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void AssertAt(Vector expected, Vector actual) =>
|
||||||
|
Assert.True(expected.DistanceTo(actual) < 1e-9, $"expected {expected}, was {actual}");
|
||||||
|
|
||||||
|
private List<Part> RealParts() => plate.Parts.Where(p => !p.BaseDrawing.IsCutOff).ToList();
|
||||||
|
|
||||||
|
private PlaceTool Copy(params Part[] parts)
|
||||||
|
{
|
||||||
|
host.Selection.Clear();
|
||||||
|
host.Selection.Select(parts);
|
||||||
|
return PlateClipboard.Copy(host, host.Tools, Order);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Part Triangle(double x, double y)
|
||||||
|
{
|
||||||
|
var program = new Program();
|
||||||
|
program.Codes.Add(new RapidMove(new Vector(0, 0)));
|
||||||
|
program.Codes.Add(new LinearMove(new Vector(40, 0)));
|
||||||
|
program.Codes.Add(new LinearMove(new Vector(0, 40)));
|
||||||
|
program.Codes.Add(new LinearMove(new Vector(0, 0)));
|
||||||
|
return new Part(new Drawing("triangle", program), new Vector(x, y));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Part Square(double size, double x, double y) =>
|
||||||
|
new(new Drawing("square", InteractionFixtures.Rect(size, size)), new Vector(x, y));
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Previews_follow_the_pointer_by_their_lower_left_corner()
|
||||||
|
{
|
||||||
|
var tool = Copy(plate.Parts[2]);
|
||||||
|
|
||||||
|
Assert.Same(tool, host.Tools.Current);
|
||||||
|
Assert.Equal("Clone Parts", host.Tools.Status);
|
||||||
|
Assert.True(tool.PointerMoved(host.At(30, 60, ToolButton.None)));
|
||||||
|
|
||||||
|
Assert.Equal(2, tool.Previews.Count);
|
||||||
|
AssertAt(new Vector(30, 60), tool.Previews.GetBoundingBox().Location);
|
||||||
|
AssertAt(new Vector(30, 60), tool.Previews[0].Location);
|
||||||
|
AssertAt(new Vector(40.05, 60), tool.Previews[1].Location);
|
||||||
|
AssertAt(new Vector(40, 0), plate.Parts[2].Location);
|
||||||
|
Assert.True(host.Invalidations > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_move_to_the_same_screen_point_keeps_a_nudge()
|
||||||
|
{
|
||||||
|
var tool = Copy(plate.Parts[1]);
|
||||||
|
tool.PointerMoved(host.At(30, 60));
|
||||||
|
edits.NudgeBy(5, 0);
|
||||||
|
AssertAt(new Vector(35, 60), tool.Previews[0].Location);
|
||||||
|
|
||||||
|
tool.PointerMoved(host.At(30, 60));
|
||||||
|
AssertAt(new Vector(35, 60), tool.Previews[0].Location);
|
||||||
|
|
||||||
|
tool.PointerMoved(host.At(31, 60));
|
||||||
|
AssertAt(new Vector(31, 60), tool.Previews[0].Location);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_click_adds_copies_and_one_undo_removes_them()
|
||||||
|
{
|
||||||
|
var recorder = host.RecordHistory();
|
||||||
|
var source = plate.Parts[1];
|
||||||
|
var tool = Copy(source);
|
||||||
|
var count = plate.Parts.Count;
|
||||||
|
tool.PointerMoved(host.At(30, 60));
|
||||||
|
|
||||||
|
Assert.True(tool.PointerPressed(host.At(30, 60)));
|
||||||
|
tool.PointerMoved(host.At(60, 60));
|
||||||
|
Assert.True(tool.PointerPressed(host.At(60, 60)));
|
||||||
|
|
||||||
|
Assert.Equal(count + 2, plate.Parts.Count);
|
||||||
|
AssertAt(new Vector(20, 0), source.Location);
|
||||||
|
AssertAt(new Vector(30, 60), plate.Parts[count].Location);
|
||||||
|
AssertAt(new Vector(60, 60), plate.Parts[count + 1].Location);
|
||||||
|
Assert.DoesNotContain(tool.Previews[0], plate.Parts);
|
||||||
|
Assert.Equal(new[] { "Add Part", "Add Part" }, host.ChangeLabels);
|
||||||
|
Assert.Same(tool, host.Tools.Current);
|
||||||
|
|
||||||
|
recorder.Undo();
|
||||||
|
Assert.Equal(count + 1, recorder.Document.Nest.Plates[0].Parts.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Placing_several_parts_is_labelled_add_parts()
|
||||||
|
{
|
||||||
|
var tool = Copy(plate.Parts[1], plate.Parts[4]);
|
||||||
|
tool.PointerMoved(host.At(30, 60));
|
||||||
|
|
||||||
|
tool.Apply(ToolModifiers.None);
|
||||||
|
|
||||||
|
Assert.Equal(new[] { "Add Parts" }, host.ChangeLabels);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Other_buttons_do_not_place()
|
||||||
|
{
|
||||||
|
var tool = Copy(plate.Parts[1]);
|
||||||
|
var count = plate.Parts.Count;
|
||||||
|
|
||||||
|
Assert.False(tool.PointerPressed(host.At(30, 60, ToolButton.Right)));
|
||||||
|
Assert.False(tool.PointerPressed(host.At(30, 60, ToolButton.Middle)));
|
||||||
|
|
||||||
|
Assert.Equal(count, plate.Parts.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(1, false, false)]
|
||||||
|
[InlineData(2, true, false)]
|
||||||
|
[InlineData(3, true, true)]
|
||||||
|
[InlineData(4, false, true)]
|
||||||
|
public void Shift_settles_toward_the_quadrant_corner(int quadrant, bool right, bool up)
|
||||||
|
{
|
||||||
|
var empty = new Plate(new Size(100, 100)) { Quadrant = quadrant };
|
||||||
|
var emptyHost = new TestToolHost(empty);
|
||||||
|
var tool = new PlaceTool(emptyHost, new[] { Square(10, 0, 0) }, Order);
|
||||||
|
var center = empty.WorkArea().Center;
|
||||||
|
tool.PointerMoved(emptyHost.At(center.X, center.Y));
|
||||||
|
|
||||||
|
tool.Apply(ToolModifiers.Shift);
|
||||||
|
|
||||||
|
var area = empty.WorkArea();
|
||||||
|
var box = empty.Parts.Single().BoundingBox;
|
||||||
|
Assert.Equal(right ? area.Right : area.Left, right ? box.Right : box.Left, 9);
|
||||||
|
Assert.Equal(up ? area.Top : area.Bottom, up ? box.Top : box.Bottom, 9);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Shift_settles_on_geometry_and_ctrl_on_bounding_boxes()
|
||||||
|
{
|
||||||
|
var shiftLocation = SettleBesideTriangle(ToolModifiers.Shift, out var shiftPlate);
|
||||||
|
var ctrlLocation = SettleBesideTriangle(ToolModifiers.Control, out _);
|
||||||
|
var bothLocation = SettleBesideTriangle(ToolModifiers.Shift | ToolModifiers.Control, out _);
|
||||||
|
|
||||||
|
// Pushed left onto the hypotenuse x + y = 40, inside the triangle's box but clear of it.
|
||||||
|
AssertAt(new Vector(10, 30), shiftLocation);
|
||||||
|
// Boxes only: it starts inside the triangle's box, so it never nests into the shape.
|
||||||
|
AssertAt(new Vector(30, 30), ctrlLocation);
|
||||||
|
AssertAt(shiftLocation, bothLocation);
|
||||||
|
Assert.Equal(2, shiftPlate.Parts.Count);
|
||||||
|
Assert.Equal(3, orderReads);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Vector SettleBesideTriangle(ToolModifiers modifiers, out Plate triangles)
|
||||||
|
{
|
||||||
|
triangles = new Plate(new Size(100, 100));
|
||||||
|
triangles.Parts.Add(Triangle(0, 0));
|
||||||
|
var trianglesHost = new TestToolHost(triangles);
|
||||||
|
var tool = new PlaceTool(trianglesHost, new[] { Square(10, 0, 0) }, Order);
|
||||||
|
tool.PointerMoved(trianglesHost.At(30, 30));
|
||||||
|
tool.Apply(modifiers);
|
||||||
|
AssertAt(triangles.Parts[1].Location, tool.Previews[0].Location);
|
||||||
|
return triangles.Parts[1].Location;
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void The_placement_order_is_read_at_each_settling_click()
|
||||||
|
{
|
||||||
|
var tool = Copy(plate.Parts[1]);
|
||||||
|
Assert.Equal(0, orderReads);
|
||||||
|
tool.PointerMoved(host.At(30, 60));
|
||||||
|
|
||||||
|
tool.Apply(ToolModifiers.None);
|
||||||
|
Assert.Equal(0, orderReads);
|
||||||
|
tool.Apply(ToolModifiers.Shift);
|
||||||
|
tool.Apply(ToolModifiers.Control);
|
||||||
|
|
||||||
|
Assert.Equal(2, orderReads);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Copied_common_lines_join_the_placed_copies_with_the_source_kerf()
|
||||||
|
{
|
||||||
|
var tool = Copy(plate.Parts[2]);
|
||||||
|
tool.PointerMoved(host.At(20, 60));
|
||||||
|
|
||||||
|
tool.Apply(ToolModifiers.None);
|
||||||
|
|
||||||
|
var placed = plate.Parts.Skip(plate.Parts.Count - 2).ToList();
|
||||||
|
var group = plate.CommonLineGroupOf(placed[0]);
|
||||||
|
Assert.NotNull(group);
|
||||||
|
Assert.True(group.Contains(placed[1]));
|
||||||
|
Assert.Equal(0.05, group.Kerf, 12);
|
||||||
|
Assert.Equal(2, plate.CommonLines.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_click_rebuilds_the_cut_offs_around_the_copy()
|
||||||
|
{
|
||||||
|
var before = PlateEditsTests.CutOffStrokes(plate);
|
||||||
|
var tool = Copy(plate.Parts[1]);
|
||||||
|
tool.PointerMoved(host.At(75, 40));
|
||||||
|
|
||||||
|
tool.Apply(ToolModifiers.None);
|
||||||
|
|
||||||
|
Assert.NotEqual(before, PlateEditsTests.CutOffStrokes(plate));
|
||||||
|
var twin = InteractionFixtures.Plate();
|
||||||
|
twin.Parts.Add(new Part(plate.Parts[1].BaseDrawing, new Vector(75, 40)));
|
||||||
|
twin.RegenerateCutOffs(new CutOffSettings());
|
||||||
|
Assert.Equal(PlateEditsTests.CutOffStrokes(twin), PlateEditsTests.CutOffStrokes(plate));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Delete_removes_the_sources_and_selected_parts_as_one_step()
|
||||||
|
{
|
||||||
|
var recorder = host.RecordHistory();
|
||||||
|
var source = plate.Parts[1];
|
||||||
|
var other = plate.Parts[4];
|
||||||
|
var tool = Copy(source);
|
||||||
|
host.Selection.Select(other);
|
||||||
|
|
||||||
|
edits.Delete();
|
||||||
|
|
||||||
|
Assert.DoesNotContain(source, plate.Parts);
|
||||||
|
Assert.DoesNotContain(other, plate.Parts);
|
||||||
|
Assert.Equal(3, RealParts().Count);
|
||||||
|
Assert.True(host.Selection.IsEmpty);
|
||||||
|
Assert.Equal(new[] { "Delete" }, host.ChangeLabels);
|
||||||
|
Assert.Equal(1, recorder.History.UndoCount);
|
||||||
|
Assert.Single(tool.Previews);
|
||||||
|
Assert.Same(tool, host.Tools.Current);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Delete_after_a_cut_records_nothing()
|
||||||
|
{
|
||||||
|
var recorder = host.RecordHistory();
|
||||||
|
host.Selection.Select(plate.Parts[1]);
|
||||||
|
var tool = PlateClipboard.Cut(host, host.Tools, Order);
|
||||||
|
Assert.Equal(1, recorder.History.UndoCount);
|
||||||
|
|
||||||
|
tool.DeleteSources();
|
||||||
|
|
||||||
|
Assert.Equal(1, recorder.History.UndoCount);
|
||||||
|
Assert.Equal("Cut", recorder.History.UndoLabel);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Delete_with_no_source_left_keeps_the_cut_offs()
|
||||||
|
{
|
||||||
|
var crossing = new Part(plate.Parts[1].BaseDrawing, new Vector(75, 40));
|
||||||
|
plate.Parts.Add(crossing);
|
||||||
|
plate.RegenerateCutOffs(host.CutOffSettings);
|
||||||
|
host.Selection.Select(crossing);
|
||||||
|
var tool = PlateClipboard.Cut(host, host.Tools, Order);
|
||||||
|
var strokes = PlateEditsTests.CutOffStrokes(plate);
|
||||||
|
// A rebuild now would give the cut-offs new programs: an unrecorded change.
|
||||||
|
host.ThrowOnCutOffSettings = true;
|
||||||
|
|
||||||
|
tool.DeleteSources();
|
||||||
|
|
||||||
|
Assert.Equal(strokes, PlateEditsTests.CutOffStrokes(plate));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Delete_rebuilds_the_cut_offs()
|
||||||
|
{
|
||||||
|
var crossing = new Part(plate.Parts[1].BaseDrawing, new Vector(75, 40));
|
||||||
|
var expected = PlateEditsTests.CutOffStrokes(plate);
|
||||||
|
plate.Parts.Add(crossing);
|
||||||
|
plate.RegenerateCutOffs(host.CutOffSettings);
|
||||||
|
var tool = Copy(crossing);
|
||||||
|
|
||||||
|
tool.DeleteSources();
|
||||||
|
|
||||||
|
Assert.Equal(expected, PlateEditsTests.CutOffStrokes(plate));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Cut_removes_the_sources_in_one_step_without_rebuilding_cut_offs()
|
||||||
|
{
|
||||||
|
var recorder = host.RecordHistory();
|
||||||
|
var crossing = new Part(plate.Parts[1].BaseDrawing, new Vector(75, 40));
|
||||||
|
plate.Parts.Add(crossing);
|
||||||
|
plate.RegenerateCutOffs(host.CutOffSettings);
|
||||||
|
var strokes = PlateEditsTests.CutOffStrokes(plate);
|
||||||
|
recorder.Reset();
|
||||||
|
host.Selection.Select(crossing);
|
||||||
|
host.Selection.Select(plate.Parts[2]);
|
||||||
|
|
||||||
|
var tool = PlateClipboard.Cut(host, host.Tools, Order);
|
||||||
|
|
||||||
|
Assert.Same(tool, host.Tools.Current);
|
||||||
|
Assert.Equal(3, tool.Previews.Count);
|
||||||
|
Assert.DoesNotContain(crossing, plate.Parts);
|
||||||
|
Assert.Equal(3, RealParts().Count);
|
||||||
|
Assert.Equal(strokes, PlateEditsTests.CutOffStrokes(plate));
|
||||||
|
Assert.True(host.Selection.IsEmpty);
|
||||||
|
Assert.Equal(new[] { "Cut" }, host.ChangeLabels);
|
||||||
|
Assert.Equal(1, recorder.History.UndoCount);
|
||||||
|
|
||||||
|
// The cut group is joined again among its copies.
|
||||||
|
tool.PointerMoved(host.At(10, 60));
|
||||||
|
tool.Apply(ToolModifiers.None);
|
||||||
|
Assert.Single(plate.CommonLines);
|
||||||
|
|
||||||
|
recorder.Undo();
|
||||||
|
recorder.Undo();
|
||||||
|
Assert.Equal(6, recorder.Document.Nest.Plates[0].Parts.Count(p => !p.BaseDrawing.IsCutOff));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Copy_and_cut_need_selected_parts_on_the_plate()
|
||||||
|
{
|
||||||
|
Assert.Null(PlateClipboard.Copy(host, host.Tools, Order));
|
||||||
|
Assert.Null(PlateClipboard.Cut(host, host.Tools, Order));
|
||||||
|
|
||||||
|
host.Selection.Select(plate.Parts[1]);
|
||||||
|
plate.Parts.RemoveAt(1);
|
||||||
|
Assert.Null(PlateClipboard.Cut(host, host.Tools, Order));
|
||||||
|
|
||||||
|
Assert.IsType<SelectTool>(host.Tools.Current);
|
||||||
|
Assert.Empty(host.ChangeLabels);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Copy_keeps_the_sources_on_the_plate()
|
||||||
|
{
|
||||||
|
var count = plate.Parts.Count;
|
||||||
|
var tool = Copy(plate.Parts[1], plate.Parts[4]);
|
||||||
|
|
||||||
|
Assert.Equal(count, plate.Parts.Count);
|
||||||
|
Assert.Equal(2, tool.Previews.Count);
|
||||||
|
Assert.Empty(host.ChangeLabels);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Edits_move_the_previews_without_an_undo_step()
|
||||||
|
{
|
||||||
|
var recorder = host.RecordHistory();
|
||||||
|
var tool = Copy(plate.Parts[1]);
|
||||||
|
tool.PointerMoved(host.At(30, 60));
|
||||||
|
var before = RealParts().Select(p => p.Location).ToList();
|
||||||
|
var strokes = PlateEditsTests.CutOffStrokes(plate);
|
||||||
|
Assert.True(edits.HasPartsToEdit);
|
||||||
|
|
||||||
|
edits.Nudge(PushDirection.Right);
|
||||||
|
AssertAt(new Vector(40, 60), tool.Previews[0].Location);
|
||||||
|
edits.Push(PushDirection.Down);
|
||||||
|
AssertAt(new Vector(40, 10), tool.Previews[0].Location);
|
||||||
|
edits.Step(PushDirection.Up);
|
||||||
|
// A step adds a hair over the part's height.
|
||||||
|
Assert.True(new Vector(40, 20).DistanceTo(tool.Previews[0].Location) < 1e-4);
|
||||||
|
tool.Previews[0].Offset(new Vector(36, 0));
|
||||||
|
// Rebuilding cut-offs would throw: previews are not on the plate.
|
||||||
|
host.ThrowOnCutOffSettings = true;
|
||||||
|
edits.RotateQuarterTurn();
|
||||||
|
edits.RotateByWheel(1, fine: false);
|
||||||
|
|
||||||
|
Assert.True(new Vector(76, 20).DistanceTo(tool.Previews[0].BoundingBox.Location) < 1e-4);
|
||||||
|
Assert.NotEqual(0, tool.Previews[0].Rotation, 6);
|
||||||
|
Assert.Equal(before, RealParts().Select(p => p.Location).ToList());
|
||||||
|
Assert.Equal(strokes, PlateEditsTests.CutOffStrokes(plate));
|
||||||
|
Assert.Empty(host.ChangeLabels);
|
||||||
|
Assert.False(recorder.CanUndo);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Without_tools_or_a_place_tool_edits_move_the_selection()
|
||||||
|
{
|
||||||
|
Assert.False(edits.HasPartsToEdit);
|
||||||
|
host.Selection.Select(plate.Parts[4]);
|
||||||
|
Assert.True(edits.HasPartsToEdit);
|
||||||
|
|
||||||
|
edits.NudgeBy(1, 0);
|
||||||
|
|
||||||
|
AssertAt(new Vector(21, 20), plate.Parts[4].Location);
|
||||||
|
Assert.Equal(new[] { "Nudge" }, host.ChangeLabels);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Locked_edits_refuse_placing_deleting_cutting_and_copying()
|
||||||
|
{
|
||||||
|
var tool = Copy(plate.Parts[1]);
|
||||||
|
tool.PointerMoved(host.At(30, 60));
|
||||||
|
var count = plate.Parts.Count;
|
||||||
|
host.Selection.Select(plate.Parts[4]);
|
||||||
|
host.EditsLocked = true;
|
||||||
|
|
||||||
|
Assert.False(tool.PointerPressed(host.At(30, 60)));
|
||||||
|
// WinForms raises no mouse move while locked, so the copy stays put.
|
||||||
|
Assert.False(tool.PointerMoved(host.At(50, 20)));
|
||||||
|
tool.Apply(ToolModifiers.None);
|
||||||
|
tool.DeleteSources();
|
||||||
|
edits.Delete();
|
||||||
|
edits.NudgeBy(5, 0);
|
||||||
|
Assert.Null(PlateClipboard.Copy(host, host.Tools, Order));
|
||||||
|
Assert.Null(PlateClipboard.Cut(host, host.Tools, Order));
|
||||||
|
|
||||||
|
Assert.Equal(count, plate.Parts.Count);
|
||||||
|
AssertAt(new Vector(30, 60), tool.Previews[0].Location);
|
||||||
|
Assert.Same(tool, host.Tools.Current);
|
||||||
|
Assert.Empty(host.ChangeLabels);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Without_a_plate_a_click_does_nothing()
|
||||||
|
{
|
||||||
|
var tool = Copy(plate.Parts[1]);
|
||||||
|
host.Plate = null;
|
||||||
|
|
||||||
|
Assert.False(tool.PointerPressed(host.At(30, 60)));
|
||||||
|
tool.Apply(ToolModifiers.None);
|
||||||
|
tool.DeleteSources();
|
||||||
|
|
||||||
|
Assert.Empty(host.ChangeLabels);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void The_tool_survives_a_plate_change_with_its_previews()
|
||||||
|
{
|
||||||
|
var tool = Copy(plate.Parts[2]);
|
||||||
|
var other = new Plate(new Size(100, 100));
|
||||||
|
host.Plate = other;
|
||||||
|
host.Selection.Plate = other;
|
||||||
|
|
||||||
|
host.Tools.OnPlateChanged();
|
||||||
|
|
||||||
|
Assert.Same(tool, host.Tools.Current);
|
||||||
|
Assert.Equal(2, tool.Previews.Count);
|
||||||
|
tool.PointerMoved(host.At(10, 10));
|
||||||
|
tool.Apply(ToolModifiers.None);
|
||||||
|
Assert.Equal(2, other.Parts.Count);
|
||||||
|
Assert.Single(other.CommonLines);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_failing_settle_opens_no_step()
|
||||||
|
{
|
||||||
|
host.RecordHistory();
|
||||||
|
host.Selection.Select(plate.Parts[1]);
|
||||||
|
var tool = new PlaceTool(host, host.Selection.Parts.ToList(),
|
||||||
|
() => throw new System.InvalidOperationException("settings unreadable"));
|
||||||
|
host.Tools.SetTool(tool);
|
||||||
|
var count = RealParts().Count;
|
||||||
|
|
||||||
|
Assert.Throws<System.InvalidOperationException>(() => tool.Apply(ToolModifiers.Shift));
|
||||||
|
|
||||||
|
// Nothing touched the nest, so no step opened and no restore replaced its objects.
|
||||||
|
Assert.Empty(host.ChangeLabels);
|
||||||
|
Assert.Same(plate, host.Recorder.Document.Nest.Plates[0]);
|
||||||
|
Assert.Equal(count, RealParts().Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_failing_cut_off_rebuild_rolls_the_placement_back()
|
||||||
|
{
|
||||||
|
var crossing = new Part(plate.Parts[1].BaseDrawing, new Vector(75, 40));
|
||||||
|
plate.Parts.Add(crossing);
|
||||||
|
plate.RegenerateCutOffs(host.CutOffSettings);
|
||||||
|
var recorder = host.RecordHistory();
|
||||||
|
var count = RealParts().Count;
|
||||||
|
var tool = Copy(plate.Parts[2]);
|
||||||
|
host.ThrowOnCutOffSettings = true;
|
||||||
|
|
||||||
|
Assert.ThrowsAny<System.Exception>(() => tool.Apply(ToolModifiers.None));
|
||||||
|
|
||||||
|
Assert.Equal(0, recorder.History.UndoCount);
|
||||||
|
Assert.Equal(count,
|
||||||
|
recorder.Document.Nest.Plates[0].Parts.Count(p => !p.BaseDrawing.IsCutOff));
|
||||||
|
// Whether the tool survives is the view's call: a rollback swaps the nest in, and the
|
||||||
|
// Avalonia view then ends the tool, as WinForms does.
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_failing_cut_off_rebuild_rolls_the_delete_back()
|
||||||
|
{
|
||||||
|
var crossing = new Part(plate.Parts[1].BaseDrawing, new Vector(75, 40));
|
||||||
|
plate.Parts.Add(crossing);
|
||||||
|
plate.RegenerateCutOffs(host.CutOffSettings);
|
||||||
|
var recorder = host.RecordHistory();
|
||||||
|
var count = RealParts().Count;
|
||||||
|
var tool = Copy(crossing);
|
||||||
|
host.ThrowOnCutOffSettings = true;
|
||||||
|
|
||||||
|
Assert.ThrowsAny<System.Exception>(() => tool.DeleteSources());
|
||||||
|
|
||||||
|
Assert.Equal(0, recorder.History.UndoCount);
|
||||||
|
Assert.Equal(count,
|
||||||
|
recorder.Document.Nest.Plates[0].Parts.Count(p => !p.BaseDrawing.IsCutOff));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Turning_the_copy_after_a_click_leaves_the_placed_part()
|
||||||
|
{
|
||||||
|
var tool = Copy(plate.Parts[2]);
|
||||||
|
tool.PointerMoved(host.At(60, 60));
|
||||||
|
tool.Apply(ToolModifiers.None);
|
||||||
|
var placed = plate.Parts[^1];
|
||||||
|
var rotation = placed.Rotation;
|
||||||
|
var location = placed.Location;
|
||||||
|
|
||||||
|
edits.RotateQuarterTurn();
|
||||||
|
edits.NudgeBy(5, 0);
|
||||||
|
|
||||||
|
Assert.Equal(rotation, placed.Rotation);
|
||||||
|
AssertAt(location, placed.Location);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_second_escape_resumes_the_tool()
|
||||||
|
{
|
||||||
|
var tool = Copy(plate.Parts[1]);
|
||||||
|
|
||||||
|
host.Tools.Escape();
|
||||||
|
host.Tools.Escape();
|
||||||
|
|
||||||
|
Assert.Same(tool, host.Tools.Current);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Escape_ends_the_tool()
|
||||||
|
{
|
||||||
|
Copy(plate.Parts[1]);
|
||||||
|
|
||||||
|
host.Tools.Escape();
|
||||||
|
|
||||||
|
Assert.IsType<SelectTool>(host.Tools.Current);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
namespace OpenNest.Desktop.Interaction;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The drawing list's pick-up, as WinForms arms it: a single left press on a drawing picks it
|
||||||
|
/// up, and the next time the plate view takes the keyboard (the pointer entering it focuses
|
||||||
|
/// it) the drawing then selected in the list starts the place tool. A drop of the dragged
|
||||||
|
/// drawing on the plate, a double-click and an Undo or Redo put it down.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class DrawingPickup
|
||||||
|
{
|
||||||
|
/// <summary>Whether a drawing is picked up.</summary>
|
||||||
|
public bool IsArmed { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>A single left press on a drawing in the list.</summary>
|
||||||
|
public void PickUp() => IsArmed = true;
|
||||||
|
|
||||||
|
/// <summary>A drop on the plate, a double-click or an Undo: nothing left to place.</summary>
|
||||||
|
public void PutDown() => IsArmed = false;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The plate view took the keyboard: the drawing to place, the one selected in the list,
|
||||||
|
/// or null. As in WinForms, a pick-up with nothing selected stays armed.
|
||||||
|
/// </summary>
|
||||||
|
public Drawing TakeOnPlateEnter(Drawing selected)
|
||||||
|
{
|
||||||
|
if (!IsArmed || selected == null)
|
||||||
|
return null;
|
||||||
|
IsArmed = false;
|
||||||
|
return selected;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
using System;
|
||||||
|
using OpenNest.Engine.Fill;
|
||||||
|
using OpenNest.Geometry;
|
||||||
|
|
||||||
|
namespace OpenNest.Desktop.Interaction;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Adding a part from the nest's drawing list, as the WinForms nest window does: dropping a
|
||||||
|
/// dragged drawing on the plate adds one part centred where it was dropped, and a drawing
|
||||||
|
/// picked in the list then carried into the plate view starts the place tool with it.
|
||||||
|
/// </summary>
|
||||||
|
public static class DrawingPlacement
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// A drawing dropped on the plate: one part with its bounding box centred on
|
||||||
|
/// <paramref name="at"/>, as one "Add Part" undo step; null without a plate or while edits
|
||||||
|
/// are locked. As in WinForms, the plate's cut-offs are not rebuilt.
|
||||||
|
/// </summary>
|
||||||
|
public static Part AddPart(IPlateToolHost host, Drawing drawing, Vector at)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(host);
|
||||||
|
ArgumentNullException.ThrowIfNull(drawing);
|
||||||
|
var plate = host.Plate;
|
||||||
|
if (plate == null || host.EditsLocked)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var part = new Part(drawing, at);
|
||||||
|
var center = part.BoundingBox.Center;
|
||||||
|
part.Offset(at.X - center.X, at.Y - center.Y);
|
||||||
|
|
||||||
|
using var change = host.BeginChange("Add Part");
|
||||||
|
change.MarkChanged();
|
||||||
|
plate.Parts.Add(part);
|
||||||
|
host.Invalidate();
|
||||||
|
change.Complete();
|
||||||
|
return part;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The place tool with one new part of <paramref name="drawing"/>.</summary>
|
||||||
|
public static PlaceTool CreatePlaceTool(
|
||||||
|
IPlateToolHost host, Drawing drawing, Func<SettleOrder> placementOrder)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(host);
|
||||||
|
ArgumentNullException.ThrowIfNull(drawing);
|
||||||
|
return new PlaceTool(host, new[] { new Part(drawing) }, placementOrder);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using OpenNest.Desktop.Rendering;
|
||||||
|
using OpenNest.Engine.Fill;
|
||||||
|
using OpenNest.Geometry;
|
||||||
|
|
||||||
|
namespace OpenNest.Desktop.Interaction;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The WinForms Clone Parts action, toolkit-neutral: copies of the source parts follow the
|
||||||
|
/// pointer (their combined lower-left corner at it) and each left click places another copy on
|
||||||
|
/// the plate, as one "Add Part"/"Add Parts" undo step. Shift settles the copy toward the plate's
|
||||||
|
/// quadrant corner on the parts' geometry; Ctrl alone settles it on bounding boxes only. Copied
|
||||||
|
/// common-line groups are joined again among the placed copies, and cut-offs are rebuilt. The
|
||||||
|
/// tool stays active until Escape and survives a plate change; <see cref="PlateEdits"/> nudges,
|
||||||
|
/// pushes and rotates its <see cref="Previews"/> while it is active, and its Delete removes the
|
||||||
|
/// sources (<see cref="DeleteSources"/>).
|
||||||
|
/// </summary>
|
||||||
|
public sealed class PlaceTool : PlateTool
|
||||||
|
{
|
||||||
|
private readonly List<Part> previews;
|
||||||
|
private readonly List<Part> sources;
|
||||||
|
private readonly List<(int[] Members, double Kerf)> commonLines;
|
||||||
|
private readonly Func<SettleOrder> placementOrder;
|
||||||
|
private ScreenPoint? restingPoint;
|
||||||
|
|
||||||
|
/// <param name="sources">The parts copied; kept so Delete can remove them.</param>
|
||||||
|
/// <param name="placementOrder">
|
||||||
|
/// Which way Shift+click and Ctrl+click settle the copy, read at each click so a changed
|
||||||
|
/// setting applies without restarting the tool.
|
||||||
|
/// </param>
|
||||||
|
public PlaceTool(
|
||||||
|
IPlateToolHost host, IReadOnlyList<Part> sources, Func<SettleOrder> placementOrder)
|
||||||
|
: base(host)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(sources);
|
||||||
|
ArgumentNullException.ThrowIfNull(placementOrder);
|
||||||
|
this.placementOrder = placementOrder;
|
||||||
|
this.sources = sources.ToList();
|
||||||
|
previews = this.sources.Select(source => source.Clone() as Part).ToList();
|
||||||
|
commonLines = CopiedCommonLines(host.Plate, this.sources);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override string Name => "Clone Parts";
|
||||||
|
|
||||||
|
public override bool IsBusy => false;
|
||||||
|
|
||||||
|
public override bool SurvivesPlateChange => true;
|
||||||
|
|
||||||
|
/// <summary>The copies following the pointer; they are not on the plate.</summary>
|
||||||
|
public IReadOnlyList<Part> Previews => previews;
|
||||||
|
|
||||||
|
public override void Cancel() { }
|
||||||
|
|
||||||
|
public override void OnPlateChanged() => Host.Invalidate();
|
||||||
|
|
||||||
|
// The common-line groups among the copied parts, by index into the copy, so each placement
|
||||||
|
// joins its copies the same way. Read now: Cut removes the sources, and their groups, next.
|
||||||
|
private static List<(int[] Members, double Kerf)> CopiedCommonLines(
|
||||||
|
Plate plate, List<Part> copied)
|
||||||
|
{
|
||||||
|
var groups = new List<(int[] Members, double Kerf)>();
|
||||||
|
if (plate == null)
|
||||||
|
return groups;
|
||||||
|
|
||||||
|
foreach (var group in plate.CommonLines)
|
||||||
|
{
|
||||||
|
var members = Enumerable.Range(0, copied.Count)
|
||||||
|
.Where(i => group.Contains(copied[i]))
|
||||||
|
.ToArray();
|
||||||
|
if (members.Length >= 2)
|
||||||
|
groups.Add((members, group.Kerf));
|
||||||
|
}
|
||||||
|
|
||||||
|
return groups;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Moves the previews' lower-left corner to the pointer. A move to the screen point last seen
|
||||||
|
/// is ignored, as WinForms ignores the mouse moves posted when a dialog opens or closes, so
|
||||||
|
/// an arrow-key nudge of the previews is not thrown away.
|
||||||
|
/// </summary>
|
||||||
|
public override bool PointerMoved(ToolPointer pointer)
|
||||||
|
{
|
||||||
|
// The WinForms view raises no mouse move while its edits are locked.
|
||||||
|
if (Host.EditsLocked)
|
||||||
|
return false;
|
||||||
|
if (restingPoint == pointer.Screen)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
restingPoint = pointer.Screen;
|
||||||
|
if (previews.Count > 0)
|
||||||
|
{
|
||||||
|
var offset = pointer.World - previews.GetBoundingBox().Location;
|
||||||
|
foreach (var preview in previews)
|
||||||
|
preview.Offset(offset);
|
||||||
|
}
|
||||||
|
Host.Invalidate();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override bool PointerPressed(ToolPointer pointer)
|
||||||
|
{
|
||||||
|
if (pointer.Button != ToolButton.Left || Host.Plate == null || Host.EditsLocked)
|
||||||
|
return false;
|
||||||
|
Apply(pointer.Modifiers);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Places a copy of the previews on the plate (see the class summary); the previews stay
|
||||||
|
/// where they settled, so the next click places another copy beside this one.
|
||||||
|
/// </summary>
|
||||||
|
public void Apply(ToolModifiers modifiers)
|
||||||
|
{
|
||||||
|
var plate = Host.Plate;
|
||||||
|
if (plate == null || Host.EditsLocked || previews.Count == 0)
|
||||||
|
return;
|
||||||
|
|
||||||
|
// Settling moves only the previews, which are not on the nest, so it runs before the
|
||||||
|
// step opens: if reading the order or settling throws, there is nothing to roll back.
|
||||||
|
var shift = (modifiers & ToolModifiers.Shift) == ToolModifiers.Shift;
|
||||||
|
var boxesOnly = !shift && (modifiers & ToolModifiers.Control) == ToolModifiers.Control;
|
||||||
|
if (shift || boxesOnly)
|
||||||
|
{
|
||||||
|
var (horizontal, vertical) = SettleDirections(plate.Quadrant);
|
||||||
|
Compactor.SettlePlacement(previews, plate, horizontal, vertical,
|
||||||
|
order: placementOrder(), boundingBoxesOnly: boxesOnly);
|
||||||
|
Host.Invalidate();
|
||||||
|
}
|
||||||
|
|
||||||
|
using var change = Host.BeginChange(previews.Count == 1 ? "Add Part" : "Add Parts");
|
||||||
|
change.MarkChanged();
|
||||||
|
var placed = previews.Select(preview => preview.Clone() as Part).ToList();
|
||||||
|
foreach (var part in placed)
|
||||||
|
plate.Parts.Add(part);
|
||||||
|
foreach (var (members, kerf) in commonLines)
|
||||||
|
plate.JoinCommonLine(members.Select(i => placed[i]), kerf);
|
||||||
|
|
||||||
|
if (plate.CutOffs.Count > 0)
|
||||||
|
plate.RegenerateCutOffs(Host.CutOffSettings);
|
||||||
|
Host.Invalidate();
|
||||||
|
change.Complete();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Removes the source parts, and any parts selected on the plate (Select All while placing),
|
||||||
|
/// as one "Delete" undo step; the previews stay. Recorded only when any of them was still on
|
||||||
|
/// the plate.
|
||||||
|
/// </summary>
|
||||||
|
public void DeleteSources()
|
||||||
|
{
|
||||||
|
var plate = Host.Plate;
|
||||||
|
if (plate == null || Host.EditsLocked)
|
||||||
|
return;
|
||||||
|
|
||||||
|
var doomed = sources.Concat(Host.Selection.Parts).ToList();
|
||||||
|
using var change = Host.BeginChange("Delete");
|
||||||
|
var removing = doomed.Any(plate.Parts.Contains);
|
||||||
|
if (removing)
|
||||||
|
change.MarkChanged();
|
||||||
|
foreach (var part in doomed)
|
||||||
|
plate.Parts.Remove(part);
|
||||||
|
|
||||||
|
// Only after a removal: a rebuild gives the cut-offs new programs, which would count as
|
||||||
|
// an unrecorded change (WinForms rebuilds either way).
|
||||||
|
if (removing && plate.CutOffs.Count > 0)
|
||||||
|
plate.RegenerateCutOffs(Host.CutOffSettings);
|
||||||
|
Host.Selection.Clear();
|
||||||
|
Host.Invalidate();
|
||||||
|
change.Complete();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Toward the quadrant's origin corner, as WinForms: 1 lower-left, 2 lower-right,
|
||||||
|
// 3 upper-right, 4 upper-left.
|
||||||
|
private static (PushDirection Horizontal, PushDirection Vertical) SettleDirections(
|
||||||
|
int quadrant) =>
|
||||||
|
quadrant switch
|
||||||
|
{
|
||||||
|
2 => (PushDirection.Right, PushDirection.Down),
|
||||||
|
3 => (PushDirection.Right, PushDirection.Up),
|
||||||
|
4 => (PushDirection.Left, PushDirection.Up),
|
||||||
|
_ => (PushDirection.Left, PushDirection.Down),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using OpenNest.Engine.Fill;
|
||||||
|
|
||||||
|
namespace OpenNest.Desktop.Interaction;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Edit > Cut and Copy, toolkit-neutral: both start a <see cref="PlaceTool"/> with the parts
|
||||||
|
/// selected on the plate, in selection order. Neither does anything without a plate or selected
|
||||||
|
/// parts, or while the host's edits are locked.
|
||||||
|
/// </summary>
|
||||||
|
public static class PlateClipboard
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Starts placing copies of the selected parts; null when nothing was started.
|
||||||
|
/// </summary>
|
||||||
|
public static PlaceTool Copy(
|
||||||
|
IPlateToolHost host, PlateToolManager tools, Func<SettleOrder> order)
|
||||||
|
{
|
||||||
|
var sources = Sources(host, tools);
|
||||||
|
if (sources == null)
|
||||||
|
return null;
|
||||||
|
var tool = new PlaceTool(host, sources, order);
|
||||||
|
tools.SetTool(tool);
|
||||||
|
return tool;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Starts placing copies of the selected parts, then removes them from the plate as one
|
||||||
|
/// "Cut" undo step. As in WinForms, the plate's cut-offs are not rebuilt here.
|
||||||
|
/// </summary>
|
||||||
|
public static PlaceTool Cut(
|
||||||
|
IPlateToolHost host, PlateToolManager tools, Func<SettleOrder> order)
|
||||||
|
{
|
||||||
|
var sources = Sources(host, tools);
|
||||||
|
if (sources == null)
|
||||||
|
return null;
|
||||||
|
// The tool reads the sources' common-line groups, which their removal ends.
|
||||||
|
var tool = new PlaceTool(host, sources, order);
|
||||||
|
tools.SetTool(tool);
|
||||||
|
|
||||||
|
var plate = host.Plate;
|
||||||
|
using var change = host.BeginChange("Cut");
|
||||||
|
change.MarkChanged();
|
||||||
|
foreach (var part in sources)
|
||||||
|
plate.Parts.Remove(part);
|
||||||
|
host.Selection.Clear();
|
||||||
|
host.Invalidate();
|
||||||
|
change.Complete();
|
||||||
|
return tool;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<Part> Sources(IPlateToolHost host, PlateToolManager tools)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(host);
|
||||||
|
ArgumentNullException.ThrowIfNull(tools);
|
||||||
|
if (host.Plate == null || host.EditsLocked)
|
||||||
|
return null;
|
||||||
|
host.Selection.Prune();
|
||||||
|
var sources = host.Selection.Parts.ToList();
|
||||||
|
return sources.Count == 0 ? null : sources;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ using System.Runtime.CompilerServices;
|
|||||||
using OpenNest.Engine.Fill;
|
using OpenNest.Engine.Fill;
|
||||||
using OpenNest.Geometry;
|
using OpenNest.Geometry;
|
||||||
using OpenNest.Math;
|
using OpenNest.Math;
|
||||||
|
using OpenNest.Undo;
|
||||||
|
|
||||||
namespace OpenNest.Desktop.Interaction;
|
namespace OpenNest.Desktop.Interaction;
|
||||||
|
|
||||||
@@ -14,6 +15,12 @@ namespace OpenNest.Desktop.Interaction;
|
|||||||
/// same parts, and wheel rotations, undo as one. Every edit does nothing without a plate or
|
/// same parts, and wheel rotations, undo as one. Every edit does nothing without a plate or
|
||||||
/// selected parts (Delete also acts on selected cut-offs alone) and redraws the view, and nothing
|
/// selected parts (Delete also acts on selected cut-offs alone) and redraws the view, and nothing
|
||||||
/// at all while the host's edits are locked (<see cref="IPlateToolHost.EditsLocked"/>).
|
/// at all while the host's edits are locked (<see cref="IPlateToolHost.EditsLocked"/>).
|
||||||
|
/// <para>
|
||||||
|
/// While a <see cref="PlaceTool"/> is active in <see cref="Tools"/>, nudge, step, push and rotate
|
||||||
|
/// move its previews instead, which are not on the plate: no undo step is opened (WinForms
|
||||||
|
/// records an empty one) and cut-offs are not rebuilt. Delete then removes the tool's sources
|
||||||
|
/// (<see cref="PlaceTool.DeleteSources"/>).
|
||||||
|
/// </para>
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class PlateEdits
|
public sealed class PlateEdits
|
||||||
{
|
{
|
||||||
@@ -24,6 +31,21 @@ public sealed class PlateEdits
|
|||||||
|
|
||||||
public IPlateToolHost Host { get; }
|
public IPlateToolHost Host { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The view's tools, so edits can act on a place tool's previews; null for none.
|
||||||
|
/// </summary>
|
||||||
|
public PlateToolManager Tools { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Whether nudge, push and rotate have parts to move: a place tool's previews, or selected
|
||||||
|
/// parts still on the plate. The view checks it before a middle click or Shift+wheel rotates.
|
||||||
|
/// </summary>
|
||||||
|
public bool HasPartsToEdit =>
|
||||||
|
Placing is { Previews.Count: > 0 }
|
||||||
|
|| (Host.Plate != null && Host.Selection.Parts.Any(Host.Plate.Parts.Contains));
|
||||||
|
|
||||||
|
private PlaceTool Placing => Tools?.Current as PlaceTool;
|
||||||
|
|
||||||
/// <summary>How far an arrow-key nudge moves the selection, in plate units.</summary>
|
/// <summary>How far an arrow-key nudge moves the selection, in plate units.</summary>
|
||||||
public double OffsetIncrement { get; set; } = 10;
|
public double OffsetIncrement { get; set; } = 10;
|
||||||
|
|
||||||
@@ -45,6 +67,11 @@ public sealed class PlateEdits
|
|||||||
var plate = Host.Plate;
|
var plate = Host.Plate;
|
||||||
if (plate == null || Host.EditsLocked)
|
if (plate == null || Host.EditsLocked)
|
||||||
return;
|
return;
|
||||||
|
if (Placing is { } placing)
|
||||||
|
{
|
||||||
|
placing.DeleteSources();
|
||||||
|
return;
|
||||||
|
}
|
||||||
var selection = Host.Selection;
|
var selection = Host.Selection;
|
||||||
selection.Prune();
|
selection.Prune();
|
||||||
var parts = selection.Parts.ToList();
|
var parts = selection.Parts.ToList();
|
||||||
@@ -85,10 +112,10 @@ public sealed class PlateEdits
|
|||||||
/// <summary>Moves the selection by (<paramref name="dx"/>, <paramref name="dy"/>).</summary>
|
/// <summary>Moves the selection by (<paramref name="dx"/>, <paramref name="dy"/>).</summary>
|
||||||
public void NudgeBy(double dx, double dy)
|
public void NudgeBy(double dx, double dy)
|
||||||
{
|
{
|
||||||
if (!TryGetSelectedParts(out var plate, out var parts))
|
if (!TryGetEditParts(out var plate, out var parts, out var previews))
|
||||||
return;
|
return;
|
||||||
|
|
||||||
using var change = Host.BeginChange("Nudge", new SelectionKey("Nudge", plate, parts));
|
using var change = BeginEdit(previews, "Nudge", new SelectionKey("Nudge", plate, parts));
|
||||||
change.MarkChanged();
|
change.MarkChanged();
|
||||||
foreach (var part in parts)
|
foreach (var part in parts)
|
||||||
part.Offset(dx, dy);
|
part.Offset(dx, dy);
|
||||||
@@ -102,10 +129,10 @@ public sealed class PlateEdits
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public void Step(PushDirection direction)
|
public void Step(PushDirection direction)
|
||||||
{
|
{
|
||||||
if (!TryGetSelectedParts(out var plate, out var parts))
|
if (!TryGetEditParts(out var plate, out var parts, out var previews))
|
||||||
return;
|
return;
|
||||||
|
|
||||||
using var change = Host.BeginChange("Nudge", new SelectionKey("Nudge", plate, parts));
|
using var change = BeginEdit(previews, "Nudge", new SelectionKey("Nudge", plate, parts));
|
||||||
if (Compactor.Step(parts, plate, direction) > 0)
|
if (Compactor.Step(parts, plate, direction) > 0)
|
||||||
change.MarkChanged();
|
change.MarkChanged();
|
||||||
Host.Invalidate();
|
Host.Invalidate();
|
||||||
@@ -117,10 +144,10 @@ public sealed class PlateEdits
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public void Push(PushDirection direction)
|
public void Push(PushDirection direction)
|
||||||
{
|
{
|
||||||
if (!TryGetSelectedParts(out var plate, out var parts))
|
if (!TryGetEditParts(out var plate, out var parts, out var previews))
|
||||||
return;
|
return;
|
||||||
|
|
||||||
using var change = Host.BeginChange("Push");
|
using var change = BeginEdit(previews, "Push");
|
||||||
change.MarkChanged();
|
change.MarkChanged();
|
||||||
Compactor.Push(parts, plate, direction);
|
Compactor.Push(parts, plate, direction);
|
||||||
Host.Invalidate();
|
Host.Invalidate();
|
||||||
@@ -133,10 +160,10 @@ public sealed class PlateEdits
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public void Rotate(double radians, bool coalesce = false)
|
public void Rotate(double radians, bool coalesce = false)
|
||||||
{
|
{
|
||||||
if (!TryGetSelectedParts(out var plate, out var parts))
|
if (!TryGetEditParts(out var plate, out var parts, out var previews))
|
||||||
return;
|
return;
|
||||||
|
|
||||||
using var change = Host.BeginChange("Rotate",
|
using var change = BeginEdit(previews, "Rotate",
|
||||||
coalesce ? new SelectionKey("Rotate", plate, parts) : null);
|
coalesce ? new SelectionKey("Rotate", plate, parts) : null);
|
||||||
change.MarkChanged();
|
change.MarkChanged();
|
||||||
var bounds = parts.GetBoundingBox();
|
var bounds = parts.GetBoundingBox();
|
||||||
@@ -149,7 +176,7 @@ public sealed class PlateEdits
|
|||||||
foreach (var part in parts)
|
foreach (var part in parts)
|
||||||
part.Offset(diff);
|
part.Offset(diff);
|
||||||
|
|
||||||
if (plate.CutOffs.Count > 0)
|
if (!previews && plate.CutOffs.Count > 0)
|
||||||
plate.RegenerateCutOffs(Host.CutOffSettings);
|
plate.RegenerateCutOffs(Host.CutOffSettings);
|
||||||
Host.Invalidate();
|
Host.Invalidate();
|
||||||
change.Complete();
|
change.Complete();
|
||||||
@@ -173,17 +200,29 @@ public sealed class PlateEdits
|
|||||||
Rotate(angle, coalesce: true);
|
Rotate(angle, coalesce: true);
|
||||||
}
|
}
|
||||||
|
|
||||||
private bool TryGetSelectedParts(out Plate plate, out List<Part> parts)
|
// The parts an edit moves: a place tool's previews (previews is true), else the selection.
|
||||||
|
private bool TryGetEditParts(out Plate plate, out List<Part> parts, out bool previews)
|
||||||
{
|
{
|
||||||
plate = Host.Plate;
|
plate = Host.Plate;
|
||||||
parts = null;
|
parts = null;
|
||||||
|
previews = false;
|
||||||
if (plate == null || Host.EditsLocked)
|
if (plate == null || Host.EditsLocked)
|
||||||
return false;
|
return false;
|
||||||
|
if (Placing is { } placing)
|
||||||
|
{
|
||||||
|
previews = true;
|
||||||
|
parts = placing.Previews.ToList();
|
||||||
|
return parts.Count > 0;
|
||||||
|
}
|
||||||
Host.Selection.Prune();
|
Host.Selection.Prune();
|
||||||
parts = Host.Selection.Parts.ToList();
|
parts = Host.Selection.Parts.ToList();
|
||||||
return parts.Count > 0;
|
return parts.Count > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Previews are not on the nest, so moving them opens no undo step.
|
||||||
|
private ChangeScope BeginEdit(bool previews, string label, object coalesceKey = null) =>
|
||||||
|
previews ? ChangeScope.Detached() : Host.BeginChange(label, coalesceKey);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Equal for the same edit of the same parts, in the same order, on the same plate, so
|
/// Equal for the same edit of the same parts, in the same order, on the same plate, so
|
||||||
/// repeated nudges or wheel turns coalesce into one undo entry.
|
/// repeated nudges or wheel turns coalesce into one undo entry.
|
||||||
|
|||||||
@@ -105,6 +105,22 @@ public class IrregularBlockTests
|
|||||||
Assert.Single(fill.Parts);
|
Assert.Single(fill.Parts);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void RectangleNarrowerThanThePartIsChargedAsAnEmptyProposal()
|
||||||
|
{
|
||||||
|
var job = Job(new[] { Part("ell", LShape(9, 7, 3), 20, RotationPolicy.Automatic) },
|
||||||
|
new[] { Stock("sheet", 40, 200, spacing: 0.25) });
|
||||||
|
var types = PartCatalog.Build(job);
|
||||||
|
var counter = new WorkCounter();
|
||||||
|
using var blocks = new BlockCatalog(0.25, types, NoPairs, counter, long.MaxValue);
|
||||||
|
var strip = new Box(0, 0, 200, 2.5);
|
||||||
|
Assert.Empty(blocks.Get(types[0], 20, strip, CancellationToken.None));
|
||||||
|
// Counted and charged as the Fill would have been, so later decisions do not change.
|
||||||
|
Assert.Equal(1, blocks.PreparationCount);
|
||||||
|
Assert.Equal(20L * 20 * types[0].Orientations[0].Outline.Count, counter.Value);
|
||||||
|
Assert.Empty(blocks.Band(types[0], 20, strip, CancellationToken.None));
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ForbiddenRotationsAreRejectedBeforeAddingGroupOrientations()
|
public void ForbiddenRotationsAreRejectedBeforeAddingGroupOrientations()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -25,14 +25,34 @@ public class IrregularSearchUntilCancelledTests
|
|||||||
{
|
{
|
||||||
public List<NestJobResult> Plans { get; } = new();
|
public List<NestJobResult> Plans { get; } = new();
|
||||||
|
|
||||||
|
/// <summary>Every plan reported, improved or alternative, in order.</summary>
|
||||||
|
public List<NestJobResult> All { get; } = new();
|
||||||
|
|
||||||
public void Report(NestJobProgress value)
|
public void Report(NestJobProgress value)
|
||||||
{
|
{
|
||||||
if (value.Stage == NestJobStage.PlanImproved)
|
if (value.Stage == NestJobStage.PlanImproved)
|
||||||
Plans.Add(value.Plan!);
|
Plans.Add(value.Plan!);
|
||||||
|
if (value.Stage is NestJobStage.PlanImproved or NestJobStage.PlanAlternative)
|
||||||
|
All.Add(value.Plan!);
|
||||||
also?.Invoke(value);
|
also?.Invoke(value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Whether <paramref name="expected"/> appears in <paramref name="reported"/> in order.</summary>
|
||||||
|
private static bool InOrder(IEnumerable<NestJobResult> expected, IEnumerable<NestJobResult> reported)
|
||||||
|
{
|
||||||
|
using var next = reported.GetEnumerator();
|
||||||
|
foreach (var plan in expected)
|
||||||
|
{
|
||||||
|
var found = false;
|
||||||
|
while (!found && next.MoveNext())
|
||||||
|
found = Placements(next.Current).SequenceEqual(Placements(plan));
|
||||||
|
if (!found)
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
private static List<(string, int, double, double, double)> Placements(NestJobResult result) =>
|
private static List<(string, int, double, double, double)> Placements(NestJobResult result) =>
|
||||||
result.Plates.SelectMany(p => p.Placements.Select(q => (q.PartId, q.InstanceIndex, q.X, q.Y, q.Rotation)))
|
result.Plates.SelectMany(p => p.Placements.Select(q => (q.PartId, q.InstanceIndex, q.X, q.Y, q.Rotation)))
|
||||||
.ToList();
|
.ToList();
|
||||||
@@ -47,6 +67,57 @@ public class IrregularSearchUntilCancelledTests
|
|||||||
Assert.Equal(Placements(plain), Placements(flagged));
|
Assert.Equal(Placements(plain), Placements(flagged));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ASolveThatCanEndUnlimitedReportsNoQuickPlan()
|
||||||
|
{
|
||||||
|
// The quick plan belongs to a solve that ends only at its limit: without the option, or
|
||||||
|
// without a token that can cancel it, the plans reported are the usual ones.
|
||||||
|
var plain = new Recorder();
|
||||||
|
var plainResult = new IrregularNestingEngine().Solve(MixedJob(false), plain);
|
||||||
|
var quick = new IrregularNestingEngine().QuickPlanForTesting(MixedJob(false));
|
||||||
|
Assert.DoesNotContain(plain.All, p => Placements(p).SequenceEqual(Placements(quick)));
|
||||||
|
|
||||||
|
using var cancel = new CancellationTokenSource();
|
||||||
|
var cancellable = new Recorder();
|
||||||
|
var flagged = new Recorder();
|
||||||
|
var cancellableResult = new IrregularNestingEngine().Solve(MixedJob(false), cancellable, cancel.Token);
|
||||||
|
var flaggedResult = new IrregularNestingEngine().Solve(MixedJob(true), flagged);
|
||||||
|
|
||||||
|
foreach (var (recorder, result) in new[] { (cancellable, cancellableResult), (flagged, flaggedResult) })
|
||||||
|
{
|
||||||
|
Assert.Equal(Placements(plainResult), Placements(result));
|
||||||
|
Assert.Equal(plain.All.Select(Placements), recorder.All.Select(Placements));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ATimeLimitedSolveReportsAQuickPlanFirst()
|
||||||
|
{
|
||||||
|
// The first variant without Lattice blocks, reported before the normal search finishes its
|
||||||
|
// first sheet: stopped there, the solve has the quick plan, a valid layout, to return.
|
||||||
|
var job = MixedJob(true);
|
||||||
|
var quickSheets = 0;
|
||||||
|
var quick = new IrregularNestingEngine { SheetPacked = () => quickSheets++ }.QuickPlanForTesting(job);
|
||||||
|
using var cancel = new CancellationTokenSource();
|
||||||
|
var sheets = 0;
|
||||||
|
var engine = new IrregularNestingEngine
|
||||||
|
{
|
||||||
|
SheetPacked = () =>
|
||||||
|
{
|
||||||
|
if (++sheets > quickSheets)
|
||||||
|
cancel.Cancel();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
var recorder = new Recorder();
|
||||||
|
|
||||||
|
Assert.ThrowsAny<OperationCanceledException>(() => engine.Solve(job, recorder, cancel.Token));
|
||||||
|
|
||||||
|
var plan = Assert.Single(recorder.Plans);
|
||||||
|
Assert.Equal(Placements(quick), Placements(plan));
|
||||||
|
Assert.NotEmpty(Placements(plan));
|
||||||
|
LayoutAssert.Valid(MixedJob(false), plan);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void KeepsSearchingAfterTheNormalSearchUntilCancelled()
|
public void KeepsSearchingAfterTheNormalSearchUntilCancelled()
|
||||||
{
|
{
|
||||||
@@ -58,6 +129,10 @@ public class IrregularSearchUntilCancelledTests
|
|||||||
var plainResult = new IrregularNestingEngine { GroupLikeParts = false }.Solve(MixedJob(false, Ells), plain);
|
var plainResult = new IrregularNestingEngine { GroupLikeParts = false }.Solve(MixedJob(false, Ells), plain);
|
||||||
var normalSheets = 0;
|
var normalSheets = 0;
|
||||||
new IrregularNestingEngine { GroupLikeParts = false, SheetPacked = () => normalSheets++ }.Solve(MixedJob(false, Ells));
|
new IrregularNestingEngine { GroupLikeParts = false, SheetPacked = () => normalSheets++ }.Solve(MixedJob(false, Ells));
|
||||||
|
// A time-limited solve packs its quick plan before the normal search.
|
||||||
|
var quickSheets = 0;
|
||||||
|
var quick = new IrregularNestingEngine { GroupLikeParts = false, SheetPacked = () => quickSheets++ }
|
||||||
|
.QuickPlanForTesting(MixedJob(false, Ells));
|
||||||
|
|
||||||
var extendedSheets = 0;
|
var extendedSheets = 0;
|
||||||
var extendedTailBudgets = new List<long>();
|
var extendedTailBudgets = new List<long>();
|
||||||
@@ -65,16 +140,17 @@ public class IrregularSearchUntilCancelledTests
|
|||||||
var engine = new IrregularNestingEngine
|
var engine = new IrregularNestingEngine
|
||||||
{
|
{
|
||||||
GroupLikeParts = false,
|
GroupLikeParts = false,
|
||||||
// The normal search packs exactly normalSheets sheets; later ones are extended.
|
// The quick plan and the normal search pack exactly quickSheets + normalSheets sheets;
|
||||||
|
// later ones are extended.
|
||||||
TailReplanning = budget =>
|
TailReplanning = budget =>
|
||||||
{
|
{
|
||||||
if (extendedSheets > normalSheets)
|
if (extendedSheets > quickSheets + normalSheets)
|
||||||
extendedTailBudgets.Add(budget);
|
extendedTailBudgets.Add(budget);
|
||||||
},
|
},
|
||||||
SheetPacked = () =>
|
SheetPacked = () =>
|
||||||
{
|
{
|
||||||
// Let the extended search pack several more whole plans, then stop it.
|
// Let the extended search pack several more whole plans, then stop it.
|
||||||
if (++extendedSheets >= normalSheets * 12)
|
if (++extendedSheets >= quickSheets + normalSheets * 12)
|
||||||
cancel.Cancel();
|
cancel.Cancel();
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@@ -82,22 +158,24 @@ public class IrregularSearchUntilCancelledTests
|
|||||||
|
|
||||||
Assert.ThrowsAny<OperationCanceledException>(() => engine.Solve(MixedJob(true, Ells), extended, cancel.Token));
|
Assert.ThrowsAny<OperationCanceledException>(() => engine.Solve(MixedJob(true, Ells), extended, cancel.Token));
|
||||||
|
|
||||||
Assert.True(extendedSheets >= normalSheets * 12);
|
Assert.True(extendedSheets >= quickSheets + normalSheets * 12);
|
||||||
// The normal search runs first, unchanged; the extended search improves on it and
|
// The quick plan comes first. The normal search then runs unchanged, reporting its plans as
|
||||||
// re-plans the tails of its plans.
|
// before; the extended search improves on it and re-plans the tails of its plans.
|
||||||
Assert.True(extended.Plans.Count > plain.Plans.Count);
|
Assert.Equal(Placements(quick), Placements(extended.Plans[0]));
|
||||||
|
Assert.True(InOrder(plain.Plans, extended.Plans.Skip(1)));
|
||||||
|
Assert.Contains(extended.Plans.Skip(1),
|
||||||
|
p => !plain.Plans.Any(q => Placements(q).SequenceEqual(Placements(p))));
|
||||||
// Each improvement gets a tail re-plan with its own fresh budget.
|
// Each improvement gets a tail re-plan with its own fresh budget.
|
||||||
Assert.NotEmpty(extendedTailBudgets);
|
Assert.NotEmpty(extendedTailBudgets);
|
||||||
Assert.All(extendedTailBudgets, b => Assert.Equal(2 * new IrregularNestingEngine().WorkBudget, b));
|
Assert.All(extendedTailBudgets, b => Assert.Equal(2 * new IrregularNestingEngine().WorkBudget, b));
|
||||||
for (var i = 0; i < plain.Plans.Count; i++)
|
|
||||||
Assert.Equal(Placements(plain.Plans[i]), Placements(extended.Plans[i]));
|
|
||||||
var job = MixedJob(false, Ells);
|
var job = MixedJob(false, Ells);
|
||||||
var last = CandidateScore.Of(job, extended.Plans[^1], 0);
|
var last = CandidateScore.Of(job, extended.Plans[^1], 0);
|
||||||
Assert.False(CandidateScore.Of(job, plainResult, 0).IsBetterThan(last));
|
Assert.False(CandidateScore.Of(job, plainResult, 0).IsBetterThan(last));
|
||||||
foreach (var plan in extended.Plans)
|
foreach (var plan in extended.Plans)
|
||||||
LayoutAssert.Valid(job, plan);
|
LayoutAssert.Valid(job, plan);
|
||||||
// Each reported plan beats the one before it: no seed reports a worse plan.
|
// After the quick plan, each reported plan beats the one before it: no seed reports a
|
||||||
for (var i = 1; i < extended.Plans.Count; i++)
|
// worse plan. The deadline wrapper ranks the quick plan against them.
|
||||||
|
for (var i = 2; i < extended.Plans.Count; i++)
|
||||||
Assert.True(
|
Assert.True(
|
||||||
CandidateScore.Of(job, extended.Plans[i], 0)
|
CandidateScore.Of(job, extended.Plans[i], 0)
|
||||||
.IsBetterThan(CandidateScore.Of(job, extended.Plans[i - 1], 0)),
|
.IsBetterThan(CandidateScore.Of(job, extended.Plans[i - 1], 0)),
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
using OpenNest.Engine.Jobs;
|
||||||
|
using OpenNest.Engine.NestingEngines.Irregular;
|
||||||
|
using static OpenNest.Engine.Tests.NestingEngines.JobBuilder;
|
||||||
|
using static OpenNest.Engine.Tests.NestingEngines.Shapes;
|
||||||
|
|
||||||
|
namespace OpenNest.Engine.Tests.NestingEngines;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A tail re-plan's decode skips stock trials that can neither be chosen nor change the choice:
|
||||||
|
/// once the block budget is spent it packs fewer sheets and decides exactly as when it packs every
|
||||||
|
/// trial.
|
||||||
|
/// </summary>
|
||||||
|
public class IrregularStockPruningTests
|
||||||
|
{
|
||||||
|
private static NestJob MixedJob(NestJobOptions? options) =>
|
||||||
|
Job(
|
||||||
|
new[] { Part("disc", Disc(3), 10), Part("ell", LShape(12, 8, 4), 10), Part("tri", Triangle(9, 7), 8) },
|
||||||
|
// Small sheets first, so a trial is packed before the large sheet is considered.
|
||||||
|
new[] { Stock("small", 20, 30, spacing: 0.5), Stock("sheet", 40, 60, spacing: 0.5), Stock("large", 120, 200, spacing: 0.5) },
|
||||||
|
options
|
||||||
|
);
|
||||||
|
|
||||||
|
private static List<(string, string, int, double, double, double)> Placements(NestJobResult result) =>
|
||||||
|
result.Plates.SelectMany(p => p.Placements.Select(q => (p.Stock.Id, q.PartId, q.InstanceIndex, q.X, q.Y, q.Rotation)))
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
// Pruning starts only once the block budget is spent; this small job spends a small budget
|
||||||
|
// in its variants, leaving its tail re-plans to prune.
|
||||||
|
private const long Budget = 20_000;
|
||||||
|
|
||||||
|
public static TheoryData<bool> Salvage => new() { false, true };
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(Salvage))]
|
||||||
|
public void SkippedTrialsChangeNoChoice(bool salvage)
|
||||||
|
{
|
||||||
|
var options = salvage ? new NestJobOptions(salvageRate: 0.5, minimumSalvageDimension: 1) : null;
|
||||||
|
var all = 0;
|
||||||
|
var pruned = 0;
|
||||||
|
var full = new IrregularNestingEngine { WorkBudget = Budget, PruneStockTrials = false, SheetPacked = () => all++ }.Solve(MixedJob(options));
|
||||||
|
var skipped = new IrregularNestingEngine { WorkBudget = Budget, SheetPacked = () => pruned++ }.Solve(MixedJob(options));
|
||||||
|
|
||||||
|
Assert.Equal(Placements(full), Placements(skipped));
|
||||||
|
Assert.NotEmpty(Placements(full));
|
||||||
|
Assert.True(pruned < all, $"packed {pruned} of {all} sheets");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -421,17 +421,35 @@ namespace OpenNest.Engine.Fill
|
|||||||
/// produces overlapping parts.
|
/// produces overlapping parts.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private List<Part> TilePatternBbox(Pattern basePattern, NestDirection direction)
|
private List<Part> TilePatternBbox(Pattern basePattern, NestDirection direction)
|
||||||
|
{
|
||||||
|
var copies = BboxCopies(basePattern, direction);
|
||||||
|
var copyDistance = GetDimension(basePattern.BoundingBox, direction) + PartSpacing;
|
||||||
|
var result = new List<Part>();
|
||||||
|
|
||||||
|
for (var count = 1; count <= copies; count++)
|
||||||
|
{
|
||||||
|
var offset = MakeOffset(direction, copyDistance * count);
|
||||||
|
|
||||||
|
foreach (var part in basePattern.Parts)
|
||||||
|
result.Add(part.CloneAtOffset(offset));
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The number of whole copies <see cref="TilePatternBbox"/> adds, found without cloning.
|
||||||
|
/// </summary>
|
||||||
|
private int BboxCopies(Pattern basePattern, NestDirection direction)
|
||||||
{
|
{
|
||||||
var copyDistance = GetDimension(basePattern.BoundingBox, direction) + PartSpacing;
|
var copyDistance = GetDimension(basePattern.BoundingBox, direction) + PartSpacing;
|
||||||
|
|
||||||
if (copyDistance <= 0)
|
if (copyDistance <= 0)
|
||||||
return new List<Part>();
|
return 0;
|
||||||
|
|
||||||
var dim = GetDimension(basePattern.BoundingBox, direction);
|
var dim = GetDimension(basePattern.BoundingBox, direction);
|
||||||
var start = GetStart(basePattern.BoundingBox, direction);
|
var start = GetStart(basePattern.BoundingBox, direction);
|
||||||
var limit = GetLimit(direction);
|
var limit = GetLimit(direction);
|
||||||
|
|
||||||
var result = new List<Part>();
|
|
||||||
var count = 1;
|
var count = 1;
|
||||||
|
|
||||||
while (true)
|
while (true)
|
||||||
@@ -441,15 +459,10 @@ namespace OpenNest.Engine.Fill
|
|||||||
if (nextPos + dim > limit + Tolerance.Epsilon)
|
if (nextPos + dim > limit + Tolerance.Epsilon)
|
||||||
break;
|
break;
|
||||||
|
|
||||||
var offset = MakeOffset(direction, copyDistance * count);
|
|
||||||
|
|
||||||
foreach (var part in basePattern.Parts)
|
|
||||||
result.Add(part.CloneAtOffset(offset));
|
|
||||||
|
|
||||||
count++;
|
count++;
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
return count - 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static bool HasOverlappingParts(
|
private static bool HasOverlappingParts(
|
||||||
@@ -521,7 +534,11 @@ namespace OpenNest.Engine.Fill
|
|||||||
/// a row, then tiling that row along the perpendicular axis to form a grid.
|
/// a row, then tiling that row along the perpendicular axis to form a grid.
|
||||||
/// After the grid is formed, fills the remaining strip with individual parts.
|
/// After the grid is formed, fills the remaining strip with individual parts.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private List<Part> FillGrid(Pattern pattern, NestDirection direction, OffsetPerimeterCache cache)
|
/// <remarks>
|
||||||
|
/// Step 1's check runs here, as it decides how the grid is built. The final check, on the
|
||||||
|
/// whole grid, is left to the returned grid's <see cref="DeferredGrid.Resolve"/>.
|
||||||
|
/// </remarks>
|
||||||
|
private DeferredGrid FillGrid(Pattern pattern, NestDirection direction, OffsetPerimeterCache cache)
|
||||||
{
|
{
|
||||||
var perpAxis = PerpendicularAxis(direction);
|
var perpAxis = PerpendicularAxis(direction);
|
||||||
|
|
||||||
@@ -547,21 +564,16 @@ namespace OpenNest.Engine.Fill
|
|||||||
{
|
{
|
||||||
row = Tile(pattern, perpAxis, cache, MaxParts);
|
row = Tile(pattern, perpAxis, cache, MaxParts);
|
||||||
|
|
||||||
if (pattern.Parts.Count > 1 && HasOverlappingParts(row, out var a2, out var b2))
|
return pattern.Parts.Count > 1
|
||||||
{
|
? new DeferredGrid(this, row, "Step1-PerpOnly", perpAxis, pattern)
|
||||||
LogOverlap("Step1-PerpOnly", perpAxis, pattern, row, a2, b2);
|
: new DeferredGrid(row);
|
||||||
row = new List<Part>(pattern.Parts);
|
|
||||||
row.AddRange(TilePatternBbox(pattern, perpAxis));
|
|
||||||
}
|
|
||||||
|
|
||||||
return row;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// A capped fill whose first row already holds enough parts needs no more rows.
|
// A capped fill whose first row already holds enough parts needs no more rows.
|
||||||
// Step 2's check could only switch perpendicular tiling to the bbox fallback; it
|
// Step 2's check could only switch perpendicular tiling to the bbox fallback; it
|
||||||
// never repairs the row itself, so returning the row loses no protection.
|
// never repairs the row itself, so returning the row loses no protection.
|
||||||
if (MaxParts > 0 && row.Count >= MaxParts)
|
if (MaxParts > 0 && row.Count >= MaxParts)
|
||||||
return row;
|
return new DeferredGrid(row);
|
||||||
|
|
||||||
// Step 2: Build row pattern and tile along perpendicular axis
|
// Step 2: Build row pattern and tile along perpendicular axis
|
||||||
var rowPattern = new Pattern();
|
var rowPattern = new Pattern();
|
||||||
@@ -573,15 +585,83 @@ namespace OpenNest.Engine.Fill
|
|||||||
// Only the unchanged row is covered by Step 1's clean verdict: skip Step 2
|
// Only the unchanged row is covered by Step 1's clean verdict: skip Step 2
|
||||||
// only when the perpendicular tiling appended zero parts, so gridResult
|
// only when the perpendicular tiling appended zero parts, so gridResult
|
||||||
// still contains the same Part objects, in the same order and poses.
|
// still contains the same Part objects, in the same order and poses.
|
||||||
if ((!rowIsVerified || gridResult.Count != row.Count)
|
return !rowIsVerified || gridResult.Count != row.Count
|
||||||
&& HasOverlappingParts(gridResult, out var a3, out var b3))
|
? new DeferredGrid(this, gridResult, "Step2-Perp", perpAxis, rowPattern)
|
||||||
|
: new DeferredGrid(gridResult);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A grid tiled by <see cref="FillGrid"/> whose final overlap check may not have run yet.
|
||||||
|
/// Until <see cref="Resolve"/> runs it, the grid holds either its tiling, when no two
|
||||||
|
/// parts overlap, or the fallback that tiles the same pattern by bounding boxes
|
||||||
|
/// (<see cref="TilePatternBbox"/>); both part counts are known without the check.
|
||||||
|
/// <see cref="Resolve"/> returns exactly what the eager fill returned, so a caller may
|
||||||
|
/// skip the check only on a grid whose outcome it never uses. Not thread-safe.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class DeferredGrid
|
||||||
|
{
|
||||||
|
private readonly FillLinear owner;
|
||||||
|
private readonly string step;
|
||||||
|
private readonly NestDirection axis;
|
||||||
|
private Pattern basePattern;
|
||||||
|
private List<Part> parts;
|
||||||
|
private int? fallbackCount;
|
||||||
|
|
||||||
|
/// <summary>A grid with no check left to run.</summary>
|
||||||
|
internal DeferredGrid(List<Part> parts) => this.parts = parts;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A grid whose tiling <paramref name="parts"/> of <paramref name="basePattern"/> along
|
||||||
|
/// <paramref name="axis"/> still has to pass the overlap check.
|
||||||
|
/// </summary>
|
||||||
|
internal DeferredGrid(
|
||||||
|
FillLinear owner,
|
||||||
|
List<Part> parts,
|
||||||
|
string step,
|
||||||
|
NestDirection axis,
|
||||||
|
Pattern basePattern
|
||||||
|
)
|
||||||
{
|
{
|
||||||
LogOverlap("Step2-Perp", perpAxis, rowPattern, gridResult, a3, b3);
|
this.owner = owner;
|
||||||
gridResult = new List<Part>(rowPattern.Parts);
|
this.parts = parts;
|
||||||
gridResult.AddRange(TilePatternBbox(rowPattern, perpAxis));
|
this.step = step;
|
||||||
|
this.axis = axis;
|
||||||
|
this.basePattern = basePattern;
|
||||||
}
|
}
|
||||||
|
|
||||||
return gridResult;
|
/// <summary>True until <see cref="Resolve"/> has run the overlap check.</summary>
|
||||||
|
public bool IsPending => basePattern != null;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The part count of the grid as it stands: its tiling while the check is pending, the
|
||||||
|
/// checked parts once resolved.
|
||||||
|
/// </summary>
|
||||||
|
public int Count => parts.Count;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// While <see cref="IsPending"/>, the part count of the bounding-box fallback, should
|
||||||
|
/// the check fail.
|
||||||
|
/// </summary>
|
||||||
|
public int FallbackCount =>
|
||||||
|
fallbackCount ??= (1 + owner.BboxCopies(basePattern, axis)) * basePattern.Parts.Count;
|
||||||
|
|
||||||
|
/// <summary>Runs the overlap check if it is pending and returns the grid's parts.</summary>
|
||||||
|
public List<Part> Resolve()
|
||||||
|
{
|
||||||
|
if (basePattern == null)
|
||||||
|
return parts;
|
||||||
|
|
||||||
|
if (HasOverlappingParts(parts, out var a, out var b))
|
||||||
|
{
|
||||||
|
owner.LogOverlap(step, axis, basePattern, parts, a, b);
|
||||||
|
var fallback = new List<Part>(basePattern.Parts);
|
||||||
|
fallback.AddRange(owner.TilePatternBbox(basePattern, axis));
|
||||||
|
parts = fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
basePattern = null;
|
||||||
|
return parts;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void LogOverlap(
|
private void LogOverlap(
|
||||||
@@ -672,11 +752,18 @@ namespace OpenNest.Engine.Fill
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Fills the work area by tiling a pre-built pattern along both axes.
|
/// Fills the work area by tiling a pre-built pattern along both axes.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public List<Part> Fill(Pattern pattern, NestDirection primaryAxis)
|
public List<Part> Fill(Pattern pattern, NestDirection primaryAxis) =>
|
||||||
|
FillDeferred(pattern, primaryAxis).Resolve();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// <see cref="Fill(Pattern, NestDirection)"/> with the grid's final overlap check left to
|
||||||
|
/// the caller: <see cref="DeferredGrid.Resolve"/> returns exactly what Fill returns.
|
||||||
|
/// </summary>
|
||||||
|
internal DeferredGrid FillDeferred(Pattern pattern, NestDirection primaryAxis)
|
||||||
{
|
{
|
||||||
var cache = new OffsetPerimeterCache(HalfSpacing);
|
var cache = new OffsetPerimeterCache(HalfSpacing);
|
||||||
if (pattern.Parts.Count == 0)
|
if (pattern.Parts.Count == 0)
|
||||||
return new List<Part>();
|
return new DeferredGrid(new List<Part>());
|
||||||
|
|
||||||
var offset = WorkArea.Location - pattern.BoundingBox.Location;
|
var offset = WorkArea.Location - pattern.BoundingBox.Location;
|
||||||
var basePattern = pattern.Clone(offset);
|
var basePattern = pattern.Clone(offset);
|
||||||
@@ -685,7 +772,7 @@ namespace OpenNest.Engine.Fill
|
|||||||
basePattern.BoundingBox.Width > WorkArea.Width + Tolerance.Epsilon
|
basePattern.BoundingBox.Width > WorkArea.Width + Tolerance.Epsilon
|
||||||
|| basePattern.BoundingBox.Length > WorkArea.Length + Tolerance.Epsilon
|
|| basePattern.BoundingBox.Length > WorkArea.Length + Tolerance.Epsilon
|
||||||
)
|
)
|
||||||
return new List<Part>();
|
return new DeferredGrid(new List<Part>());
|
||||||
|
|
||||||
return FillGrid(basePattern, primaryAxis, cache);
|
return FillGrid(basePattern, primaryAxis, cache);
|
||||||
}
|
}
|
||||||
@@ -702,7 +789,7 @@ namespace OpenNest.Engine.Fill
|
|||||||
if (seed.Parts.Count == 0)
|
if (seed.Parts.Count == 0)
|
||||||
return new List<Part>();
|
return new List<Part>();
|
||||||
|
|
||||||
return FillGrid(seed, primaryAxis, cache);
|
return FillGrid(seed, primaryAxis, cache).Resolve();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,6 +2,7 @@ using System;
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
using System.Runtime.ExceptionServices;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using OpenNest.Engine;
|
using OpenNest.Engine;
|
||||||
@@ -102,6 +103,15 @@ namespace OpenNest.Engine.Fill
|
|||||||
this.remnantFiller = new PairRemnantFiller(plate, this.comparer);
|
this.remnantFiller = new PairRemnantFiller(plate, this.comparer);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The fill pipeline's stripe convergences, for the stripe fills of the remnant strips.
|
||||||
|
/// </summary>
|
||||||
|
internal StripeConvergenceCache StripeConvergence
|
||||||
|
{
|
||||||
|
get => remnantFiller.StripeConvergence;
|
||||||
|
init => remnantFiller.StripeConvergence = value;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The Fill
|
/// The Fill
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -545,30 +555,34 @@ namespace OpenNest.Engine.Fill
|
|||||||
CancellationToken token
|
CancellationToken token
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
// Phase 1: evaluate all grids (fast)
|
// Phase 1: tile all grids (fast). Each grid's final overlap check, the bulk of the
|
||||||
var grids = new List<(List<Part> Parts, NestDirection Dir)>();
|
// work, waits until the ranking or Phase 2 needs its outcome (see CompareByCount).
|
||||||
|
var grids = new List<FillLinear.DeferredGrid>();
|
||||||
var engine = new FillLinear(workArea, partSpacing) { Label = "Pairs" };
|
var engine = new FillLinear(workArea, partSpacing) { Label = "Pairs" };
|
||||||
foreach (var (pattern, dir) in claimed)
|
foreach (var (pattern, dir) in claimed)
|
||||||
{
|
{
|
||||||
token.ThrowIfCancellationRequested();
|
token.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
var gridParts = engine.Fill(pattern, dir);
|
var grid = engine.FillDeferred(pattern, dir);
|
||||||
if (gridParts != null && gridParts.Count > 0)
|
if (grid.IsPending && (grid.Count == 0 || grid.FallbackCount == 0))
|
||||||
grids.Add((gridParts, dir));
|
grid.Resolve();
|
||||||
|
if (grid.IsPending || grid.Count > 0)
|
||||||
|
grids.Add(grid);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (grids.Count == 0)
|
if (grids.Count == 0)
|
||||||
return null;
|
return null;
|
||||||
|
|
||||||
// Sort by count descending so we try the best grids first
|
// Sort by count descending so we try the best grids first
|
||||||
grids.Sort((a, b) => b.Parts.Count.CompareTo(a.Parts.Count));
|
SortByCount(grids);
|
||||||
|
|
||||||
// Early abort: if the best grid + optimistic remnant can't beat the global best, skip Phase 2
|
// Early abort: if the best grid + optimistic remnant can't beat the global best, skip Phase 2
|
||||||
if (minCountToBeat > 0)
|
if (minCountToBeat > 0)
|
||||||
{
|
{
|
||||||
var topCount = grids[0].Parts.Count;
|
var topParts = grids[0].Resolve();
|
||||||
|
var topCount = topParts.Count;
|
||||||
var optimisticRemnant = remnantFiller.EstimateUpperBound(
|
var optimisticRemnant = remnantFiller.EstimateUpperBound(
|
||||||
grids[0].Parts,
|
topParts,
|
||||||
workArea,
|
workArea,
|
||||||
maxUtilization,
|
maxUtilization,
|
||||||
partArea
|
partArea
|
||||||
@@ -585,10 +599,12 @@ namespace OpenNest.Engine.Fill
|
|||||||
// Phase 2: try remnant for each grid, skip if grid is too far behind
|
// Phase 2: try remnant for each grid, skip if grid is too far behind
|
||||||
List<Part> best = null;
|
List<Part> best = null;
|
||||||
|
|
||||||
foreach (var (gridParts, dir) in grids)
|
foreach (var grid in grids)
|
||||||
{
|
{
|
||||||
token.ThrowIfCancellationRequested();
|
token.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
|
var gridParts = grid.Resolve();
|
||||||
|
|
||||||
// If this grid + max possible remnant can't beat current best, skip
|
// If this grid + max possible remnant can't beat current best, skip
|
||||||
if (best != null)
|
if (best != null)
|
||||||
{
|
{
|
||||||
@@ -622,6 +638,73 @@ namespace OpenNest.Engine.Fill
|
|||||||
return best;
|
return best;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Sorts grids with <see cref="CompareByCount"/>. A check that throws during the sort
|
||||||
|
/// surfaces as itself, as it did when every grid was checked before sorting, rather than
|
||||||
|
/// wrapped by <see cref="List{T}.Sort(Comparison{T})"/>.
|
||||||
|
/// </summary>
|
||||||
|
internal static void SortByCount(List<FillLinear.DeferredGrid> grids)
|
||||||
|
{
|
||||||
|
ExceptionDispatchInfo failure = null;
|
||||||
|
grids.Sort((a, b) =>
|
||||||
|
{
|
||||||
|
if (failure != null)
|
||||||
|
return 0;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return CompareByCount(a, b);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
failure = ExceptionDispatchInfo.Capture(ex);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
failure?.Throw();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Orders grids by part count, descending, as <c>b.Count.CompareTo(a.Count)</c> on their
|
||||||
|
/// checked parts. A grid whose check is pending may keep its tiling or fall back to its
|
||||||
|
/// bounding-box tiling; when those counts could order the pair differently, the check
|
||||||
|
/// runs. Every answer is the one the checked counts give, so the sort makes the same
|
||||||
|
/// moves, ties included, as on grids checked up front, and the checks it skips are of
|
||||||
|
/// grids it never needed to tell apart.
|
||||||
|
/// </summary>
|
||||||
|
internal static int CompareByCount(FillLinear.DeferredGrid a, FillLinear.DeferredGrid b)
|
||||||
|
{
|
||||||
|
if (ReferenceEquals(a, b))
|
||||||
|
return 0;
|
||||||
|
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
if (TryCompareByCount(a, b, out var order))
|
||||||
|
return order;
|
||||||
|
|
||||||
|
if (a.IsPending)
|
||||||
|
a.Resolve();
|
||||||
|
else
|
||||||
|
b.Resolve();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The order of <paramref name="a"/> and <paramref name="b"/> when every count either
|
||||||
|
/// grid can still have gives the same one.
|
||||||
|
/// </summary>
|
||||||
|
private static bool TryCompareByCount(
|
||||||
|
FillLinear.DeferredGrid a,
|
||||||
|
FillLinear.DeferredGrid b,
|
||||||
|
out int order
|
||||||
|
)
|
||||||
|
{
|
||||||
|
order = b.Count.CompareTo(a.Count);
|
||||||
|
return (!a.IsPending || b.Count.CompareTo(a.FallbackCount) == order)
|
||||||
|
&& (!b.IsPending || b.FallbackCount.CompareTo(a.Count) == order)
|
||||||
|
&& (!a.IsPending || !b.IsPending || b.FallbackCount.CompareTo(a.FallbackCount) == order);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The BuildTilingAngles
|
/// The BuildTilingAngles
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
@@ -50,6 +50,13 @@ namespace OpenNest.Engine.Fill
|
|||||||
this.plate = plate;
|
this.plate = plate;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The fill pipeline's stripe convergences, shared with the strips' stripe fills: a strip
|
||||||
|
/// along a full side of the work area converges the same spans as the Row strategy and
|
||||||
|
/// as every other such strip. Null converges each strip on its own.
|
||||||
|
/// </summary>
|
||||||
|
internal StripeConvergenceCache StripeConvergence { get; set; }
|
||||||
|
|
||||||
public int EstimateUpperBound(
|
public int EstimateUpperBound(
|
||||||
List<Part> gridParts,
|
List<Part> gridParts,
|
||||||
Box workArea,
|
Box workArea,
|
||||||
@@ -224,6 +231,8 @@ namespace OpenNest.Engine.Fill
|
|||||||
Policy = new FillPolicy(comparer),
|
Policy = new FillPolicy(comparer),
|
||||||
};
|
};
|
||||||
context.SharedState["BestFits"] = bestFits;
|
context.SharedState["BestFits"] = bestFits;
|
||||||
|
if (StripeConvergence != null)
|
||||||
|
context.SharedState[StripeConvergenceCache.SharedStateKey] = StripeConvergence;
|
||||||
|
|
||||||
// The stripe filler lays rows along both axes itself; its axis only names it.
|
// The stripe filler lays rows along both axes itself; its axis only names it.
|
||||||
var best = new StripeFiller(context, NestDirection.Horizontal).Fill();
|
var best = new StripeFiller(context, NestDirection.Horizontal).Fill();
|
||||||
|
|||||||
@@ -0,0 +1,149 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using OpenNest.Engine.BestFit;
|
||||||
|
using OpenNest.Geometry;
|
||||||
|
|
||||||
|
namespace OpenNest.Engine.Fill;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// One estimate row of a stripe convergence: the turned pair's span along the row and across
|
||||||
|
/// it, and the parts and remaining span of the row tiled across the sheet (zero parts and NaN
|
||||||
|
/// when none fit, or when the span leaves no room to step).
|
||||||
|
/// </summary>
|
||||||
|
internal readonly record struct StripeRow(double PairSpan, double PerpDim, int Count, double Remaining);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The stripe angles <see cref="StripeFiller"/> converged in one fill pipeline, so each pair,
|
||||||
|
/// axis, variant and span converges once, and the turned bounds and estimate rows they were
|
||||||
|
/// converged from. The Row and Column strategies converge the same layouts (both lay rows along
|
||||||
|
/// both axes), every pair remnant strip along a full side of the work area repeats the same
|
||||||
|
/// span, and the expanding and shrinking variants revisit each other's angles. Each value is a
|
||||||
|
/// pure function of its key (the pair's parts rebuilt from the drawing, the angle, the span,
|
||||||
|
/// the spacing and the row cap), so a hit returns exactly what computing it again would. A
|
||||||
|
/// canceled convergence stores no result; the rows and bounds it stored are complete.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class StripeConvergenceCache
|
||||||
|
{
|
||||||
|
internal const string SharedStateKey = "StripeConvergence";
|
||||||
|
|
||||||
|
private readonly ConcurrentDictionary<Key, (double Angle, double Waste, int Count)> results =
|
||||||
|
new();
|
||||||
|
|
||||||
|
private readonly ConcurrentDictionary<Key, ConcurrentDictionary<double, Box>> bounds = new();
|
||||||
|
|
||||||
|
private readonly ConcurrentDictionary<Key, ConcurrentDictionary<double, Lazy<StripeRow>>> rows =
|
||||||
|
new();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The cached convergence for the key, or the one <paramref name="converge"/> computes,
|
||||||
|
/// stored unless it throws.
|
||||||
|
/// </summary>
|
||||||
|
public (double Angle, double Waste, int Count) GetOrAdd(
|
||||||
|
BestFitResult candidate,
|
||||||
|
Drawing drawing,
|
||||||
|
NestDirection axis,
|
||||||
|
int variant,
|
||||||
|
double sheetSpan,
|
||||||
|
double spacing,
|
||||||
|
int maxParts,
|
||||||
|
Func<(double Angle, double Waste, int Count)> converge
|
||||||
|
)
|
||||||
|
{
|
||||||
|
var key = new Key(candidate, drawing, axis, variant, sheetSpan, spacing, maxParts);
|
||||||
|
if (results.TryGetValue(key, out var cached))
|
||||||
|
return cached;
|
||||||
|
|
||||||
|
// Threads converging the same key at once compute identical results; the first stored wins.
|
||||||
|
var result = converge();
|
||||||
|
results.TryAdd(key, result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The number of convergences stored.</summary>
|
||||||
|
internal int Count => results.Count;
|
||||||
|
|
||||||
|
/// <summary>The pair's parts turned about their center: bounding boxes by angle.</summary>
|
||||||
|
public ConcurrentDictionary<double, Box> Bounds(BestFitResult candidate, Drawing drawing) =>
|
||||||
|
bounds.GetOrAdd(
|
||||||
|
new Key(candidate, drawing, default, -1, 0, 0, 0),
|
||||||
|
_ => new ConcurrentDictionary<double, Box>()
|
||||||
|
);
|
||||||
|
|
||||||
|
/// <summary>The pair's estimate rows across one span, by angle.</summary>
|
||||||
|
public ConcurrentDictionary<double, Lazy<StripeRow>> Rows(
|
||||||
|
BestFitResult candidate,
|
||||||
|
Drawing drawing,
|
||||||
|
NestDirection axis,
|
||||||
|
double sheetSpan,
|
||||||
|
double spacing,
|
||||||
|
int maxParts
|
||||||
|
) =>
|
||||||
|
rows.GetOrAdd(
|
||||||
|
new Key(candidate, drawing, axis, -1, sheetSpan, spacing, maxParts),
|
||||||
|
_ => new ConcurrentDictionary<double, Lazy<StripeRow>>()
|
||||||
|
);
|
||||||
|
|
||||||
|
/// <summary>Gets or creates the pipeline's cache in a fill context's shared state.</summary>
|
||||||
|
public static StripeConvergenceCache GetOrCreate(Dictionary<string, object> sharedState)
|
||||||
|
{
|
||||||
|
if (sharedState.TryGetValue(SharedStateKey, out var existing))
|
||||||
|
return (StripeConvergenceCache)existing;
|
||||||
|
|
||||||
|
var cache = new StripeConvergenceCache();
|
||||||
|
sharedState[SharedStateKey] = cache;
|
||||||
|
return cache;
|
||||||
|
}
|
||||||
|
|
||||||
|
private readonly struct Key : IEquatable<Key>
|
||||||
|
{
|
||||||
|
private readonly BestFitResult candidate;
|
||||||
|
private readonly Drawing drawing;
|
||||||
|
private readonly NestDirection axis;
|
||||||
|
private readonly int variant;
|
||||||
|
private readonly long sheetSpanBits;
|
||||||
|
private readonly long spacingBits;
|
||||||
|
private readonly int maxParts;
|
||||||
|
|
||||||
|
public Key(
|
||||||
|
BestFitResult candidate,
|
||||||
|
Drawing drawing,
|
||||||
|
NestDirection axis,
|
||||||
|
int variant,
|
||||||
|
double sheetSpan,
|
||||||
|
double spacing,
|
||||||
|
int maxParts
|
||||||
|
)
|
||||||
|
{
|
||||||
|
this.candidate = candidate;
|
||||||
|
this.drawing = drawing;
|
||||||
|
this.axis = axis;
|
||||||
|
this.variant = variant;
|
||||||
|
sheetSpanBits = BitConverter.DoubleToInt64Bits(sheetSpan);
|
||||||
|
spacingBits = BitConverter.DoubleToInt64Bits(spacing);
|
||||||
|
this.maxParts = maxParts;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Equals(Key other) =>
|
||||||
|
ReferenceEquals(candidate, other.candidate)
|
||||||
|
&& ReferenceEquals(drawing, other.drawing)
|
||||||
|
&& axis == other.axis
|
||||||
|
&& variant == other.variant
|
||||||
|
&& sheetSpanBits == other.sheetSpanBits
|
||||||
|
&& spacingBits == other.spacingBits
|
||||||
|
&& maxParts == other.maxParts;
|
||||||
|
|
||||||
|
public override bool Equals(object obj) => obj is Key other && Equals(other);
|
||||||
|
|
||||||
|
public override int GetHashCode() =>
|
||||||
|
HashCode.Combine(
|
||||||
|
System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(candidate),
|
||||||
|
System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(drawing),
|
||||||
|
axis,
|
||||||
|
variant,
|
||||||
|
sheetSpanBits,
|
||||||
|
spacingBits,
|
||||||
|
maxParts
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
using System;
|
using System;
|
||||||
|
using System.Collections.Concurrent;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
@@ -23,6 +24,7 @@ public class StripeFiller
|
|||||||
private readonly NestDirection _primaryAxis;
|
private readonly NestDirection _primaryAxis;
|
||||||
private readonly IFillComparer _comparer;
|
private readonly IFillComparer _comparer;
|
||||||
private readonly GridDedup _dedup;
|
private readonly GridDedup _dedup;
|
||||||
|
private readonly StripeConvergenceCache _convergence;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// When true, only complete stripes are placed — no partial rows/columns.
|
/// When true, only complete stripes are placed — no partial rows/columns.
|
||||||
@@ -35,6 +37,7 @@ public class StripeFiller
|
|||||||
_primaryAxis = primaryAxis;
|
_primaryAxis = primaryAxis;
|
||||||
_comparer = context.Policy?.Comparer ?? new DefaultFillComparer();
|
_comparer = context.Policy?.Comparer ?? new DefaultFillComparer();
|
||||||
_dedup = GridDedup.GetOrCreate(context.SharedState);
|
_dedup = GridDedup.GetOrCreate(context.SharedState);
|
||||||
|
_convergence = StripeConvergenceCache.GetOrCreate(context.SharedState);
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<Part> Fill()
|
public List<Part> Fill()
|
||||||
@@ -124,6 +127,8 @@ public class StripeFiller
|
|||||||
/// configuration is not yet claimed and no earlier layout shares it: claims are only ever
|
/// configuration is not yet claimed and no earlier layout shares it: claims are only ever
|
||||||
/// added, so exactly those are the grids the sequential loop would have tiled.
|
/// added, so exactly those are the grids the sequential loop would have tiled.
|
||||||
/// <see cref="Fill"/> then claims, fills remnants and ranks in the original order.
|
/// <see cref="Fill"/> then claims, fills remnants and ranks in the original order.
|
||||||
|
/// Convergence goes through the pipeline's <see cref="StripeConvergenceCache"/>: the Column
|
||||||
|
/// strategy and pair remnant strips repeat the Row strategy's.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private StripeLayout[] ComputeLayouts(List<BestFitResult> bestFits, Drawing drawing)
|
private StripeLayout[] ComputeLayouts(List<BestFitResult> bestFits, Drawing drawing)
|
||||||
{
|
{
|
||||||
@@ -134,7 +139,7 @@ public class StripeFiller
|
|||||||
var variant = index % VariantsPerAxis;
|
var variant = index % VariantsPerAxis;
|
||||||
var axis = Axes[index / VariantsPerAxis % Axes.Length];
|
var axis = Axes[index / VariantsPerAxis % Axes.Length];
|
||||||
var candidate = bestFits[index / VariantsPerAxis / Axes.Length];
|
var candidate = bestFits[index / VariantsPerAxis / Axes.Length];
|
||||||
layouts[index] = Converge(candidate.BuildParts(drawing), axis, variant);
|
layouts[index] = Converge(candidate, drawing, axis, variant);
|
||||||
});
|
});
|
||||||
|
|
||||||
var batch = new GridDedup();
|
var batch = new GridDedup();
|
||||||
@@ -176,15 +181,35 @@ public class StripeFiller
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private StripeLayout Converge(List<Part> pairParts, NestDirection axis, int variant)
|
private StripeLayout Converge(BestFitResult candidate, Drawing drawing, NestDirection axis, int variant)
|
||||||
{
|
{
|
||||||
var spacing = _context.Plate.PartSpacing;
|
var spacing = _context.Plate.PartSpacing;
|
||||||
var sheetSpan = GetDimension(_context.WorkArea, axis);
|
var sheetSpan = GetDimension(_context.WorkArea, axis);
|
||||||
|
var maxParts = _context.MaxQuantity;
|
||||||
|
|
||||||
var bounds = new RotatedBounds(pairParts);
|
// Convergence only reads the parts (its rotations are clones), so the pattern below is
|
||||||
var (angle, waste, count) = variant == 0
|
// built from parts as fresh as those a cache hit converged.
|
||||||
? ConvergeStripeAngle(bounds, sheetSpan, spacing, axis, _context.Token, _context.MaxQuantity)
|
var pairParts = candidate.BuildParts(drawing);
|
||||||
: ConvergeStripeAngleShrink(bounds, sheetSpan, spacing, axis, _context.Token, _context.MaxQuantity);
|
var (angle, waste, count) = _convergence.GetOrAdd(
|
||||||
|
candidate,
|
||||||
|
drawing,
|
||||||
|
axis,
|
||||||
|
variant,
|
||||||
|
sheetSpan,
|
||||||
|
spacing,
|
||||||
|
maxParts,
|
||||||
|
() =>
|
||||||
|
{
|
||||||
|
// Both variants, and every other fill of this pipeline, share the pair's rotated
|
||||||
|
// bounds and the estimate rows tiled at each angle for this span: the variants
|
||||||
|
// revisit each other's angles, and a trajectory often cycles between two angles.
|
||||||
|
var bounds = new RotatedBounds(pairParts, _convergence.Bounds(candidate, drawing));
|
||||||
|
var rows = _convergence.Rows(candidate, drawing, axis, sheetSpan, spacing, maxParts);
|
||||||
|
return variant == 0
|
||||||
|
? ConvergeStripeAngle(bounds, rows, sheetSpan, spacing, axis, _context.Token, maxParts)
|
||||||
|
: ConvergeStripeAngleShrink(bounds, rows, sheetSpan, spacing, axis, _context.Token, maxParts);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
var layout = new StripeLayout { Angle = angle, Waste = waste, Count = count };
|
var layout = new StripeLayout { Angle = angle, Waste = waste, Count = count };
|
||||||
if (count > 0)
|
if (count > 0)
|
||||||
@@ -397,20 +422,32 @@ public class StripeFiller
|
|||||||
/// Bounding boxes of one pattern's parts rotated about their common center, by angle. A
|
/// Bounding boxes of one pattern's parts rotated about their common center, by angle. A
|
||||||
/// box is a pure function of the parts and the angle, and the angle searches sample the
|
/// box is a pure function of the parts and the angle, and the angle searches sample the
|
||||||
/// same angles over and over (every <see cref="FindAngleForTargetSpan"/> scans the same
|
/// same angles over and over (every <see cref="FindAngleForTargetSpan"/> scans the same
|
||||||
/// grid), so each is built once. The parts must not change while it is in use.
|
/// grid), so each is built once. The parts must not change while it is in use. The boxes
|
||||||
|
/// may be shared, on any thread, with other instances whose parts are built alike from the
|
||||||
|
/// same pair.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private sealed class RotatedBounds
|
private sealed class RotatedBounds
|
||||||
{
|
{
|
||||||
private readonly Dictionary<double, Box> boxes = new();
|
private readonly ConcurrentDictionary<double, Box> boxes;
|
||||||
|
|
||||||
public RotatedBounds(List<Part> parts) => Parts = parts;
|
public RotatedBounds(List<Part> parts)
|
||||||
|
: this(parts, new ConcurrentDictionary<double, Box>()) { }
|
||||||
|
|
||||||
|
public RotatedBounds(List<Part> parts, ConcurrentDictionary<double, Box> boxes)
|
||||||
|
{
|
||||||
|
Parts = parts;
|
||||||
|
this.boxes = boxes;
|
||||||
|
}
|
||||||
|
|
||||||
public List<Part> Parts { get; }
|
public List<Part> Parts { get; }
|
||||||
|
|
||||||
public Box At(double angle)
|
public Box At(double angle)
|
||||||
{
|
{
|
||||||
if (!boxes.TryGetValue(angle, out var box))
|
if (!boxes.TryGetValue(angle, out var box))
|
||||||
boxes[angle] = box = FillHelpers.BuildRotatedPattern(Parts, angle).BoundingBox;
|
{
|
||||||
|
box = FillHelpers.BuildRotatedPattern(Parts, angle).BoundingBox;
|
||||||
|
boxes.TryAdd(angle, box);
|
||||||
|
}
|
||||||
return box;
|
return box;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -499,10 +536,12 @@ public class StripeFiller
|
|||||||
NestDirection axis,
|
NestDirection axis,
|
||||||
CancellationToken token = default,
|
CancellationToken token = default,
|
||||||
int maxParts = 0
|
int maxParts = 0
|
||||||
) => ConvergeStripeAngle(new RotatedBounds(patternParts), sheetSpan, spacing, axis, token, maxParts);
|
) => ConvergeStripeAngle(new RotatedBounds(patternParts), new ConcurrentDictionary<double, Lazy<StripeRow>>(),
|
||||||
|
sheetSpan, spacing, axis, token, maxParts);
|
||||||
|
|
||||||
private static (double Angle, double Waste, int Count) ConvergeStripeAngle(
|
private static (double Angle, double Waste, int Count) ConvergeStripeAngle(
|
||||||
RotatedBounds patternParts,
|
RotatedBounds patternParts,
|
||||||
|
ConcurrentDictionary<double, Lazy<StripeRow>> rows,
|
||||||
double sheetSpan,
|
double sheetSpan,
|
||||||
double spacing,
|
double spacing,
|
||||||
NestDirection axis,
|
NestDirection axis,
|
||||||
@@ -511,7 +550,7 @@ public class StripeFiller
|
|||||||
)
|
)
|
||||||
{
|
{
|
||||||
var startAngle = OrientShortSideAlong(patternParts, axis);
|
var startAngle = OrientShortSideAlong(patternParts, axis);
|
||||||
return ConvergeFromAngle(patternParts, startAngle, sheetSpan, spacing, axis, token, maxParts);
|
return ConvergeFromAngle(patternParts, rows, startAngle, sheetSpan, spacing, axis, token, maxParts);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -525,10 +564,12 @@ public class StripeFiller
|
|||||||
NestDirection axis,
|
NestDirection axis,
|
||||||
CancellationToken token = default,
|
CancellationToken token = default,
|
||||||
int maxParts = 0
|
int maxParts = 0
|
||||||
) => ConvergeStripeAngleShrink(new RotatedBounds(patternParts), sheetSpan, spacing, axis, token, maxParts);
|
) => ConvergeStripeAngleShrink(new RotatedBounds(patternParts), new ConcurrentDictionary<double, Lazy<StripeRow>>(),
|
||||||
|
sheetSpan, spacing, axis, token, maxParts);
|
||||||
|
|
||||||
private static (double Angle, double Waste, int Count) ConvergeStripeAngleShrink(
|
private static (double Angle, double Waste, int Count) ConvergeStripeAngleShrink(
|
||||||
RotatedBounds patternParts,
|
RotatedBounds patternParts,
|
||||||
|
ConcurrentDictionary<double, Lazy<StripeRow>> rows,
|
||||||
double sheetSpan,
|
double sheetSpan,
|
||||||
double spacing,
|
double spacing,
|
||||||
NestDirection axis,
|
NestDirection axis,
|
||||||
@@ -550,11 +591,14 @@ public class StripeFiller
|
|||||||
return (0, double.MaxValue, 0);
|
return (0, double.MaxValue, 0);
|
||||||
|
|
||||||
var startAngle = FindAngleForTargetSpan(patternParts, targetSpan, axis);
|
var startAngle = FindAngleForTargetSpan(patternParts, targetSpan, axis);
|
||||||
return ConvergeFromAngle(patternParts, startAngle, sheetSpan, spacing, axis, token, maxParts);
|
return ConvergeFromAngle(patternParts, rows, startAngle, sheetSpan, spacing, axis, token, maxParts);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <param name="rows">The estimate rows already tiled at each angle for these parts, span,
|
||||||
|
/// spacing, axis and cap (<see cref="EstimateRow"/>), shared by every convergence of them.</param>
|
||||||
private static (double Angle, double Waste, int Count) ConvergeFromAngle(
|
private static (double Angle, double Waste, int Count) ConvergeFromAngle(
|
||||||
RotatedBounds patternParts,
|
RotatedBounds patternParts,
|
||||||
|
ConcurrentDictionary<double, Lazy<StripeRow>> rows,
|
||||||
double startAngle,
|
double startAngle,
|
||||||
double sheetSpan,
|
double sheetSpan,
|
||||||
double spacing,
|
double spacing,
|
||||||
@@ -573,33 +617,27 @@ public class StripeFiller
|
|||||||
{
|
{
|
||||||
token.ThrowIfCancellationRequested();
|
token.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
var rotated = FillHelpers.BuildRotatedPattern(patternParts.Parts, currentAngle);
|
// Fills of this pipeline converge on several threads at once and often reach the same
|
||||||
var pairSpan = GetDimension(rotated.BoundingBox, axis);
|
// angle together: one tiles the row while the others wait for it.
|
||||||
var perpDim =
|
var parts = patternParts.Parts;
|
||||||
axis == NestDirection.Horizontal
|
var row = rows.GetOrAdd(
|
||||||
? rotated.BoundingBox.Width
|
currentAngle,
|
||||||
: rotated.BoundingBox.Length;
|
angle => new Lazy<StripeRow>(() =>
|
||||||
|
EstimateRow(parts, angle, sheetSpan, spacing, axis, maxParts))
|
||||||
|
).Value;
|
||||||
|
|
||||||
|
var pairSpan = row.PairSpan;
|
||||||
|
var perpDim = row.PerpDim;
|
||||||
|
|
||||||
if (pairSpan + spacing <= 0)
|
if (pairSpan + spacing <= 0)
|
||||||
break;
|
break;
|
||||||
|
|
||||||
var stripeBox =
|
var n = row.Count;
|
||||||
axis == NestDirection.Horizontal
|
|
||||||
? new Box(0, 0, sheetSpan, perpDim)
|
|
||||||
: new Box(0, 0, perpDim, sheetSpan);
|
|
||||||
var engine = new FillLinear(stripeBox, spacing)
|
|
||||||
{
|
|
||||||
Label = "Stripe-EstimateRow",
|
|
||||||
MaxParts = maxParts,
|
|
||||||
};
|
|
||||||
var filled = engine.Fill(rotated, axis);
|
|
||||||
var n = filled?.Count ?? 0;
|
|
||||||
|
|
||||||
if (n <= 0)
|
if (n <= 0)
|
||||||
break;
|
break;
|
||||||
|
|
||||||
var filledBox = ((IEnumerable<IBoundable>)filled).GetBoundingBox();
|
var remaining = row.Remaining;
|
||||||
var remaining = sheetSpan - GetDimension(filledBox, axis);
|
|
||||||
|
|
||||||
Debug.WriteLine(
|
Debug.WriteLine(
|
||||||
$"[Converge] iter={iteration}: angle={Angle.ToDegrees(currentAngle):F2}°, "
|
$"[Converge] iter={iteration}: angle={Angle.ToDegrees(currentAngle):F2}°, "
|
||||||
@@ -632,6 +670,49 @@ public class StripeFiller
|
|||||||
return (bestAngle, bestWaste, bestCount);
|
return (bestAngle, bestWaste, bestCount);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// One stripe row of the parts turned to <paramref name="angle"/>, tiled across the span:
|
||||||
|
/// a pure function of its arguments. The row is not tiled when the turned pattern's span
|
||||||
|
/// leaves no room to step.
|
||||||
|
/// </summary>
|
||||||
|
private static StripeRow EstimateRow(
|
||||||
|
List<Part> patternParts,
|
||||||
|
double angle,
|
||||||
|
double sheetSpan,
|
||||||
|
double spacing,
|
||||||
|
NestDirection axis,
|
||||||
|
int maxParts
|
||||||
|
)
|
||||||
|
{
|
||||||
|
var rotated = FillHelpers.BuildRotatedPattern(patternParts, angle);
|
||||||
|
var pairSpan = GetDimension(rotated.BoundingBox, axis);
|
||||||
|
var perpDim =
|
||||||
|
axis == NestDirection.Horizontal
|
||||||
|
? rotated.BoundingBox.Width
|
||||||
|
: rotated.BoundingBox.Length;
|
||||||
|
|
||||||
|
if (pairSpan + spacing <= 0)
|
||||||
|
return new StripeRow(pairSpan, perpDim, 0, double.NaN);
|
||||||
|
|
||||||
|
var stripeBox =
|
||||||
|
axis == NestDirection.Horizontal
|
||||||
|
? new Box(0, 0, sheetSpan, perpDim)
|
||||||
|
: new Box(0, 0, perpDim, sheetSpan);
|
||||||
|
var engine = new FillLinear(stripeBox, spacing)
|
||||||
|
{
|
||||||
|
Label = "Stripe-EstimateRow",
|
||||||
|
MaxParts = maxParts,
|
||||||
|
};
|
||||||
|
var filled = engine.Fill(rotated, axis);
|
||||||
|
var n = filled?.Count ?? 0;
|
||||||
|
|
||||||
|
if (n <= 0)
|
||||||
|
return new StripeRow(pairSpan, perpDim, 0, double.NaN);
|
||||||
|
|
||||||
|
var filledBox = ((IEnumerable<IBoundable>)filled).GetBoundingBox();
|
||||||
|
return new StripeRow(pairSpan, perpDim, n, sheetSpan - GetDimension(filledBox, axis));
|
||||||
|
}
|
||||||
|
|
||||||
private static double BisectForTarget(
|
private static double BisectForTarget(
|
||||||
RotatedBounds patternParts,
|
RotatedBounds patternParts,
|
||||||
double lo,
|
double lo,
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ internal sealed class BlockCatalog : IDisposable
|
|||||||
private readonly Dictionary<int, Drawing> drawings = new();
|
private readonly Dictionary<int, Drawing> drawings = new();
|
||||||
private readonly Func<NestJobPart, Drawing>? drawingFor;
|
private readonly Func<NestJobPart, Drawing>? drawingFor;
|
||||||
private readonly Dictionary<int, List<Orientation>> orientations = new();
|
private readonly Dictionary<int, List<Orientation>> orientations = new();
|
||||||
|
private readonly Dictionary<int, (double Width, double Area)> footprints = new();
|
||||||
private readonly Dictionary<int, int> attempts = new();
|
private readonly Dictionary<int, int> attempts = new();
|
||||||
internal int PreparationCount => attempts.Values.Sum();
|
internal int PreparationCount => attempts.Values.Sum();
|
||||||
private readonly Dictionary<(int Type, int Quantity, double Length, double Width), IReadOnlyList<Placed>> cache = new();
|
private readonly Dictionary<(int Type, int Quantity, double Length, double Width), IReadOnlyList<Placed>> cache = new();
|
||||||
@@ -55,9 +56,53 @@ internal sealed class BlockCatalog : IDisposable
|
|||||||
if (pairs.TryGetValue(type.Index, out var found))
|
if (pairs.TryGetValue(type.Index, out var found))
|
||||||
poses.AddRange(found.SelectMany(p => new[] { p.A, p.B }));
|
poses.AddRange(found.SelectMany(p => new[] { p.A, p.B }));
|
||||||
orientations[type.Index] = poses.Distinct().ToList();
|
orientations[type.Index] = poses.Distinct().ToList();
|
||||||
|
if (type.Orientations.Count > 0)
|
||||||
|
footprints[type.Index] = Footprint(type.Orientations[0]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Lower bounds on the true part's width at any rotation and on its area: the outline's
|
||||||
|
/// convex-hull width and area, less what flattening within the outline's tolerance (and a
|
||||||
|
/// margin for Fill's boundary rounding) could hide.
|
||||||
|
/// </summary>
|
||||||
|
private static (double Width, double Area) Footprint(Orientation orientation)
|
||||||
|
{
|
||||||
|
var outline = orientation.Outline;
|
||||||
|
var hull = ConvexHull.Compute(outline.Select(p => new Vector(p.x, p.y)).ToList()).Vertices;
|
||||||
|
var width = double.PositiveInfinity;
|
||||||
|
for (var i = 0; i < hull.Count; i++)
|
||||||
|
{
|
||||||
|
var a = hull[i];
|
||||||
|
var b = hull[(i + 1) % hull.Count];
|
||||||
|
var length = a.DistanceTo(b);
|
||||||
|
if (length <= Tolerance.Epsilon)
|
||||||
|
continue;
|
||||||
|
var across = hull.Max(p => System.Math.Abs((b.X - a.X) * (p.Y - a.Y) - (b.Y - a.Y) * (p.X - a.X)) / length);
|
||||||
|
width = System.Math.Min(width, across);
|
||||||
|
}
|
||||||
|
var perimeter = 0.0;
|
||||||
|
for (var i = 0; i < outline.Count; i++)
|
||||||
|
{
|
||||||
|
var a = outline[i];
|
||||||
|
var b = outline[(i + 1) % outline.Count];
|
||||||
|
perimeter += System.Math.Sqrt((b.x - a.x) * (b.x - a.x) + (b.y - a.y) * (b.y - a.y));
|
||||||
|
}
|
||||||
|
const double margin = 0.001;
|
||||||
|
return (double.IsFinite(width) ? width - 2 * orientation.Tolerance - margin : 0,
|
||||||
|
System.Math.Abs(Clipper.Area(outline)) - perimeter * (orientation.Tolerance + margin));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// True when the rectangle cannot hold three copies of the type: it is narrower than the part
|
||||||
|
/// at every rotation, or smaller than three parts. Fill could return at most two members there,
|
||||||
|
/// which never form a block, so its proposal is known to be empty without running it.
|
||||||
|
/// </summary>
|
||||||
|
private bool CannotHoldBlock(PartType type, Box rectangle) =>
|
||||||
|
footprints.TryGetValue(type.Index, out var footprint)
|
||||||
|
&& (System.Math.Min(rectangle.Length, rectangle.Width) < footprint.Width
|
||||||
|
|| rectangle.Area() < 3 * footprint.Area);
|
||||||
|
|
||||||
internal static IReadOnlyList<Box> Rectangles(Box work, IReadOnlyList<Placed> placed, double spacing)
|
internal static IReadOnlyList<Box> Rectangles(Box work, IReadOnlyList<Placed> placed, double spacing)
|
||||||
{
|
{
|
||||||
var free = new PathsD { new PathD
|
var free = new PathsD { new PathD
|
||||||
@@ -127,8 +172,10 @@ internal sealed class BlockCatalog : IDisposable
|
|||||||
{
|
{
|
||||||
// Types may build bands in parallel: each type's drawing and orientation list are its
|
// Types may build bands in parallel: each type's drawing and orientation list are its
|
||||||
// own. Prefetches of one type fill their own drawings and only read the orientations.
|
// own. Prefetches of one type fill their own drawings and only read the orientations.
|
||||||
var (members, poses) = Propose(type, quantity, rectangle, token,
|
var (members, poses) = CannotHoldBlock(type, rectangle)
|
||||||
spacing + System.Math.Pow(10, -NoFitCache.Precision), prefetch ?? DrawingOf(type));
|
? (Array.Empty<Placed>(), null)
|
||||||
|
: Propose(type, quantity, rectangle, token,
|
||||||
|
spacing + System.Math.Pow(10, -NoFitCache.Precision), prefetch ?? DrawingOf(type));
|
||||||
lock (bands)
|
lock (bands)
|
||||||
if (!bands.TryGetValue(key, out entry))
|
if (!bands.TryGetValue(key, out entry))
|
||||||
bands[key] = entry = new BandEntry(members, poses, Cost(type, quantity));
|
bands[key] = entry = new BandEntry(members, poses, Cost(type, quantity));
|
||||||
@@ -173,7 +220,11 @@ internal sealed class BlockCatalog : IDisposable
|
|||||||
// PrivatePlateFill.Run below is a full independent NFP-based pack whose own operations
|
// PrivatePlateFill.Run below is a full independent NFP-based pack whose own operations
|
||||||
// never touch this solve's effort meter; charge it here using the same factors - demand
|
// never touch this solve's effort meter; charge it here using the same factors - demand
|
||||||
// and outline complexity - that drive its real cost, so the shared budget actually sees it.
|
// and outline complexity - that drive its real cost, so the shared budget actually sees it.
|
||||||
|
// A rectangle that cannot hold a block is charged and counted as if filled, so the meter,
|
||||||
|
// and every later decision it steers, reads the same as when the Fill ran.
|
||||||
counter.Add(Cost(type, quantity));
|
counter.Add(Cost(type, quantity));
|
||||||
|
if (CannotHoldBlock(type, rectangle))
|
||||||
|
return Array.Empty<Placed>();
|
||||||
var (members, poses) = Propose(type, quantity, rectangle, token, spacing, DrawingOf(type));
|
var (members, poses) = Propose(type, quantity, rectangle, token, spacing, DrawingOf(type));
|
||||||
return members ?? Bind(type, poses!, orientations[type.Index], token);
|
return members ?? Bind(type, poses!, orientations[type.Index], token);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,8 @@ namespace OpenNest.Engine.NestingEngines.Irregular;
|
|||||||
/// With <see cref="NestJobOptions.SearchUntilCancelled"/>, a cancellable token and a progress
|
/// With <see cref="NestJobOptions.SearchUntilCancelled"/>, a cancellable token and a progress
|
||||||
/// listener, the search then keeps decoding the variants with seeded per-type weights on the
|
/// listener, the search then keeps decoding the variants with seeded per-type weights on the
|
||||||
/// placement rule, reporting each better plan, until cancelled (not for one-type jobs, where
|
/// placement rule, reporting each better plan, until cancelled (not for one-type jobs, where
|
||||||
/// the weights change nothing).
|
/// the weights change nothing). Such a solve first reports a quick plan, the first variant
|
||||||
|
/// without Lattice blocks, metered apart so the search after it is unchanged.
|
||||||
///
|
///
|
||||||
/// Fully deterministic: no clocks or randomness influence any decision. The weights come from
|
/// Fully deterministic: no clocks or randomness influence any decision. The weights come from
|
||||||
/// fixed seeds 1, 2, 3, ..., so an extended search depends only on how far it got.
|
/// fixed seeds 1, 2, 3, ..., so an extended search depends only on how far it got.
|
||||||
@@ -74,6 +75,12 @@ public sealed class IrregularNestingEngine : INestingEngine
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
internal long WorkBudget { get; init; } = 1_500_000;
|
internal long WorkBudget { get; init; } = 1_500_000;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Whether a tail re-plan's decode skips stock trials that can neither be chosen nor change the
|
||||||
|
/// choice; off only in tests that compare against packing every trial.
|
||||||
|
/// </summary>
|
||||||
|
internal bool PruneStockTrials { get; init; } = true;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// One private drawing per part geometry, shared by the best-fit pair and Fill block
|
/// One private drawing per part geometry, shared by the best-fit pair and Fill block
|
||||||
/// catalogs and by every solve of this instance (a pipeline's cutout trial and its ordinary
|
/// catalogs and by every solve of this instance (a pipeline's cutout trial and its ordinary
|
||||||
@@ -102,7 +109,7 @@ public sealed class IrregularNestingEngine : INestingEngine
|
|||||||
token.ThrowIfCancellationRequested();
|
token.ThrowIfCancellationRequested();
|
||||||
var types = PartCatalog.Build(job);
|
var types = PartCatalog.Build(job);
|
||||||
using var solver = new Solver(job, types, progress, token, WorkBudget, DrawingFor, SheetPacked, BatchSelected, TailReplaced,
|
using var solver = new Solver(job, types, progress, token, WorkBudget, DrawingFor, SheetPacked, BatchSelected, TailReplaced,
|
||||||
TailReplanning);
|
TailReplanning, PruneStockTrials);
|
||||||
|
|
||||||
// Pair-only orientations may fit stock even when the sampled single poses do not.
|
// Pair-only orientations may fit stock even when the sampled single poses do not.
|
||||||
// Demand that neither a single nor a pair can fit is reported unplaced.
|
// Demand that neither a single nor a pair can fit is reported unplaced.
|
||||||
@@ -117,6 +124,25 @@ public sealed class IrregularNestingEngine : INestingEngine
|
|||||||
|| (type.Part.Quantity > 2 && type.Orientations.Count > 0) ? type.Part.Quantity : 0;
|
|| (type.Part.Quantity > 2 && type.Orientations.Count > 0) ? type.Part.Quantity : 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// More searching can only end in cancellation, so it needs a listener for its plans, and
|
||||||
|
// it needs demand and two or more types, or every weighted decode repeats a variant.
|
||||||
|
var searchOn = job.Options.SearchUntilCancelled && token.CanBeCanceled && progress != null
|
||||||
|
&& types.Count > 1 && demand.Any(d => d > 0);
|
||||||
|
|
||||||
|
// A solve that ends only at its limit reports a quick plan first: the first variant without
|
||||||
|
// Lattice blocks, whose preparation takes most of the first decode's time on big jobs. It is
|
||||||
|
// metered apart, so the search below runs as without it. The search's plans are reported as
|
||||||
|
// before: only the deadline wrapper sets SearchUntilCancelled, and it keeps the best reported
|
||||||
|
// plan that passes the layout check, so a quick plan that fails the check hides none of them.
|
||||||
|
// Without a type of three or more copies no block is ever prepared, and the quick plan would
|
||||||
|
// only repeat the first variant.
|
||||||
|
if (searchOn && demand.Any(d => d > 2))
|
||||||
|
{
|
||||||
|
var quick = solver.QuickPlan(demand);
|
||||||
|
if (quick.Sheets.Count > 0)
|
||||||
|
ReportPlan(job, types, quick, progress, token);
|
||||||
|
}
|
||||||
|
|
||||||
Plan? best = null;
|
Plan? best = null;
|
||||||
foreach (var (axis, beta) in Variants)
|
foreach (var (axis, beta) in Variants)
|
||||||
{
|
{
|
||||||
@@ -195,10 +221,7 @@ public sealed class IrregularNestingEngine : INestingEngine
|
|||||||
ReportPlan(job, types, improved, progress, token);
|
ReportPlan(job, types, improved, progress, token);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// More searching can only end in cancellation, so it needs a listener for its plans, and
|
if (searchOn)
|
||||||
// it needs demand and two or more types, or every weighted decode repeats a variant.
|
|
||||||
if (job.Options.SearchUntilCancelled && token.CanBeCanceled && progress != null
|
|
||||||
&& types.Count > 1 && demand.Any(d => d > 0))
|
|
||||||
SearchUntilCancelled(job, types, solver, demand, improved, groups, progress, token);
|
SearchUntilCancelled(job, types, solver, demand, improved, groups, progress, token);
|
||||||
return BuildResult(job, types, improved, progress, token);
|
return BuildResult(job, types, improved, progress, token);
|
||||||
}
|
}
|
||||||
@@ -311,6 +334,14 @@ public sealed class IrregularNestingEngine : INestingEngine
|
|||||||
return BuildResult(job, types, solver.Plan(demand, axis, beta, weights), null, default);
|
return BuildResult(job, types, solver.Plan(demand, axis, beta, weights), null, default);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>The quick plan a time-limited solve reports first, whole demand placeable; for tests.</summary>
|
||||||
|
internal NestJobResult QuickPlanForTesting(NestJob job)
|
||||||
|
{
|
||||||
|
var types = PartCatalog.Build(job);
|
||||||
|
using var solver = new Solver(job, types, null, default, WorkBudget, DrawingFor, SheetPacked, BatchSelected, TailReplaced);
|
||||||
|
return BuildResult(job, types, solver.QuickPlan(types.Select(t => t.Part.Quantity).ToArray()), null, default);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Shared state for one solve: job, catalog, NFP caches, effort meter.</summary>
|
/// <summary>Shared state for one solve: job, catalog, NFP caches, effort meter.</summary>
|
||||||
private sealed class Solver(
|
private sealed class Solver(
|
||||||
NestJob job,
|
NestJob job,
|
||||||
@@ -322,7 +353,8 @@ public sealed class IrregularNestingEngine : INestingEngine
|
|||||||
Action? sheetPacked,
|
Action? sheetPacked,
|
||||||
Action<RepeatBatch>? batchSelected,
|
Action<RepeatBatch>? batchSelected,
|
||||||
Action<int>? tailReplaced,
|
Action<int>? tailReplaced,
|
||||||
Action<long>? tailReplanning = null
|
Action<long>? tailReplanning = null,
|
||||||
|
bool pruneTrials = true
|
||||||
) : IDisposable
|
) : IDisposable
|
||||||
{
|
{
|
||||||
public void Dispose()
|
public void Dispose()
|
||||||
@@ -350,7 +382,32 @@ public sealed class IrregularNestingEngine : INestingEngine
|
|||||||
return found;
|
return found;
|
||||||
}
|
}
|
||||||
|
|
||||||
public WorkCounter Work { get; } = new();
|
public WorkCounter Work { get; private set; } = new();
|
||||||
|
|
||||||
|
/// <summary>Whether the decode under way is <see cref="QuickPlan"/>'s, which offers no blocks.</summary>
|
||||||
|
private bool quick;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The first variant decoded without Lattice blocks, on a work meter of its own, so the
|
||||||
|
/// search after it runs as without it: what it adds to the shared caches (no-fit polygons,
|
||||||
|
/// pairs, clamps, boundaries) depends only on the job, never on when it was built.
|
||||||
|
/// </summary>
|
||||||
|
public Plan QuickPlan(int[] demand)
|
||||||
|
{
|
||||||
|
var meter = Work;
|
||||||
|
Work = new WorkCounter();
|
||||||
|
quick = true;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return Plan(demand, Variants[0].Axis, Variants[0].Beta);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Work = meter;
|
||||||
|
quick = false;
|
||||||
|
Alternatives = Array.Empty<Plan>();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private double Penalty => NestJobCost.UnplacedPartPenalty(job);
|
private double Penalty => NestJobCost.UnplacedPartPenalty(job);
|
||||||
|
|
||||||
@@ -676,6 +733,7 @@ public sealed class IrregularNestingEngine : INestingEngine
|
|||||||
}
|
}
|
||||||
|
|
||||||
var trials = new List<(SheetFill Fill, double Net)>();
|
var trials = new List<(SheetFill Fill, double Net)>();
|
||||||
|
var areaLeft = types.Sum(t => remaining[t.Index] * t.Area);
|
||||||
foreach (var stock in job.Plates)
|
foreach (var stock in job.Plates)
|
||||||
{
|
{
|
||||||
token.ThrowIfCancellationRequested();
|
token.ThrowIfCancellationRequested();
|
||||||
@@ -683,12 +741,16 @@ public sealed class IrregularNestingEngine : INestingEngine
|
|||||||
continue;
|
continue;
|
||||||
if (stock.Quantity is int available && used[stock.Id] >= available)
|
if (stock.Quantity is int available && used[stock.Id] >= available)
|
||||||
continue;
|
continue;
|
||||||
|
// Only once the block budget is spent: before that a skipped trial would leave
|
||||||
|
// block attempts and work unspent that a later trial could then use.
|
||||||
|
if (pruneTrials && finishers == null && Work.Value >= workBudget && CannotWin(stock, trials, areaLeft))
|
||||||
|
continue;
|
||||||
progress?.Report(new NestJobProgress(NestJobStage.EvaluatingCandidate, stock.Id, sheets.Count, 0, 0));
|
progress?.Report(new NestJobProgress(NestJobStage.EvaluatingCandidate, stock.Id, sheets.Count, 0, 0));
|
||||||
// Grouped fills pack groups from singles and pairs: Fill blocks cost far more per
|
// Grouped fills pack groups from singles and pairs: Fill blocks cost far more per
|
||||||
// fill there and gave no denser groups. A banded fill's bands are Fill patterns
|
// fill there and gave no denser groups. A banded fill's bands are Fill patterns
|
||||||
// already; its gap fill takes singles and pairs.
|
// already; its gap fill takes singles and pairs.
|
||||||
FrontierPacker Packer(IReadOnlyList<int>? ranks, double? reach) => new(types, CacheFor(stock),
|
FrontierPacker Packer(IReadOnlyList<int>? ranks, double? reach) => new(types, CacheFor(stock),
|
||||||
PairsFor(stock), stock, axis, beta, Work, grouped || banded ? null : BlocksFor(stock), ClampsFor(stock), BoundaryFor(stock),
|
PairsFor(stock), stock, axis, beta, Work, grouped || banded || quick ? null : BlocksFor(stock), ClampsFor(stock), BoundaryFor(stock),
|
||||||
weights, ranks, reach);
|
weights, ranks, reach);
|
||||||
var fill = banded
|
var fill = banded
|
||||||
? Banded(stock, remaining, weights, Packer)
|
? Banded(stock, remaining, weights, Packer)
|
||||||
@@ -773,6 +835,27 @@ public sealed class IrregularNestingEngine : INestingEngine
|
|||||||
|
|
||||||
return new Run(sheets, net, reason);
|
return new Run(sheets, net, reason);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Whether a trial of <paramref name="stock"/> could neither be chosen nor change the
|
||||||
|
/// choice, so the decode may skip it: its least possible net cost (the whole sheet, less
|
||||||
|
/// full salvage credit) already exceeds the best estimate so far, and over the remaining
|
||||||
|
/// part area it cannot have a better cost ratio than the best so far. Later trials only
|
||||||
|
/// lower the ratio and the estimates, so the decode picks the same sheet without it.
|
||||||
|
/// </summary>
|
||||||
|
private bool CannotWin(NestPlateStock stock, List<(SheetFill Fill, double Net)> trials, double areaLeft)
|
||||||
|
{
|
||||||
|
if (trials.Count == 0 || stock.Cost < 0 || areaLeft <= 0)
|
||||||
|
return false;
|
||||||
|
var rate = job.Options.SalvageRate != 0 && job.Options.MinimumSalvageDimension > 0 ? job.Options.SalvageRate : 0;
|
||||||
|
if (rate is < 0 or > 1)
|
||||||
|
return false;
|
||||||
|
var least = (stock.Cost ?? stock.Area) * (1 - rate);
|
||||||
|
var ratio = trials.Min(t => t.Net / System.Math.Max(t.Fill.PartArea, 1e-12));
|
||||||
|
var estimate = trials.Min(t => t.Net + System.Math.Max(0, areaLeft - t.Fill.PartArea) * ratio);
|
||||||
|
const double Margin = 1 + 1e-9;
|
||||||
|
return least > estimate * Margin && least >= ratio * areaLeft * Margin;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private sealed record Run(IReadOnlyList<SheetFill> Sheets, double Net, NestJobStopReason Reason);
|
private sealed record Run(IReadOnlyList<SheetFill> Sheets, double Net, NestJobStopReason Reason);
|
||||||
|
|||||||
@@ -28,7 +28,10 @@ namespace OpenNest.Engine.Strategies
|
|||||||
{
|
{
|
||||||
var comparer = context.Policy?.Comparer;
|
var comparer = context.Policy?.Comparer;
|
||||||
var dedup = GridDedup.GetOrCreate(context.SharedState);
|
var dedup = GridDedup.GetOrCreate(context.SharedState);
|
||||||
var filler = new PairFiller(context.Plate, comparer, dedup);
|
var filler = new PairFiller(context.Plate, comparer, dedup)
|
||||||
|
{
|
||||||
|
StripeConvergence = StripeConvergenceCache.GetOrCreate(context.SharedState),
|
||||||
|
};
|
||||||
var result = filler.Fill(
|
var result = filler.Fill(
|
||||||
context.Item,
|
context.Item,
|
||||||
context.WorkArea,
|
context.WorkArea,
|
||||||
|
|||||||
@@ -0,0 +1,195 @@
|
|||||||
|
using OpenNest.Engine;
|
||||||
|
using OpenNest.Engine.BestFit;
|
||||||
|
using OpenNest.Engine.Fill;
|
||||||
|
using OpenNest.Engine.Strategies;
|
||||||
|
using OpenNest.Geometry;
|
||||||
|
using OpenNest.Tests.BestFit;
|
||||||
|
|
||||||
|
namespace OpenNest.Tests.Fill;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The pair filler ranks grids before their final overlap checks run and checks only those it
|
||||||
|
/// needs (<see cref="PairFiller.CompareByCount"/>); the stripe filler reuses convergences
|
||||||
|
/// (<see cref="StripeConvergenceCache"/>). Both must leave every layout exactly as computing
|
||||||
|
/// everything up front would.
|
||||||
|
/// </summary>
|
||||||
|
[Collection(nameof(FillCacheCollection))]
|
||||||
|
public class DeferredGridCheckTests
|
||||||
|
{
|
||||||
|
private const double Spacing = 0.5;
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Resolve_ReturnsExactlyWhatFillReturns()
|
||||||
|
{
|
||||||
|
foreach (var (area, pattern, direction) in GridCases())
|
||||||
|
{
|
||||||
|
var expected = new FillLinear(area, Spacing).Fill(pattern, direction);
|
||||||
|
var actual = new FillLinear(area, Spacing).FillDeferred(pattern, direction).Resolve();
|
||||||
|
Assert.Equal(Poses(expected), Poses(actual));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void CompareByCount_SortsLikeCheckedCounts_AndSkipsChecks()
|
||||||
|
{
|
||||||
|
var cases = GridCases();
|
||||||
|
var expectedFallbacks = 0;
|
||||||
|
var skipped = 0;
|
||||||
|
|
||||||
|
for (var seed = 0; seed < 25; seed++)
|
||||||
|
{
|
||||||
|
var order = Enumerable.Range(0, cases.Count).ToList();
|
||||||
|
var random = new Random(seed);
|
||||||
|
for (var i = order.Count - 1; i > 0; i--)
|
||||||
|
{
|
||||||
|
var j = random.Next(i + 1);
|
||||||
|
(order[i], order[j]) = (order[j], order[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
var eager = order
|
||||||
|
.Select(index =>
|
||||||
|
{
|
||||||
|
var (area, pattern, direction) = cases[index];
|
||||||
|
return (Index: index, Parts: new FillLinear(area, Spacing).Fill(pattern, direction));
|
||||||
|
})
|
||||||
|
.ToList();
|
||||||
|
eager.Sort((a, b) => b.Parts.Count.CompareTo(a.Parts.Count));
|
||||||
|
|
||||||
|
var indexOf = new Dictionary<FillLinear.DeferredGrid, int>(ReferenceEqualityComparer.Instance);
|
||||||
|
var lazy = new List<FillLinear.DeferredGrid>();
|
||||||
|
foreach (var index in order)
|
||||||
|
{
|
||||||
|
var (area, pattern, direction) = cases[index];
|
||||||
|
var grid = new FillLinear(area, Spacing).FillDeferred(pattern, direction);
|
||||||
|
if (grid.IsPending && grid.Count != grid.FallbackCount)
|
||||||
|
{
|
||||||
|
var tiled = grid.Count;
|
||||||
|
var checkedCount = new FillLinear(area, Spacing).Fill(pattern, direction).Count;
|
||||||
|
if (checkedCount != tiled)
|
||||||
|
expectedFallbacks++;
|
||||||
|
}
|
||||||
|
indexOf.Add(grid, index);
|
||||||
|
lazy.Add(grid);
|
||||||
|
}
|
||||||
|
PairFiller.SortByCount(lazy);
|
||||||
|
|
||||||
|
Assert.Equal(eager.Select(e => e.Index), lazy.Select(g => indexOf[g]));
|
||||||
|
skipped += lazy.Count(g => g.IsPending);
|
||||||
|
|
||||||
|
for (var k = 0; k < lazy.Count; k++)
|
||||||
|
Assert.Equal(Poses(eager[k].Parts), Poses(lazy[k].Resolve()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// The fixture holds grids whose check fails and changes their count, and the ranking
|
||||||
|
// left some checks unrun.
|
||||||
|
Assert.True(expectedFallbacks > 0);
|
||||||
|
Assert.True(skipped > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void StripeConvergenceCache_HitsReproduceTheConvergedLayouts()
|
||||||
|
{
|
||||||
|
var drawing = TestHelpers.MakeLShapeDrawing();
|
||||||
|
var bestFits = new List<BestFitResult>
|
||||||
|
{
|
||||||
|
MakePair(drawing, 0, new Vector(10.5, 0)),
|
||||||
|
MakePair(drawing, System.Math.PI, new Vector(10.5, 10)),
|
||||||
|
};
|
||||||
|
|
||||||
|
List<Part> Run(StripeConvergenceCache cache, NestDirection axis, int maxQuantity)
|
||||||
|
{
|
||||||
|
var context = new FillContext
|
||||||
|
{
|
||||||
|
Item = new NestItem { Drawing = drawing, Quantity = maxQuantity },
|
||||||
|
WorkArea = new Box(0, 0, 97.5, 47.25),
|
||||||
|
Plate = new Plate(47.25, 97.5) { PartSpacing = Spacing },
|
||||||
|
MaxQuantity = maxQuantity,
|
||||||
|
};
|
||||||
|
context.SharedState["BestFits"] = bestFits;
|
||||||
|
if (cache != null)
|
||||||
|
context.SharedState[StripeConvergenceCache.SharedStateKey] = cache;
|
||||||
|
return new StripeFiller(context, axis) { CompleteStripesOnly = true }.Fill();
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var maxQuantity in new[] { 0, 30 })
|
||||||
|
{
|
||||||
|
foreach (var axis in new[] { NestDirection.Horizontal, NestDirection.Vertical })
|
||||||
|
{
|
||||||
|
var cold = Run(null, axis, maxQuantity);
|
||||||
|
var cache = new StripeConvergenceCache();
|
||||||
|
var filling = Run(cache, axis, maxQuantity);
|
||||||
|
var entries = cache.Count;
|
||||||
|
var warm = Run(cache, axis, maxQuantity);
|
||||||
|
|
||||||
|
Assert.NotEmpty(cold);
|
||||||
|
Assert.True(entries > 0);
|
||||||
|
Assert.Equal(entries, cache.Count);
|
||||||
|
Assert.Equal(Poses(cold), Poses(filling));
|
||||||
|
Assert.Equal(Poses(cold), Poses(warm));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Grids across work areas, both directions and three patterns: a single concave part, a
|
||||||
|
/// valid pair of it, and a pair of overlapping copies whose checks fail. At widths 16.75 and
|
||||||
|
/// 25.75 the overlapping pair's fallback holds fewer and more parts than its tiling.
|
||||||
|
/// </summary>
|
||||||
|
private static List<(Box Area, Pattern Pattern, NestDirection Direction)> GridCases()
|
||||||
|
{
|
||||||
|
var concave = FillExtentsTests.MakeFixture("concave");
|
||||||
|
var single = new Pattern();
|
||||||
|
single.Parts.Add(Part.CreateAtOrigin(concave));
|
||||||
|
single.UpdateBounds();
|
||||||
|
|
||||||
|
var first = Part.CreateAtOrigin(concave);
|
||||||
|
var second = Part.CreateAtOrigin(concave, System.Math.PI);
|
||||||
|
second.Offset(new Vector(10.5, 0));
|
||||||
|
var pair = new Pattern();
|
||||||
|
pair.Parts.AddRange(new[] { first, second });
|
||||||
|
pair.UpdateBounds();
|
||||||
|
|
||||||
|
var overlapping = new Pattern();
|
||||||
|
overlapping.Parts.AddRange(new[] { first, first.CloneAtOffset(new Vector(0.25, 0.25)) });
|
||||||
|
overlapping.UpdateBounds();
|
||||||
|
Assert.True(FillHelpers.HasOverlappingParts(overlapping.Parts));
|
||||||
|
|
||||||
|
var cases = new List<(Box, Pattern, NestDirection)>();
|
||||||
|
foreach (var length in new[] { 21.0, 30.0, 40.0 })
|
||||||
|
foreach (var width in new[] { 12.0, 16.75, 25.75 })
|
||||||
|
foreach (var pattern in new[] { single, pair, overlapping })
|
||||||
|
foreach (var direction in new[] { NestDirection.Horizontal, NestDirection.Vertical })
|
||||||
|
cases.Add((new Box(0, 0, length, width), pattern, direction));
|
||||||
|
return cases;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static BestFitResult MakePair(Drawing drawing, double rotation, Vector offset)
|
||||||
|
{
|
||||||
|
var bounds = drawing.Program.BoundingBox();
|
||||||
|
return new BestFitResult
|
||||||
|
{
|
||||||
|
Candidate = new PairCandidate
|
||||||
|
{
|
||||||
|
Drawing = drawing,
|
||||||
|
Part2Rotation = rotation,
|
||||||
|
Part2Offset = offset,
|
||||||
|
Spacing = Spacing,
|
||||||
|
},
|
||||||
|
BoundingWidth = bounds.Length + offset.X,
|
||||||
|
BoundingHeight = bounds.Width + offset.Y,
|
||||||
|
OptimalRotation = 0,
|
||||||
|
Keep = true,
|
||||||
|
Reason = "Valid",
|
||||||
|
HullAngles = new List<double>(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<(long X, long Y, long Rotation)> Poses(List<Part> parts) =>
|
||||||
|
parts
|
||||||
|
.Select(p => (
|
||||||
|
BitConverter.DoubleToInt64Bits(p.Location.X),
|
||||||
|
BitConverter.DoubleToInt64Bits(p.Location.Y),
|
||||||
|
BitConverter.DoubleToInt64Bits(p.Rotation)
|
||||||
|
))
|
||||||
|
.ToList();
|
||||||
|
}
|
||||||
@@ -168,11 +168,12 @@ public class PartOverlapCheckerTests
|
|||||||
var actual = WorldPolygon(checker, p);
|
var actual = WorldPolygon(checker, p);
|
||||||
Assert.Equal(PolygonBits(expected), PolygonBits(actual));
|
Assert.Equal(PolygonBits(expected), PolygonBits(actual));
|
||||||
// Cached triangles equal a fresh triangulation of the pre-change world polygon.
|
// Cached triangles equal a fresh triangulation of the pre-change world polygon.
|
||||||
|
// The checker keeps them as clip triangles: each polygon's open vertices and box.
|
||||||
var expectedTriangles = Collision.Triangulate(expected);
|
var expectedTriangles = Collision.Triangulate(expected);
|
||||||
var actualTriangles = WorldTriangles(checker, p);
|
var actualTriangles = WorldTriangles(checker, p);
|
||||||
Assert.Equal(expectedTriangles.Count, actualTriangles.Count);
|
Assert.Equal(expectedTriangles.Count, actualTriangles.Count);
|
||||||
for (var t = 0; t < expectedTriangles.Count; t++)
|
for (var t = 0; t < expectedTriangles.Count; t++)
|
||||||
Assert.Equal(PolygonBits(expectedTriangles[t]), PolygonBits(actualTriangles[t]));
|
Assert.Equal(ClipBits(expectedTriangles[t]), ClipBits(actualTriangles[t]));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -367,8 +368,25 @@ public class PartOverlapCheckerTests
|
|||||||
private static Polygon WorldPolygon(PartOverlapChecker checker, Part part) =>
|
private static Polygon WorldPolygon(PartOverlapChecker checker, Part part) =>
|
||||||
(Polygon)PreparedPartMember(checker, part, "Polygon");
|
(Polygon)PreparedPartMember(checker, part, "Polygon");
|
||||||
|
|
||||||
private static List<Polygon> WorldTriangles(PartOverlapChecker checker, Part part) =>
|
private static List<CollisionTriangle> WorldTriangles(PartOverlapChecker checker, Part part) =>
|
||||||
((Func<List<Polygon>>)PreparedPartMember(checker, part, "Triangles"))();
|
((Func<List<CollisionTriangle>>)PreparedPartMember(checker, part, "Triangles"))();
|
||||||
|
|
||||||
|
/// <summary>A triangle polygon as the clip loop reads it: open vertices, then box sides.</summary>
|
||||||
|
private static long[] ClipBits(Polygon triangle)
|
||||||
|
{
|
||||||
|
var open = triangle.Vertices.ToList();
|
||||||
|
if (open.Count > 1 && open[0].X == open[^1].X && open[0].Y == open[^1].Y)
|
||||||
|
open.RemoveAt(open.Count - 1);
|
||||||
|
var box = triangle.BoundingBox;
|
||||||
|
return open.SelectMany(v => new[] { v.X, v.Y })
|
||||||
|
.Concat(new[] { box.Left, box.Right, box.Bottom, box.Top })
|
||||||
|
.Select(BitConverter.DoubleToInt64Bits).ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static long[] ClipBits(CollisionTriangle triangle) =>
|
||||||
|
Enumerable.Range(0, triangle.Count).SelectMany(i => new[] { triangle[i].X, triangle[i].Y })
|
||||||
|
.Concat(new[] { triangle.Left, triangle.Right, triangle.Bottom, triangle.Top })
|
||||||
|
.Select(BitConverter.DoubleToInt64Bits).ToArray();
|
||||||
|
|
||||||
private static object PreparedPartMember(PartOverlapChecker checker, Part part, string property)
|
private static object PreparedPartMember(PartOverlapChecker checker, Part part, string property)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -133,6 +133,103 @@ public class CollisionOverlapOnlyTests
|
|||||||
Assert.Equal(new[] { "a", "c" }, resolved);
|
Assert.Equal(new[] { "a", "c" }, resolved);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The clip triangles PartOverlapChecker caches give the legacy verdicts, reused across many
|
||||||
|
/// pairs, and read every triangle exactly as the polygon triangulation does.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public void SeededClippingTriangles_ReusedAcrossPairs_MatchLegacyVerdicts()
|
||||||
|
{
|
||||||
|
var random = new Random(17112026);
|
||||||
|
var decisions = 0;
|
||||||
|
var overlaps = 0;
|
||||||
|
var boxOverlapClear = 0;
|
||||||
|
for (var group = 0; group < 40; group++)
|
||||||
|
{
|
||||||
|
var polygons = new List<Polygon>();
|
||||||
|
var shapeA = Make(random, group % 6);
|
||||||
|
var shapeB = Make(random, (group / 6) % 6);
|
||||||
|
for (var sample = 0; sample < 25; sample++)
|
||||||
|
{
|
||||||
|
var (ax, ay, bx, by) = Offsets(random, shapeA, shapeB, sample);
|
||||||
|
var dx = random.NextDouble() * 4 - ax;
|
||||||
|
var dy = random.NextDouble() * 4 - ay;
|
||||||
|
polygons.Add(Move(shapeA, ax + dx, ay + dy));
|
||||||
|
polygons.Add(Move(shapeB, bx + dx, by + dy));
|
||||||
|
}
|
||||||
|
var triangles = polygons.Select(p => new Lazy<List<CollisionTriangle>>(() => Collision.TriangulateForClipping(p)))
|
||||||
|
.ToArray();
|
||||||
|
for (var i = 0; i < polygons.Count; i++)
|
||||||
|
for (var j = i + 1; j < polygons.Count; j++)
|
||||||
|
{
|
||||||
|
var expected = LegacyCollision.HasOverlap(polygons[i], polygons[j]);
|
||||||
|
var ti = triangles[i];
|
||||||
|
var tj = triangles[j];
|
||||||
|
var actual = Collision.HasOverlapTriangulated(polygons[i], () => ti.Value, polygons[j], () => tj.Value);
|
||||||
|
Assert.True(expected == actual, $"group={group} i={i} j={j} expected={expected}");
|
||||||
|
decisions++;
|
||||||
|
if (expected)
|
||||||
|
overlaps++;
|
||||||
|
else if (BoxesOverlap(polygons[i].BoundingBox, polygons[j].BoundingBox))
|
||||||
|
boxOverlapClear++;
|
||||||
|
}
|
||||||
|
for (var i = 0; i < polygons.Count; i++)
|
||||||
|
if (triangles[i].IsValueCreated)
|
||||||
|
Assert.Equal(ClipBits(Collision.Triangulate(polygons[i])), ClipBits(triangles[i].Value));
|
||||||
|
}
|
||||||
|
output.WriteLine($"clip-triangle decisions={decisions}; overlaps={overlaps}; bbox-overlap but clear={boxOverlapClear}");
|
||||||
|
Assert.Equal(40 * 50 * 49 / 2, decisions);
|
||||||
|
Assert.True(overlaps > 10000);
|
||||||
|
Assert.True(boxOverlapClear > 2000);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Ears whose neighbors coincide exactly, or only within the fuzzy equality that closes a
|
||||||
|
/// triangle polygon, keep the polygon's open vertices and bounds.
|
||||||
|
/// </summary>
|
||||||
|
[Theory]
|
||||||
|
[InlineData(0.0)]
|
||||||
|
[InlineData(1e-12)]
|
||||||
|
[InlineData(1e-6)]
|
||||||
|
public void TriangulateForClipping_DegenerateEars_MatchTriangulateBitwise(double offset)
|
||||||
|
{
|
||||||
|
var polygons = new[]
|
||||||
|
{
|
||||||
|
// A spike back onto its own vertex, and collinear runs.
|
||||||
|
Ring((0, 0), (4, 0), (4, 2), (2, 2), (2 + offset, 3), (2, 2), (0, 2)),
|
||||||
|
Ring((0, 0), (1, 0), (2, 0), (3, offset), (3, 1), (2, 1), (1, 1 + offset), (0, 1)),
|
||||||
|
Ring((0, 0), (5, 0), (5, 5), (5 + offset, 5), (0, 5)),
|
||||||
|
Move(Make(new Random(3), 4), 123.456, -78.9),
|
||||||
|
};
|
||||||
|
foreach (var polygon in polygons)
|
||||||
|
{
|
||||||
|
var expected = ClipBits(Collision.Triangulate(polygon));
|
||||||
|
Assert.Equal(expected, ClipBits(Collision.TriangulateForClipping(polygon)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Each triangle as the clip loop reads it: open vertices, then box sides.</summary>
|
||||||
|
private static long[] ClipBits(List<Polygon> triangles) => triangles
|
||||||
|
.SelectMany(t =>
|
||||||
|
{
|
||||||
|
var open = t.Vertices.ToList();
|
||||||
|
if (open.Count > 1 && open[0].X == open[^1].X && open[0].Y == open[^1].Y)
|
||||||
|
open.RemoveAt(open.Count - 1);
|
||||||
|
var box = t.BoundingBox;
|
||||||
|
return new[] { (long)open.Count }
|
||||||
|
.Concat(open.SelectMany(VectorBits))
|
||||||
|
.Concat(new[] { Bits(box.Left), Bits(box.Right), Bits(box.Bottom), Bits(box.Top) });
|
||||||
|
})
|
||||||
|
.Prepend(triangles.Count)
|
||||||
|
.ToArray();
|
||||||
|
|
||||||
|
private static long[] ClipBits(List<CollisionTriangle> triangles) => triangles
|
||||||
|
.SelectMany(t => new[] { (long)t.Count }
|
||||||
|
.Concat(Enumerable.Range(0, t.Count).SelectMany(i => VectorBits(t[i])))
|
||||||
|
.Concat(new[] { Bits(t.Left), Bits(t.Right), Bits(t.Bottom), Bits(t.Top) }))
|
||||||
|
.Prepend(triangles.Count)
|
||||||
|
.ToArray();
|
||||||
|
|
||||||
private static long[] TriangleBits(List<Polygon> triangles) => triangles
|
private static long[] TriangleBits(List<Polygon> triangles) => triangles
|
||||||
.SelectMany(t => new[] { t.BoundingBox.X, t.BoundingBox.Y, t.BoundingBox.Length, t.BoundingBox.Width }
|
.SelectMany(t => new[] { t.BoundingBox.X, t.BoundingBox.Y, t.BoundingBox.Length, t.BoundingBox.Width }
|
||||||
.Concat(t.Vertices.SelectMany(v => new[] { v.X, v.Y })))
|
.Concat(t.Vertices.SelectMany(v => new[] { v.X, v.Y })))
|
||||||
|
|||||||
@@ -17,6 +17,8 @@ public class ShapeCutDirectionTests
|
|||||||
{
|
{
|
||||||
var shapes = new ShapeDefinition[]
|
var shapes = new ShapeDefinition[]
|
||||||
{
|
{
|
||||||
|
new AngleShape(),
|
||||||
|
new ChannelShape(),
|
||||||
new CircleShape(),
|
new CircleShape(),
|
||||||
new IsoscelesTriangleShape(),
|
new IsoscelesTriangleShape(),
|
||||||
new LShape(),
|
new LShape(),
|
||||||
@@ -26,6 +28,7 @@ public class ShapeCutDirectionTests
|
|||||||
new RectangleShape(),
|
new RectangleShape(),
|
||||||
new RightTriangleShape(),
|
new RightTriangleShape(),
|
||||||
new RingShape(),
|
new RingShape(),
|
||||||
|
new RolledPlateShape(),
|
||||||
new RoundedRectangleShape(),
|
new RoundedRectangleShape(),
|
||||||
new TShape(),
|
new TShape(),
|
||||||
new TrapezoidShape(),
|
new TrapezoidShape(),
|
||||||
@@ -75,6 +78,9 @@ public class ShapeCutDirectionTests
|
|||||||
Assert.True(perimeter >= 0, $"{name}: no perimeter");
|
Assert.True(perimeter >= 0, $"{name}: no perimeter");
|
||||||
for (var i = 0; i < contours.Count; i++)
|
for (var i = 0; i < contours.Count; i++)
|
||||||
{
|
{
|
||||||
|
// Marks such as etched bend lines are open: they have no winding.
|
||||||
|
if (contours[i].IsMark)
|
||||||
|
continue;
|
||||||
var area = ContourWinding.SignedArea(contours[i]);
|
var area = ContourWinding.SignedArea(contours[i]);
|
||||||
if (i == perimeter)
|
if (i == perimeter)
|
||||||
Assert.True(area < 0, $"{name}: outside is not clockwise");
|
Assert.True(area < 0, $"{name}: outside is not clockwise");
|
||||||
@@ -86,6 +92,7 @@ public class ShapeCutDirectionTests
|
|||||||
/// <summary>Each contour's winding sign, in a stable order so reordering does not matter.</summary>
|
/// <summary>Each contour's winding sign, in a stable order so reordering does not matter.</summary>
|
||||||
private static List<int> Directions(Program program) =>
|
private static List<int> Directions(Program program) =>
|
||||||
PostContours.Extract(program, Vector.Zero)
|
PostContours.Extract(program, Vector.Zero)
|
||||||
|
.Where(c => !c.IsMark)
|
||||||
.Select(c => System.Math.Sign(ContourWinding.SignedArea(c)))
|
.Select(c => System.Math.Sign(ContourWinding.SignedArea(c)))
|
||||||
.OrderBy(s => s)
|
.OrderBy(s => s)
|
||||||
.ToList();
|
.ToList();
|
||||||
|
|||||||
@@ -20,7 +20,10 @@ public class ShapeDimensionTests
|
|||||||
{
|
{
|
||||||
var shape = (ShapeDefinition)Activator.CreateInstance(shapeType)!;
|
var shape = (ShapeDefinition)Activator.CreateInstance(shapeType)!;
|
||||||
shape.SetPreviewDefaults();
|
shape.SetPreviewDefaults();
|
||||||
var dimensions = shape.GetDimensions();
|
// A side view's dimensions show parameters too, each once across both views.
|
||||||
|
var dimensions = shape.GetDimensions()
|
||||||
|
.Concat(shape.GetSideView()?.Dimensions ?? Array.Empty<ShapeDimension>())
|
||||||
|
.ToList();
|
||||||
|
|
||||||
Assert.NotEmpty(dimensions);
|
Assert.NotEmpty(dimensions);
|
||||||
Assert.Equal(dimensions.Count, dimensions.Select(d => d.Property).Distinct().Count());
|
Assert.Equal(dimensions.Count, dimensions.Select(d => d.Property).Distinct().Count());
|
||||||
|
|||||||
@@ -0,0 +1,182 @@
|
|||||||
|
using OpenNest.Bending;
|
||||||
|
using OpenNest.CNC;
|
||||||
|
using OpenNest.Geometry;
|
||||||
|
using OpenNest.Shapes;
|
||||||
|
|
||||||
|
namespace OpenNest.Tests.Shapes;
|
||||||
|
|
||||||
|
public class SheetMetalShapeTests
|
||||||
|
{
|
||||||
|
// 90° bend at 5/16 inside radius, 1/8 thick, K 0.42.
|
||||||
|
private static readonly double Allowance = System.Math.PI / 2 * (0.3125 + 0.42 * 0.125);
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Angle_BlankIsTheDevelopedWidthByTheLength()
|
||||||
|
{
|
||||||
|
var shape = new AngleShape();
|
||||||
|
shape.SetPreviewDefaults();
|
||||||
|
|
||||||
|
var box = shape.GetDrawing().Program.BoundingBox();
|
||||||
|
|
||||||
|
// Legs' flats: 2 - 1/8 - 5/16 and 4 - 1/8 - 5/16.
|
||||||
|
var expected = 1.5625 + 3.5625 + Allowance;
|
||||||
|
Assert.Equal(expected, shape.FlatLength, 9);
|
||||||
|
Assert.Equal(12, box.Length, 6);
|
||||||
|
Assert.Equal(expected, box.Width, 6);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Angle_BendsUpAcrossTheBlankFromTheShorterLeg()
|
||||||
|
{
|
||||||
|
var shape = new AngleShape();
|
||||||
|
shape.SetPreviewDefaults();
|
||||||
|
|
||||||
|
var bend = Assert.Single(shape.GetDrawing().Bends);
|
||||||
|
|
||||||
|
var y = 1.5625 + Allowance / 2;
|
||||||
|
Assert.Equal(y, shape.BendLineDim, 9);
|
||||||
|
Assert.Equal(new Vector(0, y), bend.StartPoint);
|
||||||
|
Assert.Equal(new Vector(12, y), bend.EndPoint);
|
||||||
|
Assert.Equal(BendDirection.Up, bend.Direction);
|
||||||
|
Assert.Equal(90, bend.Angle);
|
||||||
|
Assert.Equal(0.3125, bend.Radius);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Channel_BlankHasTwoBendsInFromEachSide()
|
||||||
|
{
|
||||||
|
var shape = new ChannelShape();
|
||||||
|
shape.SetPreviewDefaults();
|
||||||
|
|
||||||
|
var drawing = shape.GetDrawing();
|
||||||
|
var box = drawing.Program.BoundingBox();
|
||||||
|
|
||||||
|
// Sides' flats: 2 - 1/8 - 5/16 each; bottom: 4 - 2(1/8) - 2(5/16).
|
||||||
|
var expected = 1.5625 * 2 + 3.125 + Allowance * 2;
|
||||||
|
Assert.Equal(expected, shape.FlatLength, 9);
|
||||||
|
Assert.Equal(expected, box.Width, 6);
|
||||||
|
var lines = drawing.Bends.Select(b => b.StartPoint.Y).OrderBy(y => y).ToList();
|
||||||
|
var inset = 1.5625 + Allowance / 2;
|
||||||
|
Assert.Equal(2, lines.Count);
|
||||||
|
Assert.Equal(inset, lines[0], 9);
|
||||||
|
Assert.Equal(expected - inset, lines[1], 9);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void RolledPlate_BlankIsTheNeutralCircumference()
|
||||||
|
{
|
||||||
|
var shape = new RolledPlateShape { InsideDiameter = 10, Thickness = 0.25, KFactor = 0.5, Length = 24 };
|
||||||
|
|
||||||
|
var drawing = shape.GetDrawing();
|
||||||
|
var box = drawing.Program.BoundingBox();
|
||||||
|
|
||||||
|
var expected = System.Math.PI * 2 * (5 + 0.125);
|
||||||
|
Assert.Equal(expected, shape.FlatLength, 9);
|
||||||
|
Assert.Equal(24, box.Length, 6);
|
||||||
|
Assert.Equal(expected, box.Width, 6);
|
||||||
|
Assert.Empty(drawing.Bends);
|
||||||
|
Assert.Equal(10.5, shape.OutsideDiameter, 9);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void BendLines_AreEtchedOnTheBlank()
|
||||||
|
{
|
||||||
|
var shape = new ChannelShape();
|
||||||
|
shape.SetPreviewDefaults();
|
||||||
|
|
||||||
|
var etches = shape.GetDrawing().Program.Codes
|
||||||
|
.OfType<LinearMove>()
|
||||||
|
.Count(m => m.Layer == LayerType.Scribe);
|
||||||
|
|
||||||
|
// Each 12" bend line gets a 1" dash at either end.
|
||||||
|
Assert.Equal(4, etches);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Angle_LegNoLongerThanThicknessPlusRadius_DoesNotMakeAShape()
|
||||||
|
{
|
||||||
|
var shape = new AngleShape { OutsideWidth = 4, OutsideHeight = 0.4, Thickness = 0.125, InsideRadius = 0.3125, KFactor = 0.42, Length = 12 };
|
||||||
|
|
||||||
|
Assert.Throws<InvalidOperationException>(() => shape.GetDrawing());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void KFactorAboveOne_DoesNotMakeAShape()
|
||||||
|
{
|
||||||
|
var shape = new ChannelShape();
|
||||||
|
shape.SetPreviewDefaults();
|
||||||
|
shape.KFactor = 1.5;
|
||||||
|
|
||||||
|
Assert.Throws<InvalidOperationException>(() => shape.GetDrawing());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void AngleSideView_IsOneClosedSectionOfTheFormedAngle()
|
||||||
|
{
|
||||||
|
var shape = new AngleShape();
|
||||||
|
shape.SetPreviewDefaults();
|
||||||
|
|
||||||
|
var section = Assert.Single(ShapeBuilder.GetShapes(shape.GetSideView().Entities));
|
||||||
|
|
||||||
|
// Two legs' flats and a quarter annulus at the bend.
|
||||||
|
const double t = 0.125, ir = 0.3125, or = ir + t;
|
||||||
|
var expected = t * (4 - or) + t * (2 - or) + System.Math.PI / 4 * (or * or - ir * ir);
|
||||||
|
Assert.True(section.IsClosed());
|
||||||
|
Assert.Equal(expected, section.Area(), 1e-4);
|
||||||
|
var box = section.BoundingBox;
|
||||||
|
Assert.Equal(4, box.Length, 6);
|
||||||
|
Assert.Equal(2, box.Width, 6);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ChannelSideView_IsOneClosedSectionOfTheFormedChannel()
|
||||||
|
{
|
||||||
|
var shape = new ChannelShape();
|
||||||
|
shape.SetPreviewDefaults();
|
||||||
|
|
||||||
|
var section = Assert.Single(ShapeBuilder.GetShapes(shape.GetSideView().Entities));
|
||||||
|
|
||||||
|
// Two sides' and the bottom's flats and two quarter annuli at the bends.
|
||||||
|
const double t = 0.125, ir = 0.3125, or = ir + t;
|
||||||
|
var expected = t * (2 - or) * 2 + t * (4 - 2 * or) + System.Math.PI / 2 * (or * or - ir * ir);
|
||||||
|
Assert.True(section.IsClosed());
|
||||||
|
Assert.Equal(expected, section.Area(), 1e-4);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void SideViews_DimensionTheSizesTheBlankCannotShow()
|
||||||
|
{
|
||||||
|
var angle = new AngleShape();
|
||||||
|
angle.SetPreviewDefaults();
|
||||||
|
var rolled = new RolledPlateShape();
|
||||||
|
rolled.SetPreviewDefaults();
|
||||||
|
|
||||||
|
Assert.Equal(
|
||||||
|
new[] { nameof(AngleShape.OutsideWidth), nameof(AngleShape.OutsideHeight), nameof(AngleShape.Thickness), nameof(AngleShape.InsideRadius) },
|
||||||
|
angle.GetSideView().Dimensions.Select(d => d.Property));
|
||||||
|
var radius = angle.GetSideView().Dimensions.Single(d => d.Property == nameof(AngleShape.InsideRadius));
|
||||||
|
Assert.Equal(0.3125, radius.ArcRadius, 9);
|
||||||
|
Assert.Equal("R", radius.Prefix);
|
||||||
|
Assert.Equal(
|
||||||
|
new[] { nameof(RolledPlateShape.InsideDiameter), nameof(RolledPlateShape.Thickness) },
|
||||||
|
rolled.GetSideView().Dimensions.Select(d => d.Property));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void FlatShapes_HaveNoSideView()
|
||||||
|
{
|
||||||
|
Assert.Null(new RectangleShape { Length = 10, Width = 5 }.GetSideView());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GeneratedNames_DescribeThePart()
|
||||||
|
{
|
||||||
|
var angle = new AngleShape();
|
||||||
|
angle.SetPreviewDefaults();
|
||||||
|
var rolled = new RolledPlateShape();
|
||||||
|
rolled.SetPreviewDefaults();
|
||||||
|
|
||||||
|
Assert.Equal("Angle 4x2x0.125 x 12", angle.GenerateName());
|
||||||
|
Assert.Equal("Rolled Plate 10 ID x 0.188 x 12", rolled.GenerateName());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -42,9 +42,9 @@ public class DrawingLibraryFormTests
|
|||||||
Assert.Equal("Deburr both sides", notes.Text);
|
Assert.Equal("Deburr both sides", notes.Text);
|
||||||
|
|
||||||
quantity.Value = 3;
|
quantity.Value = 3;
|
||||||
Run(form.View.AddSelectedAsync());
|
Add(form);
|
||||||
quantity.Value = 2;
|
quantity.Value = 2;
|
||||||
Run(form.View.AddSelectedAsync());
|
Add(form);
|
||||||
|
|
||||||
Assert.Empty(messages);
|
Assert.Empty(messages);
|
||||||
var drawing = Assert.Single(nest.Drawings);
|
var drawing = Assert.Single(nest.Drawings);
|
||||||
@@ -57,6 +57,86 @@ public class DrawingLibraryFormTests
|
|||||||
"The drawing library dialog test did not complete.");
|
"The drawing library dialog test did not complete.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void EachAdd_ShowsTheBannerAndRaisesNestChangedWhileTheDialogIsOpen()
|
||||||
|
{
|
||||||
|
StaTestThread.Run(
|
||||||
|
() =>
|
||||||
|
{
|
||||||
|
var library = new FakeLibrary();
|
||||||
|
var record = library.Add("SYN-111", "Synthetic Steel", "Grade A", 0.25, Units.Inches, "");
|
||||||
|
var nest = MatchingNest();
|
||||||
|
var changed = new List<Drawing>();
|
||||||
|
|
||||||
|
using var form = new DrawingLibraryForm(library, Server, nest);
|
||||||
|
form.View.ShowMessage = (text, _, _) => throw new Xunit.Sdk.XunitException(text);
|
||||||
|
form.View.LoadPreview = (_, _) => Task.FromResult<Drawing>(null!);
|
||||||
|
form.NestChanged += (_, drawing) => changed.Add(drawing);
|
||||||
|
form.Show();
|
||||||
|
var grid = Field<DataGridView>(form, "drawingGrid");
|
||||||
|
var banner = Field<OpenNest.Controls.NoticeBanner>(form, "addedBanner");
|
||||||
|
var quantity = Field<NumericUpDown>(form, "quantityBox");
|
||||||
|
|
||||||
|
PumpUntilListed(grid, "the library page");
|
||||||
|
Assert.False(banner.Visible);
|
||||||
|
|
||||||
|
quantity.Value = 3;
|
||||||
|
Add(form);
|
||||||
|
var drawing = Assert.Single(nest.Drawings);
|
||||||
|
Assert.False(banner.InvokeRequired);
|
||||||
|
Assert.True(banner.Visible);
|
||||||
|
Assert.Equal($"Added 'SYN-111' revision {record.Revision} to the nest, quantity 3.", banner.Message);
|
||||||
|
Assert.Same(drawing, Assert.Single(changed));
|
||||||
|
|
||||||
|
quantity.Value = 2;
|
||||||
|
Add(form);
|
||||||
|
Assert.Equal("Added 2 more of 'SYN-111' to the nest (now 5 required).", banner.Message);
|
||||||
|
Assert.Equal(new[] { drawing, drawing }, changed);
|
||||||
|
|
||||||
|
// The In This Nest tab's quantity edits are listed behind the dialog too.
|
||||||
|
var nestGrid = Field<DataGridView>(form, "nestGrid");
|
||||||
|
Field<TabControl>(form, "tabControl").SelectedTab = Field<TabPage>(form, "nestTab");
|
||||||
|
nestGrid.CurrentCell = nestGrid.Rows[0].Cells["nestRequiredColumn"];
|
||||||
|
Assert.True(nestGrid.BeginEdit(true));
|
||||||
|
nestGrid.EditingControl!.Text = "7";
|
||||||
|
nestGrid.NotifyCurrentCellDirty(true);
|
||||||
|
Assert.True(nestGrid.EndEdit());
|
||||||
|
Assert.Equal(3, changed.Count);
|
||||||
|
Assert.Equal(7, drawing.Quantity.Required);
|
||||||
|
},
|
||||||
|
TestTimeout,
|
||||||
|
"The drawing library banner test did not complete.");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void RefusedAdd_ShowsNoBannerAndRaisesNothing()
|
||||||
|
{
|
||||||
|
StaTestThread.Run(
|
||||||
|
() =>
|
||||||
|
{
|
||||||
|
var library = new FakeLibrary();
|
||||||
|
library.Add("SYN-313", "Synthetic Steel", "Grade A", 0.25, Units.Millimeters, "");
|
||||||
|
var nest = MatchingNest();
|
||||||
|
var changed = 0;
|
||||||
|
|
||||||
|
using var form = new DrawingLibraryForm(library, Server, nest);
|
||||||
|
form.View.ShowMessage = (_, _, _) => DialogResult.OK;
|
||||||
|
form.View.LoadPreview = (_, _) => Task.FromResult<Drawing>(null!);
|
||||||
|
form.NestChanged += (_, _) => changed++;
|
||||||
|
form.Show();
|
||||||
|
var grid = Field<DataGridView>(form, "drawingGrid");
|
||||||
|
|
||||||
|
PumpUntilListed(grid, "the library page");
|
||||||
|
Add(form);
|
||||||
|
|
||||||
|
Assert.Empty(nest.Drawings);
|
||||||
|
Assert.False(Field<OpenNest.Controls.NoticeBanner>(form, "addedBanner").Visible);
|
||||||
|
Assert.Equal(0, changed);
|
||||||
|
},
|
||||||
|
TestTimeout,
|
||||||
|
"The drawing library refused-add banner test did not complete.");
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void SelectingADrawing_ShowsItsDetailsAndPreviewsItsGeometry()
|
public void SelectingADrawing_ShowsItsDetailsAndPreviewsItsGeometry()
|
||||||
{
|
{
|
||||||
@@ -122,7 +202,7 @@ public class DrawingLibraryFormTests
|
|||||||
|
|
||||||
PumpUntilListed(grid, "the library page");
|
PumpUntilListed(grid, "the library page");
|
||||||
Field<NumericUpDown>(form, "quantityBox").Value = 2;
|
Field<NumericUpDown>(form, "quantityBox").Value = 2;
|
||||||
Run(form.View.AddSelectedAsync());
|
Add(form);
|
||||||
Assert.Equal("In This Nest (2)", nestTab.Text);
|
Assert.Equal("In This Nest (2)", nestTab.Text);
|
||||||
Assert.Equal($"Revision {record.Revision}", nestGrid.Rows[1].Cells["nestLibraryColumn"].Value);
|
Assert.Equal($"Revision {record.Revision}", nestGrid.Rows[1].Cells["nestLibraryColumn"].Value);
|
||||||
Assert.Equal(2, nestGrid.Rows[1].Cells["nestRequiredColumn"].Value);
|
Assert.Equal(2, nestGrid.Rows[1].Cells["nestRequiredColumn"].Value);
|
||||||
@@ -183,9 +263,9 @@ public class DrawingLibraryFormTests
|
|||||||
PumpUntilListed(grid, "the unfiltered page");
|
PumpUntilListed(grid, "the unfiltered page");
|
||||||
Assert.Equal(("", "", (double?)null), (library.Queries[^1].MaterialName, library.Queries[^1].MaterialGrade, library.Queries[^1].Thickness));
|
Assert.Equal(("", "", (double?)null), (library.Queries[^1].MaterialName, library.Queries[^1].MaterialGrade, library.Queries[^1].Thickness));
|
||||||
|
|
||||||
Run(form.View.AddSelectedAsync());
|
Add(form);
|
||||||
Assert.Empty(nest.Drawings);
|
Assert.Empty(nest.Drawings);
|
||||||
Run(form.View.AddSelectedAsync());
|
Add(form);
|
||||||
|
|
||||||
Assert.Equal(2, messages.Count);
|
Assert.Equal(2, messages.Count);
|
||||||
Assert.Contains("thickness 0.1875 (nest 0.25)", messages[0]);
|
Assert.Contains("thickness 0.1875 (nest 0.25)", messages[0]);
|
||||||
@@ -213,7 +293,7 @@ public class DrawingLibraryFormTests
|
|||||||
var grid = Field<DataGridView>(form, "drawingGrid");
|
var grid = Field<DataGridView>(form, "drawingGrid");
|
||||||
|
|
||||||
PumpUntilListed(grid, "the library page");
|
PumpUntilListed(grid, "the library page");
|
||||||
Run(form.View.AddSelectedAsync());
|
Add(form);
|
||||||
|
|
||||||
Assert.Contains("millimeters", Assert.Single(messages));
|
Assert.Contains("millimeters", Assert.Single(messages));
|
||||||
Assert.Empty(nest.Drawings);
|
Assert.Empty(nest.Drawings);
|
||||||
@@ -262,7 +342,7 @@ public class DrawingLibraryFormTests
|
|||||||
Assert.Equal("Yes", grid.Rows[0].Cells["cutFirstColumn"].Value);
|
Assert.Equal("Yes", grid.Rows[0].Cells["cutFirstColumn"].Value);
|
||||||
|
|
||||||
SelectFirstRow(grid);
|
SelectFirstRow(grid);
|
||||||
Run(form.View.AddSelectedAsync());
|
Add(form);
|
||||||
Assert.True(Assert.Single(nest.Drawings).CutFirst);
|
Assert.True(Assert.Single(nest.Drawings).CutFirst);
|
||||||
},
|
},
|
||||||
TestTimeout,
|
TestTimeout,
|
||||||
@@ -524,7 +604,7 @@ public class DrawingLibraryFormTests
|
|||||||
Assert.DoesNotContain(Field<TabPage>(form, "nestTab"), Field<TabControl>(form, "tabControl").TabPages.Cast<TabPage>());
|
Assert.DoesNotContain(Field<TabPage>(form, "nestTab"), Field<TabControl>(form, "tabControl").TabPages.Cast<TabPage>());
|
||||||
Assert.False(Field<Button>(form, "addButton").Visible);
|
Assert.False(Field<Button>(form, "addButton").Visible);
|
||||||
Assert.Equal("Edit Drawing...", Field<Button>(form, "editButton").Text);
|
Assert.Equal("Edit Drawing...", Field<Button>(form, "editButton").Text);
|
||||||
Run(form.View.AddSelectedAsync());
|
Add(form);
|
||||||
Assert.Empty(library.Downloads);
|
Assert.Empty(library.Downloads);
|
||||||
|
|
||||||
typeof(DataGridView).GetMethod("OnCellDoubleClick", BindingFlags.Instance | BindingFlags.NonPublic)!
|
typeof(DataGridView).GetMethod("OnCellDoubleClick", BindingFlags.Instance | BindingFlags.NonPublic)!
|
||||||
@@ -635,6 +715,17 @@ public class DrawingLibraryFormTests
|
|||||||
Material = new Material("Synthetic Steel", "Grade A"),
|
Material = new Material("Synthetic Steel", "Grade A"),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Adds the selected drawing and waits for it. Each DoEvents leaves a plain synchronization
|
||||||
|
/// context on the thread, so the WinForms one is put back first: as in the dialog's own
|
||||||
|
/// message loop, the add's awaits then return to the UI thread rather than the thread pool.
|
||||||
|
/// </summary>
|
||||||
|
private static void Add(DrawingLibraryForm form)
|
||||||
|
{
|
||||||
|
SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext());
|
||||||
|
Run(form.View.AddSelectedAsync());
|
||||||
|
}
|
||||||
|
|
||||||
// A faulted task rethrows here, so a failed step reports its own error instead of a later timeout.
|
// A faulted task rethrows here, so a failed step reports its own error instead of a later timeout.
|
||||||
private static void Run(Task task)
|
private static void Run(Task task)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -27,7 +27,11 @@ public class DrawingLibraryGridFormTests
|
|||||||
Run(form.CheckAllPagesAsync());
|
Run(form.CheckAllPagesAsync());
|
||||||
|
|
||||||
Assert.Equal(DrawingLibraryGridForm.PageSize + 1, form.DrawingsShown);
|
Assert.Equal(DrawingLibraryGridForm.PageSize + 1, form.DrawingsShown);
|
||||||
var problem = Assert.Single(form.Problems);
|
// Slow-timing reports depend on the machine (a loaded CI runner paints a tile
|
||||||
|
// past 500 ms); a hang is still reported as a failure.
|
||||||
|
var failures = form.Problems.Where(
|
||||||
|
p => !p.Problem.StartsWith("Slow ", StringComparison.Ordinal));
|
||||||
|
var problem = Assert.Single(failures);
|
||||||
Assert.Same(missing, problem.Record);
|
Assert.Same(missing, problem.Record);
|
||||||
Assert.Equal("Revision not on the server", problem.Problem);
|
Assert.Equal("Revision not on the server", problem.Problem);
|
||||||
Assert.Equal(new[] { 0, DrawingLibraryGridForm.PageSize }, library.Offsets.Skip(library.Offsets.Count - 2));
|
Assert.Equal(new[] { 0, DrawingLibraryGridForm.PageSize }, library.Offsets.Skip(library.Offsets.Count - 2));
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
using System.Reflection;
|
||||||
|
using System.Windows.Forms;
|
||||||
|
using OpenNest.Controls;
|
||||||
|
using OpenNest.Forms;
|
||||||
|
using OpenNest.Shapes;
|
||||||
|
|
||||||
|
namespace OpenNest.WinForms.Tests.Forms;
|
||||||
|
|
||||||
|
[Collection("Fill operation lifetime")]
|
||||||
|
public class EditNestLibraryChangeTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void ALibraryAdd_IsListedOnTheDrawingsTabAndSelectedThere() => RunSta(() =>
|
||||||
|
{
|
||||||
|
var nest = new Nest("library add");
|
||||||
|
var existing = new RectangleShape { Name = "A-EXISTING", Length = 3, Width = 1 }.GetDrawing();
|
||||||
|
existing.Quantity.Required = 1;
|
||||||
|
nest.Drawings.Add(existing);
|
||||||
|
|
||||||
|
using var form = new EditNestForm(nest) { Width = 1100, Height = 700 };
|
||||||
|
form.PlateView.SetOverlapAutoCheck(null);
|
||||||
|
form.Show();
|
||||||
|
Application.DoEvents();
|
||||||
|
|
||||||
|
var tabs = Field<TabControl>(form, "tabControl1");
|
||||||
|
var drawingsTab = Field<TabPage>(form, "tabPage2");
|
||||||
|
var list = Field<DrawingListBox>(form, "drawingListBox1");
|
||||||
|
tabs.SelectedTab = Field<TabPage>(form, "tabPage1");
|
||||||
|
|
||||||
|
// What the Drawing Library dialog does to the nest before it raises NestChanged.
|
||||||
|
var added = new RectangleShape { Name = "B-LIBRARY", Length = 4, Width = 2 }.GetDrawing();
|
||||||
|
added.Quantity.Required = 3;
|
||||||
|
nest.Drawings.Add(added);
|
||||||
|
form.ShowLibraryChange(added);
|
||||||
|
|
||||||
|
Assert.Same(drawingsTab, tabs.SelectedTab);
|
||||||
|
Assert.Equal(new object[] { existing, added }, list.Items.Cast<object>());
|
||||||
|
Assert.Same(added, list.SelectedItem);
|
||||||
|
});
|
||||||
|
|
||||||
|
private static T Field<T>(EditNestForm form, string name) =>
|
||||||
|
(T)typeof(EditNestForm)
|
||||||
|
.GetField(name, BindingFlags.Instance | BindingFlags.NonPublic)!
|
||||||
|
.GetValue(form)!;
|
||||||
|
|
||||||
|
private static void RunSta(System.Action action) =>
|
||||||
|
StaTestThread.Run(action, TimeSpan.FromMinutes(3), "The STA test did not complete.");
|
||||||
|
}
|
||||||
@@ -101,6 +101,52 @@ public class ShapeLibraryFormTests
|
|||||||
Assert.True(Find<Button>(form, "addButton").Enabled);
|
Assert.True(Find<Button>(form, "addButton").Enabled);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void KFactorIsAPlainNumberNotALength() => ArchUnitsTests.RunSta(() =>
|
||||||
|
{
|
||||||
|
using var form = new ShapeLibraryForm();
|
||||||
|
SelectShape(form, typeof(ChannelShape));
|
||||||
|
var preview = Find<ShapePreviewControl>(form, "previewBox");
|
||||||
|
var width = preview.Plate.Parts.Single().BoundingBox.Width;
|
||||||
|
|
||||||
|
Assert.Equal("K-Factor: 0.42", preview.LabelText("KFactor"));
|
||||||
|
|
||||||
|
var box = OpenEditor(form, "KFactor");
|
||||||
|
box.Text = "1.5";
|
||||||
|
Press(box, Keys.Enter);
|
||||||
|
Assert.Same(box, form.ActiveEditor);
|
||||||
|
|
||||||
|
box.Text = "0.5";
|
||||||
|
Press(box, Keys.Enter);
|
||||||
|
Assert.Null(form.ActiveEditor);
|
||||||
|
Assert.Equal("K-Factor: 0.5", preview.LabelText("KFactor"));
|
||||||
|
// Two bends' allowance grows by 90° x 0.08 of the 1/8" thickness each.
|
||||||
|
Assert.Equal(width + System.Math.PI * 0.08 * 0.125, preview.Plate.Parts.Single().BoundingBox.Width, 6);
|
||||||
|
});
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ASheetMetalPartsSideViewDimensionsItsSection() => ArchUnitsTests.RunSta(() =>
|
||||||
|
{
|
||||||
|
using var form = new ShapeLibraryForm();
|
||||||
|
SelectShape(form, typeof(AngleShape));
|
||||||
|
var preview = Find<ShapePreviewControl>(form, "previewBox");
|
||||||
|
var blank = preview.Plate.Parts.Single().BoundingBox;
|
||||||
|
|
||||||
|
Assert.Equal(new[] { "Length", "OutsideWidth", "OutsideHeight", "Thickness", "InsideRadius", "KFactor" }, preview.LabelKeys);
|
||||||
|
Assert.Equal("4\"", preview.LabelText("OutsideWidth"));
|
||||||
|
Assert.Equal("R5/16\"", preview.LabelText("InsideRadius"));
|
||||||
|
// The section sits to the right of the blank, its dimensions with it.
|
||||||
|
Assert.True(preview.LabelBounds("OutsideWidth")!.Value.Left > preview.LabelBounds("Length")!.Value.Right);
|
||||||
|
|
||||||
|
var box = OpenEditor(form, "OutsideWidth");
|
||||||
|
box.Text = "6";
|
||||||
|
Press(box, Keys.Enter);
|
||||||
|
|
||||||
|
Assert.Null(form.ActiveEditor);
|
||||||
|
Assert.Equal("6\"", preview.LabelText("OutsideWidth"));
|
||||||
|
Assert.Equal(blank.Width + 2, preview.Plate.Parts.Single().BoundingBox.Width, 6);
|
||||||
|
});
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void TabCommitsAndMovesToTheNextDimension() => ArchUnitsTests.RunSta(() =>
|
public void TabCommitsAndMovesToTheNextDimension() => ArchUnitsTests.RunSta(() =>
|
||||||
{
|
{
|
||||||
|
|||||||
+14
-3
@@ -86,6 +86,7 @@ namespace OpenNest.Controls
|
|||||||
editButton = new System.Windows.Forms.Button();
|
editButton = new System.Windows.Forms.Button();
|
||||||
exportButton = new System.Windows.Forms.Button();
|
exportButton = new System.Windows.Forms.Button();
|
||||||
statusLabel = new System.Windows.Forms.Label();
|
statusLabel = new System.Windows.Forms.Label();
|
||||||
|
addedBanner = new OpenNest.Controls.NoticeBanner();
|
||||||
searchTimer = new System.Windows.Forms.Timer(components);
|
searchTimer = new System.Windows.Forms.Timer(components);
|
||||||
previewTimer = new System.Windows.Forms.Timer(components);
|
previewTimer = new System.Windows.Forms.Timer(components);
|
||||||
drawingMenu = new System.Windows.Forms.ContextMenuStrip(components);
|
drawingMenu = new System.Windows.Forms.ContextMenuStrip(components);
|
||||||
@@ -263,13 +264,15 @@ namespace OpenNest.Controls
|
|||||||
layoutTable.ColumnCount = 1;
|
layoutTable.ColumnCount = 1;
|
||||||
layoutTable.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
|
layoutTable.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
|
||||||
layoutTable.Controls.Add(filterTable, 0, 0);
|
layoutTable.Controls.Add(filterTable, 0, 0);
|
||||||
layoutTable.Controls.Add(splitContainer, 0, 1);
|
layoutTable.Controls.Add(addedBanner, 0, 1);
|
||||||
layoutTable.Controls.Add(statusLabel, 0, 2);
|
layoutTable.Controls.Add(splitContainer, 0, 2);
|
||||||
|
layoutTable.Controls.Add(statusLabel, 0, 3);
|
||||||
layoutTable.Dock = System.Windows.Forms.DockStyle.Fill;
|
layoutTable.Dock = System.Windows.Forms.DockStyle.Fill;
|
||||||
layoutTable.Margin = new System.Windows.Forms.Padding(0);
|
layoutTable.Margin = new System.Windows.Forms.Padding(0);
|
||||||
layoutTable.Padding = new System.Windows.Forms.Padding(8);
|
layoutTable.Padding = new System.Windows.Forms.Padding(8);
|
||||||
layoutTable.Name = "layoutTable";
|
layoutTable.Name = "layoutTable";
|
||||||
layoutTable.RowCount = 3;
|
layoutTable.RowCount = 4;
|
||||||
|
layoutTable.RowStyles.Add(new System.Windows.Forms.RowStyle());
|
||||||
layoutTable.RowStyles.Add(new System.Windows.Forms.RowStyle());
|
layoutTable.RowStyles.Add(new System.Windows.Forms.RowStyle());
|
||||||
layoutTable.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
|
layoutTable.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
|
||||||
layoutTable.RowStyles.Add(new System.Windows.Forms.RowStyle());
|
layoutTable.RowStyles.Add(new System.Windows.Forms.RowStyle());
|
||||||
@@ -788,6 +791,13 @@ namespace OpenNest.Controls
|
|||||||
statusLabel.Size = new System.Drawing.Size(100, 20);
|
statusLabel.Size = new System.Drawing.Size(100, 20);
|
||||||
statusLabel.TabIndex = 2;
|
statusLabel.TabIndex = 2;
|
||||||
//
|
//
|
||||||
|
// addedBanner
|
||||||
|
//
|
||||||
|
addedBanner.Dock = System.Windows.Forms.DockStyle.Top;
|
||||||
|
addedBanner.Margin = new System.Windows.Forms.Padding(0, 0, 0, 6);
|
||||||
|
addedBanner.Name = "addedBanner";
|
||||||
|
addedBanner.TabIndex = 3;
|
||||||
|
//
|
||||||
// searchTimer
|
// searchTimer
|
||||||
//
|
//
|
||||||
searchTimer.Interval = 300;
|
searchTimer.Interval = 300;
|
||||||
@@ -988,6 +998,7 @@ namespace OpenNest.Controls
|
|||||||
private System.Windows.Forms.Button addButton;
|
private System.Windows.Forms.Button addButton;
|
||||||
private System.Windows.Forms.Button editButton;
|
private System.Windows.Forms.Button editButton;
|
||||||
private System.Windows.Forms.Label statusLabel;
|
private System.Windows.Forms.Label statusLabel;
|
||||||
|
private OpenNest.Controls.NoticeBanner addedBanner;
|
||||||
private System.Windows.Forms.Timer searchTimer;
|
private System.Windows.Forms.Timer searchTimer;
|
||||||
private System.Windows.Forms.Timer previewTimer;
|
private System.Windows.Forms.Timer previewTimer;
|
||||||
private System.Windows.Forms.ContextMenuStrip drawingMenu;
|
private System.Windows.Forms.ContextMenuStrip drawingMenu;
|
||||||
|
|||||||
@@ -20,8 +20,9 @@ namespace OpenNest.Controls
|
|||||||
/// <see cref="DrawingLibraryBrowseSession"/>, filtered to the nest's material and thickness
|
/// <see cref="DrawingLibraryBrowseSession"/>, filtered to the nest's material and thickness
|
||||||
/// unless Show all is ticked. Add downloads the listed revision's exact package, plans it
|
/// unless Show all is ticked. Add downloads the listed revision's exact package, plans it
|
||||||
/// with <see cref="LibraryDrawingInsert"/>, shows any warning or refusal first and only then
|
/// with <see cref="LibraryDrawingInsert"/>, shows any warning or refusal first and only then
|
||||||
/// changes the nest. Opened without a nest, it lists every active drawing and has no In This
|
/// changes the nest; a green banner confirms each add and <see cref="NestChanged"/> lets the
|
||||||
/// Nest tab; as the Library tab of <see cref="DrawingSetsForm"/> a double-click, Enter or Add
|
/// host list it behind the dialog at once. Opened without a nest, it lists every active
|
||||||
|
/// drawing and has no In This Nest tab; as the Library tab of <see cref="DrawingSetsForm"/> a double-click, Enter or Add
|
||||||
/// to Release adds the drawing on its own, at the entered quantity, to the window's
|
/// to Release adds the drawing on its own, at the entered quantity, to the window's
|
||||||
/// <see cref="ReleasePanel"/>, and elsewhere a double-click edits it. Edit Drawing changes the
|
/// <see cref="ReleasePanel"/>, and elsewhere a double-click edits it. Edit Drawing changes the
|
||||||
/// selected drawing's details, notes and nesting settings (Cut first, priority, rotation,
|
/// selected drawing's details, notes and nesting settings (Cut first, priority, rotation,
|
||||||
@@ -116,6 +117,12 @@ namespace OpenNest.Controls
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public bool QuantitiesChanged { get; private set; }
|
public bool QuantitiesChanged { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Raised each time an add or an In This Nest quantity edit changes the nest, while the
|
||||||
|
/// dialog is still open, so the host can show the change behind it at once.
|
||||||
|
/// </summary>
|
||||||
|
public event EventHandler<Drawing> NestChanged;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The window that owns this view's dialogs. A dialog owned by a child control is not kept
|
/// The window that owns this view's dialogs. A dialog owned by a child control is not kept
|
||||||
/// above its top-level window, so it can fall behind it.
|
/// above its top-level window, so it can fall behind it.
|
||||||
@@ -853,6 +860,7 @@ namespace OpenNest.Controls
|
|||||||
|
|
||||||
adding = true;
|
adding = true;
|
||||||
UpdateCommands();
|
UpdateCommands();
|
||||||
|
addedBanner.Hide();
|
||||||
statusLabel.Text = $"Downloading '{record.Name}' revision {record.Revision}...";
|
statusLabel.Text = $"Downloading '{record.Name}' revision {record.Revision}...";
|
||||||
var quantity = (int)quantityBox.Value;
|
var quantity = (int)quantityBox.Value;
|
||||||
try
|
try
|
||||||
@@ -895,9 +903,11 @@ namespace OpenNest.Controls
|
|||||||
if (!AddedDrawings.Contains(insert.Drawing))
|
if (!AddedDrawings.Contains(insert.Drawing))
|
||||||
AddedDrawings.Add(insert.Drawing);
|
AddedDrawings.Add(insert.Drawing);
|
||||||
RefreshNestTab();
|
RefreshNestTab();
|
||||||
statusLabel.Text = insert.Kind == LibraryInsertKind.AddQuantity
|
statusLabel.Text = "";
|
||||||
? $"Added {quantity} to '{insert.Drawing.Name}' (now {insert.Drawing.Quantity.Required})."
|
addedBanner.Show(insert.Kind == LibraryInsertKind.AddQuantity
|
||||||
: $"Added '{insert.Drawing.Name}' revision {record.Revision}, quantity {quantity}.";
|
? $"Added {quantity:N0} more of '{insert.Drawing.Name}' to the nest (now {insert.Drawing.Quantity.Required:N0} required)."
|
||||||
|
: $"Added '{insert.Drawing.Name}' revision {record.Revision} to the nest, quantity {quantity:N0}.");
|
||||||
|
NestChanged?.Invoke(this, insert.Drawing);
|
||||||
}
|
}
|
||||||
catch (ServerTooOldException ex)
|
catch (ServerTooOldException ex)
|
||||||
{
|
{
|
||||||
@@ -1101,6 +1111,7 @@ namespace OpenNest.Controls
|
|||||||
|
|
||||||
statusLabel.Text = $"'{drawing.Name}' now requires {value:N0} (was {before:N0}).";
|
statusLabel.Text = $"'{drawing.Name}' now requires {value:N0} (was {before:N0}).";
|
||||||
UpdateNestSummary();
|
UpdateNestSummary();
|
||||||
|
NestChanged?.Invoke(this, drawing);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void UpdateNestSummary()
|
private void UpdateNestSummary()
|
||||||
|
|||||||
@@ -0,0 +1,75 @@
|
|||||||
|
using System.Drawing;
|
||||||
|
using System.Windows.Forms;
|
||||||
|
|
||||||
|
namespace OpenNest.Controls
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// A slim green confirmation strip, one line of text 30 pixels high (scaled with the form):
|
||||||
|
/// a pale tint with dark text and a border in the same hue, and a close button. A message
|
||||||
|
/// longer than the strip ends in an ellipsis. Hidden until <see cref="Show(string)"/>; it
|
||||||
|
/// stays until the next message replaces it or the operator closes it.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class NoticeBanner : Panel
|
||||||
|
{
|
||||||
|
private static readonly Color Tint = Color.FromArgb(221, 240, 214);
|
||||||
|
private static readonly Color Ink = Color.FromArgb(28, 88, 28);
|
||||||
|
|
||||||
|
private readonly Label messageLabel;
|
||||||
|
private readonly Button closeButton;
|
||||||
|
private string message = "";
|
||||||
|
|
||||||
|
public NoticeBanner()
|
||||||
|
{
|
||||||
|
BackColor = Tint;
|
||||||
|
Height = 30;
|
||||||
|
Padding = new Padding(8, 1, 1, 1);
|
||||||
|
DoubleBuffered = true;
|
||||||
|
ResizeRedraw = true;
|
||||||
|
Visible = false;
|
||||||
|
|
||||||
|
messageLabel = new Label
|
||||||
|
{
|
||||||
|
AutoEllipsis = true,
|
||||||
|
AutoSize = false,
|
||||||
|
Dock = DockStyle.Fill,
|
||||||
|
ForeColor = Ink,
|
||||||
|
Name = "messageLabel",
|
||||||
|
TextAlign = ContentAlignment.MiddleLeft,
|
||||||
|
};
|
||||||
|
closeButton = new Button
|
||||||
|
{
|
||||||
|
Dock = DockStyle.Right,
|
||||||
|
FlatStyle = FlatStyle.Flat,
|
||||||
|
ForeColor = Ink,
|
||||||
|
AccessibleName = "Close",
|
||||||
|
Name = "closeButton",
|
||||||
|
TabStop = false,
|
||||||
|
Text = "✕",
|
||||||
|
Width = 26,
|
||||||
|
};
|
||||||
|
closeButton.FlatAppearance.BorderSize = 0;
|
||||||
|
closeButton.Click += (_, _) => Hide();
|
||||||
|
|
||||||
|
// Fill is laid out last, so the label takes what the button leaves.
|
||||||
|
Controls.Add(messageLabel);
|
||||||
|
Controls.Add(closeButton);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The message shown, or empty while hidden.</summary>
|
||||||
|
public string Message => Visible ? message : "";
|
||||||
|
|
||||||
|
/// <summary>Shows <paramref name="message"/>, replacing whatever was there.</summary>
|
||||||
|
public void Show(string message)
|
||||||
|
{
|
||||||
|
this.message = message ?? "";
|
||||||
|
messageLabel.Text = this.message;
|
||||||
|
Visible = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnPaint(PaintEventArgs e)
|
||||||
|
{
|
||||||
|
base.OnPaint(e);
|
||||||
|
ControlPaint.DrawBorder(e.Graphics, ClientRectangle, Ink, ButtonBorderStyle.Solid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -58,6 +58,16 @@ namespace OpenNest.Controls
|
|||||||
|
|
||||||
// The shown drawing's cut geometry, in its own coordinates (as dimension points are).
|
// The shown drawing's cut geometry, in its own coordinates (as dimension points are).
|
||||||
private List<Entity> profile = new();
|
private List<Entity> profile = new();
|
||||||
|
|
||||||
|
// A sheet metal part's section beside the blank, in its own coordinates, and where it is
|
||||||
|
// shown: view = offset + point * scale. Empty when the shape has none.
|
||||||
|
private List<Entity> sideProfile = new();
|
||||||
|
private List<Polygon> sideOutlines = new();
|
||||||
|
private Vector sideOffset;
|
||||||
|
private double sideScale = 1;
|
||||||
|
|
||||||
|
// The view the dimension being laid out belongs to.
|
||||||
|
private Frame frame;
|
||||||
private IReadOnlyList<Annotation> annotations = Array.Empty<Annotation>();
|
private IReadOnlyList<Annotation> annotations = Array.Empty<Annotation>();
|
||||||
private IReadOnlyList<Note> notes = Array.Empty<Note>();
|
private IReadOnlyList<Note> notes = Array.Empty<Note>();
|
||||||
private AnnotationLayout layout;
|
private AnnotationLayout layout;
|
||||||
@@ -97,7 +107,7 @@ namespace OpenNest.Controls
|
|||||||
internal bool IsUserView => userView;
|
internal bool IsUserView => userView;
|
||||||
|
|
||||||
/// <summary>A dimension to draw: its text, and the count text after it when it has one.</summary>
|
/// <summary>A dimension to draw: its text, and the count text after it when it has one.</summary>
|
||||||
public sealed record Annotation(ShapeDimension Dimension, string Text, string CountText = null);
|
public sealed record Annotation(ShapeDimension Dimension, string Text, string CountText = null, bool OnSideView = false);
|
||||||
|
|
||||||
/// <summary>A parameter with no place on the drawing, shown as a chip along the bottom.</summary>
|
/// <summary>A parameter with no place on the drawing, shown as a chip along the bottom.</summary>
|
||||||
public sealed record Note(string Key, string Text, bool Enabled = true);
|
public sealed record Note(string Key, string Text, bool Enabled = true);
|
||||||
@@ -134,6 +144,9 @@ namespace OpenNest.Controls
|
|||||||
/// <summary>The keys of the labels on screen, in drawing order (dimensions, then notes).</summary>
|
/// <summary>The keys of the labels on screen, in drawing order (dimensions, then notes).</summary>
|
||||||
internal IReadOnlyList<string> LabelKeys => CurrentLayout().Labels.Select(l => l.Key).ToList();
|
internal IReadOnlyList<string> LabelKeys => CurrentLayout().Labels.Select(l => l.Key).ToList();
|
||||||
|
|
||||||
|
/// <summary>The text of the label for <paramref name="key"/>, or null when none is shown.</summary>
|
||||||
|
internal string LabelText(string key) => CurrentLayout().Labels.FirstOrDefault(l => l.Key == key)?.Text;
|
||||||
|
|
||||||
/// <summary>Where the label for <paramref name="key"/> is on the control, or null when none is shown.</summary>
|
/// <summary>Where the label for <paramref name="key"/> is on the control, or null when none is shown.</summary>
|
||||||
public Rectangle? LabelBounds(string key)
|
public Rectangle? LabelBounds(string key)
|
||||||
{
|
{
|
||||||
@@ -142,11 +155,17 @@ namespace OpenNest.Controls
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Shows <paramref name="drawing"/>. A new shape (<paramref name="newShape"/>) fits the
|
/// Shows <paramref name="drawing"/>, and to its right <paramref name="sideView"/>, a sheet metal
|
||||||
/// view and puts dragged dimensions back; a changed parameter keeps a hand-set view.
|
/// part's section, enlarged when it would be too small to read beside the blank. A new
|
||||||
|
/// shape (<paramref name="newShape"/>) fits the view and puts dragged dimensions back; a
|
||||||
|
/// changed parameter keeps a hand-set view.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public void ShowDrawing(Drawing drawing, bool newShape = true)
|
public void ShowDrawing(Drawing drawing, bool newShape = true, IReadOnlyList<Entity> sideView = null)
|
||||||
{
|
{
|
||||||
|
sideProfile = drawing?.Program != null && sideView != null ? sideView.ToList() : new List<Entity>();
|
||||||
|
sideOutlines = sideProfile.Count == 0
|
||||||
|
? new List<Polygon>()
|
||||||
|
: ShapeBuilder.GetShapes(sideProfile).Select(s => s.ToPolygon()).ToList();
|
||||||
if (newShape)
|
if (newShape)
|
||||||
{
|
{
|
||||||
userView = false;
|
userView = false;
|
||||||
@@ -167,6 +186,7 @@ namespace OpenNest.Controls
|
|||||||
var shown = Plate.Parts[0].BoundingBox;
|
var shown = Plate.Parts[0].BoundingBox;
|
||||||
var source = drawing.Program.BoundingBox();
|
var source = drawing.Program.BoundingBox();
|
||||||
shapeOffset = new Vector(shown.X - source.X, shown.Y - source.Y);
|
shapeOffset = new Vector(shown.X - source.X, shown.Y - source.Y);
|
||||||
|
PlaceSideView(shown);
|
||||||
FitUnlessUserView();
|
FitUnlessUserView();
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
@@ -176,6 +196,54 @@ namespace OpenNest.Controls
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Puts the side view to the right of the blank, centered on it, a quarter of the blank's
|
||||||
|
/// larger size away. A section under 35% of that size is enlarged to it, so a long part's
|
||||||
|
/// section stays readable; its dimensions show the true sizes.
|
||||||
|
/// </summary>
|
||||||
|
private void PlaceSideView(Box blank)
|
||||||
|
{
|
||||||
|
sideScale = 1;
|
||||||
|
sideOffset = Vector.Zero;
|
||||||
|
var section = SideBounds();
|
||||||
|
if (section == null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
var blankSize = System.Math.Max(blank.Length, blank.Width);
|
||||||
|
var sectionSize = System.Math.Max(section.Length, section.Width);
|
||||||
|
if (sectionSize > 0)
|
||||||
|
sideScale = System.Math.Max(1, 0.35 * blankSize / sectionSize);
|
||||||
|
var gap = 0.25 * blankSize;
|
||||||
|
sideOffset = new Vector(
|
||||||
|
blank.Right + gap - section.X * sideScale,
|
||||||
|
blank.Center.Y - (section.Y + section.Width / 2) * sideScale);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The side view's bounds in its own coordinates; null when there is none.</summary>
|
||||||
|
private Box SideBounds()
|
||||||
|
{
|
||||||
|
if (sideProfile.Count == 0)
|
||||||
|
return null;
|
||||||
|
var boxes = sideProfile.Select(e => e.BoundingBox).ToList();
|
||||||
|
var left = boxes.Min(b => b.Left);
|
||||||
|
var bottom = boxes.Min(b => b.Bottom);
|
||||||
|
return new Box(left, bottom, boxes.Max(b => b.Right) - left, boxes.Max(b => b.Top) - bottom);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The blank's and the side view's bounds together, in view coordinates.</summary>
|
||||||
|
private Box ViewBounds()
|
||||||
|
{
|
||||||
|
var blank = Plate.Parts[0].BoundingBox;
|
||||||
|
var section = SideBounds();
|
||||||
|
if (section == null)
|
||||||
|
return blank;
|
||||||
|
var left = System.Math.Min(blank.Left, sideOffset.X + section.Left * sideScale);
|
||||||
|
var bottom = System.Math.Min(blank.Bottom, sideOffset.Y + section.Bottom * sideScale);
|
||||||
|
var right = System.Math.Max(blank.Right, sideOffset.X + section.Right * sideScale);
|
||||||
|
var top = System.Math.Max(blank.Top, sideOffset.Y + section.Top * sideScale);
|
||||||
|
return new Box(left, bottom, right - left, top - bottom);
|
||||||
|
}
|
||||||
|
|
||||||
protected override void OnResize(EventArgs e)
|
protected override void OnResize(EventArgs e)
|
||||||
{
|
{
|
||||||
base.OnResize(e);
|
base.OnResize(e);
|
||||||
@@ -217,7 +285,7 @@ namespace OpenNest.Controls
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var box = Plate.Parts[0].BoundingBox;
|
var box = ViewBounds();
|
||||||
if (box.Length <= 0 || box.Width <= 0)
|
if (box.Length <= 0 || box.Width <= 0)
|
||||||
{
|
{
|
||||||
base.ZoomToFit(redraw);
|
base.ZoomToFit(redraw);
|
||||||
@@ -251,7 +319,7 @@ namespace OpenNest.Controls
|
|||||||
UpdateMatrix();
|
UpdateMatrix();
|
||||||
|
|
||||||
layout = BuildLayout();
|
layout = BuildLayout();
|
||||||
var shape = ShapeRect();
|
var shape = GuiRect(box);
|
||||||
var reach = layout.DimensionBounds;
|
var reach = layout.DimensionBounds;
|
||||||
if (reach.IsEmpty)
|
if (reach.IsEmpty)
|
||||||
break;
|
break;
|
||||||
@@ -438,12 +506,34 @@ namespace OpenNest.Controls
|
|||||||
Renderer.DrawPlate(e.Graphics);
|
Renderer.DrawPlate(e.Graphics);
|
||||||
Renderer.DrawLibraryParts(e.Graphics, ColorScheme.Default);
|
Renderer.DrawLibraryParts(e.Graphics, ColorScheme.Default);
|
||||||
e.Graphics.ResetTransform();
|
e.Graphics.ResetTransform();
|
||||||
|
PaintSideView(e.Graphics);
|
||||||
|
|
||||||
layout = BuildLayout();
|
layout = BuildLayout();
|
||||||
PaintAnnotations(e.Graphics, layout);
|
PaintAnnotations(e.Graphics, layout);
|
||||||
PaintInfo(e.Graphics);
|
PaintInfo(e.Graphics);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Fills and outlines the side view's section as the blank is drawn.</summary>
|
||||||
|
private void PaintSideView(Graphics g)
|
||||||
|
{
|
||||||
|
if (sideOutlines.Count == 0 || Plate.Parts.Count == 0)
|
||||||
|
return;
|
||||||
|
|
||||||
|
frame = SideFrame();
|
||||||
|
using var path = new GraphicsPath(FillMode.Alternate);
|
||||||
|
foreach (var outline in sideOutlines)
|
||||||
|
{
|
||||||
|
var points = outline.Vertices.Select(ToScreen).ToArray();
|
||||||
|
if (points.Length > 2)
|
||||||
|
path.AddPolygon(points);
|
||||||
|
}
|
||||||
|
var scheme = ColorScheme.Default;
|
||||||
|
using var fill = new SolidBrush(scheme.LibraryFillColor);
|
||||||
|
using var pen = new Pen(scheme.LibraryOutlineColor);
|
||||||
|
g.FillPath(fill, path);
|
||||||
|
g.DrawPath(pen, path);
|
||||||
|
}
|
||||||
|
|
||||||
private void PaintInfo(Graphics g)
|
private void PaintInfo(Graphics g)
|
||||||
{
|
{
|
||||||
if (infoLines == null)
|
if (infoLines == null)
|
||||||
@@ -534,15 +624,34 @@ namespace OpenNest.Controls
|
|||||||
new(TextRenderer.MeasureText(text, Font, System.Drawing.Size.Empty, TextFormatFlags.NoPadding).Width + 2 * LabelPadding,
|
new(TextRenderer.MeasureText(text, Font, System.Drawing.Size.Empty, TextFormatFlags.NoPadding).Width + 2 * LabelPadding,
|
||||||
LabelHeight);
|
LabelHeight);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// One view's place on the control, the blank's or the side view's: its points are
|
||||||
|
/// shown at <see cref="Offset"/> + point x <see cref="Scale"/>.
|
||||||
|
/// </summary>
|
||||||
|
private readonly record struct Frame(Vector Offset, double Scale, List<Entity> Profile, RectangleF Rect);
|
||||||
|
|
||||||
|
private Frame BlankFrame() =>
|
||||||
|
new(shapeOffset, 1, profile, GuiRect(Plate.Parts[0].BoundingBox));
|
||||||
|
|
||||||
|
private Frame SideFrame()
|
||||||
|
{
|
||||||
|
var section = SideBounds();
|
||||||
|
var shown = new Box(sideOffset.X + section.X * sideScale, sideOffset.Y + section.Y * sideScale,
|
||||||
|
section.Length * sideScale, section.Width * sideScale);
|
||||||
|
return new(sideOffset, sideScale, sideProfile, GuiRect(shown));
|
||||||
|
}
|
||||||
|
|
||||||
private PointF ToScreen(Vector shapePoint)
|
private PointF ToScreen(Vector shapePoint)
|
||||||
{
|
{
|
||||||
var graph = PointWorldToGraph(shapePoint.X + shapeOffset.X, shapePoint.Y + shapeOffset.Y);
|
var graph = PointWorldToGraph(shapePoint.X * frame.Scale + frame.Offset.X, shapePoint.Y * frame.Scale + frame.Offset.Y);
|
||||||
return new PointF(graph.X + origin.X, graph.Y + origin.Y);
|
return new PointF(graph.X + origin.X, graph.Y + origin.Y);
|
||||||
}
|
}
|
||||||
|
|
||||||
private RectangleF ShapeRect()
|
/// <summary>A length in the current frame's coordinates, in pixels.</summary>
|
||||||
|
private float FrameToGui(double length) => LengthWorldToGui(length * frame.Scale);
|
||||||
|
|
||||||
|
private RectangleF GuiRect(Box box)
|
||||||
{
|
{
|
||||||
var box = Plate.Parts[0].BoundingBox;
|
|
||||||
var graphTopLeft = PointWorldToGraph(box.X, box.Y + box.Width);
|
var graphTopLeft = PointWorldToGraph(box.X, box.Y + box.Width);
|
||||||
return new RectangleF(graphTopLeft.X + origin.X, graphTopLeft.Y + origin.Y,
|
return new RectangleF(graphTopLeft.X + origin.X, graphTopLeft.Y + origin.Y,
|
||||||
LengthWorldToGui(box.Length), LengthWorldToGui(box.Width));
|
LengthWorldToGui(box.Length), LengthWorldToGui(box.Width));
|
||||||
@@ -554,9 +663,14 @@ namespace OpenNest.Controls
|
|||||||
if (Plate.Parts.Count == 0)
|
if (Plate.Parts.Count == 0)
|
||||||
return result;
|
return result;
|
||||||
|
|
||||||
var shape = ShapeRect();
|
var blank = BlankFrame();
|
||||||
|
var side = sideProfile.Count > 0 ? SideFrame() : (Frame?)null;
|
||||||
foreach (var annotation in annotations)
|
foreach (var annotation in annotations)
|
||||||
{
|
{
|
||||||
|
if (annotation.OnSideView && side == null)
|
||||||
|
continue;
|
||||||
|
frame = annotation.OnSideView ? side.Value : blank;
|
||||||
|
var shape = frame.Rect;
|
||||||
var d = annotation.Dimension;
|
var d = annotation.Dimension;
|
||||||
switch (d.Kind)
|
switch (d.Kind)
|
||||||
{
|
{
|
||||||
@@ -572,6 +686,7 @@ namespace OpenNest.Controls
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
frame = blank;
|
||||||
result.Labels.AddRange(LayoutChips());
|
result.Labels.AddRange(LayoutChips());
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
@@ -621,15 +736,15 @@ namespace OpenNest.Controls
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
private float ExtensionStart(Vector point, Vector side, float reach, RectangleF shape)
|
private float ExtensionStart(Vector point, Vector side, float reach, RectangleF shape)
|
||||||
{
|
{
|
||||||
if (profile.Count == 0 || !(reach > 0))
|
if (frame.Profile == null || frame.Profile.Count == 0 || !(reach > 0))
|
||||||
return 0;
|
return 0;
|
||||||
|
|
||||||
var limit = reach + (System.Math.Abs(side.X) > System.Math.Abs(side.Y) ? shape.Width : shape.Height);
|
var limit = reach + (System.Math.Abs(side.X) > System.Math.Abs(side.Y) ? shape.Width : shape.Height);
|
||||||
var travelled = 0f;
|
var travelled = 0f;
|
||||||
for (var i = 0; i < MaxExtensionSteps && travelled < limit; i++)
|
for (var i = 0; i < MaxExtensionSteps && travelled < limit; i++)
|
||||||
{
|
{
|
||||||
var at = point + side * LengthGuiToWorld(reach - travelled);
|
var at = point + side * (LengthGuiToWorld(reach - travelled) / frame.Scale);
|
||||||
var free = LengthWorldToGui(DistanceToProfile(at)) - ExtensionClearance;
|
var free = FrameToGui(DistanceToProfile(at)) - ExtensionClearance;
|
||||||
if (free <= ExtensionPrecision)
|
if (free <= ExtensionPrecision)
|
||||||
break;
|
break;
|
||||||
travelled += free;
|
travelled += free;
|
||||||
@@ -640,7 +755,7 @@ namespace OpenNest.Controls
|
|||||||
private double DistanceToProfile(Vector point)
|
private double DistanceToProfile(Vector point)
|
||||||
{
|
{
|
||||||
var nearest = double.MaxValue;
|
var nearest = double.MaxValue;
|
||||||
foreach (var entity in profile)
|
foreach (var entity in frame.Profile)
|
||||||
nearest = System.Math.Min(nearest, point.DistanceTo(entity.ClosestPointTo(point)));
|
nearest = System.Math.Min(nearest, point.DistanceTo(entity.ClosestPointTo(point)));
|
||||||
return nearest;
|
return nearest;
|
||||||
}
|
}
|
||||||
@@ -648,7 +763,7 @@ namespace OpenNest.Controls
|
|||||||
private void AddReferenceCircle(AnnotationLayout result, ShapeDimension d)
|
private void AddReferenceCircle(AnnotationLayout result, ShapeDimension d)
|
||||||
{
|
{
|
||||||
if (d.CircleCenter is { } center && d.CircleRadius > 0)
|
if (d.CircleCenter is { } center && d.CircleRadius > 0)
|
||||||
result.Circles.Add((ToScreen(center), LengthWorldToGui(d.CircleRadius)));
|
result.Circles.Add((ToScreen(center), FrameToGui(d.CircleRadius)));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>The current zoom relative to the fitted view: 1 until zoomed by hand.</summary>
|
/// <summary>The current zoom relative to the fitted view: 1 until zoomed by hand.</summary>
|
||||||
@@ -784,7 +899,7 @@ namespace OpenNest.Controls
|
|||||||
return false;
|
return false;
|
||||||
|
|
||||||
var center = ToScreen(holeCenter);
|
var center = ToScreen(holeCenter);
|
||||||
var radius = LengthWorldToGui(d.HoleRadius);
|
var radius = FrameToGui(d.HoleRadius);
|
||||||
var toEnd = new PointF(end.X - center.X, end.Y - center.Y);
|
var toEnd = new PointF(end.X - center.X, end.Y - center.Y);
|
||||||
var distance = (float)System.Math.Sqrt(Dot(toEnd, toEnd));
|
var distance = (float)System.Math.Sqrt(Dot(toEnd, toEnd));
|
||||||
|
|
||||||
|
|||||||
@@ -23,6 +23,13 @@ namespace OpenNest.Forms
|
|||||||
/// <summary>True once the In This Nest tab changed a drawing's required quantity.</summary>
|
/// <summary>True once the In This Nest tab changed a drawing's required quantity.</summary>
|
||||||
public bool QuantitiesChanged => view.QuantitiesChanged;
|
public bool QuantitiesChanged => view.QuantitiesChanged;
|
||||||
|
|
||||||
|
/// <summary>Raised with the drawing after each add or quantity edit, while the dialog is still open.</summary>
|
||||||
|
public event EventHandler<Drawing> NestChanged
|
||||||
|
{
|
||||||
|
add => view.NestChanged += value;
|
||||||
|
remove => view.NestChanged -= value;
|
||||||
|
}
|
||||||
|
|
||||||
/// <param name="nest">The nest to add drawings to.</param>
|
/// <param name="nest">The nest to add drawings to.</param>
|
||||||
/// <param name="sets">Enables Used in Sets and Add to Set; null hides them.</param>
|
/// <param name="sets">Enables Used in Sets and Add to Set; null hides them.</param>
|
||||||
public DrawingLibraryForm(IDrawingLibraryStore library, string serverUrl, Nest nest, IDrawingSetStore sets = null)
|
public DrawingLibraryForm(IDrawingLibraryStore library, string serverUrl, Nest nest, IDrawingSetStore sets = null)
|
||||||
|
|||||||
@@ -1538,6 +1538,8 @@ namespace OpenNest.Forms
|
|||||||
// The dialog adds drawings and sets quantities as the operator works in it.
|
// The dialog adds drawings and sets quantities as the operator works in it.
|
||||||
using var change = BeginChange("Drawing Library");
|
using var change = BeginChange("Drawing Library");
|
||||||
var job = (Nest.Material, Nest.Thickness);
|
var job = (Nest.Material, Nest.Thickness);
|
||||||
|
// Each add shows on the Drawings tab behind the dialog right away.
|
||||||
|
form.NestChanged += (_, drawing) => ShowLibraryChange(drawing);
|
||||||
form.ShowDialog(DialogOwner);
|
form.ShowDialog(DialogOwner);
|
||||||
if (form.AddedDrawings.Count > 0 || form.QuantitiesChanged)
|
if (form.AddedDrawings.Count > 0 || form.QuantitiesChanged)
|
||||||
{
|
{
|
||||||
@@ -1555,6 +1557,18 @@ namespace OpenNest.Forms
|
|||||||
change.Complete();
|
change.Complete();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Lists a drawing the open Drawing Library dialog just added or changed: brings the
|
||||||
|
/// Drawings tab forward and selects it there.
|
||||||
|
/// </summary>
|
||||||
|
internal void ShowLibraryChange(Drawing drawing)
|
||||||
|
{
|
||||||
|
UpdateDrawingList();
|
||||||
|
tabControl1.SelectedTab = tabPage2;
|
||||||
|
if (drawing != null && drawingListBox1.Items.Contains(drawing))
|
||||||
|
drawingListBox1.SelectedItem = drawing;
|
||||||
|
}
|
||||||
|
|
||||||
private void drawingListBox1_SaveToLibraryRequested(object sender, Drawing drawing)
|
private void drawingListBox1_SaveToLibraryRequested(object sender, Drawing drawing)
|
||||||
{
|
{
|
||||||
SaveDrawingToLibrary(drawing);
|
SaveDrawingToLibrary(drawing);
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
using System.ComponentModel;
|
||||||
using System.Drawing;
|
using System.Drawing;
|
||||||
using System.Drawing.Drawing2D;
|
using System.Drawing.Drawing2D;
|
||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
@@ -388,21 +389,28 @@ namespace OpenNest.Forms
|
|||||||
|
|
||||||
addButton.Enabled = true;
|
addButton.Enabled = true;
|
||||||
nameTextBox.Text = shape.GenerateName();
|
nameTextBox.Text = shape.GenerateName();
|
||||||
previewBox.ShowDrawing(drawing, newShape);
|
var sideView = shape.GetSideView();
|
||||||
|
previewBox.ShowDrawing(drawing, newShape, sideView?.Entities);
|
||||||
newShape = false;
|
newShape = false;
|
||||||
|
|
||||||
var dimensions = shape.GetDimensions()
|
var dimensions = shape.GetDimensions().Select(d => (Dimension: d, OnSideView: false))
|
||||||
.Where(d => Parameter(d.Property) != null)
|
.Concat((sideView?.Dimensions ?? Array.Empty<ShapeDimension>()).Select(d => (Dimension: d, OnSideView: true)))
|
||||||
|
.Where(d => Parameter(d.Dimension.Property) != null)
|
||||||
.ToList();
|
.ToList();
|
||||||
var placed = dimensions.Select(d => d.Property)
|
var placed = dimensions.Select(d => d.Dimension.Property)
|
||||||
.Concat(dimensions.Select(d => d.CountProperty).Where(p => p != null))
|
.Concat(dimensions.Select(d => d.Dimension.CountProperty).Where(p => p != null))
|
||||||
.ToHashSet();
|
.ToHashSet();
|
||||||
previewBox.SetAnnotations(
|
previewBox.SetAnnotations(
|
||||||
dimensions.Select(d => new ShapePreviewControl.Annotation(d,
|
dimensions.Select(item =>
|
||||||
d.Prefix + FormatLength((double)values[d.Property]),
|
{
|
||||||
d.CountProperty != null && values.TryGetValue(d.CountProperty, out var count)
|
var d = item.Dimension;
|
||||||
? $"x {count} {d.CountNoun}"
|
return new ShapePreviewControl.Annotation(d,
|
||||||
: null)).ToList(),
|
d.Prefix + FormatLength((double)values[d.Property]),
|
||||||
|
d.CountProperty != null && values.TryGetValue(d.CountProperty, out var count)
|
||||||
|
? $"x {count} {d.CountNoun}"
|
||||||
|
: null,
|
||||||
|
item.OnSideView);
|
||||||
|
}).ToList(),
|
||||||
parameters.Where(p => !placed.Contains(p.Name)).Select(NoteFor).ToList());
|
parameters.Where(p => !placed.Contains(p.Name)).Select(NoteFor).ToList());
|
||||||
|
|
||||||
var bb = drawing.Program.BoundingBox();
|
var bb = drawing.Program.BoundingBox();
|
||||||
@@ -444,14 +452,18 @@ namespace OpenNest.Forms
|
|||||||
var text = value switch
|
var text = value switch
|
||||||
{
|
{
|
||||||
bool b => b ? "Yes" : "No",
|
bool b => b ? "Yes" : "No",
|
||||||
|
double d when IsUnitless(prop) => d.ToString("0.####", CultureInfo.CurrentCulture),
|
||||||
double d => FormatLength(d),
|
double d => FormatLength(d),
|
||||||
null => "None",
|
null => "None",
|
||||||
_ => value.ToString(),
|
_ => value.ToString(),
|
||||||
};
|
};
|
||||||
var enabled = prop.Name != nameof(PipeFlangeShape.PipeSize) || !Equals(values.GetValueOrDefault(nameof(PipeFlangeShape.Blind)), true);
|
var enabled = prop.Name != nameof(PipeFlangeShape.PipeSize) || !Equals(values.GetValueOrDefault(nameof(PipeFlangeShape.Blind)), true);
|
||||||
return new ShapePreviewControl.Note(prop.Name, $"{FriendlyName(prop.Name)}: {text}", enabled);
|
var label = prop.GetCustomAttribute<DisplayNameAttribute>()?.DisplayName ?? FriendlyName(prop.Name);
|
||||||
|
return new ShapePreviewControl.Note(prop.Name, $"{label}: {text}", enabled);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static bool IsUnitless(PropertyInfo prop) => prop.IsDefined(typeof(UnitlessAttribute));
|
||||||
|
|
||||||
internal static string FormatLength(double inches) => Fraction.Format(inches) + "\"";
|
internal static string FormatLength(double inches) => Fraction.Format(inches) + "\"";
|
||||||
|
|
||||||
/// <summary>The pipe sizes that fit inside the bolt holes: pipe OD + clearance < pattern - hole.</summary>
|
/// <summary>The pipe sizes that fit inside the bolt holes: pipe OD + clearance < pattern - hole.</summary>
|
||||||
@@ -669,6 +681,16 @@ namespace OpenNest.Forms
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (IsUnitless(prop))
|
||||||
|
{
|
||||||
|
if (!double.TryParse(text?.Trim(), NumberStyles.Float, CultureInfo.CurrentCulture, out var number) || !double.IsFinite(number))
|
||||||
|
return $"'{text}' is not a number.";
|
||||||
|
if (number < 0)
|
||||||
|
return "The value cannot be negative.";
|
||||||
|
value = number;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
double length;
|
double length;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
|||||||
+14
-13
@@ -443,6 +443,12 @@ plans the insert (`OpenNest.Data.LibraryDrawingInsert`) before changing anything
|
|||||||
revisions through Update Drawings.
|
revisions through Update Drawings.
|
||||||
- Another drawing with the same name: refused, naming both.
|
- Another drawing with the same name: refused, naming both.
|
||||||
|
|
||||||
|
Each add shows a green banner above the list naming what was added (or how many
|
||||||
|
more of a drawing already in the nest, and the new required quantity); it stays
|
||||||
|
until the next add replaces it or it is closed. The dialog stays open for more
|
||||||
|
adds, and the main window lists the drawing on its Drawings tab behind the
|
||||||
|
dialog at once, brings that tab forward and selects it there.
|
||||||
|
|
||||||
The added drawing is an independent copy carrying a library link (server key,
|
The added drawing is an independent copy carrying a library link (server key,
|
||||||
id, revision and a snapshot of the library details) that is saved with the nest
|
id, revision and a snapshot of the library details) that is saved with the nest
|
||||||
(see [the nest file format](nest-file-format.md#drawing-library-links)). Editing it
|
(see [the nest file format](nest-file-format.md#drawing-library-links)). Editing it
|
||||||
@@ -454,8 +460,8 @@ library or not, cutoffs excluded: name, library revision ("Not from the library"
|
|||||||
or "(other server)" when it is linked elsewhere), and the Required, Nested and
|
or "(other server)" when it is linked elsewhere), and the Required, Nested and
|
||||||
Remaining quantities, with totals below. It refreshes after every add. Required
|
Remaining quantities, with totals below. It refreshes after every add. Required
|
||||||
is edited in place (0 to 99,999; one click starts editing, a bad number keeps
|
is edited in place (0 to 99,999; one click starts editing, a bad number keeps
|
||||||
the editor open with an error) and applies to the nest at once, like an add;
|
the editor open with an error) and applies to the nest at once, like an add,
|
||||||
the main window's drawing list refreshes when the dialog closes.
|
and the main window's drawing list shows the change at once.
|
||||||
|
|
||||||
The browser's **Cut first** column shows the setting; **Size (in)** (longer x
|
The browser's **Cut first** column shows the setting; **Size (in)** (longer x
|
||||||
shorter side) and **Holes** show the measured summary, blank until it is measured
|
shorter side) and **Holes** show the measured summary, blank until it is measured
|
||||||
@@ -1305,17 +1311,12 @@ under a local name such as `server.env`, and set:
|
|||||||
one layer: verify that the network/firewall admits only trusted clients.
|
one layer: verify that the network/firewall admits only trusted clients.
|
||||||
- `OPENNEST_HOST_PORT` (default 8090) and `OPENNEST_DATA_VOLUME` (default `opennest-data`).
|
- `OPENNEST_HOST_PORT` (default 8090) and `OPENNEST_DATA_VOLUME` (default `opennest-data`).
|
||||||
|
|
||||||
Publication requires an existing verified private package; first-package
|
The published image is public, so the deployment host pulls it without a GitHub
|
||||||
initialization needs separate owner authorization outside the release workflow.
|
login or token. A public image does not make the server safe to expose: it has no
|
||||||
An authorized deployment operator must obtain a
|
authentication, so keep it on a trusted LAN as described above. Do not put
|
||||||
`read:packages` token out of band and log in on the deployment host using
|
credentials in `server.env`, Compose, the image, or source control. Until an
|
||||||
`docker login ghcr.io -u <github-user> --password-stdin`, piping the token from a
|
approved image has passed the published-digest smoke, the reference below is only
|
||||||
secret manager or a protected prompt (never a token literal in shell history).
|
a template, not an available verified image.
|
||||||
Keep Docker's credentials protected on that host; do not put credentials in
|
|
||||||
`server.env`, Compose, the image, or source control. Login/pull success does not
|
|
||||||
authorize making the package public. Until an approved image has passed the
|
|
||||||
published-digest smoke, the reference below is only a template, not an available
|
|
||||||
verified image.
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
compose="docker compose --env-file server.env -f compose.server.yaml"
|
compose="docker compose --env-file server.env -f compose.server.yaml"
|
||||||
|
|||||||
+33
-3
@@ -14,7 +14,7 @@ in `OpenNest.Engine/NestingEngines/<Name>/`, its tests in `OpenNest.Engine.Tests
|
|||||||
| Default | Any job; used when no engine is named | Runs Irregular, Rectangles and Circles, checks each layout with the layout check and keeps the best: valid first, then fewest unplaced parts, then lowest salvage-credited cost, then the largest compactness offcut; remaining ties keep the engine listed first here |
|
| Default | Any job; used when no engine is named | Runs Irregular, Rectangles and Circles, checks each layout with the layout check and keeps the best: valid first, then fewest unplaced parts, then lowest salvage-credited cost, then the largest compactness offcut; remaining ties keep the engine listed first here |
|
||||||
| Rectangles | Plain and near-rectangular plates | Each part packed as the box of its material at its minimum-area rotation, using a maximal-rectangles free list; the sheet that finishes the job is also squeezed into a shorter or narrower bin; stock chosen sheet by sheet by salvage-credited look-ahead cost |
|
| Rectangles | Plain and near-rectangular plates | Each part packed as the box of its material at its minimum-area rotation, using a maximal-rectangles free list; the sheet that finishes the job is also squeezed into a shorter or narrower bin; stock chosen sheet by sheet by salvage-credited look-ahead cost |
|
||||||
| Circles | Round parts: blanks, washers, flanges, gears by their tip circle | Each part packed as its minimum enclosing circle at centers tangent to two of walls, placed discs and clamp keep-outs, with hexagonal and square lattice seeds; bids only when every part is round; stock chosen as Rectangles does, plus whole-job runs preferring each stock and a tail re-plan |
|
| Circles | Round parts: blanks, washers, flanges, gears by their tip circle | Each part packed as its minimum enclosing circle at centers tangent to two of walls, placed discs and clamp keep-outs, with hexagonal and square lattice seeds; bids only when every part is round; stock chosen as Rectangles does, plus whole-job runs preferring each stock and a tail re-plan |
|
||||||
| Irregular | Irregular profiles | No-fit-polygon frontier packing with gap filling and best-fit pairs, six whole-job strategy variants (each also keeping a stock that finished the job when the per-sheet estimate passed it over for a plan that ended up dearer) and a tail re-plan, then grouped variants that pack like parts together, then a banded variant that packs each sheet in full-height strips, each group as its Lattice band or each strip from the largest parts down, then a sheet-reduction pass that packs edge parts first and turns a key part by its contacts; under a time limit it keeps trying seeded variants until the limit |
|
| Irregular | Irregular profiles | No-fit-polygon frontier packing with gap filling and best-fit pairs, six whole-job strategy variants (each also keeping a stock that finished the job when the per-sheet estimate passed it over for a plan that ended up dearer) and a tail re-plan, then grouped variants that pack like parts together, then a banded variant that packs each sheet in full-height strips, each group as its Lattice band or each strip from the largest parts down, then a sheet-reduction pass that packs edge parts first and turns a key part by its contacts; under a time limit it first reports a quick plan without Lattice blocks, and after its search keeps trying seeded variants until the limit |
|
||||||
| FlatBar | Flat bar: parts about as wide as the bar | Each stock read as a bar and cut in one row: the CutList cut-list packer and a best-fill search on part lengths less their self-nesting gain, then a slide-left pass that nests shaped ends and refills freed length; stock chosen bar by bar by whole-plan cost |
|
| FlatBar | Flat bar: parts about as wide as the bar | Each stock read as a bar and cut in one row: the CutList cut-list packer and a best-fill search on part lengths less their self-nesting gain, then a slide-left pass that nests shaped ends and refills freed length; stock chosen bar by bar by whole-plan cost |
|
||||||
| Lattice, Strip, Vertical Remnant, Horizontal Remnant | Many copies of a few parts | The fixed placement strategies behind interactive fill; Lattice is the multi-phase lattice fill (linear, pairs, rectangle best-fit, remainder; the pairs phase fills the strip its grid leaves with rows of pairs when they hold more than single parts, and also tiles herringbone pairs: the part turned so a hull edge lies along a sheet axis, nested into its own row, with every other row reversed), and the remnant strategies run it ranked to keep the largest drop. In whole jobs, all four place a plate with any fixed or bounded part rotation by the rotation-aware ordered placer instead |
|
| Lattice, Strip, Vertical Remnant, Horizontal Remnant | Many copies of a few parts | The fixed placement strategies behind interactive fill; Lattice is the multi-phase lattice fill (linear, pairs, rectangle best-fit, remainder; the pairs phase fills the strip its grid leaves with rows of pairs when they hold more than single parts, and also tiles herringbone pairs: the part turned so a hull edge lies along a sheet axis, nested into its own row, with every other row reversed), and the remnant strategies run it ranked to keep the largest drop. In whole jobs, all four place a plate with any fixed or bounded part rotation by the rotation-aware ordered placer instead |
|
||||||
|
|
||||||
@@ -85,7 +85,8 @@ proposals with no committed counts, all come before the plate commits, and the l
|
|||||||
returned layout. Reporting never changes the search: layouts are identical with or without a
|
returned layout. Reporting never changes the search: layouts are identical with or without a
|
||||||
progress sink.
|
progress sink.
|
||||||
|
|
||||||
- Irregular reports when a strategy variant, a grouped variant or a tail re-plan beats its best plan so far.
|
- Irregular reports when a strategy variant, a grouped variant or a tail re-plan beats its best plan so far;
|
||||||
|
under a time limit it reports a quick plan before them (see [time limits](#time-limits)).
|
||||||
- Rectangles makes one sheet-by-sheet run, so it reports the finished job as its one plan.
|
- Rectangles makes one sheet-by-sheet run, so it reports the finished job as its one plan.
|
||||||
- Circles reports when a stock-preference run or a tail re-plan beats its best result so far.
|
- Circles reports when a stock-preference run or a tail re-plan beats its best result so far.
|
||||||
- Default scores each candidate plan as it ranks results (valid, fewest unplaced, lowest cost,
|
- Default scores each candidate plan as it ranks results (valid, fewest unplaced, lowest cost,
|
||||||
@@ -126,6 +127,18 @@ candidates, and other engines ignore it; Irregular also ignores it when the toke
|
|||||||
cancelled, nobody listens for progress, or the job has a single part type. Default runs Irregular last for this
|
cancelled, nobody listens for progress, or the job has a single part type. Default runs Irregular last for this
|
||||||
reason.
|
reason.
|
||||||
|
|
||||||
|
Under those same conditions, where the solve can end only at the limit, Irregular first decodes
|
||||||
|
its first variant once without Lattice blocks and reports that quick plan, then runs its normal
|
||||||
|
search; a job with no type of three or more copies prepares no blocks, so it skips the quick plan.
|
||||||
|
Preparing blocks for each stock trial of the first sheet takes most of the first decode's time on
|
||||||
|
a big job, so the quick plan comes well before the normal search's first plan and delays it
|
||||||
|
little, as the no-fit polygons and pairs it builds serve that search too. The quick decode spends
|
||||||
|
its own work meter and shares only caches that depend on the job alone (no-fit polygons, pairs,
|
||||||
|
clamps), so the normal search makes the same decisions and reports the same plans as without it.
|
||||||
|
The quick plan is never a result of its own: the deadline wrapper keeps the best reported plan
|
||||||
|
that passes the layout check, which is the quick plan only when nothing reported later beats it,
|
||||||
|
and a solve that can finish on its own never makes one, so unlimited results are unchanged.
|
||||||
|
|
||||||
Desktop, Console and MCP do not apply a limit yet; Console can solve a job twice (with and without
|
Desktop, Console and MCP do not apply a limit yet; Console can solve a job twice (with and without
|
||||||
cutouts), so a limit there needs one deadline shared across both solves.
|
cutouts), so a limit there needs one deadline shared across both solves.
|
||||||
|
|
||||||
@@ -248,7 +261,10 @@ the empty work area and physical leftover space for up to two high-area rectangl
|
|||||||
outlines are expanded by part spacing before rectangle search. Each sheet prepares blocks initially
|
outlines are expanded by part spacing before rectangle search. Each sheet prepares blocks initially
|
||||||
and after its first placement, for up to four high-demand-area types; each type has at most eight
|
and after its first placement, for up to four high-demand-area types; each type has at most eight
|
||||||
new Lattice preparations per spacing per solve. Repeated rectangles reuse private drawing/candidate
|
new Lattice preparations per spacing per solve. Repeated rectangles reuse private drawing/candidate
|
||||||
caches. Quantity-one and quantity-two requests never run Lattice blocks.
|
caches. Quantity-one and quantity-two requests never run Lattice blocks. A rectangle narrower than
|
||||||
|
the part at every rotation, or too small for three copies, cannot hold a block, so it is not
|
||||||
|
filled (for a block or a band); it still counts as a preparation and is charged as one, so the
|
||||||
|
layouts are those the fill would have given.
|
||||||
|
|
||||||
Block members are trimmed to remaining demand, mapped back to source-frame rotations, and checked
|
Block members are trimmed to remaining demand, mapped back to source-frame rotations, and checked
|
||||||
for legal rotations and internal material clearance before competing with singles and pairs.
|
for legal rotations and internal material clearance before competing with singles and pairs.
|
||||||
@@ -258,6 +274,20 @@ or invalid Lattice proposal leaves singles and pairs available. Large enclosed-p
|
|||||||
pending the hole-geometry integration; containment cutting order and shop-use safety acceptance
|
pending the hole-geometry integration; containment cutting order and shop-use safety acceptance
|
||||||
remain separate sequencer/verification work.
|
remain separate sequencer/verification work.
|
||||||
|
|
||||||
|
Each sheet of a decode trial-packs every stock still available and keeps the one with the lowest
|
||||||
|
estimate: its net cost plus the part area it leaves, charged at the best cost per part area any
|
||||||
|
trial reached. Once the block budget is spent, so no
|
||||||
|
Lattice block can be prepared any more, a tail re-plan's decode skips a stock whose least
|
||||||
|
possible net cost (the whole sheet, less full salvage credit) already exceeds the best estimate so
|
||||||
|
far, and that over the remaining part area could not reach a better ratio than the best so far.
|
||||||
|
Later trials only lower the ratio and the estimates, so the skipped trial could neither be chosen
|
||||||
|
nor change the choice: each decode picks the sheets it picked before. Mostly large stocks on the
|
||||||
|
last sheets are skipped. Before the budget is spent a skipped trial would leave block attempts and
|
||||||
|
work unspent that a later trial could use, changing its fill. The work meter counts only packed
|
||||||
|
trials, so later tail re-plans and passes may start where before the budget had stopped them.
|
||||||
|
Whole-job variants still pack every trial: a skipped stock may have finished the job, and their
|
||||||
|
finished plans compete with the decode's.
|
||||||
|
|
||||||
### Grouped variants
|
### Grouped variants
|
||||||
|
|
||||||
After its six variants and the tail re-plan, Irregular decodes the job again with like parts
|
After its six variants and the tail re-plan, Irregular decodes the job again with like parts
|
||||||
|
|||||||
@@ -66,7 +66,7 @@ dotnet test OpenNest.Tests/OpenNest.Tests.csproj -c Debug \
|
|||||||
--filter 'FullyQualifiedName~DefaultFillComparerWorkTests|FullyQualifiedName~FillHelpersTests|FullyQualifiedName~FillExtentsTests|FullyQualifiedName~StrategyOverlapTests|FullyQualifiedName~FillLinearGeometryReuseTests|FullyQualifiedName~CollisionOverlapOnlyTests|FullyQualifiedName~PartOverlapCheckerTests'
|
--filter 'FullyQualifiedName~DefaultFillComparerWorkTests|FullyQualifiedName~FillHelpersTests|FullyQualifiedName~FillExtentsTests|FullyQualifiedName~StrategyOverlapTests|FullyQualifiedName~FillLinearGeometryReuseTests|FullyQualifiedName~CollisionOverlapOnlyTests|FullyQualifiedName~PartOverlapCheckerTests'
|
||||||
```
|
```
|
||||||
|
|
||||||
`PerfCounters.FillScoreComputations`, `PartBoundaryPreparations`, `PartBoundsUpdates`, `OffsetPerimeterEntities`, `FeatureBitmaskCells`, `CrossingPointScans`, `OverlapPolygonPreparations`, and `PolygonTriangulations` increments compile away in Release: zero Release counters prove nothing. `OverlapPolygonPreparations` counts overlap-preparation starts (material extraction), not completed polygons: `Part.Intersects` counts both parts on every call, `PartOverlapChecker` counts once per distinct `Program`. `PolygonTriangulations` counts `Collision` triangulations; the checker triangulates a part at most once per check, and only after a bounding-box hit. Serialize counter assertions in `FillCacheCollection` and reset in `finally`. Keep `OpenNest.Tests/Fill/LegacyFillExtents.cs`, `OpenNest.Tests/Fill/LegacyFillLinear.cs`, `OpenNest.Tests/Geometry/LegacyCollision.cs`, and `OpenNest.Tests/Fill/LegacyPartOverlap.cs` frozen for differential tests (never route them through production helpers), not production or before timings; measure the actual baseline production code.
|
`PerfCounters.FillScoreComputations`, `PartBoundaryPreparations`, `PartBoundsUpdates`, `OffsetPerimeterEntities`, `FeatureBitmaskCells`, `CrossingPointScans`, `OverlapPolygonPreparations`, and `PolygonTriangulations` increments compile away in Release: zero Release counters prove nothing. `OverlapPolygonPreparations` counts overlap-preparation starts (material extraction), not completed polygons: `Part.Intersects` counts both parts on every call, `PartOverlapChecker` counts once per distinct `Program`. `PolygonTriangulations` counts `Collision` triangulations; the checker triangulates a part at most once per check, and only after a bounding-box hit. `HasOverlap`, `Check` and the checker clip `CollisionTriangle`s (each ear's open vertices and box sides, without a `Polygon` per triangle) in reused buffers with the polygon path's arithmetic; `CollisionOverlapOnlyTests` holds them bitwise to `Collision.Triangulate` and their verdicts to `LegacyCollision`. On a 30-copy fill of an 80-vertex arc-cornered bracket this cut a 15 s Lattice fill to about 4 s with identical poses: per-triangle `Polygon` entities (an interlocked ID each) and per-clip lists dominated. Serialize counter assertions in `FillCacheCollection` and reset in `finally`. Keep `OpenNest.Tests/Fill/LegacyFillExtents.cs`, `OpenNest.Tests/Fill/LegacyFillLinear.cs`, `OpenNest.Tests/Geometry/LegacyCollision.cs`, and `OpenNest.Tests/Fill/LegacyPartOverlap.cs` frozen for differential tests (never route them through production helpers), not production or before timings; measure the actual baseline production code.
|
||||||
|
|
||||||
Predictor regression checks: `dotnet test OpenNest.Tests/OpenNest.Tests.csproj -c Release --filter "FullyQualifiedName~AngleCandidateBuilderTests|FullyQualifiedName~AnglePredictorTests|FullyQualifiedName~FeatureExtractorTests"` (repeat in Debug for bitmap counters). `IrregularAngles_ReportsWarmNoModelPath` measures the public builder with a missing model and skips when a model is installed; never remove real model files to benchmark. `FeatureExtraction_ReportsFullAndScalarOnly` measures extraction separately.
|
Predictor regression checks: `dotnet test OpenNest.Tests/OpenNest.Tests.csproj -c Release --filter "FullyQualifiedName~AngleCandidateBuilderTests|FullyQualifiedName~AnglePredictorTests|FullyQualifiedName~FeatureExtractorTests"` (repeat in Debug for bitmap counters). `IrregularAngles_ReportsWarmNoModelPath` measures the public builder with a missing model and skips when a model is installed; never remove real model files to benchmark. `FeatureExtraction_ReportsFullAndScalarOnly` measures extraction separately.
|
||||||
|
|
||||||
@@ -74,6 +74,12 @@ Predictor availability uses the same one-attempt session initialization as infer
|
|||||||
|
|
||||||
Whole-job before/after comparisons use `OpenNest.Benchmark` with a `*.manifest.json` corpus and `--parallel 1`. Retain input hashes, exact commands, raw results, validity, fulfillment and cost for both revisions outside source control. Record baseline failures rather than treating them as regressions or tuning the corpus around them; overlapping timing ranges are inconclusive, not proof of unchanged performance.
|
Whole-job before/after comparisons use `OpenNest.Benchmark` with a `*.manifest.json` corpus and `--parallel 1`. Retain input hashes, exact commands, raw results, validity, fulfillment and cost for both revisions outside source control. Record baseline failures rather than treating them as regressions or tuning the corpus around them; overlapping timing ranges are inconclusive, not proof of unchanged performance.
|
||||||
|
|
||||||
|
### Deferred grid checks and stripe convergence reuse
|
||||||
|
|
||||||
|
Both leave every layout bit-identical; they only skip work whose outcome is never used or already known. `FillLinear.FillDeferred` returns a `DeferredGrid` whose final overlap check (Step 2, or the perpendicular-only row) has not run; `Resolve` runs it, and `Fill` is `FillDeferred(...).Resolve()`, so eager callers do the same work as before. Step 1's check stays eager because it decides how the grid is built. While pending, a grid's count is either its tiling's or its bounding-box fallback's (`FallbackCount`, which can be lower or higher). `PairFiller.EvaluateCandidate` sorts with `CompareByCount`, which answers each comparison from those counts and runs a check only when they could order the pair differently; the early abort and Phase 2 resolve the grids they use. Every answer equals the checked comparison, so `List.Sort` (unstable) makes the same moves, ties included. Other `FillLinear` callers stay eager: a stripe trajectory feeds every row's verdict into its next angle, and the Linear, remnant and pattern sweeps rank with a pluggable `IFillComparer` that offers no count bound.
|
||||||
|
|
||||||
|
`StripeConvergenceCache` lives in the pipeline's `FillContext.SharedState` and reaches pair remnant strips through `PairFiller`. It keeps each stripe convergence by pair, drawing, axis, variant, span, spacing and row cap, the pair's turned bounds by angle, and each estimate row by angle (one thread tiles a row while others wait). Row and Column converge identical layouts, remnant strips along a full side repeat spans, and trajectories revisit angles; each value is a pure function of its key. `DeferredGridCheckTests` holds both to the eager results.
|
||||||
|
|
||||||
## Entity identity and hot-test configuration
|
## Entity identity and hot-test configuration
|
||||||
|
|
||||||
Use `-c Release` for routine cross-platform test runs, matching CI. Continue running counter-based regressions explicitly in Debug; do not treat fewer Release test cases as lost coverage without checking the DEBUG-only methods and individual skipped outcomes.
|
Use `-c Release` for routine cross-platform test runs, matching CI. Continue running counter-based regressions explicitly in Debug; do not treat fewer Release test cases as lost coverage without checking the DEBUG-only methods and individual skipped outcomes.
|
||||||
|
|||||||
+26
-17
@@ -92,23 +92,32 @@ server/image gates, and pushes the *same smoked image* to
|
|||||||
be absent; retries after even a partial upload stop instead of overwriting. There
|
be absent; retries after even a partial upload stop instead of overwriting. There
|
||||||
are no `latest`, major, or minor aliases. Do not dispatch just to test publication.
|
are no `latest`, major, or minor aliases. Do not dispatch just to test publication.
|
||||||
|
|
||||||
Publication requires an **existing owner-verifiable private package**, linked to
|
The image is **public** (owner decision): the source repository is public, and
|
||||||
`ajisaacs/OpenNest`, with repository Actions access (normally inherited from the
|
anyone may pull the image without a GitHub login. Publishing it does not make a
|
||||||
link). The job uses only its scoped `GITHUB_TOKEN`. All package metadata 404s are
|
server reachable; the server has no authentication and stays on a trusted LAN
|
||||||
refused: GitHub can mask an inaccessible private package as `Not Found`. Opaque
|
(see [nest storage](nest-storage.md#deploying-with-compose)).
|
||||||
registry token success, an empty tag list, or a registry 404 proves neither package
|
|
||||||
absence nor privacy and cannot override the metadata check. Explicit reduced
|
|
||||||
scope and failed registry read access also stop the job. The job rechecks private
|
|
||||||
association after upload.
|
|
||||||
|
|
||||||
First-package initialization is a separately owner-authorized prerequisite
|
The job builds, tests and smokes the tag's own tree, but the publication policy
|
||||||
outside this workflow. Until the private package, repository link, and Actions
|
(preflight before upload and readback after it) always comes from `master`'s copy
|
||||||
access can be verified, publication remains blocked while read-only validation
|
of `scripts/server_image_release.py`, so an older tag publishes under the current
|
||||||
can pass. There
|
policy. The job uses only its scoped `GITHUB_TOKEN`. An existing package must be public
|
||||||
is no automatic bootstrap, extra PAT, absence assertion, or bypass setting. A
|
and linked to `ajisaacs/OpenNest`; a private package or one linked to another
|
||||||
local credential's Packages API 403 proves neither absence nor privacy. No
|
repository stops the job before upload. The first publication creates the
|
||||||
workflow changes visibility. Public availability needs separate owner approval
|
package: GitHub's own package-not-found response is accepted only when the
|
||||||
and a later anonymous-pull check; it is not approved here.
|
registry also reports the repository unknown, because a package hidden from the
|
||||||
|
token still has a registry repository. Every other metadata error, denial,
|
||||||
|
reduced registry scope or failed tag-list read stops the job. Because the source
|
||||||
|
repository is public and the image carries its `org.opencontainers.image.source`
|
||||||
|
label, the new package is linked to the repository and public. The job rechecks
|
||||||
|
public visibility and association after upload, and the clean-runner
|
||||||
|
verification pulls the returned digest **without logging in**, which proves
|
||||||
|
anonymous pulls work.
|
||||||
|
|
||||||
|
If a first publication fails that recheck (the package came out private), the two
|
||||||
|
tags are already uploaded and a retry refuses them: in the package settings make
|
||||||
|
it public and confirm the anonymous pull by hand, or delete the package and
|
||||||
|
dispatch again. There is no extra PAT or bypass setting, and no workflow changes
|
||||||
|
visibility.
|
||||||
|
|
||||||
The local gate reads `docker image save` to hash the actual config and verify each
|
The local gate reads `docker image save` to hash the actual config and verify each
|
||||||
layer against its ordered uncompressed rootfs digest. It rejects unexpected
|
layer against its ordered uncompressed rootfs digest. It rejects unexpected
|
||||||
@@ -137,6 +146,6 @@ python3 -m unittest discover -s scripts -p test_server_image_release.py -v
|
|||||||
```
|
```
|
||||||
|
|
||||||
Deployment is deliberately separate; use the verified digest and the
|
Deployment is deliberately separate; use the verified digest and the
|
||||||
[private pull/Compose procedure](nest-storage.md#deploying-with-compose). No
|
[pull/Compose procedure](nest-storage.md#deploying-with-compose). No
|
||||||
publication, release creation, deployment, or visibility change is implied by
|
publication, release creation, deployment, or visibility change is implied by
|
||||||
adding or validating this workflow.
|
adding or validating this workflow.
|
||||||
@@ -117,12 +117,20 @@ def absent(status, headers, body):
|
|||||||
|
|
||||||
|
|
||||||
def package_policy(status, headers, body):
|
def package_policy(status, headers, body):
|
||||||
|
"""Return True when GitHub reports no package yet (first publication).
|
||||||
|
|
||||||
|
The repository is public and the image carries its source label, so the first
|
||||||
|
GITHUB_TOKEN push creates a public package linked to it; readback and the
|
||||||
|
anonymous pull prove that afterwards. Any other shape fails closed."""
|
||||||
data = json_body(body)
|
data = json_body(body)
|
||||||
require(isinstance(data, dict), "malformed package metadata")
|
require(isinstance(data, dict), "malformed package metadata")
|
||||||
require(status == 200, "package metadata inaccessible; privacy unknown")
|
if status == 404 and data.get("message") in ("Package not found.", "Not Found") and \
|
||||||
|
str(data.get("documentation_url", "")).startswith("https://docs.github.com/rest/packages"):
|
||||||
|
return True
|
||||||
|
require(status == 200, "package metadata inaccessible; visibility unknown")
|
||||||
require(data.get("name") == PACKAGE and data.get("package_type") == "container" and
|
require(data.get("name") == PACKAGE and data.get("package_type") == "container" and
|
||||||
data.get("visibility") == "private" and isinstance(data.get("repository"), dict) and
|
data.get("visibility") == "public" and isinstance(data.get("repository"), dict) and
|
||||||
data["repository"].get("full_name") == REPO, "package privacy/association mismatch")
|
data["repository"].get("full_name") == REPO, "package visibility/association mismatch")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
@@ -188,8 +196,12 @@ def preflight(client, release_version, sha):
|
|||||||
repo = json_body(body)
|
repo = json_body(body)
|
||||||
require(status == 200 and isinstance(repo, dict) and repo.get("full_name") == REPO and
|
require(status == 200 and isinstance(repo, dict) and repo.get("full_name") == REPO and
|
||||||
repo.get("default_branch") == "master", "repository/default branch authorization unproven")
|
repo.get("default_branch") == "master", "repository/default branch authorization unproven")
|
||||||
package_policy(*client.get(PACKAGE_API))
|
first_publication = package_policy(*client.get(PACKAGE_API))
|
||||||
tags_response = client.get(registry_path("tags/list"))
|
tags_response = client.get(registry_path("tags/list"))
|
||||||
|
if first_publication:
|
||||||
|
# A package hidden from this token would still have a registry repository.
|
||||||
|
require(absent(*tags_response), "package metadata missing but registry repository exists")
|
||||||
|
return {"package": IMAGE, "visibility": "public", "first_publication": True}
|
||||||
require(tags_response[0] == 200, "existing package registry read access unproven")
|
require(tags_response[0] == 200, "existing package registry read access unproven")
|
||||||
data = json_body(tags_response[2])
|
data = json_body(tags_response[2])
|
||||||
require(isinstance(data, dict) and data.get("name") == REGISTRY_NAME and
|
require(isinstance(data, dict) and data.get("name") == REGISTRY_NAME and
|
||||||
@@ -200,7 +212,7 @@ def preflight(client, release_version, sha):
|
|||||||
require(not any(tag in (data["tags"] or []) for tag in reserved_tags), "refusing existing immutable tag")
|
require(not any(tag in (data["tags"] or []) for tag in reserved_tags), "refusing existing immutable tag")
|
||||||
for tag in reserved_tags:
|
for tag in reserved_tags:
|
||||||
require(absent(*client.get(registry_path("manifests/" + tag))), "refusing existing immutable tag")
|
require(absent(*client.get(registry_path("manifests/" + tag))), "refusing existing immutable tag")
|
||||||
return {"package": IMAGE, "visibility": "private"}
|
return {"package": IMAGE, "visibility": "public"}
|
||||||
|
|
||||||
|
|
||||||
def content_digest(body):
|
def content_digest(body):
|
||||||
@@ -439,7 +451,7 @@ def main():
|
|||||||
local = local_identity(os.environ.get("LOCAL_IMAGE", ""))
|
local = local_identity(os.environ.get("LOCAL_IMAGE", ""))
|
||||||
if args.operation == "readback":
|
if args.operation == "readback":
|
||||||
client = Client()
|
client = Client()
|
||||||
package_policy(*client.get(PACKAGE_API))
|
require(not package_policy(*client.get(PACKAGE_API)), "package metadata missing after upload")
|
||||||
directory = pathlib.Path(os.environ.get("METADATA_DIR", ".hermes/server-image-metadata"))
|
directory = pathlib.Path(os.environ.get("METADATA_DIR", ".hermes/server-image-metadata"))
|
||||||
try:
|
try:
|
||||||
previous = json_body((directory / "local.json").read_bytes())
|
previous = json_body((directory / "local.json").read_bytes())
|
||||||
|
|||||||
@@ -19,6 +19,8 @@ assert SPEC is not None and SPEC.loader is not None
|
|||||||
release = importlib.util.module_from_spec(SPEC)
|
release = importlib.util.module_from_spec(SPEC)
|
||||||
SPEC.loader.exec_module(release)
|
SPEC.loader.exec_module(release)
|
||||||
SHA = "a" * 40
|
SHA = "a" * 40
|
||||||
|
# GitHub's real answer for a user package that does not exist (observed 2026-11-17).
|
||||||
|
GITHUB_PACKAGE_NOT_FOUND = {"message": "Package not found.", "documentation_url": "https://docs.github.com/rest/packages/packages#get-a-package-for-a-user", "status": "404"}
|
||||||
BASE = "mcr.microsoft.com/dotnet/aspnet@sha256:" + "b" * 64
|
BASE = "mcr.microsoft.com/dotnet/aspnet@sha256:" + "b" * 64
|
||||||
LAYER = b"deterministic synthetic rootfs layer"
|
LAYER = b"deterministic synthetic rootfs layer"
|
||||||
LAYER_GZIP = gzip.compress(LAYER, mtime=0)
|
LAYER_GZIP = gzip.compress(LAYER, mtime=0)
|
||||||
@@ -123,23 +125,23 @@ class RegistrySafety(unittest.TestCase):
|
|||||||
release.absent(*response(status, body))
|
release.absent(*response(status, body))
|
||||||
self.assertFalse(release.absent(*response(200, {"schemaVersion": 2})))
|
self.assertFalse(release.absent(*response(200, {"schemaVersion": 2})))
|
||||||
|
|
||||||
def test_private_associated_package(self):
|
def test_public_associated_package(self):
|
||||||
package = {"name": release.PACKAGE, "package_type": "container", "visibility": "private",
|
package = {"name": release.PACKAGE, "package_type": "container", "visibility": "public",
|
||||||
"repository": {"full_name": release.REPO}}
|
"repository": {"full_name": release.REPO}}
|
||||||
self.assertFalse(release.package_policy(*response(200, package)))
|
self.assertFalse(release.package_policy(*response(200, package)))
|
||||||
for key, value in (("visibility", "public"), ("visibility", "internal"),
|
for key, value in (("visibility", "private"), ("visibility", "internal"),
|
||||||
("repository", None), ("repository", {"full_name": "other/OpenNest"}),
|
("repository", None), ("repository", {"full_name": "other/OpenNest"}),
|
||||||
("name", "other"), ("package_type", "npm")):
|
("name", "other"), ("package_type", "npm")):
|
||||||
wrong = dict(package, **{key: value})
|
wrong = dict(package, **{key: value})
|
||||||
with self.assertRaises(release.ReleaseError):
|
with self.assertRaises(release.ReleaseError):
|
||||||
release.package_policy(*response(200, wrong))
|
release.package_policy(*response(200, wrong))
|
||||||
|
|
||||||
def test_package_metadata_404_never_authorizes_bootstrap(self):
|
def test_github_not_found_metadata_means_first_publication(self):
|
||||||
with self.assertRaises(release.ReleaseError):
|
self.assertTrue(release.package_policy(*response(404, dict(GITHUB_PACKAGE_NOT_FOUND))))
|
||||||
release.package_policy(*response(404, {
|
|
||||||
"message": "Not Found", "documentation_url": "https://docs.github.com/rest/packages"}))
|
|
||||||
for status, body in ((403, {"message": "Resource not accessible"}), (404, {}),
|
for status, body in ((403, {"message": "Resource not accessible"}), (404, {}),
|
||||||
(404, {"message": "Not Found", "documentation_url": "https://evil.test"})):
|
(404, {"message": "Not Found", "documentation_url": "https://evil.test"}),
|
||||||
|
(404, dict(GITHUB_PACKAGE_NOT_FOUND, message="Resource not accessible")),
|
||||||
|
(404, dict(GITHUB_PACKAGE_NOT_FOUND, documentation_url="https://docs.github.com/rest/repos"))):
|
||||||
with self.assertRaises(release.ReleaseError):
|
with self.assertRaises(release.ReleaseError):
|
||||||
release.package_policy(*response(status, body))
|
release.package_policy(*response(status, body))
|
||||||
|
|
||||||
@@ -151,9 +153,9 @@ class RegistrySafety(unittest.TestCase):
|
|||||||
release.registry_token(status, encoded(body))
|
release.registry_token(status, encoded(body))
|
||||||
|
|
||||||
def preflight_client(self, package_status=200, tags=None):
|
def preflight_client(self, package_status=200, tags=None):
|
||||||
package = {"name": release.PACKAGE, "package_type": "container", "visibility": "private",
|
package = {"name": release.PACKAGE, "package_type": "container", "visibility": "public",
|
||||||
"repository": {"full_name": release.REPO}}
|
"repository": {"full_name": release.REPO}}
|
||||||
missing = {"message": "Not Found", "documentation_url": "https://docs.github.com/rest/packages"}
|
missing = dict(GITHUB_PACKAGE_NOT_FOUND)
|
||||||
return FakeClient({
|
return FakeClient({
|
||||||
release.REPO_API: response(200, {"full_name": release.REPO, "default_branch": "master"}),
|
release.REPO_API: response(200, {"full_name": release.REPO, "default_branch": "master"}),
|
||||||
release.PACKAGE_API: response(package_status, package if package_status == 200 else missing),
|
release.PACKAGE_API: response(package_status, package if package_status == 200 else missing),
|
||||||
@@ -171,11 +173,20 @@ class RegistrySafety(unittest.TestCase):
|
|||||||
with self.assertRaises(release.ReleaseError):
|
with self.assertRaises(release.ReleaseError):
|
||||||
release.preflight(client, "1.2.3", SHA)
|
release.preflight(client, "1.2.3", SHA)
|
||||||
|
|
||||||
def test_missing_metadata_denies_regardless_of_registry_tags(self):
|
def test_first_publication_requires_an_absent_registry_repository(self):
|
||||||
with self.assertRaises(release.ReleaseError):
|
client = self.preflight_client(404)
|
||||||
release.preflight(self.preflight_client(404), "1.2.3", SHA)
|
unknown = response(404, {"errors": [{"code": "NAME_UNKNOWN"}]})
|
||||||
with self.assertRaises(release.ReleaseError):
|
client.responses[release.registry_path("tags/list")] = unknown
|
||||||
release.preflight(self.preflight_client(404, ["old"]), "1.2.3", SHA)
|
self.assertEqual(release.preflight(client, "1.2.3", SHA),
|
||||||
|
{"package": release.IMAGE, "visibility": "public", "first_publication": True})
|
||||||
|
for tags in ([], ["old"]):
|
||||||
|
with self.subTest(tags=tags), self.assertRaises(release.ReleaseError):
|
||||||
|
release.preflight(self.preflight_client(404, tags), "1.2.3", SHA)
|
||||||
|
for denied in (response(404, {"errors": [{"code": "DENIED"}]}), response(401, {}), response(403, {})):
|
||||||
|
client = self.preflight_client(404)
|
||||||
|
client.responses[release.registry_path("tags/list")] = denied
|
||||||
|
with self.subTest(denied=denied[0]), self.assertRaises(release.ReleaseError):
|
||||||
|
release.preflight(client, "1.2.3", SHA)
|
||||||
|
|
||||||
def test_preflight_transport_metadata_and_tag_list_errors_fail_closed(self):
|
def test_preflight_transport_metadata_and_tag_list_errors_fail_closed(self):
|
||||||
for path in (release.REPO_API, release.PACKAGE_API, release.registry_path("tags/list")):
|
for path in (release.REPO_API, release.PACKAGE_API, release.registry_path("tags/list")):
|
||||||
@@ -502,10 +513,22 @@ class ArchiveIdentity(unittest.TestCase):
|
|||||||
with self.assertRaisesRegex(release.ReleaseError, "rootfs chain"):
|
with self.assertRaisesRegex(release.ReleaseError, "rootfs chain"):
|
||||||
release.readback(client, "1.2.3", SHA, local)
|
release.readback(client, "1.2.3", SHA, local)
|
||||||
|
|
||||||
|
def test_readback_refuses_a_package_still_missing_after_upload(self):
|
||||||
|
client, local = ReadbackSafety().fixture()
|
||||||
|
client.responses[release.PACKAGE_API] = response(404, dict(GITHUB_PACKAGE_NOT_FOUND))
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
env = {"VERSION": "1.2.3", "SOURCE_SHA": SHA, "METADATA_DIR": directory}
|
||||||
|
with mock.patch.dict(os.environ, env), mock.patch.object(release, "git", return_value=SHA), \
|
||||||
|
mock.patch.object(release, "Client", return_value=client), \
|
||||||
|
mock.patch.object(release, "local_identity", return_value=local), \
|
||||||
|
mock.patch("sys.argv", ["helper", "readback"]):
|
||||||
|
with self.assertRaisesRegex(release.ReleaseError, "missing after upload"):
|
||||||
|
release.main()
|
||||||
|
|
||||||
def test_readback_requires_the_pre_smoke_identity_stamp(self):
|
def test_readback_requires_the_pre_smoke_identity_stamp(self):
|
||||||
client, local = ReadbackSafety().fixture()
|
client, local = ReadbackSafety().fixture()
|
||||||
client.responses[release.PACKAGE_API] = response(200, {"name": release.PACKAGE,
|
client.responses[release.PACKAGE_API] = response(200, {"name": release.PACKAGE,
|
||||||
"package_type": "container", "visibility": "private", "repository": {"full_name": release.REPO}})
|
"package_type": "container", "visibility": "public", "repository": {"full_name": release.REPO}})
|
||||||
with tempfile.TemporaryDirectory() as directory:
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
env = {"VERSION": "1.2.3", "SOURCE_SHA": SHA, "METADATA_DIR": directory}
|
env = {"VERSION": "1.2.3", "SOURCE_SHA": SHA, "METADATA_DIR": directory}
|
||||||
stamp = pathlib.Path(directory) / "local.json"
|
stamp = pathlib.Path(directory) / "local.json"
|
||||||
@@ -535,15 +558,12 @@ class ArchiveIdentity(unittest.TestCase):
|
|||||||
|
|
||||||
|
|
||||||
class SpecRegressions(unittest.TestCase):
|
class SpecRegressions(unittest.TestCase):
|
||||||
def test_masked_package_404_denies_even_empty_or_missing_registry(self):
|
def test_masked_package_404_denies_an_existing_registry_repository(self):
|
||||||
safety = RegistrySafety()
|
client = RegistrySafety().preflight_client(404)
|
||||||
for registry in (response(200, {"name": release.REGISTRY_NAME, "tags": []}),
|
client.responses[release.registry_path("tags/list")] = response(200, {"name": release.REGISTRY_NAME, "tags": []})
|
||||||
response(404, {"errors": [{"code": "NAME_UNKNOWN"}]})):
|
with self.assertRaises(release.ReleaseError):
|
||||||
client = safety.preflight_client(404)
|
release.preflight(client, "1.2.3", SHA)
|
||||||
client.responses[release.registry_path("tags/list")] = registry
|
self.assertFalse(any("/manifests/" in call for call in client.calls))
|
||||||
with self.subTest(registry=registry), self.assertRaises(release.ReleaseError):
|
|
||||||
release.preflight(client, "1.2.3", SHA)
|
|
||||||
self.assertNotIn(release.registry_path("tags/list"), client.calls)
|
|
||||||
|
|
||||||
def test_opaque_reduced_scope_token_cannot_authorize_masked_metadata(self):
|
def test_opaque_reduced_scope_token_cannot_authorize_masked_metadata(self):
|
||||||
with mock.patch.dict("os.environ", {"GITHUB_TOKEN": "test-only", "GITHUB_REPOSITORY": release.REPO}):
|
with mock.patch.dict("os.environ", {"GITHUB_TOKEN": "test-only", "GITHUB_REPOSITORY": release.REPO}):
|
||||||
@@ -553,7 +573,7 @@ class SpecRegressions(unittest.TestCase):
|
|||||||
token["scope"] = scope
|
token["scope"] = scope
|
||||||
responses = [response(200, token),
|
responses = [response(200, token),
|
||||||
response(200, {"full_name": release.REPO, "default_branch": "master"}),
|
response(200, {"full_name": release.REPO, "default_branch": "master"}),
|
||||||
response(404, {"message": "Not Found", "documentation_url": "https://docs.github.com/rest/packages"}),
|
response(404, dict(GITHUB_PACKAGE_NOT_FOUND)),
|
||||||
response(200, {"name": release.REGISTRY_NAME, "tags": []}),
|
response(200, {"name": release.REGISTRY_NAME, "tags": []}),
|
||||||
response(404, {"errors": [{"code": "MANIFEST_UNKNOWN"}]}),
|
response(404, {"errors": [{"code": "MANIFEST_UNKNOWN"}]}),
|
||||||
response(404, {"errors": [{"code": "MANIFEST_UNKNOWN"}]})]
|
response(404, {"errors": [{"code": "MANIFEST_UNKNOWN"}]})]
|
||||||
@@ -706,6 +726,20 @@ class WorkflowBehavior(unittest.TestCase):
|
|||||||
self.assertNotIn("'release'", condition)
|
self.assertNotIn("'release'", condition)
|
||||||
self.assertIn("github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/master'", condition)
|
self.assertIn("github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/master'", condition)
|
||||||
|
|
||||||
|
def test_publication_policy_comes_from_master_not_the_tagged_tree(self):
|
||||||
|
# The tag's tree is built and tested, but an older tag's helper must not
|
||||||
|
# decide package visibility: preflight and readback run master's copy.
|
||||||
|
workflow = pathlib.Path(__file__).resolve().parents[1] / ".github/workflows/server-image.yml"
|
||||||
|
publish = workflow.read_text().split("\n publish:\n", 1)[1].split("\n verify-published:\n", 1)[0]
|
||||||
|
source = publish.index("server_image_release.py source")
|
||||||
|
copy = publish.index('cp scripts/server_image_release.py "$RELEASE_POLICY"')
|
||||||
|
tag_checkout = publish.index("ref: ${{ steps.source.outputs.source_sha }}")
|
||||||
|
self.assertLess(source, copy)
|
||||||
|
self.assertLess(copy, tag_checkout)
|
||||||
|
for operation in ("preflight", "readback"):
|
||||||
|
self.assertIn('python3 "$RELEASE_POLICY" ' + operation, publish)
|
||||||
|
self.assertNotIn("scripts/server_image_release.py " + operation, publish)
|
||||||
|
|
||||||
def test_build_log_pipeline_preserves_docker_failure(self):
|
def test_build_log_pipeline_preserves_docker_failure(self):
|
||||||
workflow = pathlib.Path(__file__).resolve().parents[1] / ".github/workflows/server-image.yml"
|
workflow = pathlib.Path(__file__).resolve().parents[1] / ".github/workflows/server-image.yml"
|
||||||
lines = workflow.read_text().splitlines()
|
lines = workflow.read_text().splitlines()
|
||||||
|
|||||||
Reference in new issue
Block a user